Merged
[AgentCard] Get AgentCard functionality #229
[AgentCard] Get AgentCard functionality #229
Merged
youuiAdd on Jun 11
Total: 21 files changed+1987-309
@@ -2,28 +2,31 @@
2 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.2 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
3 */3 */
4 4 
5-#include <cstdlib>5+#include <nlohmann/json.hpp>
6#include <getopt.h>6#include <getopt.h>
7#include <iostream>7#include <iostream>
8-#include <nlohmann/json.hpp>8+#include <thread>
9+#include <condition_variable>
10+#include <mutex>
11+#include <atomic>
9 12 
10-#include "client/a2a_card_resolver.h"
11#include "client/client_factory.h"13#include "client/client_factory.h"
14+#include "client/http_card_resolver_builder.h"
12 15 
13constexpr int MAX_PORT = 65535;16constexpr int MAX_PORT = 65535;
14 17 
15void printUsage(const char* program_name)18void printUsage(const char* program_name)
16{19{
17- std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n"20+ std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n" <<
18- << "\nRequired options:\n"21+ "\nRequired options:\n" <<
19- << " -i, --ip <ip> Server IP address to connect to\n"22+ " -i, --ip <ip> Server IP address to connect to\n" <<
20- << " -p, --port <port> Server port to connect to (1-65535)\n"23+ " -p, --port <port> Server port to connect to (1-65535)\n" <<
21- << "\nOptional:\n"24+ "\nOptional:\n" <<
22- << " -h, --help Show this help message\n"25+ " -h, --help Show this help message\n" <<
23- << "\nExamples:\n"26+ "\nExamples:\n" <<
24- << " " << program_name << " -i 127.0.0.1 -p 8080\n"27+ " " << program_name << " -i 127.0.0.1 -p 8080\n" <<
25- << " " << program_name << " --ip=192.168.1.100 --port=8090\n"28+ " " << program_name << " --ip=192.168.1.100 --port=8090\n" <<
26- << " " << program_name << " -i localhost -p 3000\n";29+ " " << program_name << " -i localhost -p 3000\n";
27}30}
28 31 
29int main(int argc, char** argv)32int main(int argc, char** argv)
@@ -32,6 +35,9 @@ int main(int argc, char** argv)
32 int port = 0;35 int port = 0;
33 bool ip_provided = false;36 bool ip_provided = false;
34 bool port_provided = false;37 bool port_provided = false;
38+ std::mutex mtx;
39+ std::condition_variable cv;
40+ bool done = false;
35 41 
36 static struct option long_options[] = {{"ip", required_argument, 0, 'i'},42 static struct option long_options[] = {{"ip", required_argument, 0, 'i'},
37 {"port", required_argument, 0, 'p'},43 {"port", required_argument, 0, 'p'},
@@ -80,26 +86,50 @@ int main(int argc, char** argv)
80 return 1;86 return 1;
81 }87 }
82 88 
83- std::cout << "Client configuration:\n"89+ std::cout << "Client configuration:\n" <<
84- << " Connecting to: " << ip << ":" << port << "\n\n";90+ " Connecting to: " << ip << ":" << port << "\n\n";
85 91 
86 std::string base_url = std::string("http://") + ip + ":" + std::to_string(port);92 std::string base_url = std::string("http://") + ip + ":" + std::to_string(port);
87 93 
88 A2A::AgentCard card;94 A2A::AgentCard card;
89 card.name = "ExampleAgent";95 card.name = "ExampleAgent";
90 card.description = "A2A Hello World Example";96 card.description = "A2A Hello World Example";
91- card.url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";
92 card.version = "1.0.0";97 card.version = "1.0.0";
93 card.defaultInputModes = {"text"};98 card.defaultInputModes = {"text"};
94 card.defaultOutputModes = {"text"};99 card.defaultOutputModes = {"text"};
95 card.capabilities.streaming = false;100 card.capabilities.streaming = false;
96- card.preferredTransport = A2A::JSONRPC_TRANSPORT;101+ A2A::AgentInterface primaryInterface;
102+ primaryInterface.url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";
103+ primaryInterface.protocolBinding = "JSONRPC";
104+ primaryInterface.protocolVersion = "1.0";
105+ card.supportedInterfaces = {primaryInterface};
106+ 
107+ // Test get agent card via HTTP
108+ try {
109+ auto builder = std::make_shared<A2A::Client::HttpCardResolverBuilder>();
110+ auto resolver = builder->Build("http://" + ip + ":" + std::to_string(port), "/.well-known/agent-card.json", {});
111+ std::cout << "Test: GetAgentCard\n";
112+ auto card = resolver->GetAgentCard().get();
113+ std::cout << "Success: " << card.name << "\n";
114+ std::cout << "AgentCard details:\n" <<
115+ " Name: " << card.name << "\n" <<
116+ " Description: " << card.description << "\n" <<
117+ " URL: " << (card.supportedInterfaces.empty() ? "" : card.supportedInterfaces[0].url) << "\n" <<
118+ " Version: " << card.version << "\n";
119+ } catch (const std::exception& e) {
120+ std::cerr << "Failed: " << e.what() << "\n";
121+ return -1;
122+ }
97 123 
98 A2A::Client::ClientConfig cfg;124 A2A::Client::ClientConfig cfg;
99 cfg.streaming = false;125 cfg.streaming = false;
100 cfg.supportedTransports = {"JSONRPC"};126 cfg.supportedTransports = {"JSONRPC"};
101 127 
102 auto client = A2A::Client::ClientFactory::Create(card, cfg);128 auto client = A2A::Client::ClientFactory::Create(card, cfg);
129+ if (!client) {
130+ std::cerr << "Failed to create client" << std::endl;
131+ return -1;
132+ }
103 133 
104 // Build a user message with text + data parts134 // Build a user message with text + data parts
105 A2A::Message msg;135 A2A::Message msg;
@@ -116,19 +146,36 @@ int main(int argc, char** argv)
116 dp.mediaType = "application/json";146 dp.mediaType = "application/json";
117 msg.parts.push_back(dp);147 msg.parts.push_back(dp);
118 148 
119- std::cout << "--> Sending to " << card.url << std::endl;149+ std::cout << "--> Sending to " << card.supportedInterfaces[0].url << std::endl;
120 client->SendMessage(msg, nullptr, [&](const A2A::Client::ClientEvent& ev, const A2A::AgentCard& card) {150 client->SendMessage(msg, nullptr, [&](const A2A::Client::ClientEvent& ev, const A2A::AgentCard& card) {
121- if (std::holds_alternative<A2A::Message>(ev)) {151+ std::visit([&](auto&& e) {
122- auto m = std::get<A2A::Message>(ev);152+ using T = std::decay_t<decltype(e)>;
123- std::cout << "<-- Response: " << std::endl153+ if constexpr (std::is_same_v<T, A2A::Message>) {
124- << "<---- kind: " << m.kind << std::endl154+ std::cout << "<-- Response: " << std::endl <<
125- << "<---- Role: " << (uint32_t)m.role << std::endl155+ "<---- Role: " << (uint32_t)e.role << std::endl <<
126- << "<---- messageId: " << m.messageId << std::endl;156+ "<---- messageId: " << e.messageId << std::endl;
127- } else {157+ } else if constexpr (std::is_same_v<T, A2A::A2AError>) {
128- std::cout << "<-- Unexpected Task variant received (non-streaming config)" << std::endl;158+ std::cout << "<-- Error: " << std::endl <<
159+ "<---- code: " << e.code << std::endl <<
160+ "<---- message: " << e.message.value_or("") << std::endl;
161+ } else {
162+ const auto& t = e.first;
163+ std::cout << "<-- Task: " << std::endl <<
164+ "<---- contextId: " << t.contextId << std::endl <<
165+ "<---- id: " << t.id << std::endl;
166+ std::cout << std::endl << std::endl;
167+ }
168+ }, ev);
169+ {
170+ std::unique_lock<std::mutex> lock(mtx);
171+ done = true;
129 }172 }
173+ cv.notify_one();
130 });174 });
131 175 
132- ::getchar();176+ {
177+ std::unique_lock<std::mutex> lock(mtx);
178+ cv.wait(lock, [&] { return done; });
179+ }
133 return 0;180 return 0;
134-}181+}
@@ -28,22 +28,23 @@ void signal_handler(int)
28 28 
29void printUsage(const char* program_name)29void printUsage(const char* program_name)
30{30{
31- std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n"31+ std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n" <<
32- << "\nRequired options:\n"32+ "\nRequired options:\n" <<
33- << " -i, --ip <ip> Server IP address to bind to\n"33+ " -i, --ip <ip> Server IP address to bind to\n" <<
34- << " -p, --port <port> Server port to listen on (1-65535)\n"34+ " -p, --port <port> Server port to listen on (1-65535)\n" <<
35- << "\nOptional:\n"35+ "\nOptional:\n" <<
36- << " -h, --help Show this help message\n"36+ " -h, --help Show this help message\n" <<
37- << "\nExamples:\n"37+ "\nExamples:\n" <<
38- << " " << program_name << " -i 127.0.0.1 -p 8080\n"38+ " " << program_name << " -i 127.0.0.1 -p 8080\n" <<
39- << " " << program_name << " --ip=0.0.0.0 --port=9000\n"39+ " " << program_name << " --ip=0.0.0.0 --port=9000\n" <<
40- << " " << program_name << " -i 192.168.1.100 -p 3000\n";40+ " " << program_name << " -i 192.168.1.100 -p 3000\n";
41}41}
42 42 
43// 简化 AgentExecutor43// 简化 AgentExecutor
44class MyAgentExecutor : public A2A::Server::AgentExecutor {44class MyAgentExecutor : public A2A::Server::AgentExecutor {
45public:45public:
46- void Execute(const A2A::Server::RequestContext& context, std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override46+ void Execute(std::shared_ptr<A2A::Server::RequestContext> context,
47+ std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override
47 {48 {
48 std::cout << "AgentExecutor::Execute() called\n";49 std::cout << "AgentExecutor::Execute() called\n";
49 50 
@@ -59,8 +60,8 @@ public:
59 60 
60 // 从请求中提取用户输入61 // 从请求中提取用户输入
61 std::string user_input = "Hello World!";62 std::string user_input = "Hello World!";
62- if (context.GetMessage()) {63+ if (context->GetMessage()) {
63- const auto& msg = context.GetMessage();64+ const auto& msg = context->GetMessage();
64 response_msg.messageId = msg->messageId;65 response_msg.messageId = msg->messageId;
65 response_msg.contextId = msg->contextId.value_or("");66 response_msg.contextId = msg->contextId.value_or("");
66 for (const auto& part : msg->parts) {67 for (const auto& part : msg->parts) {
@@ -77,10 +78,11 @@ public:
77 response_msg.parts.push_back(text_part);78 response_msg.parts.push_back(text_part);
78 79 
79 // 发送完成状态80 // 发送完成状态
80- taskUpdater->Complete(response_msg);81+ taskUpdater->SendResponseMessage(response_msg);
81 }82 }
82 83 
83- void Cancel(const A2A::Server::RequestContext& context, std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override84+ void Cancel(std::shared_ptr<A2A::Server::RequestContext> context,
85+ std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override
84 {86 {
85 std::cout << "AgentExecutor::Cancel() called\n";87 std::cout << "AgentExecutor::Cancel() called\n";
86 taskUpdater->Cancel();88 taskUpdater->Cancel();
@@ -141,9 +143,9 @@ int main(int argc, char* argv[])
141 return 1;143 return 1;
142 }144 }
143 145 
144- std::cout << "Server configuration:\n"146+ std::cout << "Server configuration:\n" <<
145- << " IP: " << ip << "\n"147+ " IP: " << ip << "\n" <<
146- << " Port: " << port << "\n\n";148+ " Port: " << port << "\n\n";
147 149 
148 // 1. 阻塞信号150 // 1. 阻塞信号
149 sigset_t sigset;151 sigset_t sigset;
@@ -156,15 +158,18 @@ int main(int argc, char* argv[])
156 auto executor = std::make_shared<MyAgentExecutor>();158 auto executor = std::make_shared<MyAgentExecutor>();
157 159 
158 // 3. 创建 AgentCard160 // 3. 创建 AgentCard
159- auto agentCard = std::make_shared<A2A::AgentCard>();161+ A2A::AgentCard agentCard{};
160- agentCard->name = "ExampleAgent";162+ agentCard.name = "ExampleAgent";
161- agentCard->description = "A2A Hello World Example";163+ agentCard.description = "A2A Hello World Example";
162- agentCard->url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";164+ agentCard.version = "1.0.0";
163- agentCard->version = "1.0.0";165+ agentCard.defaultInputModes = {"text"};
164- agentCard->defaultInputModes = {"text"};166+ agentCard.defaultOutputModes = {"text"};
165- agentCard->defaultOutputModes = {"text"};167+ agentCard.capabilities.streaming = false;
166- agentCard->capabilities.streaming = false;168+ A2A::AgentInterface primaryInterface;
167- agentCard->preferredTransport = A2A::JSONRPC_TRANSPORT;169+ primaryInterface.url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";
170+ primaryInterface.protocolBinding = "JSONRPC";
171+ primaryInterface.protocolVersion = "1.0";
172+ agentCard.supportedInterfaces = {primaryInterface};
168 173 
169 std::cout << "--Built agent card \n";174 std::cout << "--Built agent card \n";
170 175 
@@ -177,7 +182,7 @@ int main(int argc, char* argv[])
177 auto server = A2A::Server::HttpServerBuilder::Build(182 auto server = A2A::Server::HttpServerBuilder::Build(
178 httpConfig,183 httpConfig,
179 agentCard,184 agentCard,
180- nullptr, // extendedAgentCard185+ {}, // extendedAgentCard
181 executor, // agentExecutor186 executor, // agentExecutor
182 nullptr // taskStore187 nullptr // taskStore
183 );188 );
@@ -7,11 +7,8 @@
7#include <iostream>7#include <iostream>
8#include <memory>8#include <memory>
9#include <nlohmann/json.hpp>9#include <nlohmann/json.hpp>
10-#include <variant>
11 10 
12-#include "client/a2a_card_resolver.h"
13#include "client/client_factory.h"11#include "client/client_factory.h"
14-#include "types.h"
15 12 
16using json = nlohmann::json;13using json = nlohmann::json;
17 14 
@@ -19,16 +16,16 @@ constexpr int MAX_PORT = 65535;
19 16 
20void printUsage(const char* program_name)17void printUsage(const char* program_name)
21{18{
22- std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n"19+ std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n" <<
23- << "\nRequired options:\n"20+ "\nRequired options:\n" <<
24- << " -i, --ip <ip> Server IP address to connect to\n"21+ " -i, --ip <ip> Server IP address to connect to\n" <<
25- << " -p, --port <port> Server port to connect to (1-65535)\n"22+ " -p, --port <port> Server port to connect to (1-65535)\n" <<
26- << "\nOptional:\n"23+ "\nOptional:\n" <<
27- << " -h, --help Show this help message\n"24+ " -h, --help Show this help message\n" <<
28- << "\nExamples:\n"25+ "\nExamples:\n" <<
29- << " " << program_name << " -i 127.0.0.1 -p 8083\n"26+ " " << program_name << " -i 127.0.0.1 -p 8083\n" <<
30- << " " << program_name << " --ip=192.168.1.100 --port=9000\n"27+ " " << program_name << " --ip=192.168.1.100 --port=9000\n" <<
31- << " " << program_name << " -i localhost -p 3000\n";28+ " " << program_name << " -i localhost -p 3000\n";
32}29}
33 30 
34int main(int argc, char* argv[])31int main(int argc, char* argv[])
@@ -85,8 +82,8 @@ int main(int argc, char* argv[])
85 return 1;82 return 1;
86 }83 }
87 84 
88- std::cout << "Client configuration:\n"85+ std::cout << "Client configuration:\n" <<
89- << " Connecting to: " << ip << ":" << port << "\n\n";86+ " Connecting to: " << ip << ":" << port << "\n\n";
90 87 
91 std::cout << "--- Streaming Client Demo ---" << std::endl;88 std::cout << "--- Streaming Client Demo ---" << std::endl;
92 const std::string sessionId = "demo-session";89 const std::string sessionId = "demo-session";
@@ -97,58 +94,65 @@ int main(int argc, char* argv[])
97 A2A::AgentCard card;94 A2A::AgentCard card;
98 card.name = "OrchestratorAgent";95 card.name = "OrchestratorAgent";
99 card.description = "A2A Orchestrator Example";96 card.description = "A2A Orchestrator Example";
100- card.url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";
101 card.version = "1.0.0";97 card.version = "1.0.0";
102 card.defaultInputModes = {"text"};98 card.defaultInputModes = {"text"};
103 card.defaultOutputModes = {"text"};99 card.defaultOutputModes = {"text"};
104 card.capabilities.streaming = true;100 card.capabilities.streaming = true;
105- card.preferredTransport = A2A::JSONRPC_TRANSPORT;101+ A2A::AgentInterface primaryInterface;
102+ primaryInterface.url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";
103+ primaryInterface.protocolBinding = "JSONRPC";
104+ primaryInterface.protocolVersion = "1.0";
105+ card.supportedInterfaces = {primaryInterface};
106 106 
107 A2A::Client::ClientConfig cfg;107 A2A::Client::ClientConfig cfg;
108 cfg.streaming = true;108 cfg.streaming = true;
109 cfg.supportedTransports = {"JSONRPC"};109 cfg.supportedTransports = {"JSONRPC"};
110 auto client = A2A::Client::ClientFactory::Create(card, cfg);110 auto client = A2A::Client::ClientFactory::Create(card, cfg);
111+ if (!client) {
112+ std::cerr << "Failed to create client" << std::endl;
113+ return -1;
114+ }
111 115 
112 std::cout << "Client created for agent: " << card.name << std::endl;116 std::cout << "Client created for agent: " << card.name << std::endl;
113 117 
114- // Consumer to log events with card context118+ auto f = [](auto&& e) {
115- std::cout << "[2] Adding a global event consumer..." << std::endl;119+ using T = std::decay_t<decltype(e)>;
116- client->AddEventConsumer([](const A2A::Client::ClientEvent& ev, const A2A::AgentCard& card) {120+ if constexpr (std::is_same_v<T, A2A::Message>) {
117- std::cout << "[consumer] Event for " << card.name << ":" << std::endl;121+ std::cout << "<-- Response: " << std::endl <<
118- std::visit(122+ "<---- Role: " << (uint32_t)e.role << std::endl <<
119- [&](auto&& e) {123+ "<---- messageId: " << e.messageId << std::endl;
120- using T = std::decay_t<decltype(e)>;124+ } else if constexpr (std::is_same_v<T, A2A::A2AError>) {
121- if constexpr (std::is_same_v<T, A2A::Message>) {125+ std::cout << "<-- Error: " << std::endl <<
122- std::cout << "<-- Response: " << std::endl126+ "<---- code: " << e.code << std::endl <<
123- << "<---- kind: " << e.kind << std::endl127+ "<---- message: " << e.message.value_or("") << std::endl;
124- << "<---- Role: " << (uint32_t)e.role << std::endl128+ } else {
125- << "<---- messageId: " << e.messageId << std::endl;129+ const auto& t = e.first;
126- } else {130+ const auto& upd = e.second;
127- const auto& t = e.first;131+ std::cout << "<-- Task: " << std::endl <<
128- const auto& upd = e.second;132+ "<---- contextId: " << t.contextId << std::endl <<
129- std::cout << "<-- Task: " << std::endl133+ "<---- id: " << t.id << std::endl;
130- << "<---- kind: " << t.kind << std::endl134+ if (!std::holds_alternative<std::monostate>(upd)) {
131- << "<---- contextId: " << t.contextId << std::endl135+ if (std::holds_alternative<A2A::TaskStatusUpdateEvent>(upd)) {
132- << "<---- id: " << t.id << std::endl;136+ auto u = std::get<A2A::TaskStatusUpdateEvent>(upd);
133- if (!std::holds_alternative<std::monostate>(upd)) {137+ std::cout << "<-- Status: " << std::endl <<
134- if (std::holds_alternative<A2A::TaskStatusUpdateEvent>(upd)) {138+ "<---- status: " << (uint32_t)u.status.state << std::endl <<
135- auto u = std::get<A2A::TaskStatusUpdateEvent>(upd);139+ "<---- taskId: " << u.taskId << std::endl;
136- std::cout << "<-- Status: " << std::endl140+ } else {
137- << "<---- kind: " << u.kind << std::endl141+ auto u = std::get<A2A::TaskArtifactUpdateEvent>(upd);
138- << "<---- status: " << static_cast<uint32_t>(u.status.state) << std::endl142+ std::cout << "<-- Status: " << std::endl <<
139- << "<---- taskId: " << u.taskId << std::endl;143+ "<---- contextId: " << u.contextId << std::endl <<
140- } else {144+ "<---- taskId: " << u.taskId << std::endl;
141- auto u = std::get<A2A::TaskArtifactUpdateEvent>(upd);
142- std::cout << "<-- Status: " << std::endl
143- << "<---- kind: " << u.kind << std::endl
144- << "<---- contextId: " << u.contextId << std::endl
145- << "<---- taskId: " << u.taskId << std::endl;
146- }
147 }145 }
148 }146 }
149 std::cout << std::endl << std::endl;147 std::cout << std::endl << std::endl;
150- },148+ }
151- ev);149+ };
150+ 
151+ // Consumer to log events with card context
152+ std::cout << "[2] Adding a global event consumer..." << std::endl;
153+ client->AddEventConsumer([&f](const A2A::Client::ClientEvent& ev, const A2A::AgentCard& card) {
154+ std::cout << "[consumer] Event for " << card.name << ":" << std::endl;
155+ std::visit(f, ev);
152 });156 });
153 157 
154 // Build request message from user158 // Build request message from user
@@ -166,48 +170,16 @@ int main(int argc, char* argv[])
166 // Per-call context with sessionId for credential lookup170 // Per-call context with sessionId for credential lookup
167 std::cout << "[4] Preparing call context with sessionId..." << std::endl;171 std::cout << "[4] Preparing call context with sessionId..." << std::endl;
168 A2A::ClientCallContext ctx;172 A2A::ClientCallContext ctx;
169- ctx.state["sessionId"] = sessionId;173+ json j;
170- 174+ j["sessionId"] = sessionId;
175+ ctx.state = j.dump();
171 std::cout << "\n--> [5] Sending streaming request to Orchestrator..." << std::endl;176 std::cout << "\n--> [5] Sending streaming request to Orchestrator..." << std::endl;
172- client->SendMessage(m, &ctx, [](const A2A::Client::ClientEvent& ev, const A2A::AgentCard& card) {177+ auto ret = client->SendMessage(m, &ctx, [&f](const A2A::Client::ClientEvent& ev, const A2A::AgentCard& card) {
173 std::cout << "[callback] Received event:" << std::endl;178 std::cout << "[callback] Received event:" << std::endl;
174- std::visit(179+ std::visit(f, ev);
175- [&](auto&& e) {
176- using T = std::decay_t<decltype(e)>;
177- if constexpr (std::is_same_v<T, A2A::Message>) {
178- std::cout << "<-- Response: " << std::endl
179- << "<---- kind: " << e.kind << std::endl
180- << "<---- Role: " << (uint32_t)e.role << std::endl
181- << "<---- messageId: " << e.messageId << std::endl;
182- } else {
183- const auto& t = e.first;
184- const auto& upd = e.second;
185- std::cout << "<-- Task: " << std::endl
186- << "<---- kind: " << t.kind << std::endl
187- << "<---- contextId: " << t.contextId << std::endl
188- << "<---- id: " << t.id << std::endl;
189- if (!std::holds_alternative<std::monostate>(upd)) {
190- if (std::holds_alternative<A2A::TaskStatusUpdateEvent>(upd)) {
191- auto u = std::get<A2A::TaskStatusUpdateEvent>(upd);
192- std::cout << "<-- Status: " << std::endl
193- << "<---- kind: " << u.kind << std::endl
194- << "<---- status: " << static_cast<uint32_t>(u.status.state) << std::endl
195- << "<---- taskId: " << u.taskId << std::endl;
196- } else {
197- auto u = std::get<A2A::TaskArtifactUpdateEvent>(upd);
198- std::cout << "<-- Status: " << std::endl
199- << "<---- kind: " << u.kind << std::endl
200- << "<---- contextId: " << u.contextId << std::endl
201- << "<---- taskId: " << u.taskId << std::endl;
202- }
203- }
204- std::cout << std::endl << std::endl;
205- }
206- },
207- ev);
208 });180 });
209 181 
210- ::getchar();182+ ret.wait();
211 std::cout << "\nDone." << std::endl;183 std::cout << "\nDone." << std::endl;
212 return 0;184 return 0;
213-}185+}
@@ -14,7 +14,6 @@
14 14 
15#include "server/server.h"15#include "server/server.h"
16#include "types.h"16#include "types.h"
17-#include "utils/utils_message.h"
18 17 
19using json = nlohmann::json;18using json = nlohmann::json;
20 19 
@@ -23,13 +22,13 @@ constexpr int MAX_PORT = 65535;
23// --------------------- Streaming Orchestrator Executor ---------------------22// --------------------- Streaming Orchestrator Executor ---------------------
24class OrchestratorAgentExecutor : public A2A::Server::AgentExecutor {23class OrchestratorAgentExecutor : public A2A::Server::AgentExecutor {
25public:24public:
26- void Execute(const A2A::Server::RequestContext& context,25+ void Execute(std::shared_ptr<A2A::Server::RequestContext> context,
27 std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override26 std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override
28 {27 {
29 std::cout << "OrchestratorAgentExecutor::Execute() called\n";28 std::cout << "OrchestratorAgentExecutor::Execute() called\n";
30 29 
31 // 获取请求消息30 // 获取请求消息
32- const A2A::Message* req = context.GetMessage();31+ const A2A::Message* req = context->GetMessage();
33 if (!req) {32 if (!req) {
34 // 错误处理:发 error 事件33 // 错误处理:发 error 事件
35 const auto errMsg = makeErrorPart("No message in request");34 const auto errMsg = makeErrorPart("No message in request");
@@ -43,7 +42,7 @@ public:
43 for (const auto& part : req->parts) {42 for (const auto& part : req->parts) {
44 if (part.data.has_value()) {43 if (part.data.has_value()) {
45 const auto& d = part.data.value();44 const auto& d = part.data.value();
46- nlohmann::json j = nlohmann::json::parse(d);45+ nlohmann::json j = nlohmann::json::parse(std::get<std::string>(d));
47 destination = j.value("destination", destination);46 destination = j.value("destination", destination);
48 date = j.value("date", date);47 date = j.value("date", date);
49 }48 }
@@ -94,7 +93,7 @@ public:
94 taskUpdater->Complete(merged_req);93 taskUpdater->Complete(merged_req);
95 }94 }
96 95 
97- void Cancel(const A2A::Server::RequestContext& context,96+ void Cancel(std::shared_ptr<A2A::Server::RequestContext> context,
98 std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override97 std::shared_ptr<A2A::Server::TaskUpdater> taskUpdater) override
99 {98 {
100 std::cout << "OrchestratorAgentExecutor::Cancel() called\n";99 std::cout << "OrchestratorAgentExecutor::Cancel() called\n";
@@ -107,7 +106,7 @@ private:
107 A2A::Part dp;106 A2A::Part dp;
108 dp.data = nlohmann::json({{"tag", tag}, {"payload", payload}}).dump();107 dp.data = nlohmann::json({{"tag", tag}, {"payload", payload}}).dump();
109 dp.mediaType = "application/json";108 dp.mediaType = "application/json";
110- return A2A::NewAgentPartsMessage({dp});109+ return NewAgentPartsMessage({dp});
111 }110 }
112 111 
113 std::optional<A2A::Message> makeErrorPart(const std::string& msg)112 std::optional<A2A::Message> makeErrorPart(const std::string& msg)
@@ -115,7 +114,7 @@ private:
115 A2A::Part dp;114 A2A::Part dp;
116 dp.data = nlohmann::json({{"error", msg}}).dump();115 dp.data = nlohmann::json({{"error", msg}}).dump();
117 dp.mediaType = "application/json";116 dp.mediaType = "application/json";
118- return A2A::NewAgentPartsMessage({dp});117+ return NewAgentPartsMessage({dp});
119 }118 }
120 119 
121 std::optional<A2A::Message> makeCombinedMessage(const A2A::Message& input)120 std::optional<A2A::Message> makeCombinedMessage(const A2A::Message& input)
@@ -125,7 +124,7 @@ private:
125 for (const auto& part : input.parts) {124 for (const auto& part : input.parts) {
126 if (part.data.has_value()) {125 if (part.data.has_value()) {
127 const auto& d = part.data.value();126 const auto& d = part.data.value();
128- nlohmann::json j = nlohmann::json::parse(d);127+ nlohmann::json j = nlohmann::json::parse(std::get<std::string>(d));
129 destination = j.value("destination", destination);128 destination = j.value("destination", destination);
130 date = j.value("date", date);129 date = j.value("date", date);
131 }130 }
@@ -137,7 +136,22 @@ private:
137 A2A::Part dp;136 A2A::Part dp;
138 dp.data = combined.dump();137 dp.data = combined.dump();
139 dp.mediaType = "application/json";138 dp.mediaType = "application/json";
140- return A2A::NewAgentPartsMessage({dp});139+ return NewAgentPartsMessage({dp});
140+ }
141+ 
142+ static A2A::Message NewAgentPartsMessage(
143+ const std::vector<A2A::Part>& parts,
144+ const std::optional<std::string>& context_id = std::nullopt,
145+ const std::optional<std::string>& task_id = std::nullopt)
146+ {
147+ static int count = 0;
148+ A2A::Message m;
149+ m.role = A2A::Role::AGENT;
150+ m.parts = parts;
151+ m.messageId = "message-" + std::to_string(++count);
152+ m.taskId = task_id;
153+ m.contextId = context_id;
154+ return m;
141 }155 }
142};156};
143 157 
@@ -152,16 +166,16 @@ void signal_handler(int sig)
152 166 
153void printUsage(const char* program_name)167void printUsage(const char* program_name)
154{168{
155- std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n"169+ std::cout << "Usage: " << program_name << " -i <ip> -p <port> [OPTIONS]\n" <<
156- << "\nRequired options:\n"170+ "\nRequired options:\n" <<
157- << " -i, --ip <ip> Server IP address to bind to\n"171+ " -i, --ip <ip> Server IP address to bind to\n" <<
158- << " -p, --port <port> Server port to listen on (1-65535)\n"172+ " -p, --port <port> Server port to listen on (1-65535)\n" <<
159- << "\nOptional:\n"173+ "\nOptional:\n" <<
160- << " -h, --help Show this help message\n"174+ " -h, --help Show this help message\n" <<
161- << "\nExamples:\n"175+ "\nExamples:\n" <<
162- << " " << program_name << " -i 127.0.0.1 -p 8083\n"176+ " " << program_name << " -i 127.0.0.1 -p 8083\n" <<
163- << " " << program_name << " --ip=0.0.0.0 --port=9000\n"177+ " " << program_name << " --ip=0.0.0.0 --port=9000\n" <<
164- << " " << program_name << " -i 192.168.1.100 -p 3000\n";178+ " " << program_name << " -i 192.168.1.100 -p 3000\n";
165}179}
166 180 
167// ========================181// ========================
@@ -221,9 +235,9 @@ int main(int argc, char* argv[])
221 return 1;235 return 1;
222 }236 }
223 237 
224- std::cout << "Server configuration:\n"238+ std::cout << "Server configuration:\n" <<
225- << " IP: " << ip << "\n"239+ " IP: " << ip << "\n" <<
226- << " Port: " << port << "\n\n";240+ " Port: " << port << "\n\n";
227 241 
228 // 1. 阻塞信号242 // 1. 阻塞信号
229 sigset_t sigset;243 sigset_t sigset;
@@ -236,15 +250,18 @@ int main(int argc, char* argv[])
236 auto orch_executor = std::make_shared<OrchestratorAgentExecutor>();250 auto orch_executor = std::make_shared<OrchestratorAgentExecutor>();
237 251 
238 // 3. 创建 AgentCard252 // 3. 创建 AgentCard
239- auto agentCard = std::make_shared<A2A::AgentCard>();253+ A2A::AgentCard agentCard{};
240- agentCard->name = "OrchestratorAgent";254+ agentCard.name = "OrchestratorAgent";
241- agentCard->description = "A2A Orchestrator Example";255+ agentCard.description = "A2A Orchestrator Example";
242- agentCard->url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";256+ agentCard.version = "1.0.0";
243- agentCard->version = "1.0.0";257+ agentCard.defaultInputModes = {"text"};
244- agentCard->defaultInputModes = {"text"};258+ agentCard.defaultOutputModes = {"text"};
245- agentCard->defaultOutputModes = {"text"};259+ agentCard.capabilities.streaming = true;
246- agentCard->capabilities.streaming = true;260+ A2A::AgentInterface primaryInterface;
247- agentCard->preferredTransport = A2A::JSONRPC_TRANSPORT;261+ primaryInterface.url = "http://" + ip + ":" + std::to_string(port) + "/jsonrpc";
262+ primaryInterface.protocolBinding = "JSONRPC";
263+ primaryInterface.protocolVersion = "1.0";
264+ agentCard.supportedInterfaces = {primaryInterface};
248 265 
249 std::cout << "--Built agent card \n";266 std::cout << "--Built agent card \n";
250 267 
@@ -257,7 +274,7 @@ int main(int argc, char* argv[])
257 auto server = A2A::Server::HttpServerBuilder::Build(274 auto server = A2A::Server::HttpServerBuilder::Build(
258 httpConfig,275 httpConfig,
259 agentCard,276 agentCard,
260- nullptr, // extendedAgentCard277+ {}, // extendedAgentCard
261 orch_executor, // agentExecutor278 orch_executor, // agentExecutor
262 nullptr // taskStore279 nullptr // taskStore
263 );280 );
@@ -15,29 +15,27 @@ namespace A2A::Client {
15 15 
16class A2ACardResolver {16class A2ACardResolver {
17public:17public:
18- 
19 /**18 /**
20- * @brief destructor19+ * @brief destructor
21- */20+ */
22 virtual ~A2ACardResolver() = default;21 virtual ~A2ACardResolver() = default;
23 22 
24 /**23 /**
25- * @brief get AgentCard from relative path24+ * @brief get AgentCard from relative path
26- *25+ *
27- * @param[in] relativeCardPath relative card path26+ * @param[in] relativeCardPath relative card path
28- * @return future to valid AgentCard if read successful27+ * @return future to valid AgentCard if read successful
29- */28+ */
30 virtual std::future<AgentCard> GetAgentCard(29 virtual std::future<AgentCard> GetAgentCard(
31 const std::optional<std::string>& relativeCardPath = std::nullopt) const = 0;30 const std::optional<std::string>& relativeCardPath = std::nullopt) const = 0;
32 31 
33 /**32 /**
34- * @brief get all AgentCard from local path33+ * @brief get all AgentCard from local path
35- *34+ *
36- * @return future to vector of AgentCards35+ * @return future to vector of AgentCards
37- */36+ */
38 virtual std::future<std::vector<AgentCard>> GetAllAgentCards() const = 0;37 virtual std::future<std::vector<AgentCard>> GetAllAgentCards() const = 0;
39};38};
40- 
41} // namespace A2A::Client39} // namespace A2A::Client
42 40 
43-#endif41+#endif // A2A_CARD_RESOLVER
@@ -9,6 +9,7 @@
9#include <vector>9#include <vector>
10 10 
11#include "client/client.h"11#include "client/client.h"
12+#include "client/client_transport.h"
12#include "types.h"13#include "types.h"
13 14 
14namespace A2A::Client {15namespace A2A::Client {
@@ -32,6 +33,9 @@ public:
32 static std::shared_ptr<Client> Create(const AgentCard& card, const ClientConfig& config,33 static std::shared_ptr<Client> Create(const AgentCard& card, const ClientConfig& config,
33 const std::vector<Consumer>& consumers = {},34 const std::vector<Consumer>& consumers = {},
34 const std::vector<std::shared_ptr<ClientCallInterceptor>>& interceptors = {});35 const std::vector<std::shared_ptr<ClientCallInterceptor>>& interceptors = {});
36+ 
37+ static std::shared_ptr<Client> Create(const AgentCard& card, const ClientConfig& config,
38+ std::shared_ptr<ClientTransport> transport, const std::vector<Consumer>& consumers = {});
35};39};
36 40 
37} // namespace A2A::Client41} // namespace A2A::Client
@@ -5,33 +5,34 @@
5#ifndef HTTP_CARD_RESOLVER_BUILDER5#ifndef HTTP_CARD_RESOLVER_BUILDER
6#define HTTP_CARD_RESOLVER_BUILDER6#define HTTP_CARD_RESOLVER_BUILDER
7 7 
8-#include <optional>
9#include <string>8#include <string>
10#include <future>9#include <future>
10+#include <memory>
11 11 
12+#include "client/a2a_card_resolver.h"
12#include "types.h"13#include "types.h"
13 14 
14namespace A2A::Client {15namespace A2A::Client {
15 16 
16-class HttpCardResolverBuilder {17+class HttpCardResolverBuilder final {
17public:18public:
18 /**19 /**
19- * @brief destructor20+ * @brief destructor
20- */21+ */
21 ~HttpCardResolverBuilder();22 ~HttpCardResolverBuilder();
22 23 
23 /**24 /**
24- * @brief build card resolver25+ * @brief build card resolver
25- *26+ *
26- * @param[in] baseUrl base url27+ * @param[in] baseUrl base url
27- * @param[in] agentCardPath agent card path28+ * @param[in] agentCardPath agent card path
28- * @param[in] httpKwargs http args29+ * @param[in] httpKwargs http args
29- * @return A shared pointer to the created card resolver instance30+ * @return A shared pointer to the created card resolver instance
30- */31+ */
31- static shared_ptr<A2ACardResolver> Build(std::string baseUrl, std::string agentCardPath,32+ static std::shared_ptr<A2ACardResolver> Build(std::string baseUrl, std::string agentCardPath,
32 const std::map<std::string, std::string>& httpKwargs = {});33 const std::map<std::string, std::string>& httpKwargs = {});
33};34};
34 35 
35} // namespace A2A::Client36} // namespace A2A::Client
36 37 
37-#endif38+#endif
@@ -17,31 +17,32 @@ namespace A2A::Server {
17struct HttpConfig {17struct HttpConfig {
18 std::string ip;18 std::string ip;
19 int port;19 int port;
20- int ioThreadNum = 1;20+ unsigned int ioThreadNum = 1;
21+ std::string endpoint = "/jsonrpc";
21};22};
22 23 
23class HttpServerBuilder {24class HttpServerBuilder {
24public:25public:
25 /**26 /**
26- * @brief destructor27+ * @brief destructor
27- */28+ */
28 ~HttpServerBuilder();29 ~HttpServerBuilder();
29 30 
30 /**31 /**
31- * @brief create http server32+ * @brief create http server
32- *33+ *
33- * @param[in] config http config34+ * @param[in] config http config
34- * @param[in] agentCard agent card object35+ * @param[in] agentCard agent card object
35- * @param[in] extendedAgentCard extended agent card object36+ * @param[in] extendedAgentCard extended agent card object
36- * @param[in] agentExecutor agent executor object37+ * @param[in] agentExecutor agent executor object
37- * @param[in] taskStore store object to store task object38+ * @param[in] taskStore store object to store task object
38- * @return A shared pointer to the created server instance39+ * @return A shared pointer to the created server instance
39- */40+ */
40- static std::shared_ptr<Server> Build(const HttpConfig& config, std::shared_ptr<AgentCard> agentCard,41+ static std::shared_ptr<Server> Build(const HttpConfig& config, const AgentCard& agentCard,
41- std::shared_ptr<AgentCard> extendedAgentCard, std::shared_ptr<AgentExecutor> agentExecutor,42+ const AgentCard& extendedAgentCard, std::shared_ptr<AgentExecutor> agentExecutor,
42 std::shared_ptr<TaskStore> taskStore = nullptr);43 std::shared_ptr<TaskStore> taskStore = nullptr);
43};44};
44 45 
45}46}
46 47 
47-#endif48+#endif
@@ -6,8 +6,10 @@
6#define A2A_TYPES6#define A2A_TYPES
7 7 
8#include <nlohmann/json.hpp>8#include <nlohmann/json.hpp>
9+#include <map>
9#include <optional>10#include <optional>
10#include <string>11#include <string>
12+#include <unordered_map>
11#include <variant>13#include <variant>
12#include <vector>14#include <vector>
13 15 
@@ -341,6 +343,7 @@ struct AgentSkill {
341 std::optional<std::vector<std::string>> examples;343 std::optional<std::vector<std::string>> examples;
342 std::optional<std::vector<std::string>> inputModes;344 std::optional<std::vector<std::string>> inputModes;
343 std::optional<std::vector<std::string>> outputModes;345 std::optional<std::vector<std::string>> outputModes;
346+ std::optional<std::string> extension;
344};347};
345 348 
346// AgentExtension mirrors the Python model used in extensions/common.py utilities349// AgentExtension mirrors the Python model used in extensions/common.py utilities
@@ -348,13 +351,14 @@ struct AgentExtension {
348 std::string uri;351 std::string uri;
349 std::optional<bool> required;352 std::optional<bool> required;
350 std::optional<std::string> description;353 std::optional<std::string> description;
351- std::optional<nlohmann::json> params;354+ std::optional<std::string> params;
352};355};
353 356 
354struct AgentCapabilities {357struct AgentCapabilities {
355 std::optional<bool> streaming;358 std::optional<bool> streaming;
356 std::optional<bool> pushNotifications;359 std::optional<bool> pushNotifications;
357- std::optional<bool> stateTransitionHistory;360+ std::optional<bool> extendedAgentCard;
361+ std::optional<std::string> extension;
358 std::optional<std::vector<AgentExtension>> extensions;362 std::optional<std::vector<AgentExtension>> extensions;
359};363};
360 364 
@@ -364,28 +368,47 @@ struct AgentProvider {
364};368};
365 369 
366struct AgentInterface {370struct AgentInterface {
367- std::string transport;
368 std::string url;371 std::string url;
372+ std::string protocolBinding;
373+ std::string protocolVersion;
374+ std::optional<std::string> tenant;
375+};
376+ 
377+struct SecurityRequirement {
378+ std::unordered_map<std::string, std::vector<std::string>> schemes;
379+};
380+ 
381+struct AgentCardSignature {
382+ // Required. The protected JWS header. This is always a base64url-encoded JSON object.
383+ // Note: Trailing underscore because 'protected' is a C++ keyword.
384+ std::string protected_;
385+ 
386+ // Required. The computed signature, base64url-encoded.
387+ std::string signature;
388+ 
389+ // The unprotected JWS header values
390+ std::optional<std::string> header; // json like
369};391};
370 392 
371struct AgentCard {393struct AgentCard {
372- std::string protocolVersion;
373 std::string name;394 std::string name;
374 std::string description;395 std::string description;
375- std::string url;
376 std::optional<AgentProvider> provider;396 std::optional<AgentProvider> provider;
377 std::optional<std::string> iconUrl;397 std::optional<std::string> iconUrl;
378 std::string version;398 std::string version;
379 std::optional<std::string> documentationUrl;399 std::optional<std::string> documentationUrl;
380 AgentCapabilities capabilities;400 AgentCapabilities capabilities;
381 std::optional<std::map<std::string, SecurityScheme>> securitySchemes;401 std::optional<std::map<std::string, SecurityScheme>> securitySchemes;
382- std::optional<std::vector<nlohmann::json>> security;402+ std::optional<std::vector<std::string>> security;
383 std::vector<std::string> defaultInputModes;403 std::vector<std::string> defaultInputModes;
384 std::vector<std::string> defaultOutputModes;404 std::vector<std::string> defaultOutputModes;
385 std::vector<AgentSkill> skills;405 std::vector<AgentSkill> skills;
386- std::optional<bool> supportsAuthenticatedExtendedCard;406+ std::vector<AgentInterface> supportedInterfaces;
387- std::optional<std::string> preferredTransport;407+ std::optional<std::vector<SecurityRequirement>> securityRequirements;
388- std::optional<std::vector<AgentInterface>> additionalInterfaces;408+ std::optional<std::vector<AgentCardSignature>> signatures;
409+ 
410+ std::optional<std::string> category;
411+ std::optional<std::string> extension;
389};412};
390} // namespace A2A413} // namespace A2A
391 414 
@@ -2,6 +2,7 @@
2 * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.2 * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3 */3 */
4 4 
5+#include "a2a_log.h"
5#include "default_client.h"6#include "default_client.h"
6#include "jsonrpc_transport.h"7#include "jsonrpc_transport.h"
7#include "client/client_factory.h"8#include "client/client_factory.h"
@@ -14,51 +15,93 @@ std::shared_ptr<Client> ClientFactory::Create(const AgentCard& card, const Clien
14 const std::vector<Consumer>& consumers,15 const std::vector<Consumer>& consumers,
15 const std::vector<std::shared_ptr<ClientCallInterceptor>>& interceptors)16 const std::vector<std::shared_ptr<ClientCallInterceptor>>& interceptors)
16{17{
17- std::string serverPreferred = card.preferredTransport.value_or(JSONRPC_TRANSPORT);18+ try {
18- std::map<std::string, std::string> serverSet{{serverPreferred, card.url}};19+ for (const auto& itc : interceptors) {
19- if (card.additionalInterfaces) {20+ if (itc == nullptr) {
20- for (const auto& itf : *card.additionalInterfaces) {21+ return nullptr;
21- serverSet[itf.transport] = itf.url;
22- }
23- }
24- 
25- std::vector<std::string> clientSet = config.supportedTransports.empty() ?
26- std::vector<std::string>{JSONRPC_TRANSPORT} : config.supportedTransports;
27- std::string chosenProtocol;
28- std::string chosenUrl;
29- 
30- if (config.useClientPreference) {
31- for (const auto& x : clientSet) {
32- auto it = serverSet.find(x);
33- if (it != serverSet.end()) {
34- chosenProtocol = x;
35- chosenUrl = it->second;
36- break;
37 }22 }
38 }23 }
39- } else {24+ if (!config.supportedTransports.empty()) {
40- for (const auto& kv : serverSet) {25+ for (const auto& t : config.supportedTransports) {
41- if (std::find(clientSet.begin(), clientSet.end(), kv.first) != clientSet.end()) {26+ if (t.empty()) {
42- chosenProtocol = kv.first;27+ return nullptr;
43- chosenUrl = kv.second;28+ }
44- break;
45 }29 }
46 }30 }
47- }31+ if (card.supportedInterfaces.empty()) {
48- if (chosenProtocol.empty() || chosenUrl.empty()) {32+ return nullptr;
33+ }
34+ for (const auto& itf : card.supportedInterfaces) {
35+ if (itf.protocolBinding.empty() || itf.url.empty() || itf.protocolVersion.empty()) {
36+ return nullptr;
37+ }
38+ }
39+ 
40+ std::map<std::string, std::string> serverSet;
41+ for (const auto& itf : card.supportedInterfaces) {
42+ auto it = serverSet.find(itf.protocolBinding);
43+ if (it == serverSet.end()) {
44+ serverSet[itf.protocolBinding] = itf.url;
45+ } else {
46+ A2A_LOG(A2A_LOG_LEVEL_WARN, "Duplicate protocolBinding:" + itf.protocolBinding);
47+ }
48+ }
49+ 
50+ std::vector<std::string> clientSet = config.supportedTransports.empty() ?
51+ std::vector<std::string>{JSONRPC_TRANSPORT} : config.supportedTransports;
52+ std::string chosenProtocol;
53+ std::string chosenUrl;
54+ 
55+ if (config.useClientPreference) {
56+ for (const auto& x : clientSet) {
57+ auto it = serverSet.find(x);
58+ if (it != serverSet.end()) {
59+ chosenProtocol = x;
60+ chosenUrl = it->second;
61+ break;
62+ }
63+ }
64+ } else {
65+ for (const auto& kv : std::as_const(serverSet)) {
66+ if (std::find(clientSet.begin(), clientSet.end(), kv.first) != clientSet.end()) {
67+ chosenProtocol = kv.first;
68+ chosenUrl = kv.second;
69+ break;
70+ }
71+ }
72+ }
73+ if (chosenProtocol.empty() || chosenUrl.empty()) {
74+ return nullptr;
75+ }
76+ 
77+ std::shared_ptr<ClientTransport> transport = nullptr;
78+ if (chosenProtocol == JSONRPC_TRANSPORT) {
79+ transport = std::make_shared<JsonRpcTransport>(chosenUrl, card, interceptors);
80+ }
81+ 
82+ if (transport == nullptr) {
83+ return nullptr;
84+ }
85+ 
86+ return std::make_shared<DefaultClient>(card, config, transport, consumers, interceptors);
87+ } catch (const std::exception& e) {
88+ A2A_LOG(A2A_LOG_LEVEL_ERROR, std::string("exception occured: ") + e.what());
49 return nullptr;89 return nullptr;
50 }90 }
91+}
51 92 
52- std::shared_ptr<ClientTransport> transport = nullptr;93+std::shared_ptr<Client> ClientFactory::Create(const AgentCard& card, const ClientConfig& config,
53- if (chosenProtocol == JSONRPC_TRANSPORT) {94+ std::shared_ptr<ClientTransport> transport, const std::vector<Consumer>& consumers)
54- transport = std::make_shared<JsonRpcTransport>(chosenUrl, card, interceptors);95+{
55- }96+ try {
56- 97+ if (transport == nullptr) {
57- if (transport == nullptr) {98+ return nullptr;
99+ }
100+ return std::make_shared<DefaultClient>(card, config, transport, consumers);
101+ } catch (const std::exception& e) {
102+ A2A_LOG(A2A_LOG_LEVEL_ERROR, std::string("exception occured: ") + e.what());
58 return nullptr;103 return nullptr;
59 }104 }
60- 
61- return std::make_shared<DefaultClient>(card, config, transport, consumers, interceptors);
62}105}
63 106 
64} // namespace A2A::Client107} // namespace A2A::Client
@@ -0,0 +1,126 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ */
4+ 
5+#include <nlohmann/json.hpp>
6+#include <stdexcept>
7+#include <future>
8+#include <string>
9+ 
10+#include "uuid.h"
11+#include "a2a_log.h"
12+#include "jsonrpc.h"
13+#include "http_card_resolver.h"
14+ 
15+namespace A2A::Client {
16+ 
17+namespace {
18+constexpr int K_BAD_ALLOC = -32110;
19+constexpr int K_TRANSPORT_EXCEPTION = -32102;
20+constexpr int K_INVALID_FORMAT = -32106;
21+} // namespace
22+ 
23+HttpCardResolver::HttpCardResolver(
24+ std::string baseUrl,
25+ const std::optional<std::string>& relativeCardPath,
26+ std::map<std::string, std::string> httpKwargs)
27+ : baseUrl_(std::move(baseUrl)), relativeCardPath_(relativeCardPath), httpKwargs_(std::move(httpKwargs))
28+{
29+ std::string path = relativeCardPath_.value_or("");
30+ 
31+ // combine urls
32+ std::string fullPath = baseUrl_;
33+ // remove ending '/' from baseUrl
34+ if (!fullPath.empty() && fullPath.back() == '/') {
35+ fullPath.pop_back();
36+ }
37+ // ensure path starts with '/'(avoiding '//')
38+ if (!path.empty()) {
39+ if (path.front() != '/') {
40+ fullPath += '/';
41+ }
42+ fullPath += path;
43+ }
44+ // create JSONRPC transport
45+ transport_ = std::make_shared<JsonRpcTransport>(fullPath, AgentCard{},
46+ std::vector<std::shared_ptr<ClientCallInterceptor>>{});
47+ // register callback
48+ transport_->SetTransportCallback([this](const std::string& id, const TransportEvent& ev) {
49+ this->OnTransportEvent(id, ev);
50+ });
51+}
52+ 
53+std::future<AgentCard> HttpCardResolver::GetAgentCard([[maybe_unused]] const std::optional<std::string>&
54+ relativeCardPath) const
55+{
56+ std::string requestId = GenerateUuid();
57+ std::shared_ptr<std::promise<AgentCard>> promise;
58+ try {
59+ promise = std::make_shared<std::promise<AgentCard>>();
60+ {
61+ std::lock_guard<std::mutex> lock(callbackMutex_);
62+ pendingPromises_[requestId] = promise;
63+ }
64+ 
65+ // send request
66+ transport_->GetCard(requestId, nullptr);
67+ } catch (const std::bad_alloc& e) {
68+ A2A_LOG(A2A_LOG_LEVEL_ERROR, std::string("exception occured: ") + e.what());
69+ std::promise<AgentCard> fallbackPromise;
70+ fallbackPromise.set_exception(CreateExceptionPtr(K_BAD_ALLOC, e.what()));
71+ std::lock_guard<std::mutex> lock(callbackMutex_);
72+ pendingPromises_.erase(requestId);
73+ return fallbackPromise.get_future();
74+ } catch (const std::exception& e) {
75+ std::lock_guard<std::mutex> lock(callbackMutex_);
76+ pendingPromises_.erase(requestId);
77+ promise->set_exception(CreateExceptionPtr(K_TRANSPORT_EXCEPTION, e.what()));
78+ }
79+ 
80+ return promise->get_future();
81+}
82+ 
83+std::future<std::vector<AgentCard>> HttpCardResolver::GetAllAgentCards() const
84+{
85+ auto outerCardFuture = GetAgentCard(std::nullopt);
86+ return std::async(std::launch::async,
87+ [cardFuture = std::move(outerCardFuture)]() mutable -> std::vector<AgentCard> {
88+ AgentCard card = cardFuture.get();
89+ return {std::move(card)};
90+ });
91+}
92+ 
93+void HttpCardResolver::OnTransportEvent(const std::string& requestId, const TransportEvent& event)
94+{
95+ std::shared_ptr<std::promise<AgentCard>> promise;
96+ {
97+ std::lock_guard<std::mutex> lock(callbackMutex_);
98+ auto it = pendingPromises_.find(requestId);
99+ if (it != pendingPromises_.end()) {
100+ promise = std::move(it->second);
101+ pendingPromises_.erase(it);
102+ }
103+ }
104+ 
105+ if (!promise) {
106+ return;
107+ }
108+ 
109+ // check event type
110+ if (const TransportError* err = std::get_if<TransportError>(&event)) {
111+ promise->set_exception(CreateExceptionPtr(err->errorCode, err->errInfo));
112+ } else if (const AgentCard* card = std::get_if<AgentCard>(&event)) {
113+ promise->set_value(*card);
114+ } else {
115+ // wrong type (i.e. Message, Task)
116+ promise->set_exception(CreateExceptionPtr(K_INVALID_FORMAT, "invalid response format for GetCard"));
117+ }
118+}
119+ 
120+std::exception_ptr HttpCardResolver::CreateExceptionPtr(int code, const std::string& msg) const
121+{
122+ nlohmann::json error = {{"code", code}, {"message", msg}};
123+ return std::make_exception_ptr(std::runtime_error(error.dump()));
124+}
125+ 
126+} // namespace A2A::Client
@@ -0,0 +1,47 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
3+ */
4+ 
5+#ifndef HTTP_CARD_RESOLVER
6+#define HTTP_CARD_RESOLVER
7+ 
8+#include <string>
9+#include <map>
10+#include <future>
11+#include <memory>
12+#include <unordered_map>
13+#include <mutex>
14+#include <optional>
15+ 
16+#include "client/a2a_card_resolver.h"
17+#include "client/jsonrpc_transport.h"
18+ 
19+namespace A2A::Client {
20+ 
21+class HttpCardResolver : public A2ACardResolver {
22+public:
23+ HttpCardResolver(std::string baseUrl, const std::optional<std::string>& relativeCardPath,
24+ std::map<std::string, std::string> httpKwargs = {});
25+ 
26+ ~HttpCardResolver() override = default;
27+ 
28+ std::future<AgentCard> GetAgentCard(
29+ const std::optional<std::string>& relativeCardPath = std::nullopt) const override;
30+ 
31+ std::future<std::vector<AgentCard>> GetAllAgentCards() const override;
32+ 
33+protected:
34+ std::string baseUrl_;
35+ std::optional<std::string> relativeCardPath_;
36+ std::map<std::string, std::string> httpKwargs_;
37+ std::shared_ptr<JsonRpcTransport> transport_;
38+ 
39+ void OnTransportEvent(const std::string& requestId, const TransportEvent& event);
40+ std::exception_ptr CreateExceptionPtr(int code, const std::string& msg) const;
41+ mutable std::mutex callbackMutex_;
42+ mutable std::unordered_map<std::string, std::shared_ptr<std::promise<AgentCard>>> pendingPromises_;
43+};
44+ 
45+} // namespace A2A::Client
46+ 
47+#endif
@@ -0,0 +1,29 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
3+ */
4+ 
5+#include "a2a_log.h"
6+#include "http_card_resolver.h"
7+#include "client/http_card_resolver_builder.h"
8+ 
9+namespace A2A::Client {
10+ 
11+HttpCardResolverBuilder::~HttpCardResolverBuilder() = default;
12+ 
13+std::shared_ptr<A2ACardResolver> HttpCardResolverBuilder::Build(std::string baseUrl, std::string agentCardPath,
14+ const std::map<std::string, std::string>& httpKwargs)
15+{
16+ try {
17+ if (baseUrl.empty() || agentCardPath.empty()) {
18+ A2A_LOG(A2A_LOG_LEVEL_ERROR, "HttpCardResolverBuilder::Build invalid parameter.");
19+ return nullptr;
20+ }
21+ 
22+ return std::make_shared<HttpCardResolver>(std::move(baseUrl), std::move(agentCardPath), httpKwargs);
23+ } catch (const std::exception& e) {
24+ A2A_LOG(A2A_LOG_LEVEL_ERROR, std::string("exception occured: ") + e.what());
25+ return nullptr;
26+ }
27+}
28+ 
29+} // namespace A2A::Client
@@ -4,27 +4,84 @@
4 4 
5#include <memory>5#include <memory>
6#include <variant>6#include <variant>
7+#include <regex>
7 8 
8#include "server/server_impl.h"9#include "server/server_impl.h"
9#include "server/task_store.h"10#include "server/task_store.h"
10#include "server/agent_executor.h"11#include "server/agent_executor.h"
12+#include "a2a_log.h"
11#include "types.h"13#include "types.h"
12#include "server/http_server_builder.h"14#include "server/http_server_builder.h"
13 15 
14namespace A2A::Server {16namespace A2A::Server {
15 17 
18+constexpr size_t PORT_GROUP = 3;
19+constexpr size_t PATH_GROUP = 4;
20+constexpr int MAX_PORT = 65535;
21+constexpr int MIN_PORT = 1;
22+ 
16HttpServerBuilder::~HttpServerBuilder() = default;23HttpServerBuilder::~HttpServerBuilder() = default;
17 24 
18-std::shared_ptr<Server> HttpServerBuilder::Build(const HttpConfig& config,25+static std::shared_ptr<AgentCard> setProtocolBinding(const AgentCard &agentCard, const std::string& transportType)
19- std::shared_ptr<AgentCard> agentCard,
20- std::shared_ptr<AgentCard> extendedAgentCard,
21- std::shared_ptr<AgentExecutor> agentExecutor,
22- std::shared_ptr<TaskStore> taskStore)
23{26{
24- ServerConfig serverConfig = HttpConfig{config.ip, config.port};27+ auto modifiedAgentCard = std::make_shared<AgentCard>(agentCard);
28+ if (modifiedAgentCard->supportedInterfaces[0].protocolBinding != transportType) {
29+ A2A_LOG(A2A_LOG_LEVEL_WARN, "Agent card's primaryInterface.protocolBinding is not " +
30+ transportType + ", changing to default value");
31+ modifiedAgentCard->supportedInterfaces[0].protocolBinding = transportType;
32+ }
33+ return modifiedAgentCard;
34+}
35+ 
36+std::shared_ptr<Server> HttpServerBuilder::Build(const HttpConfig& config,
37+ const AgentCard& agentCard, const AgentCard& extendedAgentCard,
38+ std::shared_ptr<AgentExecutor> agentExecutor, std::shared_ptr<TaskStore> taskStore)
39+{
40+ std::string endpoint = "/jsonrpc";
41+
42+ if (agentCard.supportedInterfaces.empty()) {
43+ A2A_LOG(A2A_LOG_LEVEL_ERROR, "agentCard.supportedInterfaces is empty");
44+ throw std::runtime_error("agentCard.supportedInterfaces is empty");
45+ }
46+ 
47+ if (agentCard.supportedInterfaces[0].url.empty()) {
48+ A2A_LOG(A2A_LOG_LEVEL_ERROR, "agentCard.supportedInterfaces[0].url is empty");
49+ throw std::runtime_error("agentCard.supportedInterfaces[0].url is empty");
50+ }
51+
52+ std::regex url_regex(R"(^(https?:\/\/)?([^:\/\s]+):(\d+)(\/.*)?$)");
53+ std::smatch matches;
54+
55+ if (std::regex_match(agentCard.supportedInterfaces[0].url, matches, url_regex)) {
56+ int port = std::stoi(matches[PORT_GROUP].str());
57+ if (port < MIN_PORT || port > MAX_PORT) {
58+ A2A_LOG(A2A_LOG_LEVEL_ERROR, "Invalid port in agentCard.url");
59+ throw std::runtime_error("Invalid port in agentCard.url");
60+ }
61+
62+ if (matches[PATH_GROUP].matched) {
63+ endpoint = matches[PATH_GROUP].str();
64+ }
65+ } else {
66+ size_t last_slash = agentCard.supportedInterfaces[0].url.rfind('/');
67+ if (last_slash != std::string::npos) {
68+ endpoint = agentCard.supportedInterfaces[0].url.substr(last_slash);
69+ }
70+ A2A_LOG(A2A_LOG_LEVEL_WARN, "Using fallback endpoint extraction: " + endpoint);
71+ }
72+
73+ HttpConfig configWithEndpoint;
74+ configWithEndpoint.ip = config.ip;
75+ configWithEndpoint.port = config.port;
76+ configWithEndpoint.ioThreadNum = config.ioThreadNum;
77+ configWithEndpoint.endpoint = endpoint;
78+
79+ ServerConfig serverConfig = configWithEndpoint;
80+
81+ std::shared_ptr<AgentCard> modifiedAgentCard = setProtocolBinding(agentCard, JSONRPC_TRANSPORT);
25 auto server = std::make_shared<ServerImpl>(82 auto server = std::make_shared<ServerImpl>(
26- agentCard,83+ modifiedAgentCard,
27- extendedAgentCard,84+ std::make_shared<AgentCard>(extendedAgentCard),
28 agentExecutor,85 agentExecutor,
29 serverConfig,86 serverConfig,
30 taskStore87 taskStore
@@ -33,4 +90,4 @@ std::shared_ptr<Server> HttpServerBuilder::Build(const HttpConfig& config,
33 return server;90 return server;
34}91}
35 92 
36-} // namespace A2A::Server93+} // namespace A2A::Server
@@ -25,16 +25,15 @@ static bool IsSupportedStreamingMethod(const std::string& method)
25static std::unique_ptr<Transport::ServerTransport> BuildAgentCardTransport(25static std::unique_ptr<Transport::ServerTransport> BuildAgentCardTransport(
26 const std::shared_ptr<AgentCard>& agentCard, const ServerConfig& config)26 const std::shared_ptr<AgentCard>& agentCard, const ServerConfig& config)
27{27{
28- if (!agentCard || !agentCard->preferredTransport) {28+ if (!agentCard || agentCard->supportedInterfaces.empty()) {
29 return nullptr;29 return nullptr;
30 }30 }
31 31 
32- if (agentCard->preferredTransport.value() == JSONRPC_TRANSPORT) {32+ if (agentCard->supportedInterfaces[0].protocolBinding == JSONRPC_TRANSPORT) {
33 return std::make_unique<A2A::Transport::HttpServerTransport>(std::get<HttpConfig>(config));33 return std::make_unique<A2A::Transport::HttpServerTransport>(std::get<HttpConfig>(config));
34- } else {
35- // Placeholder for other transport types
36- return nullptr;
37 }34 }
35+ // Placeholder for other transport types
36+ return nullptr;
38}37}
39 38 
40ServerImpl::ServerImpl(std::shared_ptr<AgentCard> agentCard,39ServerImpl::ServerImpl(std::shared_ptr<AgentCard> agentCard,
@@ -5,8 +5,11 @@
5#ifndef A2A_COMMON_TYPES_H5#ifndef A2A_COMMON_TYPES_H
6#define A2A_COMMON_TYPES_H6#define A2A_COMMON_TYPES_H
7 7 
8+#include <optional>
8#include <string>9#include <string>
9 10 
11+#include "types.h"
12+ 
10namespace A2A {13namespace A2A {
11 14 
12constexpr const char* METHOD_MESSAGE_SEND = "message/send";15constexpr const char* METHOD_MESSAGE_SEND = "message/send";
@@ -45,6 +48,15 @@ struct UserData {
45 bool isStream = false;48 bool isStream = false;
46};49};
47 50 
51+struct BaseResponse {
52+ std::optional<std::string> id;
53+ std::string jsonrpc = JSON_VERSION;
54+};
55+ 
56+struct GetAgentCardSuccessResponse : public BaseResponse {
57+ AgentCard result;
58+};
59+ 
48}60}
49 61 
50#endif62#endif
@@ -12,6 +12,7 @@
12#include <vector>12#include <vector>
13 13 
14#include "types.h"14#include "types.h"
15+#include "common_types.h"
15 16 
16namespace nlohmann {17namespace nlohmann {
17 // Role serializers18 // Role serializers
@@ -1600,7 +1601,8 @@ namespace nlohmann {
1600 throw std::runtime_error("AgentSkill.name cannot be empty");1601 throw std::runtime_error("AgentSkill.name cannot be empty");
1601 }1602 }
1602 1603 
1603- j = nlohmann::json{{"id", s.id}, {"name", s.name}, {"description", s.description}, {"tags", s.tags}};1604+ j = nlohmann::json{{A2A::JSON_FIELD_ID, s.id}, {"name", s.name}, {"description", s.description},
1605+ {"tags", s.tags}};
1604 1606 
1605 if (s.examples) {1607 if (s.examples) {
1606 j["examples"] = *s.examples;1608 j["examples"] = *s.examples;
@@ -1613,15 +1615,20 @@ namespace nlohmann {
1613 if (s.outputModes) {1615 if (s.outputModes) {
1614 j["outputModes"] = *s.outputModes;1616 j["outputModes"] = *s.outputModes;
1615 }1617 }
1618+ 
1619+ if (s.extension) {
1620+ j["extension"] = *s.extension;
1621+ }
1616 }1622 }
1617 1623 
1618 static void from_json(const nlohmann::json& j, A2A::AgentSkill& s)1624 static void from_json(const nlohmann::json& j, A2A::AgentSkill& s)
1619 {1625 {
1620- if (!j.contains("id") || !j.contains("name") || !j.contains("description") || !j.contains("tags")) {1626+ if (!j.contains(A2A::JSON_FIELD_ID) || !j.contains("name") || !j.contains("description") ||
1627+ !j.contains("tags")) {
1621 throw std::runtime_error("AgentSkill missing required fields");1628 throw std::runtime_error("AgentSkill missing required fields");
1622 }1629 }
1623 1630 
1624- j.at("id").get_to(s.id);1631+ j.at(A2A::JSON_FIELD_ID).get_to(s.id);
1625 j.at("name").get_to(s.name);1632 j.at("name").get_to(s.name);
1626 j.at("description").get_to(s.description);1633 j.at("description").get_to(s.description);
1627 j.at("tags").get_to(s.tags);1634 j.at("tags").get_to(s.tags);
@@ -1644,6 +1651,10 @@ namespace nlohmann {
1644 if (j.contains("outputModes")) {1651 if (j.contains("outputModes")) {
1645 s.outputModes = j.at("outputModes").get<std::vector<std::string>>();1652 s.outputModes = j.at("outputModes").get<std::vector<std::string>>();
1646 }1653 }
1654+ 
1655+ if (j.contains("extension")) {
1656+ s.extension = j.at("extension").get<std::string>();
1657+ }
1647 }1658 }
1648 };1659 };
1649 1660 
@@ -1705,8 +1716,12 @@ namespace nlohmann {
1705 j["pushNotifications"] = *c.pushNotifications;1716 j["pushNotifications"] = *c.pushNotifications;
1706 }1717 }
1707 1718 
1708- if (c.stateTransitionHistory) {1719+ if (c.extendedAgentCard) {
1709- j["stateTransitionHistory"] = *c.stateTransitionHistory;1720+ j["extendedAgentCard"] = *c.extendedAgentCard;
1721+ }
1722+ 
1723+ if (c.extension) {
1724+ j["extension"] = *c.extension;
1710 }1725 }
1711 1726 
1712 if (c.extensions) {1727 if (c.extensions) {
@@ -1724,8 +1739,12 @@ namespace nlohmann {
1724 c.pushNotifications = j.at("pushNotifications").get<bool>();1739 c.pushNotifications = j.at("pushNotifications").get<bool>();
1725 }1740 }
1726 1741 
1727- if (j.contains("stateTransitionHistory")) {1742+ if (j.contains("extendedAgentCard")) {
1728- c.stateTransitionHistory = j.at("stateTransitionHistory").get<bool>();1743+ c.extendedAgentCard = j.at("extendedAgentCard").get<bool>();
1744+ }
1745+ 
1746+ if (j.contains("extension")) {
1747+ c.extension = j.at("extension").get<std::string>();
1729 }1748 }
1730 1749 
1731 if (j.contains("extensions")) {1750 if (j.contains("extensions")) {
@@ -1752,21 +1771,153 @@ namespace nlohmann {
1752 }1771 }
1753 };1772 };
1754 1773 
1774+ // AgentInterface serializers
1775+ template<>
1776+ struct adl_serializer<A2A::AgentInterface> {
1777+ static void to_json(nlohmann::json& j, const A2A::AgentInterface& iface)
1778+ {
1779+ j = nlohmann::json{
1780+ {"url", iface.url},
1781+ {"protocolBinding", iface.protocolBinding},
1782+ {"protocolVersion", iface.protocolVersion},
1783+ };
1784+ 
1785+ if (iface.tenant) {
1786+ j["tenant"] = *iface.tenant;
1787+ }
1788+ }
1789+ 
1790+ static void from_json(const nlohmann::json& j, A2A::AgentInterface& iface)
1791+ {
1792+ if (!j.contains("url")) {
1793+ throw std::runtime_error("AgentInterface must contain 'url' field");
1794+ }
1795+ j.at("url").get_to(iface.url);
1796+ 
1797+ if (!j.contains("protocolBinding")) {
1798+ throw std::runtime_error("AgentInterface must contain 'protocolBinding' field");
1799+ }
1800+ j.at("protocolBinding").get_to(iface.protocolBinding);
1801+ 
1802+ if (!j.contains("protocolVersion")) {
1803+ throw std::runtime_error("AgentInterface must contain 'protocolVersion' field");
1804+ }
1805+ j.at("protocolVersion").get_to(iface.protocolVersion);
1806+ 
1807+ if (j.contains("tenant")) {
1808+ iface.tenant = j.at("tenant").get<std::string>();
1809+ }
1810+ }
1811+ };
1812+ 
1813+ // SecurityRequirement serializers
1814+ template<>
1815+ struct adl_serializer<A2A::SecurityRequirement> {
1816+ static void to_json(nlohmann::json& j, const A2A::SecurityRequirement& sr)
1817+ {
1818+ j = nlohmann::json::object();
1819+ for (const auto& [scheme_name, scopes] : sr.schemes) {
1820+ j[scheme_name] = scopes;
1821+ }
1822+ }
1823+
1824+ static void from_json(const nlohmann::json& j, A2A::SecurityRequirement& sr)
1825+ {
1826+ if (!j.is_object()) {
1827+ throw std::runtime_error("SecurityRequirement must be a JSON object");
1828+ }
1829+
1830+ sr.schemes.clear();
1831+ for (auto it = j.begin(); it != j.end(); ++it) {
1832+ const std::string& scheme_name = it.key();
1833+ const nlohmann::json& scheme_value = it.value();
1834+
1835+ // Checking whether the value is an array.
1836+ if (!scheme_value.is_array()) {
1837+ throw std::runtime_error(
1838+ "SecurityRequirement scheme '" + scheme_name +
1839+ "' must be a JSON array of strings"
1840+ );
1841+ }
1842+
1843+ // Parsing a String Array
1844+ std::vector<std::string> scopes;
1845+ for (const auto& scope : scheme_value) {
1846+ if (!scope.is_string()) {
1847+ throw std::runtime_error(
1848+ "SecurityRequirement scope value must be a string in scheme '" +
1849+ scheme_name + "'"
1850+ );
1851+ }
1852+ scopes.push_back(scope.get<std::string>());
1853+ }
1854+
1855+ sr.schemes[scheme_name] = std::move(scopes);
1856+ }
1857+ }
1858+ };
1859+ 
1860+ // AgentCardSignature serializers
1861+ template<>
1862+ struct adl_serializer<A2A::AgentCardSignature> {
1863+ static void to_json(nlohmann::json& j, const A2A::AgentCardSignature& sig)
1864+ {
1865+ j = nlohmann::json{
1866+ {"protected", sig.protected_},
1867+ {"signature", sig.signature}
1868+ };
1869+
1870+ if (sig.header.has_value()) {
1871+ // The header is a JSON string and needs to be parsed before being assigned a value.
1872+ try {
1873+ j["header"] = nlohmann::json::parse(*sig.header);
1874+ } catch (const nlohmann::json::parse_error& e) {
1875+ // If the parsing fails, the value is stored as a string (fallback).
1876+ j["header"] = *sig.header;
1877+ }
1878+ }
1879+ }
1880+
1881+ static void from_json(const nlohmann::json& j, A2A::AgentCardSignature& sig)
1882+ {
1883+ if (j.contains("protected") && j["protected"].is_string()) {
1884+ sig.protected_ = j["protected"].get<std::string>();
1885+ } else {
1886+ throw std::runtime_error("AgentCardSignature missing required field: protected");
1887+ }
1888+
1889+ if (j.contains("signature") && j["signature"].is_string()) {
1890+ sig.signature = j["signature"].get<std::string>();
1891+ } else {
1892+ throw std::runtime_error("AgentCardSignature missing required field: signature");
1893+ }
1894+
1895+ if (j.contains("header") && !j["header"].is_null()) {
1896+ if (j["header"].is_string()) {
1897+ sig.header = j["header"].get<std::string>();
1898+ } else {
1899+ sig.header = j["header"].dump();
1900+ }
1901+ } else {
1902+ sig.header.reset();
1903+ }
1904+ }
1905+ };
1906+ 
1755 // AgentCard serializers1907 // AgentCard serializers
1756 template<>1908 template<>
1757 struct adl_serializer<A2A::AgentCard> {1909 struct adl_serializer<A2A::AgentCard> {
1758 static void to_json(nlohmann::json& j, const A2A::AgentCard& c)1910 static void to_json(nlohmann::json& j, const A2A::AgentCard& c)
1759 {1911 {
1760 j = nlohmann::json{1912 j = nlohmann::json{
1761- {"protocolVersion", c.protocolVersion},1913+ {"name", c.name},
1762- {"name", c.name},1914+ {"description", c.description},
1763- {"description", c.description},1915+ {"version", c.version},
1764- {"url", c.url},1916+ {"capabilities", c.capabilities},
1765- {"version", c.version},1917+ {"defaultInputModes", c.defaultInputModes},
1766- {"capabilities", c.capabilities},1918+ {"defaultOutputModes", c.defaultOutputModes},
1767- {"defaultInputModes", c.defaultInputModes},1919+ {"skills", c.skills},
1768- {"defaultOutputModes", c.defaultOutputModes},1920+ {"supportedInterfaces", c.supportedInterfaces}
1769- {"skills", c.skills}
1770 };1921 };
1771 1922 
1772 if (c.provider) {1923 if (c.provider) {
@@ -1784,19 +1935,27 @@ namespace nlohmann {
1784 if (c.security) {1935 if (c.security) {
1785 j["security"] = *c.security;1936 j["security"] = *c.security;
1786 }1937 }
1787- if (c.supportsAuthenticatedExtendedCard) {1938+ 
1788- j["supportsAuthenticatedExtendedCard"] = *c.supportsAuthenticatedExtendedCard;1939+ if (c.securityRequirements) {
1940+ j["securityRequirements"] = *c.securityRequirements;
1789 }1941 }
1790- if (c.preferredTransport) {1942+ if (c.signatures) {
1791- j["preferredTransport"] = *c.preferredTransport;1943+ j["signatures"] = *c.signatures;
1944+ }
1945+ 
1946+ if (c.category) {
1947+ j["category"] = *c.category;
1948+ }
1949+ if (c.extension) {
1950+ j["extension"] = *c.extension;
1792 }1951 }
1793 }1952 }
1794 1953 
1795 static void from_json(const nlohmann::json& j, A2A::AgentCard& c)1954 static void from_json(const nlohmann::json& j, A2A::AgentCard& c)
1796 {1955 {
1797 const std::vector<std::string> required_fields = {1956 const std::vector<std::string> required_fields = {
1798- "protocolVersion", "name", "description", "url", "version", "capabilities",1957+ "name", "description", "version", "capabilities",
1799- "defaultInputModes", "defaultOutputModes", "skills"1958+ "defaultInputModes", "defaultOutputModes", "skills", "supportedInterfaces"
1800 };1959 };
1801 1960 
1802 for (const auto& field : required_fields) {1961 for (const auto& field : required_fields) {
@@ -1805,15 +1964,14 @@ namespace nlohmann {
1805 }1964 }
1806 }1965 }
1807 1966 
1808- j.at("protocolVersion").get_to(c.protocolVersion);
1809 j.at("name").get_to(c.name);1967 j.at("name").get_to(c.name);
1810 j.at("description").get_to(c.description);1968 j.at("description").get_to(c.description);
1811- j.at("url").get_to(c.url);
1812 j.at("version").get_to(c.version);1969 j.at("version").get_to(c.version);
1813 j.at("capabilities").get_to(c.capabilities);1970 j.at("capabilities").get_to(c.capabilities);
1814 j.at("defaultInputModes").get_to(c.defaultInputModes);1971 j.at("defaultInputModes").get_to(c.defaultInputModes);
1815 j.at("defaultOutputModes").get_to(c.defaultOutputModes);1972 j.at("defaultOutputModes").get_to(c.defaultOutputModes);
1816 j.at("skills").get_to(c.skills);1973 j.at("skills").get_to(c.skills);
1974+ j.at("supportedInterfaces").get_to(c.supportedInterfaces);
1817 1975 
1818 if (j.contains("provider")) {1976 if (j.contains("provider")) {
1819 c.provider = j.at("provider").get<A2A::AgentProvider>();1977 c.provider = j.at("provider").get<A2A::AgentProvider>();
@@ -1828,16 +1986,52 @@ namespace nlohmann {
1828 c.securitySchemes = j.at("securitySchemes").get<std::map<std::string, A2A::SecurityScheme>>();1986 c.securitySchemes = j.at("securitySchemes").get<std::map<std::string, A2A::SecurityScheme>>();
1829 }1987 }
1830 if (j.contains("security")) {1988 if (j.contains("security")) {
1831- c.security = j.at("security").get<std::vector<nlohmann::json>>();1989+ c.security = j.at("security").get<std::vector<std::string>>();
1832 }1990 }
1833- if (j.contains("supportsAuthenticatedExtendedCard")) {1991+ 
1834- c.supportsAuthenticatedExtendedCard = j.at("supportsAuthenticatedExtendedCard").get<bool>();1992+ if (j.contains("securityRequirements") && j["securityRequirements"].is_array()) {
1993+ c.securityRequirements = j.at("securityRequirements").get<std::vector<A2A::SecurityRequirement>>();
1835 }1994 }
1836- if (j.contains("preferredTransport")) {1995+ if (j.contains("signatures") && j["signatures"].is_array()) {
1837- c.preferredTransport = j.at("preferredTransport").get<std::string>();1996+ c.signatures = j.at("signatures").get<std::vector<A2A::AgentCardSignature>>();
1997+ }
1998+ 
1999+ if (j.contains("category")) {
2000+ c.category = j.at("category").get<std::string>();
2001+ }
2002+ if (j.contains("extension")) {
2003+ c.extension = j.at("extension").get<std::string>();
1838 }2004 }
1839 }2005 }
1840 };2006 };
2007+ 
2008+// GetAgentCardSuccessResponse serializers
2009+template<>
2010+struct adl_serializer<A2A::GetAgentCardSuccessResponse> {
2011+ static void to_json(nlohmann::json& j, const A2A::GetAgentCardSuccessResponse& r)
2012+ {
2013+ j = {{A2A::JSON_FIELD_JSONRPC, r.jsonrpc}, {A2A::JSON_FIELD_RESULT, r.result}};
2014+ 
2015+ if (r.id) {
2016+ j[A2A::JSON_FIELD_ID] = *r.id;
2017+ }
2018+ }
2019+ 
2020+ static void from_json(const nlohmann::json& j, A2A::GetAgentCardSuccessResponse& r)
2021+ {
2022+ if (j.contains(A2A::JSON_FIELD_ID)) {
2023+ r.id = j.at(A2A::JSON_FIELD_ID);
2024+ }
2025+ 
2026+ if (j.contains(A2A::JSON_FIELD_JSONRPC)) {
2027+ r.jsonrpc = j.at(A2A::JSON_FIELD_JSONRPC).get<std::string>();
2028+ }
2029+ 
2030+ r.result = j.at(A2A::JSON_FIELD_RESULT).get<A2A::AgentCard>();
2031+ }
2032+};
2033+ 
2034+ 
1841} // namespace nlohmann2035} // namespace nlohmann
1842 2036 
1843#endif // A2A_TYPES_SERIALIZATION_H2037#endif // A2A_TYPES_SERIALIZATION_H
@@ -0,0 +1,375 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ */
4+ 
5+#include <gtest/gtest.h>
6+#include <gmock/gmock.h>
7+ 
8+#include <memory>
9+#include <string>
10+#include <vector>
11+#include <map>
12+#include <stdexcept>
13+ 
14+#include "client/client_factory.h"
15+#include "client/client_call_interceptor.h"
16+#include "client/client.h"
17+#include "types.h"
18+ 
19+namespace A2A::Client::Test {
20+ 
21+using namespace A2A;
22+using namespace A2A::Client;
23+using ::testing::_;
24+using ::testing::Return;
25+using ::testing::NiceMock;
26+ 
27+// Create a basic AgentCard with JSON-RPC and IPC interfaces.
28+static AgentCard MakeTestAgentCard()
29+{
30+ AgentCard card;
31+ card.name = "Test Agent";
32+ card.description = "Test Description";
33+ card.version = "1.0.0";
34+ 
35+ AgentInterface jsonrpcInterface;
36+ jsonrpcInterface.protocolBinding = JSONRPC_TRANSPORT;
37+ jsonrpcInterface.url = "http://localhost:8080/jsonrpc";
38+ jsonrpcInterface.protocolVersion = "2.0";
39+ 
40+ card.supportedInterfaces = {jsonrpcInterface};
41+ 
42+ return card;
43+}
44+ 
45+// Create a ClientConfig with specified transports and preference.
46+static ClientConfig MakeTestConfig(const std::vector<std::string>& transports, bool useClientPreference)
47+{
48+ ClientConfig config;
49+ config.supportedTransports = transports;
50+ config.useClientPreference = useClientPreference;
51+ return config;
52+}
53+ 
54+// Create a test consumer function.
55+static Consumer MakeTestConsumer()
56+{
57+ auto func = [](const std::variant<Message, A2AError, std::pair<Task, std::variant<std::monostate,
58+ TaskStatusUpdateEvent, TaskArtifactUpdateEvent>>>&, const AgentCard&) {
59+ // Empty implementation for testing
60+ };
61+ return Consumer(func);
62+}
63+ 
64+class MockInterceptor : public ClientCallInterceptor {
65+public:
66+ MOCK_METHOD5(Intercept,
67+ void(const std::string& methodName,
68+ std::string& payload,
69+ std::map<std::string, std::string>& headers,
70+ const AgentCard* agentCard,
71+ const ClientCallContext* context));
72+};
73+ 
74+class ClientFactoryTest : public ::testing::Test {
75+protected:
76+ void SetUp() override
77+ {
78+ card = MakeTestAgentCard();
79+ config = MakeTestConfig({JSONRPC_TRANSPORT}, true);
80+ }
81+ 
82+ AgentCard card;
83+ ClientConfig config;
84+ std::vector<Consumer> emptyConsumers;
85+ std::vector<std::shared_ptr<ClientCallInterceptor>> emptyInterceptors;
86+};
87+ 
88+// ===========================================================================
89+// Part I – Basic client creation
90+// ===========================================================================
91+ 
92+// Valid card and config should create a client successfully.
93+TEST_F(ClientFactoryTest, CreateBasicClient)
94+{
95+ auto client = ClientFactory::Create(card, config, emptyConsumers, emptyInterceptors);
96+ EXPECT_NE(client, nullptr);
97+}
98+ 
99+// Creating a client with valid HTTP/JSON-RPC configuration.
100+TEST_F(ClientFactoryTest, CreateHttpClient)
101+{
102+ AgentCard httpCard = card;
103+ httpCard.supportedInterfaces.clear();
104+ 
105+ AgentInterface httpInterface;
106+ httpInterface.protocolBinding = JSONRPC_TRANSPORT;
107+ httpInterface.url = "https://api.example.com/a2a";
108+ httpInterface.protocolVersion = "2.0";
109+ httpCard.supportedInterfaces.push_back(httpInterface);
110+ 
111+ ClientConfig httpConfig = MakeTestConfig({JSONRPC_TRANSPORT}, true);
112+ 
113+ auto client = ClientFactory::Create(httpCard, httpConfig, emptyConsumers, emptyInterceptors);
114+ EXPECT_NE(client, nullptr);
115+}
116+ 
117+// ===========================================================================
118+// Part II – Parameter validation
119+// ===========================================================================
120+ 
121+// Factory must reject a null interceptor.
122+TEST_F(ClientFactoryTest, CreateWithNullInterceptor_ReturnsNull)
123+{
124+ auto mockInterceptor = std::make_shared<NiceMock<MockInterceptor>>();
125+ std::vector<std::shared_ptr<ClientCallInterceptor>> interceptors = {mockInterceptor, nullptr};
126+ 
127+ auto client = ClientFactory::Create(card, config, emptyConsumers, interceptors);
128+ EXPECT_EQ(client, nullptr);
129+}
130+ 
131+// Factory must reject an AgentCard with empty supportedInterfaces.
132+TEST_F(ClientFactoryTest, CreateWithEmptyInterfaces_ReturnsNull)
133+{
134+ card.supportedInterfaces.clear();
135+ 
136+ auto client = ClientFactory::Create(card, config, emptyConsumers, emptyInterceptors);
137+ EXPECT_EQ(client, nullptr);
138+}
139+ 
140+// Factory must reject an AgentCard with invalid interface (missing url).
141+TEST_F(ClientFactoryTest, CreateWithInvalidInterface_MissingUrl_ReturnsNull)
142+{
143+ AgentInterface invalidInterface;
144+ invalidInterface.protocolBinding = JSONRPC_TRANSPORT;
145+ // url missing
146+ invalidInterface.protocolVersion = "2.0";
147+ card.supportedInterfaces = {invalidInterface};
148+ 
149+ auto client = ClientFactory::Create(card, config, emptyConsumers, emptyInterceptors);
150+ EXPECT_EQ(client, nullptr);
151+}
152+ 
153+// Factory must reject an AgentCard with invalid interface (missing protocolBinding).
154+TEST_F(ClientFactoryTest, CreateWithInvalidInterface_MissingProtocolBinding_ReturnsNull)
155+{
156+ AgentInterface invalidInterface;
157+ // protocolBinding missing
158+ invalidInterface.url = "http://localhost:8080/jsonrpc";
159+ invalidInterface.protocolVersion = "2.0";
160+ card.supportedInterfaces = {invalidInterface};
161+ 
162+ auto client = ClientFactory::Create(card, config, emptyConsumers, emptyInterceptors);
163+ EXPECT_EQ(client, nullptr);
164+}
165+ 
166+// Factory must reject an AgentCard with invalid interface (missing protocolVersion).
167+TEST_F(ClientFactoryTest, CreateWithInvalidInterface_MissingProtocolVersion_ReturnsNull)
168+{
169+ AgentInterface invalidInterface;
170+ invalidInterface.protocolBinding = JSONRPC_TRANSPORT;
171+ invalidInterface.url = "http://localhost:8080/jsonrpc";
172+ // protocolVersion missing
173+ 
174+ card.supportedInterfaces = {invalidInterface};
175+ 
176+ auto client = ClientFactory::Create(card, config, emptyConsumers, emptyInterceptors);
177+ EXPECT_EQ(client, nullptr);
178+}
179+ 
180+// Factory must reject a config with empty transport string.
181+TEST_F(ClientFactoryTest, CreateWithInvalidConfig_EmptyTransport_ReturnsNull)
182+{
183+ ClientConfig invalidConfig = MakeTestConfig({JSONRPC_TRANSPORT, ""}, true);
184+ 
185+ auto client = ClientFactory::Create(card, invalidConfig, emptyConsumers, emptyInterceptors);
186+ EXPECT_EQ(client, nullptr);
187+}
188+ 
189+// ===========================================================================
190+// Part III – Protocol selection logic
191+// ===========================================================================
192+ 
193+// With client preference, factory should choose first matching protocol.
194+TEST_F(ClientFactoryTest, ProtocolSelection_ClientPreference_FirstMatch)
195+{
196+ ClientConfig prefConfig = MakeTestConfig({JSONRPC_TRANSPORT}, true);
197+ 
198+ auto client = ClientFactory::Create(card, prefConfig, emptyConsumers, emptyInterceptors);
199+ EXPECT_NE(client, nullptr);
200+}
201+ 
202+// With server preference, factory should choose first server protocol supported by client.
203+TEST_F(ClientFactoryTest, ProtocolSelection_ServerPreference_FirstMatch)
204+{
205+ ClientConfig serverPrefConfig = MakeTestConfig({JSONRPC_TRANSPORT}, false);
206+ 
207+ auto client = ClientFactory::Create(card, serverPrefConfig, emptyConsumers, emptyInterceptors);
208+ EXPECT_NE(client, nullptr); // Should choose server's JSONRPC
209+}
210+ 
211+// When no matching protocol exists, factory must return null.
212+TEST_F(ClientFactoryTest, ProtocolSelection_NoMatchingProtocol_ReturnsNull)
213+{
214+ ClientConfig noMatchConfig = MakeTestConfig({"UNKNOWN_PROTOCOL"}, true);
215+ 
216+ auto client = ClientFactory::Create(card, noMatchConfig, emptyConsumers, emptyInterceptors);
217+ EXPECT_EQ(client, nullptr);
218+}
219+ 
220+// When supportedTransports is empty, factory should use default JSONRPC.
221+TEST_F(ClientFactoryTest, ProtocolSelection_DefaultTransport_WhenConfigEmpty)
222+{
223+ ClientConfig defaultConfig = MakeTestConfig({}, true);
224+ 
225+ auto client = ClientFactory::Create(card, defaultConfig, emptyConsumers, emptyInterceptors);
226+ EXPECT_NE(client, nullptr);
227+}
228+ 
229+// Duplicate protocol bindings should be handled gracefully.
230+TEST_F(ClientFactoryTest, ProtocolSelection_DuplicateBindings_Succeeds)
231+{
232+ AgentInterface duplicateInterface;
233+ duplicateInterface.protocolBinding = JSONRPC_TRANSPORT;
234+ duplicateInterface.url = "http://localhost:8080/jsonrpc2";
235+ duplicateInterface.protocolVersion = "2.0";
236+ 
237+ card.supportedInterfaces.push_back(duplicateInterface);
238+ 
239+ auto client = ClientFactory::Create(card, config, emptyConsumers, emptyInterceptors);
240+ EXPECT_NE(client, nullptr); // Should succeed, only warning logged
241+}
242+ 
243+// ===========================================================================
244+// Part IV – Component integration
245+// ===========================================================================
246+ 
247+// Factory should accept consumers.
248+TEST_F(ClientFactoryTest, CreateWithConsumers_Succeeds)
249+{
250+ std::vector<Consumer> consumers = {MakeTestConsumer()};
251+ 
252+ auto client = ClientFactory::Create(card, config, consumers, emptyInterceptors);
253+ EXPECT_NE(client, nullptr);
254+}
255+ 
256+// Factory should accept multiple consumers.
257+TEST_F(ClientFactoryTest, CreateWithMultipleConsumers_Succeeds)
258+{
259+ std::vector<Consumer> consumers = {
260+ MakeTestConsumer(),
261+ MakeTestConsumer(),
262+ MakeTestConsumer()
263+ };
264+ 
265+ auto client = ClientFactory::Create(card, config, consumers, emptyInterceptors);
266+ EXPECT_NE(client, nullptr);
267+}
268+ 
269+// Factory should accept interceptors.
270+TEST_F(ClientFactoryTest, CreateWithInterceptors_Succeeds)
271+{
272+ auto mockInterceptor = std::make_shared<NiceMock<MockInterceptor>>();
273+ std::vector<std::shared_ptr<ClientCallInterceptor>> interceptors = {mockInterceptor};
274+ 
275+ auto client = ClientFactory::Create(card, config, emptyConsumers, interceptors);
276+ EXPECT_NE(client, nullptr);
277+}
278+ 
279+// Factory should accept multiple interceptors.
280+TEST_F(ClientFactoryTest, CreateWithMultipleInterceptors_Succeeds)
281+{
282+ std::vector<std::shared_ptr<ClientCallInterceptor>> interceptors;
283+ for (int i = 0; i < 5; i++) {
284+ interceptors.push_back(std::make_shared<NiceMock<MockInterceptor>>());
285+ }
286+ 
287+ auto client = ClientFactory::Create(card, config, emptyConsumers, interceptors);
288+ EXPECT_NE(client, nullptr);
289+}
290+ 
291+// Factory should accept both consumers and interceptors.
292+TEST_F(ClientFactoryTest, CreateWithAllComponents_Succeeds)
293+{
294+ auto mockInterceptor = std::make_shared<NiceMock<MockInterceptor>>();
295+ std::vector<std::shared_ptr<ClientCallInterceptor>> interceptors = {mockInterceptor};
296+ 
297+ std::vector<Consumer> consumers = {MakeTestConsumer()};
298+ 
299+ auto client = ClientFactory::Create(card, config, consumers, interceptors);
300+ EXPECT_NE(client, nullptr);
301+}
302+ 
303+// ===========================================================================
304+// Part VII – Edge cases
305+// ===========================================================================
306+ 
307+TEST_F(ClientFactoryTest, CreateWithNullTransport_ReturnsNull)
308+{
309+ auto client = ClientFactory::Create(card, config, nullptr, emptyConsumers);
310+ EXPECT_EQ(client, nullptr);
311+}
312+ 
313+// Server preference with no matching protocol should return null.
314+TEST_F(ClientFactoryTest, ServerPreference_NoMatch_ReturnsNull)
315+{
316+ ClientConfig serverPrefConfig = MakeTestConfig({"UNSUPPORTED_TRANSPORT"}, false);
317+ 
318+ // Card only supports JSONRPC
319+ card.supportedInterfaces.clear();
320+ AgentInterface jsonrpcInterface;
321+ jsonrpcInterface.protocolBinding = JSONRPC_TRANSPORT;
322+ jsonrpcInterface.url = "http://localhost:8080/jsonrpc";
323+ jsonrpcInterface.protocolVersion = "2.0";
324+ card.supportedInterfaces.push_back(jsonrpcInterface);
325+ 
326+ auto client = ClientFactory::Create(card, serverPrefConfig, emptyConsumers, emptyInterceptors);
327+ EXPECT_EQ(client, nullptr);
328+}
329+ 
330+// Unsupported transport type should return null.
331+TEST_F(ClientFactoryTest, UnsupportedTransport_ReturnsNull)
332+{
333+ AgentInterface unsupportedInterface;
334+ unsupportedInterface.protocolBinding = "UNSUPPORTED";
335+ unsupportedInterface.url = "http://localhost:8080/unsupported";
336+ unsupportedInterface.protocolVersion = "1.0";
337+ card.supportedInterfaces = {unsupportedInterface};
338+ 
339+ ClientConfig unsupportedConfig = MakeTestConfig({"UNSUPPORTED"}, true);
340+ 
341+ auto client = ClientFactory::Create(card, unsupportedConfig, emptyConsumers, emptyInterceptors);
342+ EXPECT_EQ(client, nullptr);
343+}
344+ 
345+// Empty config should still work (default transport).
346+TEST_F(ClientFactoryTest, EmptyConfig_Succeeds)
347+{
348+ ClientConfig emptyConfig;
349+ 
350+ auto client = ClientFactory::Create(card, emptyConfig, emptyConsumers, emptyInterceptors);
351+ EXPECT_NE(client, nullptr);
352+}
353+ 
354+TEST_F(ClientFactoryTest, ServerPreference_WithUnsupportedFirst_FallsBack)
355+{
356+ card.supportedInterfaces.clear();
357+ 
358+ AgentInterface unsupportedInterface;
359+ unsupportedInterface.protocolBinding = "UNSUPPORTED";
360+ unsupportedInterface.url = "unsupported://test";
361+ unsupportedInterface.protocolVersion = "1.0";
362+ 
363+ AgentInterface jsonrpcInterface;
364+ jsonrpcInterface.protocolBinding = JSONRPC_TRANSPORT;
365+ jsonrpcInterface.url = "http://localhost:8080/jsonrpc";
366+ jsonrpcInterface.protocolVersion = "2.0";
367+ 
368+ card.supportedInterfaces = {unsupportedInterface, jsonrpcInterface};
369+ ClientConfig serverPrefConfig = MakeTestConfig({JSONRPC_TRANSPORT}, false);
370+ 
371+ auto client = ClientFactory::Create(card, serverPrefConfig, emptyConsumers, emptyInterceptors);
372+ EXPECT_NE(client, nullptr);
373+}
374+ 
375+}
@@ -0,0 +1,459 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ */
4+ 
5+#include <gtest/gtest.h>
6+#include <gmock/gmock.h>
7+#include <memory>
8+#include <future>
9+#include <chrono>
10+#include <thread>
11+#include <iostream>
12+ 
13+#include "client/http_card_resolver.h"
14+#include "client/jsonrpc_transport.h"
15+#include "types.h"
16+ 
17+namespace A2A::Client::Test {
18+ 
19+using namespace A2A::Client;
20+using ::testing::_;
21+using ::testing::Return;
22+using ::testing::Invoke;
23+using ::testing::SaveArg;
24+using ::testing::DoAll;
25+using ::testing::NiceMock;
26+ 
27+// ===========================================================================
28+// Mock JsonRpcTransport
29+// ===========================================================================
30+class MockJsonRpcTransport : public JsonRpcTransport {
31+public:
32+ MockJsonRpcTransport() : JsonRpcTransport("", AgentCard{}, ClientConfig{}, {})
33+ {}
34+ 
35+ MOCK_METHOD(void, SetTransportCallback, (TransportEventCallback), (override));
36+ MOCK_METHOD(void, GetCard, (const std::string&, const ClientCallContext*, int), (override));
37+ MOCK_METHOD(void, Close, (), (override));
38+ 
39+ MOCK_METHOD(void, SendMessage, (const std::string&, const MessageSendParams&, const ClientCallContext*, int),
40+ (override));
41+ MOCK_METHOD(void, SendMessageStreaming, (const std::string&, const MessageSendParams&,
42+ const ClientCallContext*, int), (override));
43+ MOCK_METHOD(void, GetTask, (const std::string&, const TaskQueryParams&,
44+ const ClientCallContext*, int), (override));
45+ MOCK_METHOD(void, CancelTask, (const std::string&, const TaskIdParams&, const ClientCallContext*, int),
46+ (override));
47+ MOCK_METHOD(void, SetTaskPushNotificationConfig, (const std::string&, const TaskPushNotificationConfig&,
48+ const ClientCallContext*, int), (override));
49+ MOCK_METHOD(void, GetTaskPushNotificationConfig, (const std::string&, const GetTaskPushNotificationConfigParams&,
50+ const ClientCallContext*, int), (override));
51+ MOCK_METHOD(void, ListTaskPushNotificationConfigs, (const std::string&, const ListTaskPushNotificationConfigParams&,
52+ const ClientCallContext*, int), (override));
53+ MOCK_METHOD(void, DeleteTaskPushNotificationConfig, (const std::string&,
54+ const DeleteTaskPushNotificationConfigParams&, const ClientCallContext*, int), (override));
55+ MOCK_METHOD(void, Resubscribe, (const std::string&, const TaskIdParams&, const ClientCallContext*, int),
56+ (override));
57+};
58+ 
59+// ===========================================================================
60+// Testable HttpCardResolver - 测试专用子类
61+// ===========================================================================
62+class TestableHttpCardResolver : public HttpCardResolver {
63+public:
64+ TestableHttpCardResolver(std::string baseUrl,
65+ const std::optional<std::string>& relativeCardPath,
66+ std::map<std::string, std::string> httpKwargs)
67+ : HttpCardResolver(std::move(baseUrl), relativeCardPath, std::move(httpKwargs))
68+ {
69+ }
70+ 
71+ ~TestableHttpCardResolver()
72+ {
73+ // 析构时标记为无效
74+ invalid_ = true;
75+ }
76+ 
77+ // 允许设置 mock transport
78+ void SetMockTransport(std::shared_ptr<JsonRpcTransport> transport)
79+ {
80+ transport_ = transport;
81+ 
82+ // 保存 this 指针,但会在回调中检查有效性
83+ TestableHttpCardResolver* rawThis = this;
84+ std::atomic<bool>* invalid = &invalid_;
85+ 
86+ transport_->SetTransportCallback([rawThis, invalid](const std::string& id, const TransportEvent& ev) {
87+ if (!invalid->load() && rawThis) {
88+ rawThis->OnTransportEvent(id, ev);
89+ }
90+ });
91+ }
92+ 
93+ // 暴露 protected 方法用于测试
94+ void TriggerOnTransportEvent(const std::string& requestId, const TransportEvent& event)
95+ {
96+ OnTransportEvent(requestId, event);
97+ }
98+ 
99+ // 获取 pending promises 数量
100+ size_t GetPendingPromiseCount()
101+ {
102+ std::lock_guard<std::mutex> lock(callbackMutex_);
103+ return pendingPromises_.size();
104+ }
105+ 
106+ // 获取最后一个 requestId(用于测试)
107+ std::string GetLastRequestId()
108+ {
109+ std::lock_guard<std::mutex> lock(callbackMutex_);
110+ if (pendingPromises_.empty()) {
111+ return "";
112+ }
113+ return pendingPromises_.begin()->first;
114+ }
115+ 
116+ // 验证 promise 是否存在
117+ bool HasPromiseForRequest(const std::string& requestId)
118+ {
119+ std::lock_guard<std::mutex> lock(callbackMutex_);
120+ return pendingPromises_.find(requestId) != pendingPromises_.end();
121+ }
122+ 
123+private:
124+ std::atomic<bool> invalid_{false};
125+};
126+ 
127+// ===========================================================================
128+// HttpCardResolver Mock Test Fixture
129+// ===========================================================================
130+class HttpCardResolverMockTest : public ::testing::Test {
131+protected:
132+ void SetUp() override
133+ {
134+ baseUrl = "https://api.example.com";
135+ relativePath = "agent/card";
136+ httpKwargs = {{"timeout", "30"}};
137+ 
138+ // 创建测试用的 AgentCard
139+ testCard.name = "Test Agent";
140+ testCard.description = "Test Description";
141+ testCard.version = "1.0.0";
142+ 
143+ AgentCapabilities caps;
144+ caps.streaming = true;
145+ caps.pushNotifications = false;
146+ caps.extendedAgentCard = true;
147+ testCard.capabilities = caps;
148+ 
149+ testCard.defaultInputModes = {"text/plain"};
150+ testCard.defaultOutputModes = {"text/plain"};
151+ 
152+ // 创建 mock transport
153+ mockTransport = std::make_shared<NiceMock<MockJsonRpcTransport>>();
154+ 
155+ // 创建 testable resolver
156+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
157+ 
158+ // 设置 mock transport
159+ resolver->SetMockTransport(mockTransport);
160+ }
161+ 
162+ std::string baseUrl;
163+ std::string relativePath;
164+ std::map<std::string, std::string> httpKwargs;
165+ AgentCard testCard;
166+ std::shared_ptr<NiceMock<MockJsonRpcTransport>> mockTransport;
167+ std::shared_ptr<TestableHttpCardResolver> resolver;
168+ 
169+ TransportEventCallback capturedCallback;
170+};
171+ 
172+// ===========================================================================
173+// 测试 SetTransportCallback 被调用
174+// ===========================================================================
175+TEST_F(HttpCardResolverMockTest, SetsTransportCallback)
176+{
177+ EXPECT_CALL(*mockTransport, SetTransportCallback(_))
178+ .WillOnce(SaveArg<0>(&capturedCallback));
179+ 
180+ // 重新创建 resolver 以触发 SetTransportCallback
181+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
182+ resolver->SetMockTransport(mockTransport);
183+ 
184+ ASSERT_NE(capturedCallback, nullptr);
185+}
186+ 
187+// ===========================================================================
188+// 测试 GetAgentCard 调用 GetCard
189+// ===========================================================================
190+TEST_F(HttpCardResolverMockTest, GetAgentCardCallsGetCard)
191+{
192+ std::string capturedRequestId;
193+ 
194+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
195+ .WillOnce(Invoke([&capturedRequestId](const std::string& requestId,
196+ const ClientCallContext*,
197+ int) {
198+ capturedRequestId = requestId;
199+ }));
200+ 
201+ auto future = resolver->GetAgentCard(std::nullopt);
202+ 
203+ // 验证 GetCard 被调用
204+ EXPECT_FALSE(capturedRequestId.empty());
205+ EXPECT_TRUE(resolver->HasPromiseForRequest(capturedRequestId));
206+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 1);
207+}
208+ 
209+// ===========================================================================
210+// 测试成功响应
211+// ===========================================================================
212+TEST_F(HttpCardResolverMockTest, HandlesSuccessResponse)
213+{
214+ // 捕获 requestId 和 callback
215+ std::string capturedRequestId;
216+ TransportEventCallback capturedCallback;
217+ 
218+ EXPECT_CALL(*mockTransport, SetTransportCallback(_))
219+ .WillOnce(SaveArg<0>(&capturedCallback));
220+ 
221+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
222+ .WillOnce(Invoke([&capturedRequestId](const std::string& requestId,
223+ const ClientCallContext*,
224+ int) {
225+ capturedRequestId = requestId;
226+ }));
227+ 
228+ // 重新创建 resolver 以捕获 callback
229+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
230+ resolver->SetMockTransport(mockTransport);
231+ 
232+ // 调用 GetAgentCard
233+ auto future = resolver->GetAgentCard(std::nullopt);
234+ 
235+ // 模拟 transport 成功响应
236+ ASSERT_NE(capturedCallback, nullptr);
237+ ASSERT_FALSE(capturedRequestId.empty());
238+ 
239+ // 创建 TransportEvent 包含 AgentCard
240+ TransportEvent event = testCard;
241+ 
242+ // 触发回调
243+ capturedCallback(capturedRequestId, event);
244+ 
245+ // 验证 promise 被移除
246+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 0);
247+ 
248+ // 验证 future 完成并返回正确的值
249+ EXPECT_EQ(future.wait_for(std::chrono::milliseconds(100)), std::future_status::ready);
250+ AgentCard result = future.get();
251+ EXPECT_EQ(result.name, testCard.name);
252+ EXPECT_EQ(result.version, testCard.version);
253+}
254+ 
255+// ===========================================================================
256+// 测试错误响应
257+// ===========================================================================
258+TEST_F(HttpCardResolverMockTest, HandlesErrorResponse)
259+{
260+ std::string capturedRequestId;
261+ TransportEventCallback capturedCallback;
262+ 
263+ EXPECT_CALL(*mockTransport, SetTransportCallback(_))
264+ .WillOnce(SaveArg<0>(&capturedCallback));
265+ 
266+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
267+ .WillOnce(Invoke([&capturedRequestId](const std::string& requestId,
268+ const ClientCallContext*,
269+ int) {
270+ capturedRequestId = requestId;
271+ }));
272+ 
273+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
274+ resolver->SetMockTransport(mockTransport);
275+ 
276+ auto future = resolver->GetAgentCard(std::nullopt);
277+ 
278+ // 模拟 transport 错误响应
279+ TransportError error;
280+ error.errorCode = 404;
281+ error.errInfo = "Not found";
282+ 
283+ capturedCallback(capturedRequestId, error);
284+ 
285+ // 验证 promise 被移除
286+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 0);
287+ 
288+ // 验证 future 抛出异常
289+ EXPECT_EQ(future.wait_for(std::chrono::milliseconds(100)), std::future_status::ready);
290+ EXPECT_THROW(future.get(), std::runtime_error);
291+}
292+ 
293+// ===========================================================================
294+// 测试错误响应类型
295+// ===========================================================================
296+TEST_F(HttpCardResolverMockTest, HandlesUnexpectedResponseType)
297+{
298+ std::string capturedRequestId;
299+ TransportEventCallback capturedCallback;
300+ 
301+ EXPECT_CALL(*mockTransport, SetTransportCallback(_))
302+ .WillOnce(SaveArg<0>(&capturedCallback));
303+ 
304+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
305+ .WillOnce(Invoke([&capturedRequestId](const std::string& requestId,
306+ const ClientCallContext*,
307+ int) {
308+ capturedRequestId = requestId;
309+ }));
310+ 
311+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
312+ resolver->SetMockTransport(mockTransport);
313+ 
314+ auto future = resolver->GetAgentCard(std::nullopt);
315+ 
316+ // 模拟错误响应类型(比如返回了 Message)
317+ A2A::Message message;
318+ message.messageId = "test-msg";
319+ 
320+ capturedCallback(capturedRequestId, message);
321+ 
322+ // 验证 promise 被移除
323+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 0);
324+ 
325+ // 验证 future 抛出异常
326+ EXPECT_EQ(future.wait_for(std::chrono::milliseconds(100)), std::future_status::ready);
327+ EXPECT_THROW(future.get(), std::runtime_error);
328+}
329+ 
330+// ===========================================================================
331+// 测试超时/无响应
332+// ===========================================================================
333+TEST_F(HttpCardResolverMockTest, HandlesNoResponse)
334+{
335+ std::string capturedRequestId;
336+ 
337+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
338+ .WillOnce(Invoke([&capturedRequestId](const std::string& requestId,
339+ const ClientCallContext*,
340+ int) {
341+ capturedRequestId = requestId;
342+ }));
343+ 
344+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
345+ resolver->SetMockTransport(mockTransport);
346+ 
347+ auto future = resolver->GetAgentCard(std::nullopt);
348+ 
349+ // 不触发回调,验证 promise 仍然存在
350+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 1);
351+ EXPECT_TRUE(resolver->HasPromiseForRequest(capturedRequestId));
352+ EXPECT_TRUE(future.valid());
353+}
354+ 
355+// ===========================================================================
356+// 测试多个并发请求
357+// ===========================================================================
358+TEST_F(HttpCardResolverMockTest, HandlesConcurrentRequests)
359+{
360+ std::vector<std::string> capturedRequestIds;
361+ TransportEventCallback capturedCallback;
362+ 
363+ EXPECT_CALL(*mockTransport, SetTransportCallback(_))
364+ .WillOnce(SaveArg<0>(&capturedCallback));
365+ 
366+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
367+ .Times(3)
368+ .WillRepeatedly(Invoke([&capturedRequestIds](const std::string& requestId,
369+ const ClientCallContext*,
370+ int) {
371+ capturedRequestIds.push_back(requestId);
372+ }));
373+ 
374+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
375+ resolver->SetMockTransport(mockTransport);
376+ 
377+ // 发送多个请求
378+ std::vector<std::future<AgentCard>> futures;
379+ for (int i = 0; i < 3; i++) {
380+ futures.push_back(resolver->GetAgentCard(std::nullopt));
381+ }
382+ 
383+ // 验证所有请求都被记录
384+ EXPECT_EQ(capturedRequestIds.size(), 3);
385+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 3);
386+ 
387+ // 依次响应每个请求
388+ for (size_t i = 0; i < capturedRequestIds.size(); i++) {
389+ capturedCallback(capturedRequestIds[i], testCard);
390+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 2 - i);
391+ }
392+ 
393+ // 验证所有 future 都完成
394+ for (auto& future : futures) {
395+ EXPECT_EQ(future.wait_for(std::chrono::milliseconds(100)), std::future_status::ready);
396+ EXPECT_NO_THROW(future.get());
397+ }
398+}
399+ 
400+// ===========================================================================
401+// 测试 GetAllAgentCards
402+// ===========================================================================
403+TEST_F(HttpCardResolverMockTest, GetAllAgentCardsWorks)
404+{
405+ std::string capturedRequestId;
406+ TransportEventCallback capturedCallback;
407+ 
408+ EXPECT_CALL(*mockTransport, SetTransportCallback(_))
409+ .WillOnce(SaveArg<0>(&capturedCallback));
410+ 
411+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
412+ .WillOnce(Invoke([&capturedRequestId](const std::string& requestId,
413+ const ClientCallContext*,
414+ int) {
415+ capturedRequestId = requestId;
416+ }));
417+ 
418+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
419+ resolver->SetMockTransport(mockTransport);
420+ 
421+ auto future = resolver->GetAllAgentCards();
422+ 
423+ // 验证 GetCard 被调用
424+ EXPECT_FALSE(capturedRequestId.empty());
425+ 
426+ // 模拟响应
427+ capturedCallback(capturedRequestId, testCard);
428+ 
429+ // 验证结果
430+ EXPECT_EQ(future.wait_for(std::chrono::milliseconds(100)), std::future_status::ready);
431+ std::vector<AgentCard> cards = future.get();
432+ ASSERT_EQ(cards.size(), 1);
433+ EXPECT_EQ(cards[0].name, testCard.name);
434+}
435+ 
436+// ===========================================================================
437+// 测试异常处理
438+// ===========================================================================
439+TEST_F(HttpCardResolverMockTest, HandlesTransportException)
440+{
441+ EXPECT_CALL(*mockTransport, GetCard(_, _, _))
442+ .WillOnce(Invoke([](const std::string&, const ClientCallContext*, int) {
443+ throw std::runtime_error("Transport error");
444+ }));
445+ 
446+ resolver = std::make_shared<TestableHttpCardResolver>(baseUrl, relativePath, httpKwargs);
447+ resolver->SetMockTransport(mockTransport);
448+ 
449+ auto future = resolver->GetAgentCard(std::nullopt);
450+ 
451+ // 验证 promise 被立即移除
452+ EXPECT_EQ(resolver->GetPendingPromiseCount(), 0);
453+ 
454+ // 验证 future 抛出异常
455+ EXPECT_EQ(future.wait_for(std::chrono::milliseconds(100)), std::future_status::ready);
456+ EXPECT_THROW(future.get(), std::runtime_error);
457+}
458+ 
459+} // namespace A2A::Client::Test
@@ -0,0 +1,65 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
3+ */
4+ 
5+#include <gtest/gtest.h>
6+#include <map>
7+#include <memory>
8+#include <string>
9+ 
10+#include "client/http_card_resolver_builder.h"
11+ 
12+namespace A2A::Client {
13+namespace {
14+ 
15+class HttpCardResolverBuilderTest : public ::testing::Test {
16+public:
17+ HttpCardResolverBuilder builder_;
18+};
19+ 
20+TEST_F(HttpCardResolverBuilderTest, Build_BaseUrlEmpty_ReturnsNullptr)
21+{
22+ std::map<std::string, std::string> httpKwargs {
23+ {"timeout", "10"},
24+ {"header", "application/json"}
25+ };
26+ 
27+ auto resolver = builder_.Build("", "/.well-known/agent.json", httpKwargs);
28+ 
29+ EXPECT_EQ(resolver, nullptr);
30+}
31+ 
32+TEST_F(HttpCardResolverBuilderTest, Build_AgentCardPathEmpty_ReturnsNullptr)
33+{
34+ std::map<std::string, std::string> httpKwargs {
35+ {"timeout", "10"}
36+ };
37+ 
38+ auto resolver = builder_.Build("https://example.com", "", httpKwargs);
39+ 
40+ EXPECT_EQ(resolver, nullptr);
41+}
42+ 
43+TEST_F(HttpCardResolverBuilderTest, Build_BaseUrlAndAgentCardPathEmpty_ReturnsNullptr)
44+{
45+ std::map<std::string, std::string> httpKwargs;
46+ 
47+ auto resolver = builder_.Build("", "", httpKwargs);
48+ 
49+ EXPECT_EQ(resolver, nullptr);
50+}
51+ 
52+TEST_F(HttpCardResolverBuilderTest, Build_BaseUrlAndAgentCardPathValid_ReturnsResolver)
53+{
54+ std::map<std::string, std::string> httpKwargs {
55+ {"timeout", "10"},
56+ {"verify", "true"}
57+ };
58+ 
59+ auto resolver = builder_.Build("https://example.com", "/.well-known/agent.json", httpKwargs);
60+ 
61+ ASSERT_NE(resolver, nullptr);
62+}
63+ 
64+} // namespace
65+} // namespace A2A::Client
@@ -0,0 +1,204 @@
1+/*
2+ * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
3+ */
4+ 
5+#include <gtest/gtest.h>
6+ 
7+#include <memory>
8+#include <stdexcept>
9+#include <string>
10+ 
11+#include "server/http_server_builder.h"
12+#include "server/agent_executor.h"
13+#include "server/task_store.h"
14+#include "types.h"
15+ 
16+using namespace A2A;
17+using namespace A2A::Server;
18+ 
19+namespace {
20+ 
21+class DummyAgentExecutor final : public AgentExecutor {
22+public:
23+ void Execute(std::shared_ptr<RequestContext>, std::shared_ptr<TaskUpdater>) override
24+ {
25+ }
26+ 
27+ void Cancel(std::shared_ptr<RequestContext>, std::shared_ptr<TaskUpdater>) override
28+ {
29+ }
30+};
31+ 
32+class DummyTaskStore final : public TaskStore {
33+public:
34+ void Save(const Task&, std::shared_ptr<ServerCallContext>) override
35+ {
36+ }
37+ 
38+ std::shared_ptr<Task> Get(const std::string&, std::shared_ptr<ServerCallContext>) override
39+ {
40+ return nullptr;
41+ }
42+ 
43+ void Delete(const std::string&, std::shared_ptr<ServerCallContext>) override
44+ {
45+ }
46+};
47+ 
48+AgentCard MakeAgentCard(const std::string& url, const std::string& protocolBinding = "http")
49+{
50+ AgentCard card;
51+ AgentInterface iface;
52+ iface.url = url;
53+ iface.protocolBinding = protocolBinding;
54+ card.supportedInterfaces.push_back(iface);
55+ return card;
56+}
57+ 
58+AgentCard MakeExtendedAgentCard()
59+{
60+ AgentCard card;
61+ AgentInterface iface;
62+ iface.url = "http://127.0.0.1:8080/jsonrpc";
63+ iface.protocolBinding = "http";
64+ card.supportedInterfaces.push_back(iface);
65+ return card;
66+}
67+ 
68+HttpConfig MakeHttpConfig()
69+{
70+ HttpConfig cfg;
71+ cfg.ip = "127.0.0.1";
72+ cfg.port = 8080;
73+ cfg.ioThreadNum = 1;
74+ return cfg;
75+}
76+ 
77+class HttpServerBuilderTest : public ::testing::Test {
78+protected:
79+ void SetUp() override
80+ {
81+ config = MakeHttpConfig();
82+ extendedAgentCard = MakeExtendedAgentCard();
83+ executor = std::make_shared<DummyAgentExecutor>();
84+ taskStore = std::make_shared<DummyTaskStore>();
85+ }
86+ 
87+ HttpServerBuilder builder;
88+ HttpConfig config;
89+ AgentCard extendedAgentCard;
90+ std::shared_ptr<AgentExecutor> executor;
91+ std::shared_ptr<TaskStore> taskStore;
92+};
93+ 
94+} // namespace
95+ 
96+TEST_F(HttpServerBuilderTest, Build_WhenSupportedInterfacesEmpty_Throws)
97+{
98+ AgentCard agentCard;
99+ 
100+ EXPECT_THROW(
101+ builder.Build(config, agentCard, extendedAgentCard, executor, taskStore),
102+ std::runtime_error);
103+}
104+ 
105+TEST_F(HttpServerBuilderTest, Build_WhenPrimaryUrlEmpty_Throws)
106+{
107+ AgentCard agentCard = MakeAgentCard("");
108+ 
109+ EXPECT_THROW(
110+ builder.Build(config, agentCard, extendedAgentCard, executor, taskStore),
111+ std::runtime_error);
112+}
113+ 
114+TEST_F(HttpServerBuilderTest, Build_WhenUrlPortIsZero_Throws)
115+{
116+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:0/jsonrpc");
117+ 
118+ EXPECT_THROW(
119+ builder.Build(config, agentCard, extendedAgentCard, executor, taskStore),
120+ std::runtime_error);
121+}
122+ 
123+TEST_F(HttpServerBuilderTest, Build_WhenUrlPortExceedsMax_Throws)
124+{
125+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:65536/jsonrpc");
126+ 
127+ EXPECT_THROW(
128+ builder.Build(config, agentCard, extendedAgentCard, executor, taskStore),
129+ std::runtime_error);
130+}
131+ 
132+TEST_F(HttpServerBuilderTest, Build_WhenUrlHasValidPortAndPath_ReturnsServer)
133+{
134+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:9000/custom-path");
135+ 
136+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, taskStore);
137+ 
138+ ASSERT_NE(server, nullptr);
139+}
140+ 
141+TEST_F(HttpServerBuilderTest, Build_WhenUrlHasValidPortWithoutPath_ReturnsServer)
142+{
143+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:9000");
144+ 
145+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, taskStore);
146+ 
147+ ASSERT_NE(server, nullptr);
148+}
149+ 
150+TEST_F(HttpServerBuilderTest, Build_WhenUrlHasNoSchemeButValidHostPortPath_ReturnsServer)
151+{
152+ AgentCard agentCard = MakeAgentCard("127.0.0.1:9000/jsonrpc-alt");
153+ 
154+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, taskStore);
155+ 
156+ ASSERT_NE(server, nullptr);
157+}
158+ 
159+TEST_F(HttpServerBuilderTest, Build_WhenUrlDoesNotMatchRegexButHasSlash_UsesFallbackAndReturnsServer)
160+{
161+ AgentCard agentCard = MakeAgentCard("not_a_standard_url/abc");
162+ 
163+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, taskStore);
164+ 
165+ ASSERT_NE(server, nullptr);
166+}
167+ 
168+TEST_F(HttpServerBuilderTest, Build_WhenUrlDoesNotMatchRegexAndHasNoSlash_UsesDefaultEndpointAndReturnsServer)
169+{
170+ AgentCard agentCard = MakeAgentCard("not_a_standard_url");
171+ 
172+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, taskStore);
173+ 
174+ ASSERT_NE(server, nullptr);
175+}
176+ 
177+TEST_F(HttpServerBuilderTest, Build_DoesNotMutateOriginalAgentCardProtocolBinding)
178+{
179+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:9000/jsonrpc", "something-else");
180+ const std::string originalProtocol = agentCard.supportedInterfaces[0].protocolBinding;
181+ 
182+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, taskStore);
183+ 
184+ ASSERT_NE(server, nullptr);
185+ EXPECT_EQ(agentCard.supportedInterfaces[0].protocolBinding, originalProtocol);
186+}
187+ 
188+TEST_F(HttpServerBuilderTest, Build_AcceptsNullExecutor)
189+{
190+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:9000/jsonrpc");
191+ 
192+ auto server = builder.Build(config, agentCard, extendedAgentCard, nullptr, taskStore);
193+ 
194+ ASSERT_NE(server, nullptr);
195+}
196+ 
197+TEST_F(HttpServerBuilderTest, Build_AcceptsNullTaskStore)
198+{
199+ AgentCard agentCard = MakeAgentCard("http://127.0.0.1:9000/jsonrpc");
200+ 
201+ auto server = builder.Build(config, agentCard, extendedAgentCard, executor, nullptr);
202+ 
203+ ASSERT_NE(server, nullptr);
204+}