You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@eventmesh.apache.org by ch...@apache.org on 2026/07/13 11:56:15 UTC
(eventmesh) branch develop updated: feat: port A2A Gateway runtime implementation from master to uni-architecture
This is an automated email from the ASF dual-hosted git repository.
qqeasonchen pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/eventmesh.git
The following commit(s) were added to refs/heads/develop by this push:
new 201a05861 feat: port A2A Gateway runtime implementation from master to uni-architecture
201a05861 is described below
commit 201a058615a20cf44d135f20debc5287a3ef035d
Author: qqeasonchen <qq...@gmail.com>
AuthorDate: Mon Jul 13 19:55:05 2026 +0800
feat: port A2A Gateway runtime implementation from master to uni-architecture
---
.../apache/eventmesh/a2a/demo/A2AAbstractDemo.java | 56 ++
.../apache/eventmesh/a2a/demo/AgentCardDemo.java | 199 +++++++
.../java/org/apache/eventmesh/a2a/demo/README.md | 151 +++++
.../eventmesh/a2a/demo/ce/CloudEventsCaller.java | 116 ++++
.../eventmesh/a2a/demo/ce/CloudEventsProvider.java | 99 ++++
.../eventmesh/a2a/demo/gateway/A2AGatewayDemo.java | 133 +++++
.../apache/eventmesh/a2a/demo/mcp/McpCaller.java | 154 +++++
.../apache/eventmesh/a2a/demo/mcp/McpProvider.java | 117 ++++
eventmesh-runtime/build.gradle | 2 +
eventmesh-runtime/conf/a2a-protocol-config.yaml | 35 ++
.../eventmesh/runtime/a2a/A2ACardHttpHandler.java | 218 +++++++
.../runtime/a2a/A2AGatewayHttpHandler.java | 648 +++++++++++++++++++++
.../eventmesh/runtime/a2a/A2AGatewayServer.java | 338 +++++++++++
.../eventmesh/runtime/a2a/A2AGatewayService.java | 421 +++++++++++++
.../runtime/a2a/A2APublishSubscribeService.java | 448 ++++++++++++++
.../runtime/a2a/InMemoryA2AMessageTransport.java | 118 ++++
.../apache/eventmesh/runtime/a2a/TaskRegistry.java | 348 +++++++++++
.../a2a/A2AClientServerIntegrationTest.java | 481 +++++++++++++++
.../runtime/a2a/A2AGatewayEndToEndTest.java | 234 ++++++++
.../runtime/a2a/A2AGatewayServiceTest.java | 406 +++++++++++++
.../eventmesh/runtime/a2a/AgentCardTestUtils.java | 64 ++
.../a2a/InMemoryA2AMessageTransportTest.java | 194 ++++++
.../eventmesh/runtime/a2a/TaskRegistryTest.java | 297 ++++++++++
23 files changed, 5277 insertions(+)
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/A2AAbstractDemo.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/A2AAbstractDemo.java
new file mode 100644
index 000000000..e0d2cdabf
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/A2AAbstractDemo.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo;
+
+import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig;
+import org.apache.eventmesh.common.ExampleConstants;
+import org.apache.eventmesh.common.utils.IPUtils;
+import org.apache.eventmesh.common.utils.ThreadUtils;
+import org.apache.eventmesh.util.Utils;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.io.IOException;
+import java.util.Properties;
+
+public class A2AAbstractDemo {
+
+ protected static EventMeshHttpClientConfig initEventMeshHttpClientConfig(final String groupName)
+ throws IOException {
+ final Properties properties = Utils.readPropertiesFile(ExampleConstants.CONFIG_FILE_NAME);
+ final String eventMeshIp = properties.getProperty(ExampleConstants.EVENTMESH_IP);
+ final String eventMeshHttpPort = properties.getProperty(ExampleConstants.EVENTMESH_HTTP_PORT);
+
+ String eventMeshIPPort = ExampleConstants.DEFAULT_EVENTMESH_IP_PORT;
+ if (StringUtils.isNotBlank(eventMeshIp) || StringUtils.isNotBlank(eventMeshHttpPort)) {
+ eventMeshIPPort = eventMeshIp + ":" + eventMeshHttpPort;
+ }
+
+ return EventMeshHttpClientConfig.builder()
+ .liteEventMeshAddr(eventMeshIPPort)
+ .producerGroup(groupName)
+ .env("env")
+ .idc("idc")
+ .ip(IPUtils.getLocalAddress())
+ .sys("1234")
+ .pid(String.valueOf(ThreadUtils.getPID()))
+ .userName("eventmesh")
+ .password("pass")
+ .build();
+ }
+}
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/AgentCardDemo.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/AgentCardDemo.java
new file mode 100644
index 000000000..c3418dc19
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/AgentCardDemo.java
@@ -0,0 +1,199 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo;
+
+import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig;
+import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer;
+import org.apache.eventmesh.common.Constants;
+import org.apache.eventmesh.common.ExampleConstants;
+import org.apache.eventmesh.common.utils.JsonUtils;
+import org.apache.eventmesh.protocol.a2a.A2AProtocolConstants;
+import org.apache.eventmesh.protocol.a2a.model.AgentCapabilities;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+import org.apache.eventmesh.protocol.a2a.model.AgentInterface;
+import org.apache.eventmesh.protocol.a2a.model.AgentProvider;
+import org.apache.eventmesh.protocol.a2a.model.AgentSkill;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Demo showing A2A Agent Card registration, discovery, and deletion via EventMesh.
+ */
+@Slf4j
+public class AgentCardDemo extends A2AAbstractDemo {
+
+ public static void main(String[] args) throws Exception {
+ EventMeshHttpClientConfig config = initEventMeshHttpClientConfig("a2a-agent-card-demo");
+ try (EventMeshHttpProducer producer = new EventMeshHttpProducer(config)) {
+
+ // 1. Register an Agent Card
+ registerAgentCard(producer, "my.org", "my.unit", "weather-agent");
+
+ // 2. List Agent Cards
+ listAgentCards(producer);
+
+ // 3. Get specific Agent Card
+ getAgentCard(producer, "my.org", "my.unit", "weather-agent");
+
+ // 4. Delete Agent Card
+ deleteAgentCard(producer, "my.org", "my.unit", "weather-agent");
+
+ log.info("AgentCardDemo completed.");
+ }
+ }
+
+ private static void registerAgentCard(EventMeshHttpProducer producer,
+ String orgId, String unitId, String agentId) throws Exception {
+ AgentCard card = buildSampleCard(agentId);
+
+ Map<String, Object> params = new HashMap<>();
+ params.put("org_id", orgId);
+ params.put("unit_id", unitId);
+ params.put("agent_id", agentId);
+ params.put("card", card);
+
+ Map<String, Object> request = new HashMap<>();
+ request.put("jsonrpc", "2.0");
+ request.put("method", A2AProtocolConstants.OP_REGISTER_AGENT_CARD);
+ request.put("params", params);
+ request.put("id", UUID.randomUUID().toString());
+
+ CloudEvent event = buildA2ACardEvent(request);
+ producer.publish(event);
+ log.info("Registered agent card: {}/{}/{}", orgId, unitId, agentId);
+ }
+
+ private static void listAgentCards(EventMeshHttpProducer producer) throws Exception {
+ Map<String, Object> params = new HashMap<>();
+ params.put("org_id", "my.org");
+
+ Map<String, Object> request = new HashMap<>();
+ request.put("jsonrpc", "2.0");
+ request.put("method", A2AProtocolConstants.OP_LIST_AGENT_CARDS);
+ request.put("params", params);
+ request.put("id", UUID.randomUUID().toString());
+
+ CloudEvent event = buildA2ACardEvent(request);
+ producer.publish(event);
+ log.info("Listed agent cards for org: my.org");
+ }
+
+ private static void getAgentCard(EventMeshHttpProducer producer,
+ String orgId, String unitId, String agentId) throws Exception {
+ Map<String, Object> params = new HashMap<>();
+ params.put("org_id", orgId);
+ params.put("unit_id", unitId);
+ params.put("agent_id", agentId);
+
+ Map<String, Object> request = new HashMap<>();
+ request.put("jsonrpc", "2.0");
+ request.put("method", A2AProtocolConstants.OP_GET_AGENT_CARD);
+ request.put("params", params);
+ request.put("id", UUID.randomUUID().toString());
+
+ CloudEvent event = buildA2ACardEvent(request);
+ producer.publish(event);
+ log.info("Got agent card: {}/{}/{}", orgId, unitId, agentId);
+ }
+
+ private static void deleteAgentCard(EventMeshHttpProducer producer,
+ String orgId, String unitId, String agentId) throws Exception {
+ Map<String, Object> params = new HashMap<>();
+ params.put("org_id", orgId);
+ params.put("unit_id", unitId);
+ params.put("agent_id", agentId);
+
+ Map<String, Object> request = new HashMap<>();
+ request.put("jsonrpc", "2.0");
+ request.put("method", A2AProtocolConstants.OP_DELETE_AGENT_CARD);
+ request.put("params", params);
+ request.put("id", UUID.randomUUID().toString());
+
+ CloudEvent event = buildA2ACardEvent(request);
+ producer.publish(event);
+ log.info("Deleted agent card: {}/{}/{}", orgId, unitId, agentId);
+ }
+
+ private static AgentCard buildSampleCard(String agentId) {
+ AgentInterface iface = AgentInterface.builder()
+ .url("http://localhost:8080/a2a")
+ .protocolBinding("JSONRPC")
+ .protocolVersion(A2AProtocolConstants.PROTOCOL_VERSION)
+ .build();
+
+ AgentProvider provider = AgentProvider.builder()
+ .url("https://example.org")
+ .organization("Example Org")
+ .build();
+
+ AgentCapabilities capabilities = AgentCapabilities.builder()
+ .streaming(true)
+ .pushNotifications(true)
+ .build();
+
+ AgentSkill skill = AgentSkill.builder()
+ .id("weather-query")
+ .name("Weather Query")
+ .description("Queries weather information for a given location")
+ .tags(Arrays.asList("weather", "query"))
+ .examples(Arrays.asList("What's the weather in Beijing?"))
+ .build();
+
+ return AgentCard.builder()
+ .name(agentId)
+ .description("A weather query agent")
+ .version("1.0.0")
+ .supportedInterfaces(Collections.singletonList(iface))
+ .provider(provider)
+ .capabilities(capabilities)
+ .skills(Collections.singletonList(skill))
+ .defaultInputModes(Collections.singletonList("text/plain"))
+ .defaultOutputModes(Collections.singletonList("text/plain"))
+ .build();
+ }
+
+ private static CloudEvent buildA2ACardEvent(Map<String, Object> jsonRpcBody) {
+ String content = JsonUtils.toJSONString(jsonRpcBody);
+ String method = (String) jsonRpcBody.get("method");
+ String ceType = A2AProtocolConstants.CE_TYPE_PREFIX + method.replace("/", ".") + ".req";
+
+ return CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withSource(URI.create("a2a-agent-card-demo"))
+ .withDataContentType(ExampleConstants.CLOUDEVENT_CONTENT_TYPE)
+ .withType(ceType)
+ .withData(content.getBytes(StandardCharsets.UTF_8))
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_PROTOCOL, "A2A")
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_PROTOCOL_VERSION, "2.0")
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_A2A_METHOD, method)
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_MCP_TYPE, "request")
+ .withExtension(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4_000))
+ .build();
+ }
+}
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/README.md b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/README.md
new file mode 100644
index 000000000..0e4ea34de
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/README.md
@@ -0,0 +1,151 @@
+# EventMesh A2A Gateway Demo
+
+## 架构
+
+```
+ protocol-a2a 模块 runtime 模块 examples 模块
+ ┌─────────────────┐ ┌──────────────────┐ ┌──────────────┐
+ │ A2AMessageTransport(接口) │ A2AGatewayServer │ │ A2AGatewayDemo│
+ │ A2AClient (SDK) │<──HTTP──>│ (main, Netty HTTP)│<──HTTP──>│ (纯客户端) │
+ │ AgentCard/Topic │ │ InMemoryTransport │ └──────────────┘
+ └─────────────────┘ │ GatewayService │
+ │ TaskRegistry │
+ └──────────────────┘
+```
+
+## 快速开始
+
+### 1. 编译
+
+```bash
+cd eventmesh
+./gradlew :eventmesh-protocol-plugin:eventmesh-protocol-a2a:compileJava \
+ :eventmesh-runtime:compileJava \
+ :eventmesh-examples:compileJava
+```
+
+### 2. 启动服务端
+
+```bash
+# 方式一:Gradle
+./gradlew :eventmesh-runtime:run -PmainClass=org.apache.eventmesh.runtime.a2a.A2AGatewayServer
+
+# 方式二:Java 命令行
+java -cp <classpath> org.apache.eventmesh.runtime.a2a.A2AGatewayServer [port]
+# 默认端口 10105
+```
+
+服务端启动后:
+- Netty HTTP server 监听指定端口
+- 预注册 mock `weather-agent`,自动响应 task 请求
+- TTL 清理:已完成的 task 5 分钟后自动清理,agent card 60 秒无心跳自动过期
+
+### 3. 运行客户端
+
+```bash
+# 方式一:Gradle
+./gradlew :eventmesh-examples:run -PmainClass=org.apache.eventmesh.a2a.demo.gateway.A2AGatewayDemo
+
+# 方式二:Java 命令行
+java -cp <classpath> org.apache.eventmesh.a2a.demo.gateway.A2AGatewayDemo
+```
+
+客户端流程:
+1. 注册自己的 AgentCard 到 Gateway
+2. 列出已注册的 agents
+3. 同步提交 task 到 weather-agent
+4. 异步提交 task
+5. 查询 task 状态
+
+## REST API
+
+| 方法 | 路径 | 说明 |
+|------|------|------|
+| POST | `/a2a/tasks?mode=sync` | 同步提交 task(等待结果) |
+| POST | `/a2a/tasks?mode=async` | 异步提交 task(立即返回 taskId) |
+| GET | `/a2a/tasks/{taskId}` | 查询 task 状态 |
+| DELETE | `/a2a/tasks/{taskId}` | 取消 task |
+| GET | `/a2a/tasks/{taskId}/wait` | 长轮询等待 task 结果 |
+| GET | `/a2a/tasks/{taskId}/stream` | SSE 流式推送 task 状态更新 |
+| GET | `/a2a/agents` | 列出所有已注册 agents |
+| POST | `/a2a/heartbeat` | Agent 心跳 |
+| GET | `/a2a/cards/list` | 列出所有 AgentCard |
+| POST | `/a2a/cards/card/{org}/{unit}/{agent}` | 注册 AgentCard |
+
+### 示例:curl 测试
+
+```bash
+# 同步 task
+curl -X POST 'http://localhost:10105/a2a/tasks?mode=sync' \
+ -H 'Content-Type: application/json' \
+ -d '{"targetAgent":"weather-agent","message":"Beijing"}'
+
+# 异步 task
+curl -X POST 'http://localhost:10105/a2a/tasks?mode=async' \
+ -H 'Content-Type: application/json' \
+ -d '{"targetAgent":"weather-agent","message":"Shanghai"}'
+
+# 查询状态
+curl http://localhost:10105/a2a/tasks/{taskId}
+
+# SSE 流
+curl -N http://localhost:10105/a2a/tasks/{taskId}/stream
+
+# 列出 agents
+curl http://localhost:10105/a2a/agents
+
+# 心跳
+curl -X POST http://localhost:10105/a2a/heartbeat \
+ -H 'Content-Type: application/json' \
+ -d '{"orgId":"default","unitId":"default","agentId":"weather-agent"}'
+```
+
+## A2AClient SDK
+
+```java
+A2AClient client = A2AClient.builder()
+ .gatewayUrl("http://localhost:10105")
+ .namespace("global")
+ .agentName("my-agent")
+ .agentCard(validCard)
+ .heartbeatInterval(30_000)
+ .build();
+
+client.start();
+
+// 同步 task
+TaskResult result = client.sendTaskSync("weather-agent", "Beijing", null);
+
+// 异步 task
+String taskId = client.sendTaskAsync("weather-agent", "Beijing", null);
+
+// 查询状态
+TaskResult status = client.getTaskStatus(taskId);
+
+// 取消
+boolean cancelled = client.cancelTask(taskId);
+
+// 列出 agents
+List<String> agents = client.listAgents();
+
+client.shutdown();
+```
+
+## 测试
+
+```bash
+# 全部 A2A 测试
+./gradlew :eventmesh-protocol-plugin:eventmesh-protocol-a2a:test \
+ :eventmesh-runtime:test --tests "org.apache.eventmesh.runtime.a2a.*"
+
+# 仅 HTTP 集成测试
+./gradlew :eventmesh-runtime:test --tests "org.apache.eventmesh.runtime.a2a.A2AClientServerIntegrationTest"
+```
+
+测试覆盖:
+- `A2ATopicFactoryTest` — Topic 生成/解析
+- `TaskRegistryTest` — Task 状态机 + TTL 清理
+- `InMemoryA2AMessageTransportTest` — 内存传输投递
+- `A2AGatewayServiceTest` — Gateway 服务层
+- `A2AGatewayEndToEndTest` — 进程内全链路
+- `A2AClientServerIntegrationTest` — 真实 HTTP 客户端-服务端集成测试
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/ce/CloudEventsCaller.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/ce/CloudEventsCaller.java
new file mode 100644
index 000000000..e0f6622b8
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/ce/CloudEventsCaller.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo.ce;
+
+import org.apache.eventmesh.a2a.demo.A2AAbstractDemo;
+import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig;
+import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer;
+import org.apache.eventmesh.common.Constants;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.UUID;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class CloudEventsCaller extends A2AAbstractDemo {
+
+ public static void main(String[] args) throws Exception {
+ EventMeshHttpClientConfig config = initEventMeshHttpClientConfig("CloudEventsCallerGroup");
+ try (EventMeshHttpProducer producer = new EventMeshHttpProducer(config)) {
+
+ // 1. Native CE RPC (Point-to-Point)
+ sendNativeRpc(producer);
+
+ // 2. Native CE Pub/Sub (Broadcast)
+ sendNativePubSub(producer);
+
+ // 3. Native CE Streaming
+ sendNativeStream(producer);
+ }
+ }
+
+ /**
+ * Pattern 1: Native CloudEvent RPC
+ * Uses 'targetagent' extension for routing.
+ */
+ private static void sendNativeRpc(EventMeshHttpProducer producer) throws Exception {
+ CloudEvent event = CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withSource(URI.create("ce-client"))
+ .withType("com.example.rpc.request")
+ .withSubject("rpc-topic")
+ .withData("application/text", "RPC Payload".getBytes(StandardCharsets.UTF_8))
+ .withExtension("protocol", "A2A")
+ .withExtension("targetagent", "target-agent-001") // Explicit routing
+ .withExtension(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4_000))
+ .build();
+
+ log.info("Sending Native CE RPC: {}", event);
+ producer.publish(event);
+ }
+
+ /**
+ * Pattern 2: Native CloudEvent Pub/Sub
+ * Standard CE behavior using Subject.
+ */
+ private static void sendNativePubSub(EventMeshHttpProducer producer) throws Exception {
+ CloudEvent event = CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withSource(URI.create("ce-client"))
+ .withType("com.example.notification")
+ .withSubject("broadcast.topic") // Broadcast
+ .withData("application/text", "Broadcast Message".getBytes(StandardCharsets.UTF_8))
+ .withExtension("protocol", "A2A")
+ .withExtension(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4_000))
+ .build();
+
+ log.info("Sending Native CE Pub/Sub: {}", event);
+ producer.publish(event);
+ }
+
+ /**
+ * Pattern 3: Native CloudEvent Streaming
+ * Uses 'seq' extension.
+ */
+ private static void sendNativeStream(EventMeshHttpProducer producer) throws Exception {
+ String sessionId = UUID.randomUUID().toString();
+
+ for (int i = 1; i <= 3; i++) {
+ CloudEvent event = CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withSource(URI.create("ce-client"))
+ .withType("com.example.stream")
+ .withSubject("stream-topic")
+ .withData("application/text", ("Chunk " + i).getBytes(StandardCharsets.UTF_8))
+ .withExtension("protocol", "A2A")
+ .withExtension("sessionid", sessionId)
+ .withExtension("seq", String.valueOf(i))
+ .withExtension(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4_000))
+ .build();
+
+ log.info("Sending Native CE Stream Chunk {}: {}", i, event);
+ producer.publish(event);
+ Thread.sleep(100);
+ }
+ }
+}
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/ce/CloudEventsProvider.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/ce/CloudEventsProvider.java
new file mode 100644
index 000000000..a85ee64df
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/ce/CloudEventsProvider.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo.ce;
+
+import org.apache.eventmesh.a2a.demo.A2AAbstractDemo;
+import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig;
+import org.apache.eventmesh.client.http.consumer.EventMeshHttpConsumer;
+import org.apache.eventmesh.common.protocol.SubscriptionItem;
+import org.apache.eventmesh.common.protocol.SubscriptionMode;
+import org.apache.eventmesh.common.protocol.SubscriptionType;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import io.cloudevents.CloudEvent;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class CloudEventsProvider extends A2AAbstractDemo {
+
+ public static void main(String[] args) throws Exception {
+ EventMeshHttpClientConfig config = initEventMeshHttpClientConfig("CloudEventsProviderGroup");
+ try (EventMeshHttpConsumer consumer = new EventMeshHttpConsumer(config)) {
+
+ // Subscribe to relevant topics
+ final List<SubscriptionItem> topicList = new ArrayList<>();
+
+ // 1. Subscribe to RPC Topic
+ SubscriptionItem rpcItem = new SubscriptionItem();
+ rpcItem.setTopic("rpc-topic");
+ rpcItem.setMode(SubscriptionMode.CLUSTERING);
+ rpcItem.setType(SubscriptionType.ASYNC);
+ topicList.add(rpcItem);
+
+ // 2. Subscribe to Broadcast Topic
+ SubscriptionItem broadcastItem = new SubscriptionItem();
+ broadcastItem.setTopic("broadcast.topic");
+ broadcastItem.setMode(SubscriptionMode.BROADCASTING); // Broadcast mode
+ broadcastItem.setType(SubscriptionType.ASYNC);
+ topicList.add(broadcastItem);
+
+ // 3. Subscribe to Stream Topic
+ SubscriptionItem streamItem = new SubscriptionItem();
+ streamItem.setTopic("stream-topic");
+ streamItem.setMode(SubscriptionMode.CLUSTERING);
+ streamItem.setType(SubscriptionType.ASYNC);
+ topicList.add(streamItem);
+
+ consumer.heartBeat(topicList, "http://127.0.0.1:8088/ce/callback");
+
+ log.info("CloudEvents Provider started. Listening for A2A messages...");
+
+ while (true) {
+ Thread.sleep(10000);
+ }
+ }
+ }
+
+ // Simulation of WebController logic
+ public static void handleCallback(CloudEvent event) {
+ try {
+ String protocol = (String) event.getExtension("protocol");
+ if (!"A2A".equals(protocol)) {
+ return;
+ }
+
+ String subject = event.getSubject();
+ String data = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
+
+ log.info("Received Native CloudEvent: Subject={}, Type={}, Data={}", subject, event.getType(), data);
+
+ if ("stream-topic".equals(subject)) {
+ String seq = (String) event.getExtension("seq");
+ String sessionId = (String) event.getExtension("sessionid");
+ log.info("Stream processing: Session={}, Seq={}", sessionId, seq);
+ }
+
+ } catch (Exception e) {
+ log.error("Error handling callback", e);
+ }
+ }
+}
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/gateway/A2AGatewayDemo.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/gateway/A2AGatewayDemo.java
new file mode 100644
index 000000000..432a255a0
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/gateway/A2AGatewayDemo.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo.gateway;
+
+import org.apache.eventmesh.protocol.a2a.A2AClient;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+import org.apache.eventmesh.protocol.a2a.model.AgentSkill;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * A2A Gateway Client Demo.
+ *
+ * <p>This is a pure HTTP client demo that connects to a running A2A Gateway Server.
+ * It does NOT depend on any runtime server-side classes.
+ *
+ * <p>Prerequisites:
+ * <ol>
+ * <li>Start the A2A Gateway Server first:
+ * <pre>java org.apache.eventmesh.runtime.a2a.A2AGatewayServer</pre>
+ * (server listens on port 10105 by default, with a pre-registered weather-agent)</li>
+ * <li>Then run this client demo.</li>
+ * </ol>
+ *
+ * <p>Flow:
+ * <pre>
+ * Client -HTTP-> Gateway Server -InMemory-> Weather Agent -> Gateway -> Client
+ * </pre>
+ */
+@Slf4j
+public class A2AGatewayDemo {
+
+ private static final String GATEWAY_URL = "http://localhost:10105";
+ private static final String NAMESPACE = "global";
+
+ public static void main(String[] args) throws Exception {
+ log.info("=== A2A Gateway Client Demo ===");
+ log.info("Connecting to Gateway: {}", GATEWAY_URL);
+
+ // 1. Create A2A client (as a caller, not an agent)
+ A2AClient client = A2AClient.builder()
+ .gatewayUrl(GATEWAY_URL)
+ .namespace(NAMESPACE)
+ .agentName("demo-client")
+ .agentCard(AgentCard.builder()
+ .name("demo-client")
+ .description("A demo client that calls weather-agent")
+ .version("1.0.0")
+ .supportedInterfaces(Arrays.asList(
+ org.apache.eventmesh.protocol.a2a.model.AgentInterface.builder()
+ .url("http://localhost:0/a2a")
+ .protocolBinding("JSONRPC")
+ .protocolVersion("0.3")
+ .build()
+ ))
+ .capabilities(org.apache.eventmesh.protocol.a2a.model.AgentCapabilities.builder()
+ .streaming(false)
+ .pushNotifications(false)
+ .build())
+ .skills(Arrays.asList(
+ AgentSkill.builder()
+ .id("call-weather")
+ .name("Call Weather")
+ .description("Call the weather agent for weather info")
+ .tags(Arrays.asList("demo", "client"))
+ .build()
+ ))
+ .defaultInputModes(Arrays.asList("text/plain"))
+ .defaultOutputModes(Arrays.asList("text/plain"))
+ .build())
+ .heartbeatInterval(60_000)
+ .build();
+
+ client.start();
+ log.info("Client started.");
+
+ // 2. List registered agents
+ log.info("");
+ log.info("--- Listing registered agents ---");
+ List<String> agents = client.listAgents();
+ log.info("Agents: {}", agents);
+
+ // 3. Submit a task to weather-agent (sync mode)
+ log.info("");
+ log.info("--- Submitting task to weather-agent ---");
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "Beijing", null);
+ log.info("Result: state={}, data={}", result.getState(), result.getData());
+
+ // 4. Submit another task
+ log.info("");
+ log.info("--- Submitting second task ---");
+ A2AClient.TaskResult result2 = client.sendTaskSync("weather-agent", "Shanghai", null);
+ log.info("Result: state={}, data={}", result2.getState(), result2.getData());
+
+ // 5. Async task submission
+ log.info("");
+ log.info("--- Async task submission ---");
+ java.util.concurrent.CompletableFuture<A2AClient.TaskResult> future =
+ client.sendTask("weather-agent", "Guangzhou");
+ A2AClient.TaskResult result3 = future.get(30, TimeUnit.SECONDS);
+ log.info("Async result: state={}, data={}", result3.getState(), result3.getData());
+
+ // 6. Query task status
+ log.info("");
+ log.info("--- Querying task status ---");
+ A2AClient.TaskResult status = client.getTaskStatus(result.getTaskId());
+ log.info("Status: state={}, targetAgent={}", status.getState(), status.getTargetAgent());
+
+ // 6. Cleanup
+ log.info("");
+ log.info("=== Demo Complete ===");
+ client.shutdown();
+ }
+}
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/mcp/McpCaller.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/mcp/McpCaller.java
new file mode 100644
index 000000000..8a356e17d
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/mcp/McpCaller.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo.mcp;
+
+import org.apache.eventmesh.a2a.demo.A2AAbstractDemo;
+import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig;
+import org.apache.eventmesh.client.http.producer.EventMeshHttpProducer;
+import org.apache.eventmesh.common.Constants;
+import org.apache.eventmesh.common.ExampleConstants;
+import org.apache.eventmesh.common.utils.JsonUtils;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class McpCaller extends A2AAbstractDemo {
+
+ // MCP JSON-RPC 2.0 Structure
+ // Request: { "jsonrpc": "2.0", "method": "...", "params": { ... }, "id": "..." }
+ // Notification: { "jsonrpc": "2.0", "method": "...", "params": { ... } }
+
+ public static void main(String[] args) throws Exception {
+ EventMeshHttpClientConfig config = initEventMeshHttpClientConfig("McpCallerGroup");
+ try (EventMeshHttpProducer producer = new EventMeshHttpProducer(config)) {
+
+ // 1. RPC Pattern (Tools Call)
+ sendMcpRpc(producer);
+
+ // 2. Pub/Sub Pattern (Notification)
+ sendMcpPubSub(producer);
+
+ // 3. Streaming Pattern (Sequenced Messages)
+ sendMcpStream(producer);
+ }
+ }
+
+ /**
+ * Pattern 1: RPC (Request/Response)
+ * A2A Protocol maps this to P2P routing using '_agentId' or similar.
+ */
+ private static void sendMcpRpc(EventMeshHttpProducer producer) throws Exception {
+ final String requestId = UUID.randomUUID().toString();
+ Map<String, Object> requestParams = new HashMap<>();
+ requestParams.put("name", "get_weather");
+ requestParams.put("city", "Beijing");
+
+ String targetAgent = "weather-service-01";
+ requestParams.put("_agentId", targetAgent); // Routing hint
+
+ Map<String, Object> requestMap = new HashMap<>();
+ requestMap.put("jsonrpc", "2.0");
+ requestMap.put("method", "tools/call");
+ requestMap.put("params", requestParams);
+
+ requestMap.put("id", requestId);
+
+ CloudEvent event = buildMcpEvent(requestMap, "org.apache.eventmesh.a2a.tools.call.req", "request");
+
+ log.info("Sending MCP RPC Request: {}", requestMap);
+ producer.publish(event);
+ }
+
+ /**
+ * Pattern 2: Pub/Sub (Broadcast)
+ * A2A Protocol maps this to PubSub routing using '_topic'.
+ */
+ private static void sendMcpPubSub(EventMeshHttpProducer producer) throws Exception {
+ Map<String, Object> params = new HashMap<>();
+ params.put("message", "System Maintenance in 10 mins");
+ params.put("_topic", "system.alerts"); // Broadcast Topic
+
+ Map<String, Object> notification = new HashMap<>();
+ notification.put("jsonrpc", "2.0");
+ notification.put("method", "notifications/alert");
+ notification.put("params", params);
+ // No ID for notifications
+
+ CloudEvent event = buildMcpEvent(notification, "org.apache.eventmesh.a2a.notifications.alert", "notification");
+
+ log.info("Sending MCP Pub/Sub Notification: {}", notification);
+ producer.publish(event);
+ }
+
+ /**
+ * Pattern 3: Streaming
+ * Sends multiple sequenced messages.
+ */
+ private static void sendMcpStream(EventMeshHttpProducer producer) throws Exception {
+ String streamId = UUID.randomUUID().toString();
+ String targetAgent = "log-collector";
+
+ for (int i = 1; i <= 3; i++) {
+ Map<String, Object> params = new HashMap<>();
+ params.put("logLine", "Log entry " + i);
+ params.put("_agentId", targetAgent);
+ params.put("_seq", i); // Sequence number
+
+ Map<String, Object> chunk = new HashMap<>();
+ chunk.put("jsonrpc", "2.0");
+ chunk.put("method", "message/sendStream");
+ chunk.put("params", params);
+ chunk.put("id", streamId); // Same ID for the session
+
+ CloudEvent event = buildMcpEvent(chunk, "org.apache.eventmesh.a2a.message.sendStream.stream", "request");
+ event = CloudEventBuilder.from(event)
+ .withExtension("seq", String.valueOf(i))
+ .build();
+
+ log.info("Sending MCP Stream Chunk {}: {}", i, chunk);
+ producer.publish(event);
+ Thread.sleep(100);
+ }
+ }
+
+ private static CloudEvent buildMcpEvent(Map<String, Object> jsonRpcBody, String type, String mcpType) {
+ String content = JsonUtils.toJSONString(jsonRpcBody);
+
+ return CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withSubject("a2a-mcp-topic") // This might be overridden by the Adaptor based on _topic params
+ .withSource(URI.create("mcp-client"))
+ .withDataContentType(ExampleConstants.CLOUDEVENT_CONTENT_TYPE) // application/json
+ .withType(type)
+ .withData(content.getBytes(StandardCharsets.UTF_8))
+ .withExtension("protocol", "A2A")
+ .withExtension("protocolversion", "2.0")
+ .withExtension("mcptype", mcpType)
+ .withExtension(Constants.EVENTMESH_MESSAGE_CONST_TTL, String.valueOf(4_000))
+ .build();
+ }
+}
diff --git a/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/mcp/McpProvider.java b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/mcp/McpProvider.java
new file mode 100644
index 000000000..eaad3f403
--- /dev/null
+++ b/eventmesh-examples/src/main/java/org/apache/eventmesh/a2a/demo/mcp/McpProvider.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.a2a.demo.mcp;
+
+import org.apache.eventmesh.a2a.demo.A2AAbstractDemo;
+import org.apache.eventmesh.client.http.conf.EventMeshHttpClientConfig;
+import org.apache.eventmesh.client.http.consumer.EventMeshHttpConsumer;
+import org.apache.eventmesh.common.protocol.SubscriptionItem;
+import org.apache.eventmesh.common.protocol.SubscriptionMode;
+import org.apache.eventmesh.common.protocol.SubscriptionType;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import io.cloudevents.CloudEvent;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class McpProvider extends A2AAbstractDemo {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ public static void main(String[] args) throws Exception {
+ EventMeshHttpClientConfig config = initEventMeshHttpClientConfig("McpProviderGroup");
+ try (EventMeshHttpConsumer consumer = new EventMeshHttpConsumer(config)) {
+
+ // Subscribe to relevant topics
+ final List<SubscriptionItem> topicList = new ArrayList<>();
+
+ // 1. Subscribe to Broadcast Topic (for Pub/Sub pattern)
+ SubscriptionItem pubSubItem = new SubscriptionItem();
+ pubSubItem.setTopic("system.alerts");
+ pubSubItem.setMode(SubscriptionMode.CLUSTERING);
+ pubSubItem.setType(SubscriptionType.ASYNC);
+ topicList.add(pubSubItem);
+
+ // 2. Subscribe to P2P Routing (Agent ID as topic or filtered)
+ // Note: In real A2A, this might be handled by a specific queue or filtered topic
+ // For demo, we assume the 'a2a-mcp-topic' is used or specific agent topics
+ SubscriptionItem rpcItem = new SubscriptionItem();
+ rpcItem.setTopic("a2a-mcp-topic");
+ rpcItem.setMode(SubscriptionMode.CLUSTERING);
+ rpcItem.setType(SubscriptionType.ASYNC);
+ topicList.add(rpcItem);
+
+ consumer.heartBeat(topicList, "http://127.0.0.1:8088/mcp/callback");
+
+ log.info("MCP Provider started. Listening for A2A messages...");
+
+ // In HTTP Consumer mode for EventMesh, typically a callback URL is registered.
+ // However, the Java HTTP Consumer also supports pulling or local handling if configured differently.
+ // Since EventMeshHttpConsumer is designed for Webhooks mostly in "subscribe" mode where it pushes to a URL,
+ // we simulate the handling logic here as if it received the callback.
+
+ // Simulate processing loop (in a real app, this would be a WebController receiving POSTs from EventMesh)
+ while (true) {
+ Thread.sleep(10000);
+ }
+ }
+ }
+
+ // Simulates the logic that would be inside the WebController receiving the callback
+ public static void handleCallback(CloudEvent event) {
+ try {
+ String protocol = (String) event.getExtension("protocol");
+ if (!"A2A".equals(protocol)) {
+ return;
+ }
+
+ String mcpType = (String) event.getExtension("mcptype");
+ byte[] data = event.getData().toBytes();
+ String content = new String(data, StandardCharsets.UTF_8);
+ JsonNode json = objectMapper.readTree(content);
+
+ log.info("Received A2A MCP Message: Type={}, Data={}", mcpType, content);
+
+ if ("request".equals(mcpType)) {
+ // Handle RPC or Stream
+ String method = json.get("method").asText();
+ String id = json.get("id").asText();
+
+ if ("tools/call".equals(method)) {
+ log.info("Executing Tool: {}", json.get("params"));
+ // Send Response logic here (would require a Producer to send back)
+ } else if ("message/sendStream".equals(method)) {
+ String seq = (String) event.getExtension("seq");
+ log.info("Received Stream Chunk: Seq={}", seq);
+ }
+ } else if ("notification".equals(mcpType)) {
+ log.info("Received Notification: {}", json.get("params"));
+ }
+
+ } catch (Exception e) {
+ log.error("Error handling callback", e);
+ }
+ }
+}
diff --git a/eventmesh-runtime/build.gradle b/eventmesh-runtime/build.gradle
index 4907c5db1..ab9b525a9 100644
--- a/eventmesh-runtime/build.gradle
+++ b/eventmesh-runtime/build.gradle
@@ -62,6 +62,8 @@ dependencies {
testImplementation project(':eventmesh-storage-plugin:eventmesh-storage-kafka')
// Topic creation in RealBrokerIntegrationTest (broker may have autoCreateTopicEnable=false).
testImplementation 'org.apache.rocketmq:rocketmq-tools:4.9.5'
+ // A2AClientServerIntegrationTest drives the A2A Gateway over HTTP.
+ testImplementation 'org.apache.httpcomponents:httpclient:4.5.14'
// ClientBrokerIntegrationTest drives the runtime via the real CloudEventsClient SDK over HTTP.
testImplementation project(':eventmesh-sdks:eventmesh-sdk-java')
}
diff --git a/eventmesh-runtime/conf/a2a-protocol-config.yaml b/eventmesh-runtime/conf/a2a-protocol-config.yaml
new file mode 100644
index 000000000..4ce81f502
--- /dev/null
+++ b/eventmesh-runtime/conf/a2a-protocol-config.yaml
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+eventMesh:
+ protocol:
+ plugin:
+ a2a:
+ # Whether the A2A (Agent-to-Agent) protocol adaptor is enabled
+ enabled: true
+
+ # Protocol version
+ version: "2.0"
+
+ # Features configuration
+ features:
+ # Enable delegation to existing CloudEvents/HTTP protocols
+ delegation: true
+
+ # Enable MCP (Model Context Protocol) JSON-RPC 2.0 support
+ mcp-support: true
+
+ # Enable batch processing support
+ batch-processing: true
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2ACardHttpHandler.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2ACardHttpHandler.java
new file mode 100644
index 000000000..1e9f262c8
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2ACardHttpHandler.java
@@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import org.apache.eventmesh.protocol.a2a.AgentIdentity;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.DefaultFullHttpResponse;
+import io.netty.handler.codec.http.FullHttpResponse;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpVersion;
+import io.netty.handler.codec.http.QueryStringDecoder;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * HTTP handler for A2A Agent Card Registry API.
+ * Matches EMQX's API pattern:
+ * - GET /a2a/cards/list - list agent cards
+ * - GET /a2a/cards/card/{org_id}/{unit_id}/{agent_id} - get specific card
+ * - POST /a2a/cards/card/{org_id}/{unit_id}/{agent_id} - register card
+ * - DELETE /a2a/cards/card/{org_id}/{unit_id}/{agent_id} - delete card
+ */
+@Slf4j
+public class A2ACardHttpHandler {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+ private static final String PATH_LIST = "/a2a/cards/list";
+ private static final String PATH_CARD_PREFIX = "/a2a/cards/card/";
+
+ private final A2APublishSubscribeService a2aService;
+
+ public A2ACardHttpHandler(A2APublishSubscribeService a2aService) {
+ this.a2aService = a2aService;
+ }
+
+ public FullHttpResponse handle(HttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
+ String uri = httpRequest.uri();
+ QueryStringDecoder decoder = new QueryStringDecoder(uri);
+ String path = decoder.path();
+ HttpMethod method = httpRequest.method();
+
+ try {
+ // Handle CORS preflight
+ if (method == HttpMethod.OPTIONS) {
+ return corsResponse();
+ }
+
+ if (path.equals(PATH_LIST)) {
+ return handleList(decoder);
+ }
+
+ if (path.startsWith(PATH_CARD_PREFIX)) {
+ String[] segments = path.substring(PATH_CARD_PREFIX.length()).split("/");
+ if (segments.length != 3) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST,
+ errorBody("Invalid path. Expected /a2a/cards/card/{org_id}/{unit_id}/{agent_id}"));
+ }
+
+ String orgId = segments[0];
+ String unitId = segments[1];
+ String agentId = segments[2];
+
+ if (method == HttpMethod.GET) {
+ return handleGet(orgId, unitId, agentId);
+ } else if (method == HttpMethod.POST) {
+ return handleRegister(orgId, unitId, agentId, httpRequest);
+ } else if (method == HttpMethod.DELETE) {
+ return handleDelete(orgId, unitId, agentId);
+ }
+ }
+
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Not found: " + path));
+ } catch (Exception e) {
+ log.error("A2A card handler error: {}", e.getMessage(), e);
+ return jsonResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorBody(e.getMessage()));
+ }
+ }
+
+ private FullHttpResponse handleList(QueryStringDecoder decoder) throws Exception {
+ String orgId = getQueryParam(decoder, "org_id");
+ String unitId = getQueryParam(decoder, "unit_id");
+ String agentId = getQueryParam(decoder, "agent_id");
+
+ List<A2APublishSubscribeService.CardEntry> cards = a2aService.listCards(orgId, unitId, agentId);
+ String body = objectMapper.writeValueAsString(cards);
+ return jsonResponse(HttpResponseStatus.OK, body);
+ }
+
+ private FullHttpResponse handleGet(String orgId, String unitId, String agentId) throws Exception {
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId(orgId).unitId(unitId).agentId(agentId).build();
+ A2APublishSubscribeService.CardEntry card = a2aService.getCard(identity);
+
+ if (card == null) {
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Card not found"));
+ }
+
+ String body = objectMapper.writeValueAsString(formatCardOut(card));
+ return jsonResponse(HttpResponseStatus.OK, body);
+ }
+
+ private FullHttpResponse handleRegister(String orgId, String unitId, String agentId, HttpRequest request) throws Exception {
+ // Read body from request
+ String requestBody = "";
+ if (request instanceof io.netty.handler.codec.http.FullHttpRequest) {
+ ByteBuf content = ((io.netty.handler.codec.http.FullHttpRequest) request).content();
+ requestBody = content.toString(StandardCharsets.UTF_8);
+ }
+
+ AgentCard card;
+ try {
+ card = objectMapper.readValue(requestBody, AgentCard.class);
+ } catch (Exception e) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST, errorBody("Invalid card JSON: " + e.getMessage()));
+ }
+
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId(orgId).unitId(unitId).agentId(agentId).build();
+ A2APublishSubscribeService.RegistrationResult result = a2aService.registerCard(identity, card);
+
+ if (result.isSuccess()) {
+ return jsonResponse(HttpResponseStatus.NO_CONTENT, "");
+ } else {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST, errorBody(result.getErrorMessage()));
+ }
+ }
+
+ private FullHttpResponse handleDelete(String orgId, String unitId, String agentId) throws Exception {
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId(orgId).unitId(unitId).agentId(agentId).build();
+ boolean deleted = a2aService.deleteCard(identity);
+
+ if (deleted) {
+ return jsonResponse(HttpResponseStatus.NO_CONTENT, "");
+ } else {
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Card not found"));
+ }
+ }
+
+ private Map<String, Object> formatCardOut(A2APublishSubscribeService.CardEntry entry) {
+ Map<String, Object> out = new LinkedHashMap<>();
+ out.put("namespace", entry.getNamespace());
+ out.put("id", entry.getId());
+ out.put("name", entry.getName());
+ out.put("version", entry.getVersion());
+ out.put("description", entry.getDescription());
+ out.put("status", entry.getStatus());
+ return out;
+ }
+
+ private String getQueryParam(QueryStringDecoder decoder, String key) {
+ List<String> values = decoder.parameters().get(key);
+ return (values != null && !values.isEmpty()) ? values.get(0) : null;
+ }
+
+ private String errorBody(String message) {
+ try {
+ return objectMapper.writeValueAsString(Collections.singletonMap("error", message));
+ } catch (Exception e) {
+ return "{\"error\":\"" + message + "\"}";
+ }
+ }
+
+ private FullHttpResponse jsonResponse(HttpResponseStatus status, String body) {
+ ByteBuf content = Unpooled.copiedBuffer(body, StandardCharsets.UTF_8);
+ DefaultFullHttpResponse response = new DefaultFullHttpResponse(
+ HttpVersion.HTTP_1_1, status, content);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");
+ response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
+ setCorsHeaders(response);
+ return response;
+ }
+
+ private FullHttpResponse corsResponse() {
+ DefaultFullHttpResponse response = new DefaultFullHttpResponse(
+ HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
+ setCorsHeaders(response);
+ response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
+ return response;
+ }
+
+ private void setCorsHeaders(FullHttpResponse response) {
+ response.headers().set("Access-Control-Allow-Origin", "*");
+ response.headers().set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
+ response.headers().set("Access-Control-Allow-Headers", "Content-Type, Authorization");
+ response.headers().set("Access-Control-Max-Age", "3600");
+ }
+}
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayHttpHandler.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayHttpHandler.java
new file mode 100644
index 000000000..8c4722089
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayHttpHandler.java
@@ -0,0 +1,648 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.DefaultFullHttpResponse;
+import io.netty.handler.codec.http.DefaultHttpContent;
+import io.netty.handler.codec.http.DefaultHttpResponse;
+import io.netty.handler.codec.http.FullHttpResponse;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpHeaderValues;
+import io.netty.handler.codec.http.HttpMethod;
+import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.HttpResponse;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpVersion;
+import io.netty.handler.codec.http.LastHttpContent;
+import io.netty.handler.codec.http.QueryStringDecoder;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * HTTP handler for A2A Gateway API.
+ *
+ * <p>Endpoints:
+ * <ul>
+ * <li>POST /a2a/tasks - submit a new task (sync or async)</li>
+ * <li>GET /a2a/tasks - list tasks (optional ?state=COMPLETED&limit=100&offset=0)</li>
+ * <li>GET /a2a/tasks/{taskId} - get task status</li>
+ * <li>DELETE /a2a/tasks/{taskId} - cancel a task</li>
+ * <li>GET /a2a/tasks/{taskId}/wait - wait for task result (long-poll)</li>
+ * <li>GET /a2a/tasks/{taskId}/stream - SSE stream of task status updates</li>
+ * <li>GET /a2a/agents - list registered agents</li>
+ * <li>POST /a2a/heartbeat - agent heartbeat</li>
+ * <li>GET /a2a/health - health check (for liveness/readiness probes)</li>
+ * <li>OPTIONS * - CORS preflight</li>
+ * </ul>
+ */
+@Slf4j
+public class A2AGatewayHttpHandler {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ private static final String PATH_TASKS = "/a2a/tasks";
+ private static final String PATH_AGENTS = "/a2a/agents";
+ private static final String PATH_HEARTBEAT = "/a2a/heartbeat";
+ private static final String PATH_HEALTH = "/a2a/health";
+
+ private static final long DEFAULT_WAIT_TIMEOUT_MS = 30_000L;
+
+ private final A2AGatewayService gatewayService;
+ private final A2APublishSubscribeService a2aService;
+
+ public A2AGatewayHttpHandler(A2AGatewayService gatewayService,
+ A2APublishSubscribeService a2aService) {
+ this.gatewayService = gatewayService;
+ this.a2aService = a2aService;
+ }
+
+ /**
+ * Handles an HTTP request. Returns a FullHttpResponse, or null if the response was written
+ * directly to the channel (e.g. SSE streaming).
+ */
+ public FullHttpResponse handle(HttpRequest httpRequest, ChannelHandlerContext ctx) throws Exception {
+ String uri = httpRequest.uri();
+ QueryStringDecoder decoder = new QueryStringDecoder(uri);
+ String path = decoder.path();
+ HttpMethod method = httpRequest.method();
+
+ try {
+ // Handle CORS preflight
+ if (method == HttpMethod.OPTIONS) {
+ return corsResponse(HttpResponseStatus.OK);
+ }
+
+ // POST /a2a/tasks
+ if (PATH_TASKS.equals(path) && method == HttpMethod.POST) {
+ return handleSubmitTask(httpRequest, decoder);
+ }
+
+ // GET /a2a/tasks (list tasks with optional pagination)
+ if (PATH_TASKS.equals(path) && method == HttpMethod.GET) {
+ return handleListTasks(decoder);
+ }
+
+ // /a2a/tasks/{taskId} or /a2a/tasks/{taskId}/wait
+ if (path.startsWith(PATH_TASKS + "/")) {
+ String suffix = path.substring(PATH_TASKS.length() + 1);
+ String[] parts = suffix.split("/", 2);
+ String taskId = parts[0];
+
+ if (taskId.isEmpty()) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST, errorBody("Missing taskId"));
+ }
+
+ // GET /a2a/tasks/{taskId}
+ if (method == HttpMethod.GET && parts.length == 1) {
+ return handleGetTask(taskId);
+ }
+
+ // DELETE /a2a/tasks/{taskId}
+ if (method == HttpMethod.DELETE && parts.length == 1) {
+ return handleCancelTask(taskId);
+ }
+
+ // GET /a2a/tasks/{taskId}/wait
+ if (method == HttpMethod.GET && parts.length == 2 && "wait".equals(parts[1])) {
+ return handleWaitTask(taskId, decoder);
+ }
+
+ // GET /a2a/tasks/{taskId}/stream (SSE)
+ if (method == HttpMethod.GET && parts.length == 2 && "stream".equals(parts[1])) {
+ return handleStreamTask(taskId, ctx);
+ }
+ }
+
+ // GET /a2a/health
+ if (PATH_HEALTH.equals(path) && method == HttpMethod.GET) {
+ return handleHealth();
+ }
+
+ // GET /a2a/agents
+ if (PATH_AGENTS.equals(path) && method == HttpMethod.GET) {
+ return handleListAgents();
+ }
+
+ // POST /a2a/heartbeat
+ if (PATH_HEARTBEAT.equals(path) && method == HttpMethod.POST) {
+ return handleHeartbeat(httpRequest);
+ }
+
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Not found: " + path));
+ } catch (Exception e) {
+ log.error("A2A gateway handler error: {}", e.getMessage(), e);
+ return jsonResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorBody(e.getMessage()));
+ }
+ }
+
+ // =========================================================================
+ // POST /a2a/tasks
+ // =========================================================================
+
+ private FullHttpResponse handleSubmitTask(HttpRequest request, QueryStringDecoder decoder) throws Exception {
+ String body = readBody(request);
+ TaskRequest taskRequest;
+ try {
+ taskRequest = objectMapper.readValue(body, TaskRequest.class);
+ } catch (Exception e) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST, errorBody("Invalid JSON: " + e.getMessage()));
+ }
+
+ if (taskRequest.getTargetAgent() == null || taskRequest.getTargetAgent().isEmpty()) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST, errorBody("targetAgent is required"));
+ }
+ if (taskRequest.getMessage() == null) {
+ taskRequest.setMessage("");
+ }
+
+ String mode = getQueryParam(decoder, "mode");
+ String parentTaskId = taskRequest.getParentTaskId();
+
+ // Generate taskId first so we can include it in the response
+ String taskId = "task-" + java.util.UUID.randomUUID().toString().substring(0, 8);
+
+ // Submit the task with the explicit taskId
+ java.util.concurrent.CompletableFuture<A2AGatewayService.TaskResult> future =
+ gatewayService.submitTask(taskId, taskRequest.getTargetAgent(), taskRequest.getMessage(), parentTaskId);
+
+ // For sync mode, wait for result
+ if ("sync".equalsIgnoreCase(mode) || mode == null) {
+ try {
+ A2AGatewayService.TaskResult result = future.get(DEFAULT_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("taskId", taskId);
+ response.put("state", result.getState().name());
+ response.put("data", result.getData());
+ if (result.getErrorMessage() != null) {
+ response.put("error", result.getErrorMessage());
+ }
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ } catch (java.util.concurrent.TimeoutException e) {
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("taskId", taskId);
+ response.put("state", "TIMEOUT");
+ response.put("error", "Task accepted but timed out waiting for response");
+ return jsonResponse(HttpResponseStatus.ACCEPTED, objectMapper.writeValueAsString(response));
+ } catch (java.util.concurrent.ExecutionException e) {
+ // Unwrap cause to determine correct status code
+ Throwable cause = e.getCause() != null ? e.getCause() : e;
+ if (cause instanceof IllegalArgumentException || cause instanceof IllegalStateException) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST,
+ errorBody(cause.getMessage()));
+ }
+ return jsonResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR,
+ errorBody("Task failed: " + cause.getMessage()));
+ } catch (Exception e) {
+ return jsonResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR,
+ errorBody("Task failed: " + e.getMessage()));
+ }
+ } else {
+ // Async mode: return task ID immediately
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("taskId", taskId);
+ response.put("status", "accepted");
+ response.put("message", "Task submitted. Use GET /a2a/tasks/" + taskId + " to check status.");
+ return jsonResponse(HttpResponseStatus.ACCEPTED, objectMapper.writeValueAsString(response));
+ }
+ }
+
+ // =========================================================================
+ // GET /a2a/tasks (list with optional pagination)
+ // =========================================================================
+
+ private FullHttpResponse handleListTasks(QueryStringDecoder decoder) throws Exception {
+ String stateFilter = getQueryParam(decoder, "state");
+ int limit = parseIntQueryParam(decoder, "limit", 100, 1, 1_000);
+ int offset = parseIntQueryParam(decoder, "offset", 0, 0, Integer.MAX_VALUE);
+
+ List<TaskRegistry.TaskEntry> allTasks = gatewayService.getTaskRegistry().listTasks();
+ List<Map<String, Object>> filteredTasks = new java.util.ArrayList<>();
+ for (TaskRegistry.TaskEntry entry : allTasks) {
+ if (stateFilter != null && !stateFilter.equalsIgnoreCase(entry.getState().name())) {
+ continue;
+ }
+ Map<String, Object> task = new LinkedHashMap<>();
+ task.put("taskId", entry.getTaskId());
+ task.put("state", entry.getState().name());
+ task.put("targetAgent", entry.getTargetAgent());
+ task.put("parentTaskId", entry.getParentTaskId());
+ task.put("createdAt", entry.getCreatedAt());
+ task.put("updatedAt", entry.getUpdatedAt());
+ filteredTasks.add(task);
+ }
+
+ int total = filteredTasks.size();
+ int fromIndex = Math.min(offset, total);
+ int toIndex = Math.min(fromIndex + limit, total);
+ List<Map<String, Object>> page = filteredTasks.subList(fromIndex, toIndex);
+
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("total", total);
+ response.put("count", page.size());
+ response.put("limit", limit);
+ response.put("offset", offset);
+ response.put("hasMore", toIndex < total);
+ response.put("tasks", page);
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ }
+
+ // =========================================================================
+ // GET /a2a/tasks/{taskId}
+ // =========================================================================
+
+ private FullHttpResponse handleGetTask(String taskId) throws Exception {
+ TaskRegistry.TaskEntry entry = gatewayService.getTaskStatus(taskId);
+ if (entry == null) {
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Task not found: " + taskId));
+ }
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("taskId", entry.getTaskId());
+ response.put("state", entry.getState().name());
+ response.put("targetAgent", entry.getTargetAgent());
+ response.put("gatewayId", entry.getGatewayId());
+ response.put("parentTaskId", entry.getParentTaskId());
+ response.put("createdAt", entry.getCreatedAt());
+ response.put("updatedAt", entry.getUpdatedAt());
+ if (entry.getResult() != null) {
+ response.put("result", entry.getResult());
+ }
+ if (entry.getErrorMessage() != null) {
+ response.put("error", entry.getErrorMessage());
+ }
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ }
+
+ // =========================================================================
+ // DELETE /a2a/tasks/{taskId}
+ // =========================================================================
+
+ private FullHttpResponse handleCancelTask(String taskId) throws Exception {
+ boolean cancelled = gatewayService.cancelTask(taskId);
+ if (cancelled) {
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("taskId", taskId);
+ response.put("state", "CANCELLED");
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ }
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Task not found or cannot be cancelled: " + taskId));
+ }
+
+ // =========================================================================
+ // GET /a2a/tasks/{taskId}/wait
+ // =========================================================================
+
+ private FullHttpResponse handleWaitTask(String taskId, QueryStringDecoder decoder) throws Exception {
+ String timeoutStr = getQueryParam(decoder, "timeout");
+ long timeout = timeoutStr != null ? Long.parseLong(timeoutStr) : DEFAULT_WAIT_TIMEOUT_MS;
+
+ TaskRegistry.TaskEntry entry = gatewayService.getTaskStatus(taskId);
+ if (entry == null) {
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Task not found: " + taskId));
+ }
+
+ // If already in a terminal state, return immediately
+ if (isTerminalState(entry.getState())) {
+ return handleGetTask(taskId);
+ }
+
+ // Register a status subscriber and wait
+ java.util.concurrent.CompletableFuture<TaskRegistry.TaskEntry> waitFuture = new java.util.concurrent.CompletableFuture<>();
+ A2AGatewayService.StatusSubscriber subscriber = (tid, state, data) -> {
+ if ("completed".equals(state) || "failed".equals(state) || "cancelled".equals(state)) {
+ waitFuture.complete(gatewayService.getTaskStatus(tid));
+ }
+ };
+ gatewayService.registerStatusSubscriber(taskId, subscriber);
+
+ try {
+ TaskRegistry.TaskEntry result = waitFuture.get(timeout, TimeUnit.MILLISECONDS);
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("taskId", result.getTaskId());
+ response.put("state", result.getState().name());
+ if (result.getResult() != null) {
+ response.put("result", result.getResult());
+ }
+ if (result.getErrorMessage() != null) {
+ response.put("error", result.getErrorMessage());
+ }
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ } catch (java.util.concurrent.TimeoutException e) {
+ return jsonResponse(HttpResponseStatus.OK,
+ errorBody("Task still in progress. State: " + entry.getState()));
+ } catch (Exception e) {
+ return jsonResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR,
+ errorBody("Wait failed: " + e.getMessage()));
+ } finally {
+ gatewayService.unregisterStatusSubscriber(taskId, subscriber);
+ }
+ }
+
+ // =========================================================================
+ // GET /a2a/tasks/{taskId}/stream (SSE)
+ // =========================================================================
+
+ /**
+ * Streams task status updates via Server-Sent Events.
+ * Writes directly to the channel and returns null (no FullHttpResponse).
+ */
+ private FullHttpResponse handleStreamTask(String taskId, ChannelHandlerContext ctx) throws Exception {
+ TaskRegistry.TaskEntry entry = gatewayService.getTaskStatus(taskId);
+ if (entry == null) {
+ return jsonResponse(HttpResponseStatus.NOT_FOUND, errorBody("Task not found: " + taskId));
+ }
+
+ // Write SSE response headers
+ HttpResponse headers = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
+ headers.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/event-stream; charset=utf-8");
+ headers.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");
+ headers.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
+ headers.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
+ headers.headers().set("Access-Control-Allow-Origin", "*");
+ ctx.writeAndFlush(headers);
+
+ // Send initial state
+ sendSseEvent(ctx, taskId, entry.getState().name(),
+ entry.getResult() != null ? entry.getResult() : entry.getErrorMessage());
+
+ // If already terminal, close stream
+ if (isTerminalState(entry.getState())) {
+ ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
+ ctx.close();
+ return null;
+ }
+
+ // Schedule periodic heartbeat to keep connection alive through proxies/load balancers
+ java.util.concurrent.ScheduledExecutorService heartbeatExecutor = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(r -> {
+ Thread t = new Thread(r, "a2a-sse-heartbeat");
+ t.setDaemon(true);
+ return t;
+ });
+ heartbeatExecutor.scheduleAtFixedRate(() -> {
+ try {
+ ByteBuf hb = Unpooled.copiedBuffer(": heartbeat\n\n", StandardCharsets.UTF_8);
+ ctx.writeAndFlush(new DefaultHttpContent(hb));
+ } catch (Exception e) {
+ // Channel may have been closed; ignore
+ }
+ }, 15, 15, TimeUnit.SECONDS);
+
+ // Register subscriber for ongoing updates
+ A2AGatewayService.StatusSubscriber subscriber = (tid, state, data) -> {
+ sendSseEvent(ctx, tid, state, data);
+ if ("completed".equals(state) || "failed".equals(state) || "cancelled".equals(state)) {
+ heartbeatExecutor.shutdownNow();
+ ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT)
+ .addListener(ChannelFutureListener.CLOSE);
+ }
+ };
+ gatewayService.registerStatusSubscriber(taskId, subscriber);
+
+ // Remove subscriber and stop heartbeat when channel closes
+ ctx.channel().closeFuture().addListener(future -> {
+ gatewayService.unregisterStatusSubscriber(taskId, subscriber);
+ heartbeatExecutor.shutdownNow();
+ });
+
+ return null; // Response already written to channel
+ }
+
+ private void sendSseEvent(ChannelHandlerContext ctx, String taskId, String state, String data) {
+ Map<String, Object> event = new LinkedHashMap<>();
+ event.put("taskId", taskId);
+ event.put("state", state);
+ if (data != null) {
+ event.put("data", data);
+ }
+ String json;
+ try {
+ json = objectMapper.writeValueAsString(event);
+ } catch (Exception e) {
+ json = "{\"error\":\"" + e.getMessage() + "\"}";
+ }
+ String sse = "data: " + json + "\n\n";
+ ByteBuf buf = Unpooled.copiedBuffer(sse, StandardCharsets.UTF_8);
+ ctx.writeAndFlush(new DefaultHttpContent(buf));
+ }
+
+ // =========================================================================
+ // GET /a2a/health
+ // =========================================================================
+
+ private FullHttpResponse handleHealth() throws Exception {
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("status", "UP");
+ response.put("gatewayId", gatewayService.getGatewayId());
+ response.put("namespace", gatewayService.getNamespace());
+ response.put("taskCount", gatewayService.getTaskRegistry().size());
+ response.put("agentCount", a2aService.listAllCards().size());
+ response.put("timestamp", System.currentTimeMillis());
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ }
+
+ // =========================================================================
+ // GET /a2a/agents
+ // =========================================================================
+
+ private FullHttpResponse handleListAgents() throws Exception {
+ return jsonResponse(HttpResponseStatus.OK,
+ objectMapper.writeValueAsString(a2aService.listAllCards()));
+ }
+
+ // =========================================================================
+ // POST /a2a/heartbeat
+ // =========================================================================
+
+ private FullHttpResponse handleHeartbeat(HttpRequest request) throws Exception {
+ String body = readBody(request);
+ HeartbeatRequest hb;
+ try {
+ hb = objectMapper.readValue(body, HeartbeatRequest.class);
+ } catch (Exception e) {
+ return jsonResponse(HttpResponseStatus.BAD_REQUEST, errorBody("Invalid JSON: " + e.getMessage()));
+ }
+
+ org.apache.eventmesh.protocol.a2a.AgentIdentity identity =
+ org.apache.eventmesh.protocol.a2a.AgentIdentity.builder()
+ .orgId(hb.getOrgId())
+ .unitId(hb.getUnitId())
+ .agentId(hb.getAgentId())
+ .build();
+
+ boolean refreshed = a2aService.heartbeat(identity);
+ Map<String, Object> response = new LinkedHashMap<>();
+ response.put("ok", refreshed);
+ if (!refreshed) {
+ response.put("error", "Agent not registered. POST /a2a/cards/card/{org}/{unit}/{agent} first.");
+ }
+ return jsonResponse(HttpResponseStatus.OK, objectMapper.writeValueAsString(response));
+ }
+
+ // =========================================================================
+ // Helpers
+ // =========================================================================
+
+ private boolean isTerminalState(TaskRegistry.TaskState state) {
+ return state == TaskRegistry.TaskState.COMPLETED
+ || state == TaskRegistry.TaskState.FAILED
+ || state == TaskRegistry.TaskState.CANCELLED;
+ }
+
+ private String readBody(HttpRequest request) {
+ if (request instanceof io.netty.handler.codec.http.FullHttpRequest) {
+ ByteBuf content = ((io.netty.handler.codec.http.FullHttpRequest) request).content();
+ return content.toString(StandardCharsets.UTF_8);
+ }
+ return "";
+ }
+
+ private String getQueryParam(QueryStringDecoder decoder, String key) {
+ java.util.List<String> values = decoder.parameters().get(key);
+ return (values != null && !values.isEmpty()) ? values.get(0) : null;
+ }
+
+ private int parseIntQueryParam(QueryStringDecoder decoder, String key,
+ int defaultValue, int minValue, int maxValue) {
+ String value = getQueryParam(decoder, key);
+ if (value == null || value.isEmpty()) {
+ return defaultValue;
+ }
+ try {
+ int parsed = Integer.parseInt(value);
+ if (parsed < minValue) {
+ return minValue;
+ }
+ if (parsed > maxValue) {
+ return maxValue;
+ }
+ return parsed;
+ } catch (NumberFormatException e) {
+ return defaultValue;
+ }
+ }
+
+ private String errorBody(String message) {
+ try {
+ return objectMapper.writeValueAsString(java.util.Collections.singletonMap("error", message));
+ } catch (Exception e) {
+ return "{\"error\":\"" + message + "\"}";
+ }
+ }
+
+ private FullHttpResponse jsonResponse(HttpResponseStatus status, String body) {
+ ByteBuf content = Unpooled.copiedBuffer(body, StandardCharsets.UTF_8);
+ DefaultFullHttpResponse response = new DefaultFullHttpResponse(
+ HttpVersion.HTTP_1_1, status, content);
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");
+ response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
+ setCorsHeaders(response);
+ return response;
+ }
+
+ private FullHttpResponse corsResponse(HttpResponseStatus status) {
+ DefaultFullHttpResponse response = new DefaultFullHttpResponse(
+ HttpVersion.HTTP_1_1, status);
+ setCorsHeaders(response);
+ response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
+ return response;
+ }
+
+ private void setCorsHeaders(HttpResponse response) {
+ response.headers().set("Access-Control-Allow-Origin", "*");
+ response.headers().set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
+ response.headers().set("Access-Control-Allow-Headers", "Content-Type, Authorization");
+ response.headers().set("Access-Control-Max-Age", "3600");
+ }
+
+ // =========================================================================
+ // Request / Response DTOs
+ // =========================================================================
+
+ public static class TaskRequest {
+
+ private String targetAgent;
+ private String message;
+ private String parentTaskId;
+
+ public String getTargetAgent() {
+ return targetAgent;
+ }
+
+ public void setTargetAgent(String targetAgent) {
+ this.targetAgent = targetAgent;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String getParentTaskId() {
+ return parentTaskId;
+ }
+
+ public void setParentTaskId(String parentTaskId) {
+ this.parentTaskId = parentTaskId;
+ }
+ }
+
+ public static class HeartbeatRequest {
+
+ private String orgId;
+ private String unitId;
+ private String agentId;
+
+ public String getOrgId() {
+ return orgId;
+ }
+
+ public void setOrgId(String orgId) {
+ this.orgId = orgId;
+ }
+
+ public String getUnitId() {
+ return unitId;
+ }
+
+ public void setUnitId(String unitId) {
+ this.unitId = unitId;
+ }
+
+ public String getAgentId() {
+ return agentId;
+ }
+
+ public void setAgentId(String agentId) {
+ this.agentId = agentId;
+ }
+ }
+}
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayServer.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayServer.java
new file mode 100644
index 000000000..5b8f32747
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayServer.java
@@ -0,0 +1,338 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import org.apache.eventmesh.protocol.a2a.A2AProtocolConstants;
+import org.apache.eventmesh.protocol.a2a.A2ATopicFactory;
+import org.apache.eventmesh.protocol.a2a.AgentIdentity;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+import org.apache.eventmesh.protocol.a2a.model.AgentSkill;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.UUID;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+import io.netty.bootstrap.ServerBootstrap;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInitializer;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.SocketChannel;
+import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.http.DefaultFullHttpResponse;
+import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.FullHttpResponse;
+import io.netty.handler.codec.http.HttpHeaderNames;
+import io.netty.handler.codec.http.HttpObjectAggregator;
+import io.netty.handler.codec.http.HttpRequestDecoder;
+import io.netty.handler.codec.http.HttpResponseEncoder;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.HttpVersion;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Standalone A2A Gateway Server.
+ *
+ * <p>Starts an embedded Netty HTTP server that exposes the A2A Gateway REST API.
+ * Pre-registers a mock "weather-agent" that auto-responds to task requests.
+ *
+ * <p>Usage:
+ * <pre>
+ * java org.apache.eventmesh.runtime.a2a.A2AGatewayServer [port]
+ * </pre>
+ *
+ * <p>Then run the client demo (A2AGatewayDemo) to submit tasks via HTTP.
+ */
+@Slf4j
+public class A2AGatewayServer {
+
+ private static final String NAMESPACE = "global";
+ private static final String GATEWAY_ID = "demo-gateway";
+ private static final int DEFAULT_PORT = 10105;
+
+ private final int port;
+ private EventLoopGroup bossGroup;
+ private EventLoopGroup workerGroup;
+ private ChannelFuture serverChannel;
+
+ private InMemoryA2AMessageTransport transport;
+ private TaskRegistry taskRegistry;
+ private A2APublishSubscribeService a2aService;
+ private A2AGatewayService gatewayService;
+ private A2AGatewayHttpHandler gatewayHandler;
+ private A2ACardHttpHandler cardHandler;
+
+ public A2AGatewayServer(int port) {
+ this.port = port;
+ }
+
+ public void start() throws Exception {
+ // 1. Initialize components
+ transport = new InMemoryA2AMessageTransport();
+ taskRegistry = new TaskRegistry();
+ a2aService = new A2APublishSubscribeService();
+ a2aService.init();
+ a2aService.start();
+
+ gatewayService = new A2AGatewayService(NAMESPACE, GATEWAY_ID, transport, taskRegistry, a2aService);
+ gatewayService.start();
+
+ gatewayHandler = new A2AGatewayHttpHandler(gatewayService, a2aService);
+ cardHandler = new A2ACardHttpHandler(a2aService);
+
+ // 2. Pre-register a mock weather agent
+ registerMockWeatherAgent();
+
+ // 3. Start Netty HTTP server
+ bossGroup = new NioEventLoopGroup(1);
+ workerGroup = new NioEventLoopGroup();
+
+ ServerBootstrap bootstrap = new ServerBootstrap();
+ bootstrap.group(bossGroup, workerGroup)
+ .channel(NioServerSocketChannel.class)
+ .childHandler(new ChannelInitializer<SocketChannel>() {
+ @Override
+ protected void initChannel(SocketChannel ch) {
+ ch.pipeline()
+ .addLast(new HttpRequestDecoder())
+ .addLast(new HttpObjectAggregator(65536))
+ .addLast(new HttpResponseEncoder())
+ .addLast(new A2AGatewayRequestHandler(gatewayHandler, cardHandler));
+ }
+ })
+ .option(ChannelOption.SO_BACKLOG, 128)
+ .childOption(ChannelOption.SO_KEEPALIVE, true);
+
+ serverChannel = bootstrap.bind(port).sync();
+ log.info("=== A2A Gateway Server started on port {} ===", port);
+ log.info("Gateway ID: {}, Namespace: {}", GATEWAY_ID, NAMESPACE);
+ log.info("Endpoints:");
+ log.info(" POST /a2a/tasks - submit task (sync/async)");
+ log.info(" GET /a2a/tasks - list tasks (?state=COMPLETED&limit=100&offset=0)");
+ log.info(" GET /a2a/tasks/{{taskId}} - get task status");
+ log.info(" DELETE /a2a/tasks/{{taskId}} - cancel task");
+ log.info(" GET /a2a/tasks/{{taskId}}/wait - wait for result (long-poll)");
+ log.info(" GET /a2a/tasks/{{taskId}}/stream - SSE stream of task status updates");
+ log.info(" GET /a2a/agents - list registered agents");
+ log.info(" POST /a2a/heartbeat - agent heartbeat");
+ log.info(" GET /a2a/health - health check");
+ log.info(" GET /a2a/cards/list - list agent cards");
+ log.info(" POST /a2a/cards/card/{{org}}/{{unit}}/{{agent}} - register card");
+ }
+
+ /**
+ * Registers a mock weather agent that auto-responds to task requests.
+ */
+ private void registerMockWeatherAgent() throws Exception {
+ AgentCard weatherCard = AgentCard.builder()
+ .name("weather-agent")
+ .description("A weather agent that can tell you the weather")
+ .version("1.0.0")
+ .supportedInterfaces(Arrays.asList(
+ org.apache.eventmesh.protocol.a2a.model.AgentInterface.builder()
+ .url("http://localhost:" + port + "/a2a")
+ .protocolBinding("JSONRPC")
+ .protocolVersion("0.3")
+ .build()
+ ))
+ .capabilities(org.apache.eventmesh.protocol.a2a.model.AgentCapabilities.builder()
+ .streaming(false)
+ .pushNotifications(false)
+ .build())
+ .skills(Arrays.asList(
+ AgentSkill.builder()
+ .id("get-weather")
+ .name("Get Weather")
+ .description("Get the current weather for a city")
+ .tags(Arrays.asList("weather", "test"))
+ .build()
+ ))
+ .defaultInputModes(Arrays.asList("text/plain"))
+ .defaultOutputModes(Arrays.asList("text/plain"))
+ .build();
+
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId("default").unitId("default").agentId("weather-agent").build();
+ A2APublishSubscribeService.RegistrationResult regResult =
+ a2aService.registerCard(identity, weatherCard);
+ if (!regResult.isSuccess()) {
+ log.warn("Failed to register weather-agent card: {}", regResult.getErrorMessage());
+ }
+
+ // Subscribe to agent request topic and auto-respond
+ String requestTopic = A2ATopicFactory.agentRequestTopic(NAMESPACE, "weather-agent");
+ transport.subscribe(requestTopic, (topic, event) -> {
+ String taskId = event.getId();
+ String message = event.getData() != null
+ ? new String(event.getData().toBytes(), StandardCharsets.UTF_8) : "";
+
+ log.info("[Weather Agent] Received request: taskId={}, message={}", taskId, message);
+
+ // Simulate processing delay
+ try {
+ Thread.sleep(300);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+
+ // Publish response
+ String gwId = extractGatewayId(event);
+ String responseTopic = A2ATopicFactory.gatewayResponseTopic(NAMESPACE, gwId, taskId);
+ String result = "The weather in " + message + " is sunny, 25°C";
+ CloudEvent responseEvent = CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withType(A2AProtocolConstants.CE_TYPE_PREFIX + "task.response")
+ .withSource(java.net.URI.create("agent/weather-agent"))
+ .withDataContentType("application/json")
+ .withData(result.getBytes(StandardCharsets.UTF_8))
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_A2A_METHOD, A2AProtocolConstants.OP_SEND_MESSAGE)
+ .build();
+
+ try {
+ transport.publish(responseTopic, responseEvent);
+ log.info("[Weather Agent] Response published: taskId={}", taskId);
+ } catch (Exception e) {
+ log.error("[Weather Agent] Failed to publish response", e);
+ }
+ });
+
+ log.info("Mock weather-agent registered and listening for requests.");
+ }
+
+ private String extractGatewayId(CloudEvent event) {
+ if (event.getSource() == null) {
+ return "default-gateway";
+ }
+ String source = event.getSource().toString();
+ if (source.startsWith("gateway/")) {
+ return source.substring("gateway/".length());
+ }
+ return "default-gateway";
+ }
+
+ /**
+ * Returns the actual bound port. Useful when port 0 was specified to let the OS pick a port.
+ */
+ public int getBoundPort() {
+ if (serverChannel != null) {
+ return ((io.netty.channel.socket.ServerSocketChannel) serverChannel.channel()).localAddress().getPort();
+ }
+ return port;
+ }
+
+ public void shutdown() throws Exception {
+ if (serverChannel != null) {
+ serverChannel.channel().close().sync();
+ }
+ if (workerGroup != null) {
+ workerGroup.shutdownGracefully();
+ }
+ if (bossGroup != null) {
+ bossGroup.shutdownGracefully();
+ }
+ if (gatewayService != null) {
+ gatewayService.shutdown();
+ }
+ if (a2aService != null) {
+ a2aService.shutdown();
+ }
+ log.info("A2A Gateway Server shut down.");
+ }
+
+ public static void main(String[] args) throws Exception {
+ int port = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT;
+
+ A2AGatewayServer server = new A2AGatewayServer(port);
+
+ Runtime.getRuntime().addShutdownHook(new Thread(() -> {
+ try {
+ server.shutdown();
+ } catch (Exception e) {
+ log.error("Error during shutdown", e);
+ }
+ }));
+
+ server.start();
+
+ // Keep running until interrupted
+ Thread.currentThread().join();
+ }
+
+ // =========================================================================
+ // Netty Channel Handler
+ // =========================================================================
+
+ private static class A2AGatewayRequestHandler extends io.netty.channel.SimpleChannelInboundHandler<FullHttpRequest> {
+
+ private final A2AGatewayHttpHandler gatewayHandler;
+ private final A2ACardHttpHandler cardHandler;
+
+ A2AGatewayRequestHandler(A2AGatewayHttpHandler gatewayHandler, A2ACardHttpHandler cardHandler) {
+ this.gatewayHandler = gatewayHandler;
+ this.cardHandler = cardHandler;
+ }
+
+ @Override
+ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
+ String uri = request.uri();
+ try {
+ FullHttpResponse response;
+ if (uri.startsWith("/a2a/cards")) {
+ response = cardHandler.handle(request, ctx);
+ } else if (uri.startsWith("/a2a/")) {
+ response = gatewayHandler.handle(request, ctx);
+ } else {
+ response = jsonError(HttpResponseStatus.NOT_FOUND, "Not found: " + uri);
+ }
+
+ // null means the handler wrote the response directly (e.g. SSE streaming)
+ if (response != null) {
+ ctx.writeAndFlush(response);
+ }
+ } catch (Exception e) {
+ log.error("Error handling request: {} - {}", uri, e.getMessage(), e);
+ FullHttpResponse errorResponse = jsonError(HttpResponseStatus.INTERNAL_SERVER_ERROR, e.getMessage());
+ ctx.writeAndFlush(errorResponse);
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ log.error("Channel exception: {}", cause.getMessage(), cause);
+ ctx.close();
+ }
+
+ private FullHttpResponse jsonError(HttpResponseStatus status, String message) {
+ String body = "{\"error\":\"" + message + "\"}";
+ DefaultFullHttpResponse response = new DefaultFullHttpResponse(
+ HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(body, StandardCharsets.UTF_8));
+ response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8");
+ response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
+ response.headers().set("Access-Control-Allow-Origin", "*");
+ response.headers().set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
+ response.headers().set("Access-Control-Allow-Headers", "Content-Type, Authorization");
+ return response;
+ }
+ }
+}
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayService.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayService.java
new file mode 100644
index 000000000..ed1d8ffdd
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2AGatewayService.java
@@ -0,0 +1,421 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import org.apache.eventmesh.protocol.a2a.A2AMessageTransport;
+import org.apache.eventmesh.protocol.a2a.A2AProtocolConstants;
+import org.apache.eventmesh.protocol.a2a.A2ATopicFactory;
+
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * A2A Gateway Service: orchestrates task submission, response handling, and SSE streaming.
+ *
+ * <p>This is the core component that ties together:
+ * <ul>
+ * <li>{@link A2AMessageTransport} for pub/sub</li>
+ * <li>{@link TaskRegistry} for task lifecycle</li>
+ * <li>{@link A2APublishSubscribeService} for agent discovery</li>
+ * <li>{@link A2ATopicFactory} for topic routing</li>
+ * </ul>
+ */
+@Slf4j
+public class A2AGatewayService {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ private final String namespace;
+ private final String gatewayId;
+ private final A2AMessageTransport transport;
+ private final TaskRegistry taskRegistry;
+ private final A2APublishSubscribeService a2aService;
+
+ // Pending tasks waiting for response
+ private final ConcurrentHashMap<String, CompletableFuture<TaskResult>> pendingTasks = new ConcurrentHashMap<>();
+ // SSE subscribers for status updates
+ private final ConcurrentHashMap<String, List<StatusSubscriber>> statusSubscribers = new ConcurrentHashMap<>();
+
+ private volatile boolean started = false;
+ private String responseSubscriptionId;
+ private String statusSubscriptionId;
+
+ // Task timeout: tasks that don't receive a response within this duration are auto-failed
+ private static final long DEFAULT_TASK_TIMEOUT_MS = 120_000L; // 2 minutes
+ private final long taskTimeoutMs;
+ private ScheduledExecutorService taskTimeoutScheduler;
+
+ public A2AGatewayService(String namespace, String gatewayId,
+ A2AMessageTransport transport,
+ TaskRegistry taskRegistry,
+ A2APublishSubscribeService a2aService) {
+ this(namespace, gatewayId, transport, taskRegistry, a2aService, DEFAULT_TASK_TIMEOUT_MS);
+ }
+
+ public A2AGatewayService(String namespace, String gatewayId,
+ A2AMessageTransport transport,
+ TaskRegistry taskRegistry,
+ A2APublishSubscribeService a2aService,
+ long taskTimeoutMs) {
+ this.namespace = namespace;
+ this.gatewayId = gatewayId;
+ this.transport = transport;
+ this.taskRegistry = taskRegistry;
+ this.a2aService = a2aService;
+ this.taskTimeoutMs = taskTimeoutMs;
+ }
+
+ public String getGatewayId() {
+ return gatewayId;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+
+ public A2APublishSubscribeService getA2aService() {
+ return a2aService;
+ }
+
+ public TaskRegistry getTaskRegistry() {
+ return taskRegistry;
+ }
+
+ /**
+ * Starts the gateway service: subscribes to gateway response/status topics.
+ */
+ public synchronized void start() throws Exception {
+ if (started) {
+ return;
+ }
+ // Start task registry TTL cleanup
+ taskRegistry.start();
+
+ // Start task timeout scheduler
+ taskTimeoutScheduler = Executors.newSingleThreadScheduledExecutor(r -> {
+ Thread t = new Thread(r, "a2a-task-timeout");
+ t.setDaemon(true);
+ return t;
+ });
+
+ // Subscribe to all responses for this gateway
+ String responseTopic = A2ATopicFactory.gatewayResponseWildcardTopic(namespace, gatewayId);
+ responseSubscriptionId = transport.subscribe(responseTopic, this::handleResponse);
+
+ // Subscribe to all status updates for this gateway
+ String statusTopic = A2ATopicFactory.gatewayStatusWildcardTopic(namespace, gatewayId);
+ statusSubscriptionId = transport.subscribe(statusTopic, this::handleStatus);
+
+ started = true;
+ log.info("A2AGatewayService started: gatewayId={}, namespace={}", gatewayId, namespace);
+ }
+
+ public synchronized void shutdown() throws Exception {
+ if (!started) {
+ return;
+ }
+ if (responseSubscriptionId != null) {
+ transport.unsubscribe(responseSubscriptionId);
+ }
+ if (statusSubscriptionId != null) {
+ transport.unsubscribe(statusSubscriptionId);
+ }
+ if (taskTimeoutScheduler != null) {
+ taskTimeoutScheduler.shutdownNow();
+ taskTimeoutScheduler = null;
+ }
+ pendingTasks.clear();
+ statusSubscribers.clear();
+ taskRegistry.shutdown();
+ started = false;
+ log.info("A2AGatewayService shutdown.");
+ }
+
+ // =========================================================================
+ // Task Submission
+ // =========================================================================
+
+ /**
+ * Submits an A2A task to a target agent.
+ *
+ * @param targetAgent target agent name
+ * @param message the message content (JSON string)
+ * @param parentTaskId parent task ID (null for root tasks from external clients)
+ * @return CompletableFuture that will be completed with the task result
+ */
+ public CompletableFuture<TaskResult> submitTask(String targetAgent, String message, String parentTaskId) {
+ String taskId = generateTaskId();
+ return submitTask(taskId, targetAgent, message, parentTaskId);
+ }
+
+ /**
+ * Submits an A2A task with a specific task ID.
+ */
+ public CompletableFuture<TaskResult> submitTask(String taskId, String targetAgent,
+ String message, String parentTaskId) {
+ if (!started) {
+ CompletableFuture<TaskResult> future = new CompletableFuture<>();
+ future.completeExceptionally(new IllegalStateException("Gateway not started"));
+ return future;
+ }
+
+ // Validate that the target agent is registered
+ if (!a2aService.isAgentRegistered(targetAgent)) {
+ CompletableFuture<TaskResult> future = new CompletableFuture<>();
+ future.completeExceptionally(new IllegalArgumentException(
+ "Target agent not registered: " + targetAgent));
+ return future;
+ }
+
+ // Create task entry
+ TaskRegistry.TaskEntry taskEntry = taskRegistry.createTask(taskId, parentTaskId, targetAgent, gatewayId);
+
+ // Build A2A CloudEvent
+ CloudEvent event = buildTaskRequestEvent(taskId, targetAgent, message, parentTaskId);
+
+ // Register pending future BEFORE publishing to avoid race condition:
+ // InMemoryTransport delivers synchronously, so if we publish first,
+ // handleResponse() could run before put() and the future would never complete.
+ CompletableFuture<TaskResult> future = new CompletableFuture<>();
+ pendingTasks.put(taskId, future);
+
+ // Schedule timeout: if no response within taskTimeoutMs, auto-fail the task
+ if (taskTimeoutScheduler != null) {
+ taskTimeoutScheduler.schedule(() -> {
+ CompletableFuture<TaskResult> pending = pendingTasks.get(taskId);
+ if (pending != null && !pending.isDone()) {
+ taskRegistry.markFailed(taskId, "Task timed out after " + taskTimeoutMs + "ms with no response");
+ pendingTasks.remove(taskId);
+ pending.completeExceptionally(new java.util.concurrent.TimeoutException(
+ "Task " + taskId + " timed out after " + taskTimeoutMs + "ms"));
+ notifyStatusSubscribers(taskId, "failed", "Task timed out");
+ log.warn("Task timed out: taskId={}, targetAgent={}", taskId, targetAgent);
+ }
+ }, taskTimeoutMs, TimeUnit.MILLISECONDS);
+ }
+
+ // Publish to agent request topic
+ String requestTopic = A2ATopicFactory.agentRequestTopic(namespace, targetAgent);
+ try {
+ transport.publish(requestTopic, event);
+ log.info("Task submitted: taskId={}, targetAgent={}, topic={}", taskId, targetAgent, requestTopic);
+ } catch (Exception e) {
+ log.error("Failed to publish task: taskId={}", taskId, e);
+ taskRegistry.markFailed(taskId, "Publish failed: " + e.getMessage());
+ pendingTasks.remove(taskId);
+ future.completeExceptionally(e);
+ }
+
+ return future;
+ }
+
+ /**
+ * Cancels a task.
+ */
+ public boolean cancelTask(String taskId) {
+ boolean cancelled = taskRegistry.markCancelled(taskId);
+ if (cancelled) {
+ CompletableFuture<TaskResult> future = pendingTasks.remove(taskId);
+ if (future != null) {
+ future.complete(new TaskResult(TaskRegistry.TaskState.CANCELLED, null, "Task cancelled"));
+ }
+ notifyStatusSubscribers(taskId, "cancelled", "Task cancelled");
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Gets task status.
+ */
+ public TaskRegistry.TaskEntry getTaskStatus(String taskId) {
+ return taskRegistry.getTask(taskId);
+ }
+
+ // =========================================================================
+ // SSE Status Subscription
+ // =========================================================================
+
+ /**
+ * Registers a subscriber for status updates on a specific task.
+ */
+ public void registerStatusSubscriber(String taskId, StatusSubscriber subscriber) {
+ statusSubscribers.computeIfAbsent(taskId, k -> new CopyOnWriteArrayList<>()).add(subscriber);
+ }
+
+ /**
+ * Removes a status subscriber.
+ */
+ public void unregisterStatusSubscriber(String taskId, StatusSubscriber subscriber) {
+ List<StatusSubscriber> subs = statusSubscribers.get(taskId);
+ if (subs != null) {
+ subs.remove(subscriber);
+ if (subs.isEmpty()) {
+ statusSubscribers.remove(taskId);
+ }
+ }
+ }
+
+ // =========================================================================
+ // Response / Status Handling
+ // =========================================================================
+
+ private void handleResponse(String topic, CloudEvent event) {
+ A2ATopicFactory.ParsedTopic parsed = A2ATopicFactory.parse(topic);
+ if (parsed == null || !parsed.isResponse() || parsed.getTaskId() == null) {
+ return;
+ }
+ String taskId = parsed.getTaskId();
+ log.info("Received response for task: {}", taskId);
+
+ TaskRegistry.TaskEntry entry = taskRegistry.getTask(taskId);
+ if (entry == null) {
+ log.warn("Response received for unknown task: {}", taskId);
+ return;
+ }
+
+ String resultData = extractEventData(event);
+ taskRegistry.markCompleted(taskId, resultData);
+
+ CompletableFuture<TaskResult> future = pendingTasks.remove(taskId);
+ if (future != null) {
+ future.complete(new TaskResult(TaskRegistry.TaskState.COMPLETED, resultData, null));
+ }
+
+ // Notify SSE subscribers
+ notifyStatusSubscribers(taskId, "completed", resultData);
+ }
+
+ private void handleStatus(String topic, CloudEvent event) {
+ A2ATopicFactory.ParsedTopic parsed = A2ATopicFactory.parse(topic);
+ if (parsed == null || !parsed.isStatus() || parsed.getTaskId() == null) {
+ return;
+ }
+ String taskId = parsed.getTaskId();
+ String statusData = extractEventData(event);
+ log.debug("Received status for task: {} -> {}", taskId, statusData);
+
+ // Mark as working if currently submitted
+ TaskRegistry.TaskEntry entry = taskRegistry.getTask(taskId);
+ if (entry != null && entry.getState() == TaskRegistry.TaskState.SUBMITTED) {
+ taskRegistry.markWorking(taskId);
+ }
+
+ // Notify SSE subscribers
+ notifyStatusSubscribers(taskId, "working", statusData);
+ }
+
+ private void notifyStatusSubscribers(String taskId, String state, String data) {
+ List<StatusSubscriber> subs = statusSubscribers.get(taskId);
+ if (subs != null) {
+ for (StatusSubscriber sub : subs) {
+ try {
+ sub.onStatus(taskId, state, data);
+ } catch (Exception e) {
+ log.warn("Status subscriber error for task {}: {}", taskId, e.getMessage());
+ }
+ }
+ }
+ }
+
+ // =========================================================================
+ // CloudEvent Building
+ // =========================================================================
+
+ private CloudEvent buildTaskRequestEvent(String taskId, String targetAgent,
+ String message, String parentTaskId) {
+ CloudEventBuilder builder = CloudEventBuilder.v1()
+ .withId(taskId)
+ .withType(A2AProtocolConstants.CE_TYPE_PREFIX + "task.request")
+ .withSource(java.net.URI.create("gateway/" + gatewayId))
+ .withDataContentType("application/json")
+ .withData(message.getBytes(StandardCharsets.UTF_8))
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_A2A_METHOD, A2AProtocolConstants.OP_SEND_MESSAGE)
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_TARGET_AGENT, targetAgent)
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_PROTOCOL, "A2A")
+ .withExtension(A2AProtocolConstants.CE_EXTENSION_PROTOCOL_VERSION, A2AProtocolConstants.PROTOCOL_VERSION);
+
+ if (parentTaskId != null) {
+ builder.withExtension(A2AProtocolConstants.CE_EXTENSION_COLLABORATION_ID, parentTaskId);
+ }
+
+ return builder.build();
+ }
+
+ private String extractEventData(CloudEvent event) {
+ if (event.getData() == null) {
+ return null;
+ }
+ return new String(event.getData().toBytes(), StandardCharsets.UTF_8);
+ }
+
+ private String generateTaskId() {
+ return "task-" + UUID.randomUUID().toString().substring(0, 8);
+ }
+
+ // =========================================================================
+ // Result Types
+ // =========================================================================
+
+ public static class TaskResult {
+
+ private final TaskRegistry.TaskState state;
+ private final String data;
+ private final String errorMessage;
+
+ public TaskResult(TaskRegistry.TaskState state, String data, String errorMessage) {
+ this.state = state;
+ this.data = data;
+ this.errorMessage = errorMessage;
+ }
+
+ public TaskRegistry.TaskState getState() {
+ return state;
+ }
+
+ public String getData() {
+ return data;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+ }
+
+ /**
+ * Callback interface for task status change notifications.
+ */
+ @FunctionalInterface
+ public interface StatusSubscriber {
+ void onStatus(String taskId, String state, String data);
+ }
+}
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2APublishSubscribeService.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2APublishSubscribeService.java
new file mode 100644
index 000000000..c9e678eb9
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/A2APublishSubscribeService.java
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import org.apache.eventmesh.protocol.a2a.A2AProtocolConstants;
+import org.apache.eventmesh.protocol.a2a.AgentCardValidator;
+import org.apache.eventmesh.protocol.a2a.AgentIdentity;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * A2APublishSubscribeService: Manages A2A Agent Card Registry and processes A2A events.
+ *
+ * <p>Features:
+ * - Agent Card CRUD (register, delete, get, list)
+ * - Agent status tracking (online/offline)
+ * - Event processing with status metadata augmentation
+ * - Hierarchical identity (org_id/unit_id/agent_id) with wildcard queries
+ */
+@Slf4j
+public class A2APublishSubscribeService {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ private volatile boolean isStarted = false;
+
+ private final ConcurrentHashMap<AgentIdentity, RegisteredCard> cardRegistry = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, AgentStatus> agentStatusMap = new ConcurrentHashMap<>();
+
+ private AgentCardValidator cardValidator;
+
+ // TTL heartbeat configuration
+ private static final long DEFAULT_CARD_TTL_MS = 60_000L; // 60 seconds
+ private static final long DEFAULT_CLEANUP_INTERVAL_MS = 15_000L; // 15 seconds
+ private final long cardTtlMs;
+ private final long cleanupIntervalMs;
+ private ScheduledExecutorService cleanupExecutor;
+
+ public A2APublishSubscribeService() {
+ this(DEFAULT_CARD_TTL_MS, DEFAULT_CLEANUP_INTERVAL_MS);
+ }
+
+ public A2APublishSubscribeService(long cardTtlMs, long cleanupIntervalMs) {
+ this.cardTtlMs = cardTtlMs;
+ this.cleanupIntervalMs = cleanupIntervalMs;
+ }
+
+ public void init() throws Exception {
+ this.cardValidator = new AgentCardValidator(true);
+ log.info("A2APublishSubscribeService initialized with Agent Card Registry (TTL={}ms, cleanup={}ms).",
+ cardTtlMs, cleanupIntervalMs);
+ }
+
+ public void start() throws Exception {
+ isStarted = true;
+ startCleanupScheduler();
+ log.info("A2APublishSubscribeService started.");
+ }
+
+ public void shutdown() throws Exception {
+ isStarted = false;
+ if (cleanupExecutor != null) {
+ cleanupExecutor.shutdownNow();
+ cleanupExecutor = null;
+ }
+ cardRegistry.clear();
+ agentStatusMap.clear();
+ log.info("A2APublishSubscribeService shutdown.");
+ }
+
+ // -------------------------------------------------------------------------
+ // TTL Heartbeat Cleanup
+ // -------------------------------------------------------------------------
+
+ private void startCleanupScheduler() {
+ cleanupExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
+ Thread t = new Thread(r, "a2a-card-ttl-cleanup");
+ t.setDaemon(true);
+ return t;
+ });
+ cleanupExecutor.scheduleAtFixedRate(this::cleanupExpiredCards,
+ cleanupIntervalMs, cleanupIntervalMs, TimeUnit.MILLISECONDS);
+ }
+
+ /**
+ * Removes AgentCards that have not been refreshed within the TTL window.
+ */
+ void cleanupExpiredCards() {
+ if (!isStarted) {
+ return;
+ }
+ long now = System.currentTimeMillis();
+ int removed = 0;
+ Iterator<Map.Entry<AgentIdentity, RegisteredCard>> it = cardRegistry.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<AgentIdentity, RegisteredCard> entry = it.next();
+ RegisteredCard rc = entry.getValue();
+ if (now - rc.lastHeartbeat > cardTtlMs) {
+ it.remove();
+ agentStatusMap.remove(entry.getKey().clientId());
+ removed++;
+ log.info("Agent card expired and removed: {} (lastHeartbeat={}ms ago)",
+ entry.getKey().clientId(), now - rc.lastHeartbeat);
+ }
+ }
+ if (removed > 0) {
+ log.info("TTL cleanup removed {} expired agent card(s).", removed);
+ }
+ }
+
+ /**
+ * Refreshes the heartbeat timestamp for an agent card (agent calls this periodically).
+ */
+ public boolean heartbeat(AgentIdentity identity) {
+ if (!isStarted) {
+ throw new IllegalStateException("A2APublishSubscribeService is not started");
+ }
+ RegisteredCard rc = cardRegistry.get(identity);
+ if (rc == null) {
+ return false;
+ }
+ rc.lastHeartbeat = System.currentTimeMillis();
+ agentStatusMap.put(identity.clientId(), AgentStatus.ONLINE);
+ return true;
+ }
+
+ // =========================================================================
+ // Agent Card Registry Operations
+ // =========================================================================
+
+ /**
+ * Registers an Agent Card. Validates the card and identity before storing.
+ *
+ * @param identity the agent identity (org_id/unit_id/agent_id)
+ * @param card the agent card
+ * @return RegistrationResult with success/failure
+ */
+ public RegistrationResult registerCard(AgentIdentity identity, AgentCard card) {
+ if (!isStarted) {
+ throw new IllegalStateException("A2APublishSubscribeService is not started");
+ }
+
+ // Validate identity
+ if (!identity.isValid()) {
+ String msg = String.format("Invalid agent identity: orgId=%s, unitId=%s, agentId=%s",
+ identity.getOrgId(), identity.getUnitId(), identity.getAgentId());
+ log.warn(msg);
+ return RegistrationResult.failure(msg);
+ }
+
+ // Validate card
+ try {
+ String cardJson = objectMapper.writeValueAsString(card);
+ AgentCardValidator.ValidationResult result = cardValidator.validate(cardJson);
+ if (!result.isValid()) {
+ log.warn("Agent card schema validation failed for {}: {}", identity.clientId(), result.getErrorMessage());
+ return RegistrationResult.failure(result.getErrorMessage());
+ }
+ } catch (Exception e) {
+ log.warn("Failed to serialize/validate agent card for {}: {}", identity.clientId(), e.getMessage());
+ return RegistrationResult.failure("Card validation error: " + e.getMessage());
+ }
+
+ RegisteredCard existing = cardRegistry.put(identity, new RegisteredCard(card, System.currentTimeMillis()));
+ if (existing != null) {
+ log.info("Updated agent card for {}", identity.clientId());
+ } else {
+ log.info("Registered new agent card for {}", identity.clientId());
+ }
+
+ // Set agent online
+ agentStatusMap.put(identity.clientId(), AgentStatus.ONLINE);
+
+ return RegistrationResult.success();
+ }
+
+ /**
+ * Deletes an Agent Card from the registry.
+ */
+ public boolean deleteCard(AgentIdentity identity) {
+ if (!isStarted) {
+ throw new IllegalStateException("A2APublishSubscribeService is not started");
+ }
+ RegisteredCard removed = cardRegistry.remove(identity);
+ if (removed != null) {
+ agentStatusMap.remove(identity.clientId());
+ log.info("Deleted agent card for {}", identity.clientId());
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Gets a specific Agent Card.
+ */
+ public CardEntry getCard(AgentIdentity identity) {
+ if (!isStarted) {
+ throw new IllegalStateException("A2APublishSubscribeService is not started");
+ }
+ RegisteredCard rc = cardRegistry.get(identity);
+ if (rc == null) {
+ return null;
+ }
+ return new CardEntry(identity, rc.card, lookupAgentStatus(identity));
+ }
+
+ /**
+ * Lists Agent Cards matching the given filters. Use null or "+" for wildcard matching.
+ */
+ public List<CardEntry> listCards(String orgId, String unitId, String agentId) {
+ if (!isStarted) {
+ throw new IllegalStateException("A2APublishSubscribeService is not started");
+ }
+ List<CardEntry> results = new ArrayList<>();
+ for (Map.Entry<AgentIdentity, RegisteredCard> entry : cardRegistry.entrySet()) {
+ AgentIdentity id = entry.getKey();
+ if (id.matchesFilter(orgId, unitId, agentId)) {
+ results.add(new CardEntry(id, entry.getValue().card, lookupAgentStatus(id)));
+ }
+ }
+ return results;
+ }
+
+ /**
+ * Lists all registered Agent Cards.
+ */
+ public List<CardEntry> listAllCards() {
+ return listCards(null, null, null);
+ }
+
+ /**
+ * Checks whether an agent with the given name is registered.
+ *
+ * @param agentName the agent name (or agentId segment) to look up
+ * @return true if a registered card's name matches
+ */
+ public boolean isAgentRegistered(String agentName) {
+ if (!isStarted || agentName == null) {
+ return false;
+ }
+ for (RegisteredCard rc : cardRegistry.values()) {
+ if (agentName.equals(rc.card.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // =========================================================================
+ // Agent Status
+ // =========================================================================
+
+ /**
+ * Looks up the status of an agent (online/offline).
+ */
+ public String lookupAgentStatus(AgentIdentity identity) {
+ AgentStatus status = agentStatusMap.get(identity.clientId());
+ return status != null ? status.value : A2AProtocolConstants.STATUS_OFFLINE;
+ }
+
+ /**
+ * Sets the status of an agent.
+ */
+ public void setAgentStatus(AgentIdentity identity, String status) {
+ if (A2AProtocolConstants.STATUS_ONLINE.equals(status)) {
+ agentStatusMap.put(identity.clientId(), AgentStatus.ONLINE);
+ } else {
+ agentStatusMap.put(identity.clientId(), AgentStatus.OFFLINE);
+ }
+ }
+
+ // =========================================================================
+ // Event Processing
+ // =========================================================================
+
+ /**
+ * Processes an A2A CloudEvent. Augments events with agent status metadata.
+ *
+ * @param event The CloudEvent to process.
+ * @return The processed (potentially modified) CloudEvent.
+ */
+ public CloudEvent process(CloudEvent event) {
+ if (!isStarted) {
+ throw new IllegalStateException("A2APublishSubscribeService is not started");
+ }
+
+ log.debug("Processing A2A event: {}", event.getId());
+
+ // Check if this is an A2A discovery topic event
+ String subject = event.getSubject();
+ if (subject != null && subject.startsWith(A2AProtocolConstants.TOPIC_NAMESPACE + "/")) {
+ AgentIdentity identity = AgentIdentity.fromDiscoveryTopic(subject);
+ if (identity != null) {
+ return augmentWithStatusMetadata(event, identity);
+ }
+ }
+
+ return event;
+ }
+
+ /**
+ * Augments a CloudEvent with agent status metadata (a2astatus, a2astatussource extensions).
+ * Matches EMQX's on_message_delivered hook behavior.
+ */
+ private CloudEvent augmentWithStatusMetadata(CloudEvent event, AgentIdentity identity) {
+ String status = lookupAgentStatus(identity);
+ CloudEventBuilder builder = CloudEventBuilder.from(event);
+ builder.withExtension(A2AProtocolConstants.CE_EXTENSION_A2A_STATUS, status);
+ builder.withExtension(A2AProtocolConstants.CE_EXTENSION_A2A_STATUS_SOURCE, "eventmesh");
+ return builder.build();
+ }
+
+ // =========================================================================
+ // Inner Types
+ // =========================================================================
+
+ private enum AgentStatus {
+ ONLINE(A2AProtocolConstants.STATUS_ONLINE),
+ OFFLINE(A2AProtocolConstants.STATUS_OFFLINE);
+
+ final String value;
+
+ AgentStatus(String value) {
+ this.value = value;
+ }
+ }
+
+ private static class RegisteredCard {
+
+ final AgentCard card;
+ final long registeredAt;
+ volatile long lastHeartbeat;
+
+ RegisteredCard(AgentCard card, long registeredAt) {
+ this.card = card;
+ this.registeredAt = registeredAt;
+ this.lastHeartbeat = registeredAt;
+ }
+ }
+
+ /**
+ * Represents a registered agent card entry with identity, card data, and status.
+ */
+ public static class CardEntry {
+
+ private final AgentIdentity identity;
+ private final AgentCard card;
+ private final String status;
+
+ public CardEntry(AgentIdentity identity, AgentCard card, String status) {
+ this.identity = identity;
+ this.card = card;
+ this.status = status;
+ }
+
+ public AgentIdentity getIdentity() {
+ return identity;
+ }
+
+ public AgentCard getCard() {
+ return card;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public String getNamespace() {
+ return identity.getNamespace();
+ }
+
+ public String getId() {
+ return identity.clientId();
+ }
+
+ public String getName() {
+ return card.getName();
+ }
+
+ public String getVersion() {
+ return card.getVersion();
+ }
+
+ public String getDescription() {
+ return card.getDescription();
+ }
+ }
+
+ /**
+ * Result of a card registration attempt.
+ */
+ public static class RegistrationResult {
+
+ private final boolean success;
+ private final String errorMessage;
+
+ private RegistrationResult(boolean success, String errorMessage) {
+ this.success = success;
+ this.errorMessage = errorMessage;
+ }
+
+ public static RegistrationResult success() {
+ return new RegistrationResult(true, null);
+ }
+
+ public static RegistrationResult failure(String errorMessage) {
+ return new RegistrationResult(false, errorMessage);
+ }
+
+ public boolean isSuccess() {
+ return success;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+ }
+}
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/InMemoryA2AMessageTransport.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/InMemoryA2AMessageTransport.java
new file mode 100644
index 000000000..d7f2f2ed4
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/InMemoryA2AMessageTransport.java
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import org.apache.eventmesh.protocol.a2a.A2AMessageTransport;
+
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import io.cloudevents.CloudEvent;
+
+/**
+ * Simple in-memory implementation of {@link A2AMessageTransport} for testing and PoC.
+ * Messages are delivered directly to subscribers in the same JVM.
+ */
+public class InMemoryA2AMessageTransport implements A2AMessageTransport {
+
+ private static final Logger log = LoggerFactory.getLogger(InMemoryA2AMessageTransport.class);
+
+ private final ConcurrentHashMap<String, Subscription> subscriptions = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, List<Subscription>> topicToSubscriptions = new ConcurrentHashMap<>();
+
+ @Override
+ public void publish(String topic, CloudEvent event) throws Exception {
+ log.debug("InMemory publish to topic: {}", topic);
+ int delivered = 0;
+ for (ConcurrentHashMap.Entry<String, List<Subscription>> entry : topicToSubscriptions.entrySet()) {
+ String pattern = entry.getKey();
+ if (matchesWildcard(pattern, topic)) {
+ for (Subscription sub : entry.getValue()) {
+ sub.callback.onMessage(topic, event);
+ delivered++;
+ }
+ }
+ }
+ if (delivered == 0) {
+ log.debug("No subscribers matched topic: {}", topic);
+ }
+ }
+
+ @Override
+ public String subscribe(String topicPattern, MessageCallback callback) throws Exception {
+ String subId = UUID.randomUUID().toString();
+ Subscription sub = new Subscription(subId, topicPattern, callback);
+ subscriptions.put(subId, sub);
+ topicToSubscriptions.computeIfAbsent(topicPattern, k -> new CopyOnWriteArrayList<>()).add(sub);
+ log.info("InMemory subscribe: pattern={}, subId={}", topicPattern, subId);
+ return subId;
+ }
+
+ @Override
+ public void unsubscribe(String subscriptionId) throws Exception {
+ Subscription sub = subscriptions.remove(subscriptionId);
+ if (sub != null) {
+ List<Subscription> subs = topicToSubscriptions.get(sub.topicPattern);
+ if (subs != null) {
+ subs.remove(sub);
+ if (subs.isEmpty()) {
+ topicToSubscriptions.remove(sub.topicPattern);
+ }
+ }
+ log.info("InMemory unsubscribe: subId={}", subscriptionId);
+ }
+ }
+
+ /**
+ * Simple wildcard matching supporting "+" (single-level).
+ */
+ private boolean matchesWildcard(String pattern, String topic) {
+ if (pattern.equals(topic)) {
+ return true;
+ }
+ String[] patternParts = pattern.split("/");
+ String[] topicParts = topic.split("/");
+ if (patternParts.length != topicParts.length) {
+ return false;
+ }
+ for (int i = 0; i < patternParts.length; i++) {
+ if (!"+".equals(patternParts[i]) && !patternParts[i].equals(topicParts[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static class Subscription {
+
+ final String id;
+ final String topicPattern;
+ final MessageCallback callback;
+
+ Subscription(String id, String topicPattern, MessageCallback callback) {
+ this.id = id;
+ this.topicPattern = topicPattern;
+ this.callback = callback;
+ }
+ }
+}
diff --git a/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/TaskRegistry.java b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/TaskRegistry.java
new file mode 100644
index 000000000..549296447
--- /dev/null
+++ b/eventmesh-runtime/src/main/java/org/apache/eventmesh/runtime/a2a/TaskRegistry.java
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * In-memory registry for A2A task lifecycle management.
+ *
+ * <p>Maintains task state transitions and parent-child task relationships.
+ *
+ * <p>State machine:
+ * <pre>
+ * SUBMITTED -> WORKING -> COMPLETED
+ * \-> FAILED
+ * \-> CANCELLED
+ * </pre>
+ */
+@Slf4j
+public class TaskRegistry {
+
+ public enum TaskState {
+ SUBMITTED,
+ WORKING,
+ COMPLETED,
+ FAILED,
+ CANCELLED
+ }
+
+ public static class TaskEntry {
+
+ private final String taskId;
+ private final String parentTaskId;
+ private final String targetAgent;
+ private final String gatewayId;
+ private final long createdAt;
+ private volatile long updatedAt;
+ private volatile TaskState state;
+ private volatile String result;
+ private volatile String errorMessage;
+
+ public TaskEntry(String taskId, String parentTaskId, String targetAgent, String gatewayId) {
+ this.taskId = taskId;
+ this.parentTaskId = parentTaskId;
+ this.targetAgent = targetAgent;
+ this.gatewayId = gatewayId;
+ this.createdAt = System.currentTimeMillis();
+ this.updatedAt = this.createdAt;
+ this.state = TaskState.SUBMITTED;
+ }
+
+ public String getTaskId() {
+ return taskId;
+ }
+
+ public String getParentTaskId() {
+ return parentTaskId;
+ }
+
+ public String getTargetAgent() {
+ return targetAgent;
+ }
+
+ public String getGatewayId() {
+ return gatewayId;
+ }
+
+ public long getCreatedAt() {
+ return createdAt;
+ }
+
+ public long getUpdatedAt() {
+ return updatedAt;
+ }
+
+ public TaskState getState() {
+ return state;
+ }
+
+ public String getResult() {
+ return result;
+ }
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+ }
+
+ private final ConcurrentHashMap<String, TaskEntry> tasks = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, List<String>> parentToChildren = new ConcurrentHashMap<>();
+
+ // TTL cleanup configuration
+ private static final long DEFAULT_TASK_TTL_MS = 300_000L; // 5 minutes
+ private static final long DEFAULT_TASK_CLEANUP_INTERVAL_MS = 60_000L; // 60 seconds
+ private final long taskTtlMs;
+ private final long cleanupIntervalMs;
+ private ScheduledExecutorService cleanupExecutor;
+ private volatile boolean started = false;
+
+ public TaskRegistry() {
+ this(DEFAULT_TASK_TTL_MS, DEFAULT_TASK_CLEANUP_INTERVAL_MS);
+ }
+
+ public TaskRegistry(long taskTtlMs, long cleanupIntervalMs) {
+ this.taskTtlMs = taskTtlMs;
+ this.cleanupIntervalMs = cleanupIntervalMs;
+ }
+
+ /**
+ * Starts the TTL cleanup scheduler. Terminal-state tasks older than TTL are automatically removed.
+ */
+ public void start() {
+ if (started) {
+ return;
+ }
+ started = true;
+ cleanupExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
+ Thread t = new Thread(r, "a2a-task-ttl-cleanup");
+ t.setDaemon(true);
+ return t;
+ });
+ cleanupExecutor.scheduleAtFixedRate(this::cleanupExpiredTasks,
+ cleanupIntervalMs, cleanupIntervalMs, TimeUnit.MILLISECONDS);
+ log.info("TaskRegistry started (TTL={}ms, cleanup={}ms)", taskTtlMs, cleanupIntervalMs);
+ }
+
+ /**
+ * Shuts down the TTL cleanup scheduler.
+ */
+ public void shutdown() {
+ if (!started) {
+ return;
+ }
+ started = false;
+ if (cleanupExecutor != null) {
+ cleanupExecutor.shutdownNow();
+ cleanupExecutor = null;
+ }
+ log.info("TaskRegistry shut down.");
+ }
+
+ /**
+ * Removes terminal-state tasks whose updatedAt timestamp is older than TTL.
+ */
+ void cleanupExpiredTasks() {
+ if (!started) {
+ return;
+ }
+ long now = System.currentTimeMillis();
+ int removed = 0;
+ Iterator<Map.Entry<String, TaskEntry>> it = tasks.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<String, TaskEntry> entry = it.next();
+ TaskEntry te = entry.getValue();
+ if (isTerminalState(te.getState()) && (now - te.getUpdatedAt()) > taskTtlMs) {
+ it.remove();
+ if (te.getParentTaskId() != null) {
+ List<String> siblings = parentToChildren.get(te.getParentTaskId());
+ if (siblings != null) {
+ siblings.remove(te.getTaskId());
+ }
+ }
+ removed++;
+ }
+ }
+ if (removed > 0) {
+ log.info("TTL cleanup removed {} expired task(s).", removed);
+ }
+ }
+
+ private boolean isTerminalState(TaskState state) {
+ return state == TaskState.COMPLETED || state == TaskState.FAILED || state == TaskState.CANCELLED;
+ }
+
+ /**
+ * Creates a new task entry.
+ *
+ * @param taskId unique task ID
+ * @param parentTaskId parent task ID (null for root tasks)
+ * @param targetAgent target agent name
+ * @param gatewayId gateway ID (null for agent-to-agent tasks)
+ * @return the created task entry
+ */
+ public TaskEntry createTask(String taskId, String parentTaskId, String targetAgent, String gatewayId) {
+ TaskEntry entry = new TaskEntry(taskId, parentTaskId, targetAgent, gatewayId);
+ tasks.put(taskId, entry);
+ if (parentTaskId != null) {
+ parentToChildren.computeIfAbsent(parentTaskId, k -> new CopyOnWriteArrayList<>()).add(taskId);
+ }
+ log.info("Task created: taskId={}, parentTaskId={}, targetAgent={}", taskId, parentTaskId, targetAgent);
+ return entry;
+ }
+
+ /**
+ * Transitions a task to WORKING state.
+ */
+ public boolean markWorking(String taskId) {
+ TaskEntry entry = tasks.get(taskId);
+ if (entry == null) {
+ return false;
+ }
+ synchronized (entry) {
+ if (entry.state != TaskState.SUBMITTED) {
+ log.warn("Cannot mark task {} as WORKING from state {}", taskId, entry.state);
+ return false;
+ }
+ entry.state = TaskState.WORKING;
+ entry.updatedAt = System.currentTimeMillis();
+ }
+ log.info("Task working: taskId={}", taskId);
+ return true;
+ }
+
+ /**
+ * Transitions a task to COMPLETED state with result.
+ */
+ public boolean markCompleted(String taskId, String result) {
+ TaskEntry entry = tasks.get(taskId);
+ if (entry == null) {
+ return false;
+ }
+ synchronized (entry) {
+ if (entry.state == TaskState.COMPLETED || entry.state == TaskState.CANCELLED) {
+ return false;
+ }
+ entry.state = TaskState.COMPLETED;
+ entry.result = result;
+ entry.updatedAt = System.currentTimeMillis();
+ }
+ log.info("Task completed: taskId={}", taskId);
+ return true;
+ }
+
+ /**
+ * Transitions a task to FAILED state with error message.
+ */
+ public boolean markFailed(String taskId, String errorMessage) {
+ TaskEntry entry = tasks.get(taskId);
+ if (entry == null) {
+ return false;
+ }
+ synchronized (entry) {
+ if (entry.state == TaskState.COMPLETED || entry.state == TaskState.CANCELLED) {
+ return false;
+ }
+ entry.state = TaskState.FAILED;
+ entry.errorMessage = errorMessage;
+ entry.updatedAt = System.currentTimeMillis();
+ }
+ log.info("Task failed: taskId={}, error={}", taskId, errorMessage);
+ return true;
+ }
+
+ /**
+ * Transitions a task to CANCELLED state.
+ */
+ public boolean markCancelled(String taskId) {
+ TaskEntry entry = tasks.get(taskId);
+ if (entry == null) {
+ return false;
+ }
+ synchronized (entry) {
+ if (entry.state == TaskState.COMPLETED || entry.state == TaskState.CANCELLED) {
+ return false;
+ }
+ entry.state = TaskState.CANCELLED;
+ entry.updatedAt = System.currentTimeMillis();
+ }
+ log.info("Task cancelled: taskId={}", taskId);
+ return true;
+ }
+
+ /**
+ * Gets a task entry by ID.
+ */
+ public TaskEntry getTask(String taskId) {
+ return tasks.get(taskId);
+ }
+
+ /**
+ * Lists all tasks.
+ */
+ public List<TaskEntry> listTasks() {
+ return new ArrayList<>(tasks.values());
+ }
+
+ /**
+ * Lists child tasks of a parent task.
+ */
+ public List<String> getChildTasks(String parentTaskId) {
+ List<String> children = parentToChildren.get(parentTaskId);
+ return children != null ? new ArrayList<>(children) : new ArrayList<>();
+ }
+
+ /**
+ * Removes a task from the registry.
+ */
+ public TaskEntry removeTask(String taskId) {
+ TaskEntry removed = tasks.remove(taskId);
+ if (removed != null && removed.parentTaskId != null) {
+ List<String> siblings = parentToChildren.get(removed.parentTaskId);
+ if (siblings != null) {
+ siblings.remove(taskId);
+ }
+ }
+ return removed;
+ }
+
+ /**
+ * Returns the current size of the registry.
+ */
+ public int size() {
+ return tasks.size();
+ }
+
+ /**
+ * Clears all tasks.
+ */
+ public void clear() {
+ tasks.clear();
+ parentToChildren.clear();
+ }
+}
diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AClientServerIntegrationTest.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AClientServerIntegrationTest.java
new file mode 100644
index 000000000..f22d3b2e0
--- /dev/null
+++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AClientServerIntegrationTest.java
@@ -0,0 +1,481 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.apache.eventmesh.protocol.a2a.A2AClient;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpOptions;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ * True client-server HTTP integration test.
+ *
+ * <p>Starts {@link A2AGatewayServer} on a random port, then uses {@link A2AClient}
+ * to exercise all A2A functionality over real HTTP:
+ * <ul>
+ * <li>Agent card registration</li>
+ * <li>Agent listing</li>
+ * <li>Sync task submission + response</li>
+ * <li>Task status query</li>
+ * <li>Async task submission + cancellation</li>
+ * <li>Heartbeat</li>
+ * </ul>
+ *
+ * <p>This test covers the full network path: A2AClient → HTTP → Netty → A2AGatewayHttpHandler → A2AGatewayService.
+ */
+class A2AClientServerIntegrationTest {
+
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ private A2AGatewayServer server;
+ private String gatewayUrl;
+ private A2AClient client;
+ private CloseableHttpClient rawHttpClient;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ // Start server on random port
+ server = new A2AGatewayServer(0);
+ server.start();
+ int port = server.getBoundPort();
+ gatewayUrl = "http://localhost:" + port;
+
+ // Create and start client (registers agent card + starts heartbeat)
+ client = A2AClient.builder()
+ .gatewayUrl(gatewayUrl)
+ .namespace("global")
+ .agentName("default/default/test-client-agent")
+ .agentCard(AgentCardTestUtils.createValidCard("test-client-agent"))
+ .heartbeatInterval(60_000L) // long interval so it doesn't interfere with tests
+ .socketTimeoutMs(30_000)
+ .build();
+ client.start();
+
+ rawHttpClient = HttpClients.createDefault();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ if (client != null) {
+ client.shutdown();
+ }
+ if (rawHttpClient != null) {
+ rawHttpClient.close();
+ }
+ if (server != null) {
+ server.shutdown();
+ }
+ }
+
+ /**
+ * Registers an agent card via HTTP without subscribing to request topics.
+ * The agent is "registered" but never responds — useful for testing async/cancel flows.
+ */
+ private void registerSlowAgent(String agentName) throws Exception {
+ Map<String, Object> card = new HashMap<>();
+ card.put("name", agentName);
+ card.put("version", "1.0.0");
+ card.put("description", "A slow agent for testing");
+
+ // Required fields for schema validation
+ Map<String, Object> iface = new HashMap<>();
+ iface.put("url", "http://localhost/a2a");
+ iface.put("protocolBinding", "JSONRPC");
+ iface.put("protocolVersion", "0.3");
+ java.util.List<Map<String, Object>> interfaces = new java.util.ArrayList<>();
+ interfaces.add(iface);
+ card.put("supportedInterfaces", interfaces);
+
+ Map<String, Object> capabilities = new HashMap<>();
+ capabilities.put("streaming", false);
+ capabilities.put("pushNotifications", false);
+ card.put("capabilities", capabilities);
+
+ card.put("defaultInputModes", java.util.Collections.singletonList("text/plain"));
+ card.put("defaultOutputModes", java.util.Collections.singletonList("text/plain"));
+
+ Map<String, Object> skill = new HashMap<>();
+ skill.put("id", "slow-skill");
+ skill.put("name", "Slow Skill");
+ skill.put("description", "Does nothing");
+ skill.put("tags", java.util.Collections.singletonList("test"));
+ java.util.List<Map<String, Object>> skills = new java.util.ArrayList<>();
+ skills.add(skill);
+ card.put("skills", skills);
+
+ HttpPost post = new HttpPost(gatewayUrl + "/a2a/cards/card/default/default/" + agentName);
+ post.setHeader("Content-Type", "application/json");
+ post.setEntity(new StringEntity(objectMapper.writeValueAsString(card), StandardCharsets.UTF_8));
+ HttpResponse response = rawHttpClient.execute(post);
+ int status = response.getStatusLine().getStatusCode();
+ if (status >= 400) {
+ String body = response.getEntity() != null
+ ? EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8) : "";
+ throw new RuntimeException("Failed to register slow agent: " + status + " " + body);
+ }
+ }
+
+ // =========================================================================
+ // Agent Card Registration & Listing
+ // =========================================================================
+
+ @Test
+ void testPreRegisteredWeatherAgentIsListed() throws Exception {
+ List<String> agents = client.listAgents();
+ assertNotNull(agents);
+ assertTrue(agents.contains("weather-agent"),
+ "Pre-registered weather-agent should appear in agent list: " + agents);
+ }
+
+ @Test
+ void testClientAgentRegistrationAppearsInList() throws Exception {
+ List<String> agents = client.listAgents();
+ assertNotNull(agents);
+ assertTrue(agents.contains("test-client-agent"),
+ "Client-registered test-client-agent should appear in agent list: " + agents);
+ }
+
+ // =========================================================================
+ // Sync Task Submission
+ // =========================================================================
+
+ @Test
+ void testSubmitTaskSyncToWeatherAgent() throws Exception {
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "Beijing", null);
+
+ assertNotNull(result);
+ assertNotNull(result.getTaskId(), "taskId should be returned in sync response");
+ assertEquals("COMPLETED", result.getState());
+ assertNotNull(result.getData());
+ assertTrue(result.getData().contains("Beijing"), "Response should mention Beijing: " + result.getData());
+ assertTrue(result.getData().contains("sunny"), "Response should mention sunny: " + result.getData());
+ }
+
+ @Test
+ void testSubmitTaskSyncReturnsValidTaskId() throws Exception {
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "Shanghai", null);
+
+ assertNotNull(result.getTaskId());
+ assertTrue(result.getTaskId().startsWith("task-"),
+ "Task ID should start with 'task-': " + result.getTaskId());
+ }
+
+ // =========================================================================
+ // Task Status Query
+ // =========================================================================
+
+ @Test
+ void testGetTaskStatusAfterCompletion() throws Exception {
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "Guangzhou", null);
+ String taskId = result.getTaskId();
+ assertNotNull(taskId);
+
+ // Query status via HTTP GET
+ A2AClient.TaskResult status = client.getTaskStatus(taskId);
+ assertNotNull(status);
+ assertEquals(taskId, status.getTaskId());
+ assertEquals("COMPLETED", status.getState());
+ assertEquals("weather-agent", status.getTargetAgent());
+ assertNotNull(status.getData());
+ assertTrue(status.getData().contains("Guangzhou"));
+ }
+
+ @Test
+ void testGetTaskStatusNotFound() throws Exception {
+ A2AClient.TaskResult status = client.getTaskStatus("non-existent-task-id");
+ assertNotNull(status);
+ // Server returns 404 with error JSON; Jackson maps it to TaskResult.error
+ assertTrue(status.getError() != null || status.getState() == null,
+ "Should return error for non-existent task");
+ }
+
+ // =========================================================================
+ // Async Task + Cancellation
+ // =========================================================================
+
+ @Test
+ void testSubmitAsyncTaskAndGetStatus() throws Exception {
+ // Register a slow agent that doesn't respond (card registered but no request handler)
+ registerSlowAgent("slow-agent");
+
+ String taskId = client.sendTaskAsync("slow-agent", "test message", null);
+ assertNotNull(taskId);
+ assertTrue(taskId.startsWith("task-"));
+
+ // Query status — should be SUBMITTED
+ A2AClient.TaskResult status = client.getTaskStatus(taskId);
+ assertNotNull(status);
+ assertEquals(taskId, status.getTaskId());
+ assertEquals("SUBMITTED", status.getState());
+ }
+
+ @Test
+ void testCancelTask() throws Exception {
+ // Register a slow agent that doesn't respond
+ registerSlowAgent("slow-agent");
+
+ String taskId = client.sendTaskAsync("slow-agent", "cancel me", null);
+ assertNotNull(taskId);
+
+ // Cancel the task
+ boolean cancelled = client.cancelTask(taskId);
+ assertTrue(cancelled, "Task should be cancellable");
+
+ // Verify state is CANCELLED
+ A2AClient.TaskResult status = client.getTaskStatus(taskId);
+ assertNotNull(status);
+ assertEquals("CANCELLED", status.getState());
+ }
+
+ @Test
+ void testCancelCompletedTaskFails() throws Exception {
+ // Submit sync to weather-agent (completes immediately)
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "Shenzhen", null);
+ String taskId = result.getTaskId();
+
+ // Try to cancel a completed task — should fail
+ boolean cancelled = client.cancelTask(taskId);
+ assertFalse(cancelled, "Completed task should not be cancellable");
+ }
+
+ @Test
+ void testCancelNonExistentTaskFails() throws Exception {
+ boolean cancelled = client.cancelTask("fake-task-id-99999");
+ assertFalse(cancelled, "Non-existent task should not be cancellable");
+ }
+
+ // =========================================================================
+ // Agent Validation
+ // =========================================================================
+
+ @Test
+ void testSubmitTaskToUnregisteredAgentFails() throws Exception {
+ // Attempt to submit a task to an agent that is not registered
+ try {
+ client.sendTaskSync("ghost-agent-not-registered", "hello", null);
+ org.junit.jupiter.api.Assertions.fail(
+ "Should throw exception for unregistered agent");
+ } catch (Exception e) {
+ // Expected: server returns 400 because agent is not registered
+ assertTrue(e.getMessage().contains("not registered")
+ || e.getMessage().contains("400")
+ || e.getMessage().contains("Task submission failed"),
+ "Error should mention unregistered agent: " + e.getMessage());
+ }
+ }
+
+ // =========================================================================
+ // Task Listing
+ // =========================================================================
+
+ @Test
+ void testListTasksEndpoint() throws Exception {
+ // Submit a task that completes
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "ListTest", null);
+ assertNotNull(result.getTaskId());
+
+ // List all tasks via HTTP GET /a2a/tasks
+ HttpGet get = new HttpGet(gatewayUrl + "/a2a/tasks");
+ HttpResponse response = rawHttpClient.execute(get);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+ Map<?, ?> listResponse = objectMapper.readValue(body, Map.class);
+ assertNotNull(listResponse.get("total"));
+ assertNotNull(listResponse.get("count"));
+ assertEquals(100, listResponse.get("limit"));
+ assertEquals(0, listResponse.get("offset"));
+ assertNotNull(listResponse.get("hasMore"));
+ assertNotNull(listResponse.get("tasks"));
+ }
+
+ @Test
+ void testListTasksEndpointWithPagination() throws Exception {
+ client.sendTaskSync("weather-agent", "PageTest-1", null);
+ client.sendTaskSync("weather-agent", "PageTest-2", null);
+ client.sendTaskSync("weather-agent", "PageTest-3", null);
+
+ HttpGet get = new HttpGet(gatewayUrl + "/a2a/tasks?state=COMPLETED&limit=2&offset=1");
+ HttpResponse response = rawHttpClient.execute(get);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+ Map<?, ?> listResponse = objectMapper.readValue(body, Map.class);
+ assertEquals(2, listResponse.get("limit"));
+ assertEquals(1, listResponse.get("offset"));
+ assertTrue(((Number) listResponse.get("count")).intValue() <= 2);
+ assertNotNull(listResponse.get("tasks"));
+ }
+
+ @Test
+ void testHealthEndpoint() throws Exception {
+ HttpGet get = new HttpGet(gatewayUrl + "/a2a/health");
+ HttpResponse response = rawHttpClient.execute(get);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ String body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+ Map<?, ?> health = objectMapper.readValue(body, Map.class);
+ assertEquals("UP", health.get("status"));
+ assertNotNull(health.get("gatewayId"));
+ assertNotNull(health.get("namespace"));
+ assertNotNull(health.get("taskCount"));
+ assertNotNull(health.get("agentCount"));
+ assertNotNull(health.get("timestamp"));
+ }
+
+ @Test
+ void testCorsPreflightEndpoint() throws Exception {
+ HttpOptions options = new HttpOptions(gatewayUrl + "/a2a/tasks");
+ HttpResponse response = rawHttpClient.execute(options);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+ assertEquals("*", response.getFirstHeader("Access-Control-Allow-Origin").getValue());
+ assertTrue(response.getFirstHeader("Access-Control-Allow-Methods").getValue().contains("OPTIONS"));
+ assertTrue(response.getFirstHeader("Access-Control-Allow-Headers").getValue().contains("Content-Type"));
+ }
+
+ @Test
+ void testSseStreamThroughClientSdk() throws Exception {
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", "SSE-City", null);
+ AtomicInteger eventCount = new AtomicInteger(0);
+ String[] lastState = new String[1];
+ String[] lastData = new String[1];
+
+ // Build a short-timeout client for this bounded terminal-state SSE test.
+ try (A2AClient sseClient = A2AClient.builder()
+ .gatewayUrl(gatewayUrl)
+ .namespace("global")
+ .agentName("default/default/test-sse-client-agent")
+ .agentCard(AgentCardTestUtils.createValidCard("test-sse-client-agent"))
+ .heartbeatInterval(60_000L)
+ .socketTimeoutMs(1_000)
+ .build()) {
+ sseClient.streamTaskStatus(result.getTaskId(), (taskId, state, data) -> {
+ eventCount.incrementAndGet();
+ lastState[0] = state;
+ lastData[0] = data;
+ return true;
+ });
+ }
+
+ assertTrue(eventCount.get() >= 1);
+ assertEquals("COMPLETED", lastState[0]);
+ assertTrue(lastData[0].contains("SSE-City"));
+ }
+
+ // =========================================================================
+ // Heartbeat
+ // =========================================================================
+
+ @Test
+ void testHeartbeatForRegisteredAgent() throws Exception {
+ // Send heartbeat for the pre-registered weather-agent
+ Map<String, String> body = new HashMap<>();
+ body.put("orgId", "default");
+ body.put("unitId", "default");
+ body.put("agentId", "weather-agent");
+
+ HttpPost post = new HttpPost(gatewayUrl + "/a2a/heartbeat");
+ post.setHeader("Content-Type", "application/json");
+ post.setEntity(new StringEntity(objectMapper.writeValueAsString(body), StandardCharsets.UTF_8));
+
+ HttpResponse response = rawHttpClient.execute(post);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ String respBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+ Map<?, ?> result = objectMapper.readValue(respBody, Map.class);
+ assertEquals(true, result.get("ok"), "Heartbeat for registered agent should succeed: " + respBody);
+ }
+
+ @Test
+ void testHeartbeatForUnregisteredAgentFails() throws Exception {
+ Map<String, String> body = new HashMap<>();
+ body.put("orgId", "default");
+ body.put("unitId", "default");
+ body.put("agentId", "ghost-agent");
+
+ HttpPost post = new HttpPost(gatewayUrl + "/a2a/heartbeat");
+ post.setHeader("Content-Type", "application/json");
+ post.setEntity(new StringEntity(objectMapper.writeValueAsString(body), StandardCharsets.UTF_8));
+
+ HttpResponse response = rawHttpClient.execute(post);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ String respBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
+ Map<?, ?> result = objectMapper.readValue(respBody, Map.class);
+ assertEquals(false, result.get("ok"), "Heartbeat for unregistered agent should fail: " + respBody);
+ }
+
+ // =========================================================================
+ // Multiple Tasks / Concurrency
+ // =========================================================================
+
+ @Test
+ void testMultipleSyncTasks() throws Exception {
+ String[] cities = {"Beijing", "Shanghai", "Guangzhou"};
+ for (String city : cities) {
+ A2AClient.TaskResult result = client.sendTaskSync("weather-agent", city, null);
+ assertEquals("COMPLETED", result.getState());
+ assertTrue(result.getData().contains(city),
+ "Response for " + city + " should mention the city: " + result.getData());
+ }
+ }
+
+ @Test
+ void testParentChildTaskViaHttp() throws Exception {
+ // Submit parent task (sync)
+ A2AClient.TaskResult parentResult = client.sendTaskSync("weather-agent", "parent", null);
+ String parentTaskId = parentResult.getTaskId();
+
+ // Submit child task with parentTaskId (sync)
+ A2AClient.TaskResult childResult = client.sendTaskSync("weather-agent", "child", parentTaskId);
+ String childTaskId = childResult.getTaskId();
+
+ assertNotNull(parentTaskId);
+ assertNotNull(childTaskId);
+ assertFalse(parentTaskId.equals(childTaskId), "Parent and child task IDs should differ");
+
+ // Verify child task has parentTaskId set
+ A2AClient.TaskResult childStatus = client.getTaskStatus(childTaskId);
+ assertNotNull(childStatus);
+ assertEquals(parentTaskId, childStatus.getParentTaskId(),
+ "Child task should reference parent task ID");
+ }
+}
diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AGatewayEndToEndTest.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AGatewayEndToEndTest.java
new file mode 100644
index 000000000..aedaba51b
--- /dev/null
+++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AGatewayEndToEndTest.java
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.apache.eventmesh.protocol.a2a.A2AProtocolConstants;
+import org.apache.eventmesh.protocol.a2a.A2ATopicFactory;
+import org.apache.eventmesh.protocol.a2a.AgentIdentity;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+
+import java.nio.charset.StandardCharsets;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+/**
+ * End-to-end test for A2A Gateway: task submission, agent response, and task registry.
+ */
+class A2AGatewayEndToEndTest {
+
+ private InMemoryA2AMessageTransport transport;
+ private TaskRegistry taskRegistry;
+ private A2APublishSubscribeService a2aService;
+ private A2AGatewayService gateway;
+
+ private static final String NAMESPACE = "global";
+ private static final String GATEWAY_ID = "test-gateway";
+ private static final String AGENT_NAME = "echo-agent";
+
+ @BeforeEach
+ void setUp() throws Exception {
+ transport = new InMemoryA2AMessageTransport();
+ taskRegistry = new TaskRegistry();
+ a2aService = new A2APublishSubscribeService();
+ a2aService.init();
+ a2aService.start();
+ gateway = new A2AGatewayService(NAMESPACE, GATEWAY_ID, transport, taskRegistry, a2aService);
+ gateway.start();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ gateway.shutdown();
+ a2aService.shutdown();
+ }
+
+ @Test
+ void testTaskSubmissionAndResponse() throws Exception {
+ // Register agent
+ AgentCard card = AgentCardTestUtils.createValidCard(AGENT_NAME);
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId("default").unitId("default").agentId(AGENT_NAME).build();
+ a2aService.registerCard(identity, card);
+
+ // Agent subscribes to request topic
+ String requestTopic = A2ATopicFactory.agentRequestTopic(NAMESPACE, AGENT_NAME);
+ transport.subscribe(requestTopic, (topic, event) -> {
+ String taskId = event.getId();
+ String responseTopic = A2ATopicFactory.gatewayResponseTopic(NAMESPACE, GATEWAY_ID, taskId);
+ CloudEvent response = CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withType(A2AProtocolConstants.CE_TYPE_PREFIX + "task.response")
+ .withSource(java.net.URI.create("agent/" + AGENT_NAME))
+ .withData("echo: hello".getBytes(StandardCharsets.UTF_8))
+ .build();
+ try {
+ transport.publish(responseTopic, response);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ // Submit task
+ java.util.concurrent.CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask(AGENT_NAME, "hello", null);
+
+ A2AGatewayService.TaskResult result = future.get(10, TimeUnit.SECONDS);
+
+ assertNotNull(result);
+ assertEquals(TaskRegistry.TaskState.COMPLETED, result.getState());
+ assertEquals("echo: hello", result.getData());
+ }
+
+ @Test
+ void testTaskRegistryLifecycle() {
+ String taskId = "test-task-001";
+ taskRegistry.createTask(taskId, null, "test-agent", "test-gateway");
+
+ assertEquals(TaskRegistry.TaskState.SUBMITTED, taskRegistry.getTask(taskId).getState());
+
+ assertTrue(taskRegistry.markWorking(taskId));
+ assertEquals(TaskRegistry.TaskState.WORKING, taskRegistry.getTask(taskId).getState());
+
+ assertTrue(taskRegistry.markCompleted(taskId, "done"));
+ assertEquals(TaskRegistry.TaskState.COMPLETED, taskRegistry.getTask(taskId).getState());
+ assertEquals("done", taskRegistry.getTask(taskId).getResult());
+ }
+
+ @Test
+ void testTaskCancellation() {
+ String taskId = "test-task-cancel";
+ taskRegistry.createTask(taskId, null, "test-agent", "test-gateway");
+
+ assertTrue(taskRegistry.markCancelled(taskId));
+ assertEquals(TaskRegistry.TaskState.CANCELLED, taskRegistry.getTask(taskId).getState());
+ }
+
+ @Test
+ void testParentChildTaskRelationship() {
+ String parentId = "parent-task";
+ String childId = "child-task";
+
+ taskRegistry.createTask(parentId, null, "agent-a", "gateway-1");
+ taskRegistry.createTask(childId, parentId, "agent-b", "gateway-1");
+
+ java.util.List<String> children = taskRegistry.getChildTasks(parentId);
+ assertEquals(1, children.size());
+ assertEquals(childId, children.get(0));
+ }
+
+ @Test
+ void testAgentCardTtlExpiry() throws Exception {
+ // Use a very short TTL for testing
+ a2aService.shutdown();
+ a2aService = new A2APublishSubscribeService(100L, 50L);
+ a2aService.init();
+ a2aService.start();
+
+ AgentCard card = AgentCardTestUtils.createValidCard("ttl-agent");
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId("default").unitId("default").agentId("ttl-agent").build();
+
+ a2aService.registerCard(identity, card);
+ assertNotNull(a2aService.getCard(identity));
+
+ // Wait for TTL to expire
+ Thread.sleep(300);
+
+ // Force cleanup
+ a2aService.cleanupExpiredCards();
+
+ // Card should be removed
+ assertEquals(null, a2aService.getCard(identity));
+ }
+
+ @Test
+ void testHeartbeatRefreshesTtl() throws Exception {
+ a2aService.shutdown();
+ a2aService = new A2APublishSubscribeService(500L, 250L);
+ a2aService.init();
+ a2aService.start();
+
+ AgentCard card = AgentCardTestUtils.createValidCard("hb-agent");
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId("default").unitId("default").agentId("hb-agent").build();
+
+ a2aService.registerCard(identity, card);
+
+ // Heartbeat before TTL expires
+ Thread.sleep(250);
+ assertTrue(a2aService.heartbeat(identity), "heartbeat should succeed before TTL");
+
+ // Should still be registered
+ Thread.sleep(100);
+ assertNotNull(a2aService.getCard(identity), "card should still exist after heartbeat refresh");
+ }
+
+ @Test
+ void testTopicFactoryGeneratesCorrectTopics() {
+ // Agent topics
+ assertEquals("a2a/v1/agent/request/weather-agent",
+ A2ATopicFactory.agentRequestTopic("global", "weather-agent"));
+ assertEquals("a2a/v1/agent/status/weather-agent/task-123",
+ A2ATopicFactory.agentStatusTopic("global", "weather-agent", "task-123"));
+ assertEquals("a2a/v1/agent/response/weather-agent/task-123",
+ A2ATopicFactory.agentResponseTopic("global", "weather-agent", "task-123"));
+
+ // Gateway topics
+ assertEquals("a2a/v1/gateway/status/gw-1/task-456",
+ A2ATopicFactory.gatewayStatusTopic("global", "gw-1", "task-456"));
+ assertEquals("a2a/v1/gateway/response/gw-1/task-456",
+ A2ATopicFactory.gatewayResponseTopic("global", "gw-1", "task-456"));
+
+ // Discovery topics
+ assertEquals("a2a/v1/discovery/agentcards",
+ A2ATopicFactory.discoveryTopic("global"));
+
+ // Namespaced topics
+ assertEquals("myorg/a2a/v1/agent/request/weather-agent",
+ A2ATopicFactory.agentRequestTopic("myorg", "weather-agent"));
+ }
+
+ @Test
+ void testTopicFactoryParsing() {
+ A2ATopicFactory.ParsedTopic parsed = A2ATopicFactory.parse("a2a/v1/agent/request/weather-agent");
+ assertNotNull(parsed);
+ assertEquals(A2ATopicFactory.EntityType.AGENT_REQUEST, parsed.getEntityType());
+ assertEquals("weather-agent", parsed.getAgentName());
+
+ parsed = A2ATopicFactory.parse("a2a/v1/gateway/response/gw-1/task-789");
+ assertNotNull(parsed);
+ assertEquals(A2ATopicFactory.EntityType.GATEWAY_RESPONSE, parsed.getEntityType());
+ assertEquals("gw-1", parsed.getGatewayId());
+ assertEquals("task-789", parsed.getTaskId());
+
+ parsed = A2ATopicFactory.parse("a2a/v1/discovery/agentcards");
+ assertNotNull(parsed);
+ assertEquals(A2ATopicFactory.EntityType.DISCOVERY_AGENT, parsed.getEntityType());
+ }
+}
diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AGatewayServiceTest.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AGatewayServiceTest.java
new file mode 100644
index 000000000..c5e101607
--- /dev/null
+++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/A2AGatewayServiceTest.java
@@ -0,0 +1,406 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.apache.eventmesh.protocol.a2a.A2AProtocolConstants;
+import org.apache.eventmesh.protocol.a2a.A2ATopicFactory;
+import org.apache.eventmesh.protocol.a2a.AgentIdentity;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+
+import java.nio.charset.StandardCharsets;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+/**
+ * Unit tests for {@link A2AGatewayService}.
+ */
+class A2AGatewayServiceTest {
+
+ private InMemoryA2AMessageTransport transport;
+ private TaskRegistry taskRegistry;
+ private A2APublishSubscribeService a2aService;
+ private A2AGatewayService gateway;
+
+ private static final String NAMESPACE = "global";
+ private static final String GATEWAY_ID = "test-gateway";
+
+ @BeforeEach
+ void setUp() throws Exception {
+ transport = new InMemoryA2AMessageTransport();
+ taskRegistry = new TaskRegistry();
+ a2aService = new A2APublishSubscribeService();
+ a2aService.init();
+ a2aService.start();
+ gateway = new A2AGatewayService(NAMESPACE, GATEWAY_ID, transport, taskRegistry, a2aService);
+ gateway.start();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ gateway.shutdown();
+ a2aService.shutdown();
+ }
+
+ // =========================================================================
+ // Helpers
+ // =========================================================================
+
+ private void registerAgent(String agentName) {
+ AgentCard card = AgentCardTestUtils.createValidCard(agentName);
+ AgentIdentity identity = AgentIdentity.builder()
+ .orgId("default").unitId("default").agentId(agentName).build();
+ a2aService.registerCard(identity, card);
+ }
+
+ private void subscribeEchoAgent(String agentName) throws Exception {
+ String requestTopic = A2ATopicFactory.agentRequestTopic(NAMESPACE, agentName);
+ transport.subscribe(requestTopic, (topic, event) -> {
+ String taskId = event.getId();
+ String data = event.getData() != null
+ ? new String(event.getData().toBytes(), StandardCharsets.UTF_8) : "";
+ String responseTopic = A2ATopicFactory.gatewayResponseTopic(NAMESPACE, GATEWAY_ID, taskId);
+ CloudEvent response = CloudEventBuilder.v1()
+ .withId(UUID.randomUUID().toString())
+ .withType(A2AProtocolConstants.CE_TYPE_PREFIX + "task.response")
+ .withSource(java.net.URI.create("agent/" + agentName))
+ .withData(("echo: " + data).getBytes(StandardCharsets.UTF_8))
+ .build();
+ try {
+ transport.publish(responseTopic, response);
+ } catch (Exception e) {
+ // ignore
+ }
+ });
+ }
+
+ // =========================================================================
+ // Task submission and response
+ // =========================================================================
+
+ @Test
+ void testSubmitTaskAndReceiveResponse() throws Exception {
+ registerAgent("echo-agent");
+ subscribeEchoAgent("echo-agent");
+
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("echo-agent", "hello", null);
+
+ A2AGatewayService.TaskResult result = future.get(10, TimeUnit.SECONDS);
+ assertNotNull(result);
+ assertEquals(TaskRegistry.TaskState.COMPLETED, result.getState());
+ assertEquals("echo: hello", result.getData());
+ }
+
+ @Test
+ void testTaskRegistryUpdatedAfterResponse() throws Exception {
+ registerAgent("echo-agent");
+ subscribeEchoAgent("echo-agent");
+
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("echo-agent", "test", null);
+ future.get(10, TimeUnit.SECONDS);
+
+ assertEquals(1, taskRegistry.size());
+ TaskRegistry.TaskEntry entry = taskRegistry.listTasks().get(0);
+ assertEquals(TaskRegistry.TaskState.COMPLETED, entry.getState());
+ assertEquals("echo: test", entry.getResult());
+ assertEquals("echo-agent", entry.getTargetAgent());
+ assertEquals(GATEWAY_ID, entry.getGatewayId());
+ }
+
+ @Test
+ void testSubmitTaskWithParentTaskId() throws Exception {
+ registerAgent("echo-agent");
+ subscribeEchoAgent("echo-agent");
+
+ String parentTaskId = "parent-task-001";
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("echo-agent", "child-msg", parentTaskId);
+ future.get(10, TimeUnit.SECONDS);
+
+ TaskRegistry.TaskEntry entry = taskRegistry.listTasks().get(0);
+ assertEquals(parentTaskId, entry.getParentTaskId());
+ }
+
+ // =========================================================================
+ // Task cancellation
+ // =========================================================================
+
+ @Test
+ void testCancelTask() {
+ // Register an agent that never responds
+ registerAgent("slow-agent");
+
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("slow-agent", "hello", null);
+
+ // Cancel before response
+ boolean cancelled = gateway.cancelTask(
+ taskRegistry.listTasks().get(0).getTaskId());
+
+ assertTrue(cancelled);
+ TaskRegistry.TaskEntry entry = taskRegistry.listTasks().get(0);
+ assertEquals(TaskRegistry.TaskState.CANCELLED, entry.getState());
+
+ // Future should be completed with CANCELLED
+ A2AGatewayService.TaskResult result = future.getNow(null);
+ assertNotNull(result);
+ assertEquals(TaskRegistry.TaskState.CANCELLED, result.getState());
+ }
+
+ @Test
+ void testCancelNonExistentTask() {
+ assertFalse(gateway.cancelTask("nonexistent-task"));
+ }
+
+ // =========================================================================
+ // Get task status
+ // =========================================================================
+
+ @Test
+ void testGetTaskStatus() {
+ registerAgent("echo-agent");
+
+ gateway.submitTask("echo-agent", "hello", null);
+ String taskId = taskRegistry.listTasks().get(0).getTaskId();
+
+ TaskRegistry.TaskEntry entry = gateway.getTaskStatus(taskId);
+ assertNotNull(entry);
+ assertEquals(taskId, entry.getTaskId());
+ assertEquals(TaskRegistry.TaskState.SUBMITTED, entry.getState());
+ }
+
+ @Test
+ void testGetTaskStatusNonExistent() {
+ assertNull(gateway.getTaskStatus("nonexistent"));
+ }
+
+ // =========================================================================
+ // Status subscriber (SSE)
+ // =========================================================================
+
+ @Test
+ void testStatusSubscriberNotifiedOnResponse() throws Exception {
+ registerAgent("echo-agent");
+ subscribeEchoAgent("echo-agent");
+
+ AtomicInteger notifications = new AtomicInteger(0);
+ String[] lastState = new String[1];
+
+ // Use a known task ID so we can register subscriber before submitting
+ String taskId = "status-test-task-001";
+ gateway.registerStatusSubscriber(taskId, (tid, state, data) -> {
+ lastState[0] = state;
+ notifications.incrementAndGet();
+ });
+
+ // Submit task — InMemory transport is synchronous, so subscriber must be registered first
+ gateway.submitTask(taskId, "echo-agent", "hello", null);
+
+ // Give async processing time to complete
+ Thread.sleep(500);
+
+ assertTrue(notifications.get() >= 1);
+ assertEquals("completed", lastState[0]);
+ }
+
+ // =========================================================================
+ // Agent-to-agent delegation
+ // =========================================================================
+
+ @Test
+ void testAgentDelegation() throws Exception {
+ // Agent A delegates to Agent B
+ registerAgent("agent-a");
+ registerAgent("agent-b");
+
+ // Agent B responds
+ subscribeEchoAgent("agent-b");
+
+ // Agent A receives request, then delegates to Agent B
+ String agentARequestTopic = A2ATopicFactory.agentRequestTopic(NAMESPACE, "agent-a");
+ transport.subscribe(agentARequestTopic, (topic, event) -> {
+ String taskId = event.getId();
+ // Agent A delegates to Agent B
+ String delegateTopic = A2ATopicFactory.agentRequestTopic(NAMESPACE, "agent-b");
+ CloudEvent delegatedEvent = CloudEventBuilder.v1()
+ .withId(taskId) // use same task ID for simplicity
+ .withType(A2AProtocolConstants.CE_TYPE_PREFIX + "task.delegate")
+ .withSource(java.net.URI.create("agent/agent-a"))
+ .withData("delegated".getBytes(StandardCharsets.UTF_8))
+ .build();
+ try {
+ transport.publish(delegateTopic, delegatedEvent);
+ } catch (Exception e) {
+ // ignore
+ }
+ });
+
+ // Also subscribe Agent A to publish response back to gateway
+ // Actually, Agent B's echo response goes to gateway, not Agent A
+ // Let's simplify: Agent B's response goes to gateway
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("agent-b", "delegation-test", null);
+
+ A2AGatewayService.TaskResult result = future.get(10, TimeUnit.SECONDS);
+ assertNotNull(result);
+ assertEquals(TaskRegistry.TaskState.COMPLETED, result.getState());
+ assertEquals("echo: delegation-test", result.getData());
+ }
+
+ // =========================================================================
+ // Gateway not started
+ // =========================================================================
+
+ @Test
+ void testSubmitTaskBeforeStartFails() throws Exception {
+ gateway.shutdown();
+ gateway = new A2AGatewayService(NAMESPACE, GATEWAY_ID, transport, taskRegistry, a2aService);
+ // Don't start
+
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("test-agent", "hello", null);
+
+ assertTrue(future.isCompletedExceptionally());
+ }
+
+ // =========================================================================
+ // Multiple tasks
+ // =========================================================================
+
+ @Test
+ void testMultipleConcurrentTasks() throws Exception {
+ registerAgent("echo-agent");
+ subscribeEchoAgent("echo-agent");
+
+ CompletableFuture<A2AGatewayService.TaskResult> f1 = gateway.submitTask("echo-agent", "msg1", null);
+ CompletableFuture<A2AGatewayService.TaskResult> f2 = gateway.submitTask("echo-agent", "msg2", null);
+ CompletableFuture<A2AGatewayService.TaskResult> f3 = gateway.submitTask("echo-agent", "msg3", null);
+
+ assertEquals("echo: msg1", f1.get(10, TimeUnit.SECONDS).getData());
+ assertEquals("echo: msg2", f2.get(10, TimeUnit.SECONDS).getData());
+ assertEquals("echo: msg3", f3.get(10, TimeUnit.SECONDS).getData());
+
+ assertEquals(3, taskRegistry.size());
+ }
+
+ // =========================================================================
+ // Gateway properties
+ // =========================================================================
+
+ @Test
+ void testGatewayId() {
+ assertEquals(GATEWAY_ID, gateway.getGatewayId());
+ }
+
+ @Test
+ void testNamespace() {
+ assertEquals(NAMESPACE, gateway.getNamespace());
+ }
+
+ @Test
+ void testGetA2aService() {
+ assertNotNull(gateway.getA2aService());
+ }
+
+ @Test
+ void testGetTaskRegistry() {
+ assertNotNull(gateway.getTaskRegistry());
+ }
+
+ // =========================================================================
+ // Task Timeout
+ // =========================================================================
+
+ @Test
+ void testTaskTimeoutAutoFails() throws Exception {
+ // Use a gateway with very short timeout
+ gateway.shutdown();
+ gateway = new A2AGatewayService(NAMESPACE, GATEWAY_ID, transport, taskRegistry, a2aService, 500L);
+ gateway.start();
+
+ // Register an agent that never responds
+ registerAgent("slow-agent");
+
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("slow-agent", "hello", null);
+
+ // Wait for timeout
+ try {
+ future.get(3, TimeUnit.SECONDS);
+ org.junit.jupiter.api.Assertions.fail("Future should have timed out");
+ } catch (java.util.concurrent.ExecutionException e) {
+ // Expected: TimeoutException wrapped in ExecutionException
+ assertTrue(e.getCause() instanceof java.util.concurrent.TimeoutException,
+ "Cause should be TimeoutException: " + e.getCause());
+ }
+
+ // Verify task was marked FAILED
+ TaskRegistry.TaskEntry entry = taskRegistry.listTasks().get(0);
+ assertEquals(TaskRegistry.TaskState.FAILED, entry.getState());
+ assertTrue(entry.getErrorMessage().contains("timed out"));
+ }
+
+ @Test
+ void testCancelTaskNotifiesStatusSubscriber() throws Exception {
+ registerAgent("slow-agent");
+
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("task-cancel-notify", "slow-agent", "hello", null);
+ AtomicInteger notifications = new AtomicInteger(0);
+ String[] lastState = new String[1];
+ gateway.registerStatusSubscriber("task-cancel-notify", (tid, state, data) -> {
+ notifications.incrementAndGet();
+ lastState[0] = state;
+ });
+
+ assertTrue(gateway.cancelTask("task-cancel-notify"));
+ A2AGatewayService.TaskResult result = future.get(1, TimeUnit.SECONDS);
+ assertEquals(TaskRegistry.TaskState.CANCELLED, result.getState());
+ assertEquals(1, notifications.get());
+ assertEquals("cancelled", lastState[0]);
+ }
+
+ // =========================================================================
+ // Agent Validation
+ // =========================================================================
+
+ @Test
+ void testSubmitTaskToUnregisteredAgentFails() {
+ // Don't register any agent
+ CompletableFuture<A2AGatewayService.TaskResult> future =
+ gateway.submitTask("ghost-agent", "hello", null);
+
+ assertTrue(future.isCompletedExceptionally());
+ }
+}
diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/AgentCardTestUtils.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/AgentCardTestUtils.java
new file mode 100644
index 000000000..5354d0668
--- /dev/null
+++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/AgentCardTestUtils.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import org.apache.eventmesh.protocol.a2a.model.AgentCapabilities;
+import org.apache.eventmesh.protocol.a2a.model.AgentCard;
+import org.apache.eventmesh.protocol.a2a.model.AgentInterface;
+import org.apache.eventmesh.protocol.a2a.model.AgentSkill;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+/**
+ * Test utility for creating valid AgentCard instances that pass schema validation.
+ */
+public final class AgentCardTestUtils {
+
+ private AgentCardTestUtils() {
+ }
+
+ public static AgentCard createValidCard(String name) {
+ return AgentCard.builder()
+ .name(name)
+ .description("Test agent: " + name)
+ .version("1.0.0")
+ .supportedInterfaces(Arrays.asList(
+ AgentInterface.builder()
+ .url("http://localhost:10105/a2a")
+ .protocolBinding("JSONRPC")
+ .protocolVersion("0.3")
+ .build()
+ ))
+ .capabilities(AgentCapabilities.builder()
+ .streaming(false)
+ .pushNotifications(false)
+ .build())
+ .defaultInputModes(Arrays.asList("text/plain"))
+ .defaultOutputModes(Arrays.asList("text/plain"))
+ .skills(Arrays.asList(
+ AgentSkill.builder()
+ .id("test-skill")
+ .name("Test Skill")
+ .description("A test skill")
+ .tags(Collections.singletonList("test"))
+ .build()
+ ))
+ .build();
+ }
+}
diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/InMemoryA2AMessageTransportTest.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/InMemoryA2AMessageTransportTest.java
new file mode 100644
index 000000000..0770a906f
--- /dev/null
+++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/InMemoryA2AMessageTransportTest.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.cloudevents.CloudEvent;
+import io.cloudevents.core.builder.CloudEventBuilder;
+
+/**
+ * Unit tests for {@link InMemoryA2AMessageTransport}.
+ */
+class InMemoryA2AMessageTransportTest {
+
+ private InMemoryA2AMessageTransport transport;
+
+ @BeforeEach
+ void setUp() {
+ transport = new InMemoryA2AMessageTransport();
+ }
+
+ private CloudEvent createEvent(String data) {
+ return CloudEventBuilder.v1()
+ .withId("test-id")
+ .withType("test-type")
+ .withSource(java.net.URI.create("test/source"))
+ .withData(data.getBytes(StandardCharsets.UTF_8))
+ .build();
+ }
+
+ // =========================================================================
+ // Publish / Subscribe direct match
+ // =========================================================================
+
+ @Test
+ void testDirectMatchDelivery() throws Exception {
+ AtomicInteger received = new AtomicInteger(0);
+ transport.subscribe("a2a/v1/agent/request/agent-a", (topic, event) -> received.incrementAndGet());
+
+ transport.publish("a2a/v1/agent/request/agent-a", createEvent("hello"));
+ assertEquals(1, received.get());
+ }
+
+ @Test
+ void testDirectMatchDataContent() throws Exception {
+ AtomicInteger received = new AtomicInteger(0);
+ String[] capturedData = new String[1];
+
+ transport.subscribe("a2a/v1/agent/request/agent-a", (topic, event) -> {
+ capturedData[0] = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
+ received.incrementAndGet();
+ });
+
+ transport.publish("a2a/v1/agent/request/agent-a", createEvent("test-payload"));
+ assertEquals(1, received.get());
+ assertEquals("test-payload", capturedData[0]);
+ }
+
+ // =========================================================================
+ // Wildcard matching
+ // =========================================================================
+
+ @Test
+ void testWildcardPlusMatches() throws Exception {
+ AtomicInteger received = new AtomicInteger(0);
+ // Subscribe with wildcard for task ID
+ transport.subscribe("a2a/v1/gateway/response/gw-1/+", (topic, event) -> received.incrementAndGet());
+
+ // Publish to specific task IDs
+ transport.publish("a2a/v1/gateway/response/gw-1/task-1", createEvent("r1"));
+ transport.publish("a2a/v1/gateway/response/gw-1/task-2", createEvent("r2"));
+ transport.publish("a2a/v1/gateway/response/gw-1/task-3", createEvent("r3"));
+
+ assertEquals(3, received.get());
+ }
+
+ @Test
+ void testWildcardDoesNotMatchDifferentLevels() throws Exception {
+ AtomicInteger received = new AtomicInteger(0);
+ transport.subscribe("a2a/v1/gateway/response/gw-1/+", (topic, event) -> received.incrementAndGet());
+
+ // Different gateway ID should not match
+ transport.publish("a2a/v1/gateway/response/gw-2/task-1", createEvent("r1"));
+ assertEquals(0, received.get());
+ }
+
+ @Test
+ void testWildcardDifferentDepthDoesNotMatch() throws Exception {
+ AtomicInteger received = new AtomicInteger(0);
+ transport.subscribe("a2a/v1/agent/request/+", (topic, event) -> received.incrementAndGet());
+
+ // More levels should not match
+ transport.publish("a2a/v1/agent/request/agent-a/extra", createEvent("r1"));
+ assertEquals(0, received.get());
+ }
+
+ // =========================================================================
+ // No subscribers
+ // =========================================================================
+
+ @Test
+ void testPublishWithNoSubscribersDoesNotThrow() throws Exception {
+ // Should not throw
+ transport.publish("a2a/v1/agent/request/unknown-agent", createEvent("hello"));
+ }
+
+ // =========================================================================
+ // Unsubscribe
+ // =========================================================================
+
+ @Test
+ void testUnsubscribeStopsDelivery() throws Exception {
+ AtomicInteger received = new AtomicInteger(0);
+ String subId = transport.subscribe("a2a/v1/agent/request/agent-a",
+ (topic, event) -> received.incrementAndGet());
+
+ transport.publish("a2a/v1/agent/request/agent-a", createEvent("first"));
+ assertEquals(1, received.get());
+
+ transport.unsubscribe(subId);
+ transport.publish("a2a/v1/agent/request/agent-a", createEvent("second"));
+ assertEquals(1, received.get());
+ }
+
+ // =========================================================================
+ // Multiple subscribers
+ // =========================================================================
+
+ @Test
+ void testMultipleSubscribersSameTopic() throws Exception {
+ AtomicInteger received1 = new AtomicInteger(0);
+ AtomicInteger received2 = new AtomicInteger(0);
+
+ transport.subscribe("a2a/v1/agent/request/agent-a", (topic, event) -> received1.incrementAndGet());
+ transport.subscribe("a2a/v1/agent/request/agent-a", (topic, event) -> received2.incrementAndGet());
+
+ transport.publish("a2a/v1/agent/request/agent-a", createEvent("hello"));
+
+ // Both should receive
+ assertEquals(1, received1.get());
+ assertEquals(1, received2.get());
+ }
+
+ @Test
+ void testWildcardAndDirectSubscribersBothReceive() throws Exception {
+ AtomicInteger wildcardReceived = new AtomicInteger(0);
+ AtomicInteger directReceived = new AtomicInteger(0);
+
+ transport.subscribe("a2a/v1/gateway/response/gw-1/+", (topic, event) -> wildcardReceived.incrementAndGet());
+ transport.subscribe("a2a/v1/gateway/response/gw-1/task-1", (topic, event) -> directReceived.incrementAndGet());
+
+ transport.publish("a2a/v1/gateway/response/gw-1/task-1", createEvent("hello"));
+
+ assertEquals(1, wildcardReceived.get());
+ assertEquals(1, directReceived.get());
+ }
+
+ // =========================================================================
+ // Subscription ID
+ // =========================================================================
+
+ @Test
+ void testSubscriptionIdIsNotNull() throws Exception {
+ String subId = transport.subscribe("a2a/v1/agent/request/agent-a", (topic, event) -> { });
+ assertNotNull(subId);
+ }
+
+ @Test
+ void testUnsubscribeNonExistentDoesNotThrow() throws Exception {
+ transport.unsubscribe("nonexistent-sub-id");
+ }
+}
diff --git a/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/TaskRegistryTest.java b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/TaskRegistryTest.java
new file mode 100644
index 000000000..4bac7b52b
--- /dev/null
+++ b/eventmesh-runtime/src/test/java/org/apache/eventmesh/runtime/a2a/TaskRegistryTest.java
@@ -0,0 +1,297 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.eventmesh.runtime.a2a;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Unit tests for {@link TaskRegistry}.
+ */
+class TaskRegistryTest {
+
+ private TaskRegistry registry;
+
+ @BeforeEach
+ void setUp() {
+ registry = new TaskRegistry();
+ }
+
+ // =========================================================================
+ // Create
+ // =========================================================================
+
+ @Test
+ void testCreateTask() {
+ TaskRegistry.TaskEntry entry = registry.createTask("task-1", null, "agent-a", "gw-1");
+ assertNotNull(entry);
+ assertEquals("task-1", entry.getTaskId());
+ assertNull(entry.getParentTaskId());
+ assertEquals("agent-a", entry.getTargetAgent());
+ assertEquals("gw-1", entry.getGatewayId());
+ assertEquals(TaskRegistry.TaskState.SUBMITTED, entry.getState());
+ assertEquals(1, registry.size());
+ }
+
+ @Test
+ void testCreateTaskWithParent() {
+ registry.createTask("parent-1", null, "agent-a", "gw-1");
+ registry.createTask("child-1", "parent-1", "agent-b", "gw-1");
+
+ assertEquals(2, registry.size());
+ assertEquals(1, registry.getChildTasks("parent-1").size());
+ assertEquals("child-1", registry.getChildTasks("parent-1").get(0));
+ }
+
+ // =========================================================================
+ // State transitions
+ // =========================================================================
+
+ @Test
+ void testSubmittedToWorking() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ assertTrue(registry.markWorking("task-1"));
+ assertEquals(TaskRegistry.TaskState.WORKING, registry.getTask("task-1").getState());
+ }
+
+ @Test
+ void testWorkingToCompleted() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markWorking("task-1");
+ assertTrue(registry.markCompleted("task-1", "result-data"));
+ assertEquals(TaskRegistry.TaskState.COMPLETED, registry.getTask("task-1").getState());
+ assertEquals("result-data", registry.getTask("task-1").getResult());
+ }
+
+ @Test
+ void testWorkingToFailed() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markWorking("task-1");
+ assertTrue(registry.markFailed("task-1", "something went wrong"));
+ assertEquals(TaskRegistry.TaskState.FAILED, registry.getTask("task-1").getState());
+ assertEquals("something went wrong", registry.getTask("task-1").getErrorMessage());
+ }
+
+ @Test
+ void testSubmittedDirectlyToCompleted() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ // SUBMITTED -> COMPLETED should be allowed (skip WORKING)
+ assertTrue(registry.markCompleted("task-1", "fast-result"));
+ assertEquals(TaskRegistry.TaskState.COMPLETED, registry.getTask("task-1").getState());
+ }
+
+ @Test
+ void testSubmittedToCancelled() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ assertTrue(registry.markCancelled("task-1"));
+ assertEquals(TaskRegistry.TaskState.CANCELLED, registry.getTask("task-1").getState());
+ }
+
+ // =========================================================================
+ // Invalid state transitions
+ // =========================================================================
+
+ @Test
+ void testWorkingFromWorkingFails() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markWorking("task-1");
+ assertFalse(registry.markWorking("task-1"));
+ }
+
+ @Test
+ void testCompletedFromCompletedFails() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markCompleted("task-1", "done");
+ assertFalse(registry.markCompleted("task-1", "again"));
+ }
+
+ @Test
+ void testCompletedToCancelledFails() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markCompleted("task-1", "done");
+ assertFalse(registry.markCancelled("task-1"));
+ }
+
+ @Test
+ void testCancelledToCompletedFails() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markCancelled("task-1");
+ assertFalse(registry.markCompleted("task-1", "too late"));
+ }
+
+ @Test
+ void testCancelledToFailedFails() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.markCancelled("task-1");
+ assertFalse(registry.markFailed("task-1", "error"));
+ }
+
+ @Test
+ void testWorkingOnNonExistentTaskFails() {
+ assertFalse(registry.markWorking("nonexistent"));
+ }
+
+ @Test
+ void testCompleteOnNonExistentTaskFails() {
+ assertFalse(registry.markCompleted("nonexistent", "data"));
+ }
+
+ // =========================================================================
+ // Get / List
+ // =========================================================================
+
+ @Test
+ void testGetNonExistentReturnsNull() {
+ assertNull(registry.getTask("nonexistent"));
+ }
+
+ @Test
+ void testListTasks() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.createTask("task-2", null, "agent-b", "gw-1");
+ registry.createTask("task-3", null, "agent-c", "gw-1");
+
+ assertEquals(3, registry.listTasks().size());
+ }
+
+ @Test
+ void testListTasksEmpty() {
+ assertEquals(0, registry.listTasks().size());
+ }
+
+ @Test
+ void testGetChildTasksNoParent() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ assertEquals(0, registry.getChildTasks("task-1").size());
+ }
+
+ @Test
+ void testGetChildTasksNonExistentParent() {
+ assertEquals(0, registry.getChildTasks("nonexistent").size());
+ }
+
+ @Test
+ void testMultipleChildren() {
+ registry.createTask("parent", null, "agent-a", "gw-1");
+ registry.createTask("child-1", "parent", "agent-b", "gw-1");
+ registry.createTask("child-2", "parent", "agent-c", "gw-1");
+ registry.createTask("child-3", "parent", "agent-d", "gw-1");
+
+ assertEquals(3, registry.getChildTasks("parent").size());
+ }
+
+ @Test
+ void testConcurrentChildTaskCreation() throws Exception {
+ registry.createTask("parent", null, "agent-a", "gw-1");
+ ExecutorService executor = Executors.newCachedThreadPool();
+ CountDownLatch ready = new CountDownLatch(50);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Throwable> failures = new ArrayList<>();
+
+ for (int i = 0; i < 50; i++) {
+ final int index = i;
+ executor.execute(() -> {
+ ready.countDown();
+ try {
+ start.await();
+ registry.createTask("child-" + index, "parent", "agent-b", "gw-1");
+ } catch (Throwable t) {
+ synchronized (failures) {
+ failures.add(t);
+ }
+ }
+ });
+ }
+
+ assertTrue(ready.await(30, TimeUnit.SECONDS), "Not all threads ready in time");
+ start.countDown();
+ executor.shutdown();
+ assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS), "Executor did not terminate in time");
+ assertEquals(0, failures.size());
+ assertEquals(50, registry.getChildTasks("parent").size());
+ }
+
+ // =========================================================================
+ // Remove / Clear
+ // =========================================================================
+
+ @Test
+ void testRemoveTask() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ TaskRegistry.TaskEntry removed = registry.removeTask("task-1");
+ assertNotNull(removed);
+ assertEquals("task-1", removed.getTaskId());
+ assertEquals(0, registry.size());
+ assertNull(registry.getTask("task-1"));
+ }
+
+ @Test
+ void testRemoveNonExistentReturnsNull() {
+ assertNull(registry.removeTask("nonexistent"));
+ }
+
+ @Test
+ void testRemoveChildUpdatesParentChildren() {
+ registry.createTask("parent", null, "agent-a", "gw-1");
+ registry.createTask("child-1", "parent", "agent-b", "gw-1");
+ registry.createTask("child-2", "parent", "agent-c", "gw-1");
+
+ registry.removeTask("child-1");
+ assertEquals(1, registry.getChildTasks("parent").size());
+ assertEquals("child-2", registry.getChildTasks("parent").get(0));
+ }
+
+ @Test
+ void testClear() {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ registry.createTask("task-2", "task-1", "agent-b", "gw-1");
+ registry.clear();
+ assertEquals(0, registry.size());
+ }
+
+ // =========================================================================
+ // Timestamps
+ // =========================================================================
+
+ @Test
+ void testTimestampsUpdate() throws InterruptedException {
+ registry.createTask("task-1", null, "agent-a", "gw-1");
+ long createdAt = registry.getTask("task-1").getCreatedAt();
+ long updatedAtBefore = registry.getTask("task-1").getUpdatedAt();
+
+ Thread.sleep(10);
+ registry.markWorking("task-1");
+ long updatedAtAfter = registry.getTask("task-1").getUpdatedAt();
+
+ assertEquals(createdAt, updatedAtBefore);
+ assertTrue(updatedAtAfter > updatedAtBefore);
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@eventmesh.apache.org
For additional commands, e-mail: commits-help@eventmesh.apache.org