🤖 Create Your First AMCP Agent

Build a weather monitoring agent in 15 minutes

Beginner 15 minutes Java

📋 Step 1: Project Setup

First, let's create a new Maven project and add the AMCP dependency.

Create Maven Project

mvn archetype:generate \
  -DgroupId=com.example.amcp \
  -DartifactId=weather-agent \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DinteractiveMode=false

Add AMCP Dependency

Update your pom.xml to include AMCP:

<dependencies>
    <dependency>
        <groupId>org.amcp</groupId>
        <artifactId>amcp-core</artifactId>
        <version>1.5.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version>
    </dependency>
</dependencies>

🏗️ Step 2: Create Agent Class

Create a WeatherAgent class that extends the AMCP Agent base class.

WeatherAgent.java

package com.example.amcp;

import org.amcp.core.Agent;
import org.amcp.core.Event;
import org.amcp.core.annotation.EventHandler;
import org.amcp.core.annotation.Subscribe;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class WeatherAgent extends Agent {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private Map<String, WeatherData> weatherCache = new HashMap<>();
    
    public WeatherAgent(String agentId) {
        super(agentId, "WeatherAgent");
    }
    
    @Override
    public void onActivation() {
        // Subscribe to weather request topics
        subscribe("weather.request.*");
        subscribe("weather.update.*");
        
        // Announce capabilities
        announceCapability("weather-monitoring", "1.0");
        
        log("Weather Agent activated and ready!");
    }
    
    // Weather data model
    public static class WeatherData {
        public String city;
        public double temperature;
        public String condition;
        public long timestamp;
        
        public WeatherData() {}
        
        public WeatherData(String city, double temperature, String condition) {
            this.city = city;
            this.temperature = temperature;
            this.condition = condition;
            this.timestamp = System.currentTimeMillis();
        }
    }
}

📡 Step 3: Handle Events

Add event handlers to process weather requests and updates.

Add Event Handlers

@EventHandler
@Subscribe("weather.request.*")
public void handleWeatherRequest(Event event) {
    try {
        String city = extractCityFromTopic(event.getTopic());
        WeatherData weather = weatherCache.get(city);
        
        if (weather != null) {
            // Send cached weather data
            Event response = Event.builder()
                .topic("weather.response." + city)
                .payload(objectMapper.writeValueAsString(weather))
                .correlationId(event.getCorrelationId())
                .sender(getAgentId())
                .build();
                
            publish(response);
            log("Sent weather data for " + city);
        } else {
            // Request fresh data
            requestWeatherUpdate(city);
        }
    } catch (Exception e) {
        log("Error handling weather request: " + e.getMessage());
    }
}

@EventHandler
@Subscribe("weather.update.*")
public void handleWeatherUpdate(Event event) {
    try {
        String city = extractCityFromTopic(event.getTopic());
        WeatherData weather = objectMapper.readValue(
            event.getPayload(), WeatherData.class);
        
        // Cache the weather data
        weatherCache.put(city, weather);
        
        // Broadcast update to interested parties
        Event broadcast = Event.builder()
            .topic("weather.broadcast." + city)
            .payload(event.getPayload())
            .sender(getAgentId())
            .build();
            
        publish(broadcast);
        log("Updated weather data for " + city);
    } catch (Exception e) {
        log("Error handling weather update: " + e.getMessage());
    }
}

private String extractCityFromTopic(String topic) {
    String[] parts = topic.split("\\.");
    return parts.length > 2 ? parts[2] : "unknown";
}

private void requestWeatherUpdate(String city) {
    Event request = Event.builder()
        .topic("external.weather.fetch." + city)
        .payload("{\"city\":\"" + city + "\"}")
        .sender(getAgentId())
        .build();
        
    publish(request);
    log("Requested weather update for " + city);
}

🚀 Step 4: Activate Agent

Create a main class to activate your weather agent.

WeatherAgentApp.java

package com.example.amcp;

import org.amcp.core.AgentContext;
import org.amcp.core.config.AMCPConfig;

public class WeatherAgentApp {
    
    public static void main(String[] args) {
        try {
            // Configure AMCP
            AMCPConfig config = AMCPConfig.builder()
                .brokerUrl("kafka://localhost:9092")
                .agentId("weather-agent-001")
                .build();
            
            // Create agent context
            AgentContext context = new AgentContext(config);
            
            // Create and activate weather agent
            WeatherAgent weatherAgent = new WeatherAgent("weather-001");
            context.activateAgent(weatherAgent);
            
            System.out.println("Weather Agent started successfully!");
            System.out.println("Press Ctrl+C to stop...");
            
            // Keep the application running
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.out.println("Shutting down Weather Agent...");
                context.shutdown();
            }));
            
            // Wait indefinitely
            Thread.currentThread().join();
            
        } catch (Exception e) {
            System.err.println("Failed to start Weather Agent: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

✅ Step 5: Test & Verify

Let's test our weather agent by sending some events.

Start Kafka (if using Docker)

docker run -d --name kafka \
  -p 9092:9092 \
  -e KAFKA_ZOOKEEPER_CONNECT=zookeeper:2181 \
  -e KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092 \
  confluentinc/cp-kafka:latest

Run the Agent

mvn compile exec:java -Dexec.mainClass="com.example.amcp.WeatherAgentApp"

Test with curl

# Send weather update
curl -X POST http://localhost:8080/events \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "weather.update.london",
    "payload": "{\"city\":\"london\",\"temperature\":22.5,\"condition\":\"sunny\"}"
  }'

# Request weather data
curl -X POST http://localhost:8080/events \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "weather.request.london",
    "correlationId": "req-001"
  }'

✅ Verification Checklist

  • Agent starts without errors
  • Agent subscribes to weather topics
  • Agent responds to weather requests
  • Agent caches weather data
  • Agent broadcasts weather updates