Merge adk module (Agent Development Kit, MCP, A2A, Studio, Garden, AP2)

This commit is contained in:
2026-10-24 04:35:05 +02:00
36 changed files with 4183 additions and 3 deletions
+24
View File
@@ -0,0 +1,24 @@
// Routes: GET /agent/adk, /agent/adk/status, /agent/adk/garden
#include "support/GoogleRig.hpp"
using namespace molo::example::test;
int main() {
GoogleRig none(false);
Fixture f(none.client);
auto page = f.client->get("/agent/adk");
check(page.status == 200, "page 200 without a credential");
check(contains(page.body, "agent_adk.js") && contains(page.body, "adk-run"), "page has the runner UI");
auto st = f.client->get("/agent/adk/status");
check(st.status == 200 && contains(st.body, "\"configured\":false"), "status shows not configured");
check(contains(st.body, "\"max_steps\":12") && contains(st.body, "\"max_tool_calls\":24"), "caps shown");
auto g = f.client->get("/agent/adk/garden");
check(g.status == 200, "garden 200");
for (const char* id : {"code_modernization", "financial_analysis", "economic_research", "invoice_processing"})
check(contains(g.body, id), std::string("garden lists ") + id);
check(none.mock->send_count() == 0, "side effect: no upstream traffic");
check(f.client->post("/agent/adk").status == 405, "post page is 405");
check(f.client->post("/agent/adk/garden").status == 405, "post garden is 405");
check(f.client->get("/agent/adk/run").status == 405, "get run is 405");
return finish("agent/adk page");
}
+29
View File
@@ -0,0 +1,29 @@
// Route: POST /agent/adk/run (validation and credential gate; the model call
// itself is proven live in the google suite, not scripted here)
#include "support/GoogleRig.hpp"
using namespace molo::example::test;
int main() {
GoogleRig none(false);
Fixture f(none.client);
auto post = [&](const std::string& body) {
return f.client->post("/agent/adk/run", body, "application/json");
};
auto ok = post("{\"prompt\":\"total of 2 and 3?\",\"template\":\"financial_analysis\"}");
check(ok.status == 503 && contains(ok.body, "google_not_configured"), "no credential is a loud 503");
check(post("not json").status == 422, "bad json is 422");
check(post("{\"prompt\":\"\"}").status == 422, "empty prompt is 422");
check(post("{\"prompt\":\"" + std::string(2001, 'x') + "\"}").status == 422, "prompt over cap is 422");
check(post("{\"prompt\":\"hi\",\"template\":\"nope\"}").status == 422, "unknown template is 422");
check(none.mock->send_count() == 0, "side effect: nothing sent without a credential");
GoogleRig keyed;
Fixture g(keyed.client);
check(g.client->post("/agent/adk/run", "{\"prompt\":\"\"}", "application/json").status == 422,
"validation also runs with a credential");
check(g.client->post("/agent/adk/run", "{\"prompt\":\"hi\",\"cid\":\"bad id!\"}", "application/json").status == 422,
"bad session id is 422");
check(keyed.mock->send_count() == 0, "rejected input never reached Google");
return finish("agent/adk run");
}
+40
View File
@@ -0,0 +1,40 @@
// Routes: POST /agent/adk/export, /agent/adk/import, /agent/adk/ap2/validate
#include "support/GoogleRig.hpp"
using namespace molo::example::test;
int main() {
GoogleRig none(false);
Fixture f(none.client);
auto post = [&](const std::string& path, const std::string& body) {
return f.client->post(path, body, "application/json");
};
auto ex = post("/agent/adk/export", "{\"template\":\"invoice_processing\"}");
check(ex.status == 200 && contains(ex.body, "\"agent_class\":\"LlmAgent\"") &&
contains(ex.body, "invoice_processing"),
"export returns the definition");
check(contains(ex.body, "\"yaml\":"), "export includes yaml");
check(post("/agent/adk/export", "{\"template\":\"nope\"}").status == 422, "unknown template is 422");
std::string def = "{\"agent_class\":\"SequentialAgent\",\"name\":\"flow\",\"sub_agents\":["
"{\"name\":\"a\",\"model\":\"m\",\"instruction\":\"x\",\"tools\":[{\"name\":\"word_count\"}]}]}";
auto im = post("/agent/adk/import", def);
check(im.status == 200 && contains(im.body, "\"word_count\""), "import round-trips a known tool");
check(post("/agent/adk/import", "{\"name\":\"a\",\"tools\":[{\"name\":\"ghost\"}]}").status == 422,
"unknown tool is 422");
check(post("/agent/adk/import", "{\"name\":\"a\",\"agent_class\":\"Evil\"}").status == 422, "bad class is 422");
check(post("/agent/adk/import", "oops").status == 422, "bad json is 422");
std::string intent = "{\"id\":\"i1\",\"description\":\"sleeve\",\"max_amount_minor\":5000,\"currency\":\"EUR\"}";
std::string cart = "{\"id\":\"c1\",\"intent_id\":\"i1\",\"merchant\":\"m\",\"items\":["
"{\"sku\":\"s\",\"quantity\":2,\"unit_amount_minor\":1500}],\"total_minor\":3000,\"currency\":\"EUR\"}";
check(post("/agent/adk/ap2/validate", "{\"intent\":" + intent + ",\"cart\":" + cart + "}").status == 200,
"valid mandate chain is 200");
std::string bad_cart = cart.substr(0, cart.find("3000,")) + "9999," + cart.substr(cart.find("3000,") + 5);
check(post("/agent/adk/ap2/validate", "{\"intent\":" + intent + ",\"cart\":" + bad_cart + "}").status == 422,
"cart total mismatch is 422");
check(post("/agent/adk/ap2/validate", "{}").status == 422, "missing intent is 422");
check(f.client->get("/agent/adk/export").status == 405, "get export is 405");
check(none.mock->send_count() == 0, "none of these routes call Google");
return finish("agent/adk studio");
}
+72
View File
@@ -0,0 +1,72 @@
#pragma once
// Scripted LanguageModel for ADK tests: replies come from a queue (or a
// repeat reply), every request is recorded. Thread-safe for ParallelAgent.
#include <chrono>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include "clients/body/json.h"
#include "google/gemini_types.h"
namespace adk_test {
using molo::clients::body::Json;
using molo::google::GenerateRequest;
using molo::google::GenerateResponse;
inline GenerateResponse text_reply(const std::string& text) {
return GenerateResponse::from_json(Json::parse(
"{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":" +
Json(text).dump() + "}]}}]}"));
}
inline GenerateResponse call_reply(const std::string& name, const std::string& args_json) {
return GenerateResponse::from_json(Json::parse(
"{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"functionCall\":{\"name\":\"" +
name + "\",\"args\":" + args_json + "}}]}}]}"));
}
class FakeModel : public molo::google::LanguageModel {
public:
void push(GenerateResponse r) { queue_.push_back(std::move(r)); }
// Returned forever once the queue is empty.
void repeat(GenerateResponse r) { repeat_ = std::move(r); has_repeat_ = true; }
void delay_ms(int ms) { delay_ = ms; }
GenerateResponse generate(const GenerateRequest& request) override {
std::lock_guard<std::mutex> lock(mutex_);
seen_.push_back(request);
if (delay_ > 0) std::this_thread::sleep_for(std::chrono::milliseconds(delay_));
if (!queue_.empty()) {
GenerateResponse r = std::move(queue_.front());
queue_.pop_front();
return r;
}
if (has_repeat_) return repeat_;
return text_reply("(fake model queue empty)");
}
void stream(const GenerateRequest& request,
const std::function<bool(const GenerateResponse&)>& on_chunk) override {
on_chunk(generate(request));
}
std::vector<GenerateRequest> seen() {
std::lock_guard<std::mutex> lock(mutex_);
return seen_;
}
std::size_t calls() { return seen().size(); }
private:
std::mutex mutex_;
std::deque<GenerateResponse> queue_;
GenerateResponse repeat_;
bool has_repeat_ = false;
int delay_ = 0;
std::vector<GenerateRequest> seen_;
};
} // namespace adk_test
+353
View File
@@ -0,0 +1,353 @@
// ADK core: agents, tools, runner caps, multi-agent graph, sessions, memory.
// Local logic against a fake LanguageModel; no Google traffic.
#include <memory>
#include "framework.h"
#include "fake_model.h"
#include "google/adk/agent.h"
#include "google/adk/error.h"
#include "google/adk/runner.h"
#include "google/adk/session.h"
#include "google/adk/tool.h"
using namespace molo::google;
using namespace molo::google::adk;
using AdkTool = molo::google::adk::Tool;
using adk_test::call_reply;
using adk_test::FakeModel;
using adk_test::text_reply;
using molo::clients::body::Json;
namespace {
std::shared_ptr<AdkTool> weather_tool(int* counter = nullptr) {
Json city = Json::object();
city.set("type", Json("string"));
Json props = Json::object();
props.set("city", city);
Json req = Json::array();
req.push(Json("city"));
Json schema = Json::object();
schema.set("type", Json("object"));
schema.set("properties", props);
schema.set("required", req);
return std::make_shared<FunctionTool>(
"get_weather", "Weather for a city", schema,
[counter](const Json& args, ToolContext&) {
if (counter) ++*counter;
Json out = Json::object();
out.set("city", *args.find("city"));
out.set("temp_c", Json(21));
return out;
});
}
std::shared_ptr<Agent> llm(const std::string& name, std::vector<std::shared_ptr<AdkTool>> tools = {},
const std::string& instruction = "Be brief.",
const std::string& output_key = "") {
Agent::Config c;
c.name = name;
c.model = "m";
c.instruction = instruction;
c.tools = std::move(tools);
c.output_key = output_key;
return std::make_shared<Agent>(std::move(c));
}
struct Rig {
std::shared_ptr<FakeModel> model = std::make_shared<FakeModel>();
std::shared_ptr<InMemorySessionService> sessions = std::make_shared<InMemorySessionService>();
std::shared_ptr<InMemoryMemoryService> memory = std::make_shared<InMemoryMemoryService>();
Runner runner(RunLimits l = {}) { return Runner(model, sessions, memory, l); }
};
} // namespace
TEST(adk, function_calling_loop) {
Rig r;
int calls = 0;
r.model->push(call_reply("get_weather", "{\"city\":\"Utrecht\"}"));
r.model->push(text_reply("It is 21 C in Utrecht."));
Runner runner = r.runner();
RunResult res = runner.run(llm("root", {weather_tool(&calls)}), "s1", "weather in Utrecht?");
ASSERT_EQ(calls, 1);
ASSERT_EQ(res.text, "It is 21 C in Utrecht.");
ASSERT_EQ(res.stop_reason, "completed");
ASSERT_EQ(res.steps, 2);
ASSERT_EQ(res.tool_calls, 1);
ASSERT_EQ(res.author, "root");
// Second request carries the model's call and our function response.
auto seen = r.model->seen();
ASSERT_EQ(seen.size(), 2u);
ASSERT_EQ(seen[0].tools.size(), 1u);
ASSERT_EQ(seen[0].tools[0].functions[0].name, "get_weather");
ASSERT_EQ(seen[1].contents.size(), 3u);
const Part& fr = seen[1].contents[2].parts[0];
ASSERT_TRUE(fr.function_response.has_value());
ASSERT_EQ(fr.function_response->response.find("temp_c")->as_int(), 21);
}
TEST(adk, tool_errors_go_back_to_the_model) {
Rig r;
r.model->push(call_reply("get_weather", "{}")); // missing required arg
r.model->push(call_reply("get_weather", "{\"city\":5}")); // wrong type
r.model->push(call_reply("nope", "{}")); // unknown tool
r.model->push(text_reply("done"));
Runner runner = r.runner();
RunResult res = runner.run(llm("root", {weather_tool()}), "s", "go");
ASSERT_EQ(res.text, "done");
auto seen = r.model->seen();
auto err = [&](std::size_t i) {
return seen[i].contents.back().parts[0].function_response->response.dump();
};
ASSERT_TRUE(err(1).find("missing required argument: city") != std::string::npos);
ASSERT_TRUE(err(2).find("must be string") != std::string::npos);
ASSERT_TRUE(err(3).find("unknown tool: nope") != std::string::npos);
}
TEST(adk, step_cap_stops_a_runaway_loop) {
Rig r;
r.model->repeat(call_reply("get_weather", "{\"city\":\"x\"}"));
RunLimits l;
l.max_steps = 3;
Runner runner = r.runner(l);
RunResult res = runner.run(llm("root", {weather_tool()}), "s", "loop");
ASSERT_EQ(res.stop_reason, "max_steps");
ASSERT_EQ(r.model->calls(), 3u);
}
TEST(adk, tool_call_cap) {
Rig r;
r.model->repeat(call_reply("get_weather", "{\"city\":\"x\"}"));
RunLimits l;
l.max_tool_calls = 2;
Runner runner = r.runner(l);
RunResult res = runner.run(llm("root", {weather_tool()}), "s", "loop");
ASSERT_EQ(res.stop_reason, "max_tool_calls");
ASSERT_EQ(res.tool_calls, 2);
}
TEST(adk, wall_clock_cap) {
Rig r;
r.model->delay_ms(30);
r.model->repeat(call_reply("get_weather", "{\"city\":\"x\"}"));
RunLimits l;
l.wall_clock_ms = 50;
Runner runner = r.runner(l);
RunResult res = runner.run(llm("root", {weather_tool()}), "s", "loop");
ASSERT_EQ(res.stop_reason, "timeout");
}
TEST(adk, limits_and_input_validation) {
Rig r;
RunLimits big;
big.max_steps = AdkCaps::kMaxSteps + 1;
ASSERT_THROW(r.runner(big), AdkError);
RunLimits zero;
zero.wall_clock_ms = 0;
ASSERT_THROW(r.runner(zero), AdkError);
Runner runner = r.runner();
auto a = llm("root");
ASSERT_THROW(runner.run(a, "s", ""), AdkError);
ASSERT_THROW(runner.run(a, "s", std::string(AdkCaps::kMaxInputChars + 1, 'x')), AdkError);
ASSERT_THROW(runner.run(a, "bad id/../", "hi"), AdkError);
ASSERT_EQ(r.model->calls(), 0u); // rejected before any model call
ASSERT_THROW(llm("bad name"), AdkError);
ASSERT_THROW(llm("root", {weather_tool(), weather_tool(), nullptr}), AdkError);
}
TEST(adk, too_many_calls_in_one_reply) {
Rig r;
std::string parts;
for (int i = 0; i < AdkCaps::kMaxCallsPerStep + 1; ++i)
parts += std::string(i ? "," : "") + "{\"functionCall\":{\"name\":\"get_weather\",\"args\":{\"city\":\"a\"}}}";
r.model->push(GenerateResponse::from_json(Json::parse(
"{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[" + parts + "]}}]}")));
Runner runner = r.runner();
ASSERT_EQ(runner.run(llm("root", {weather_tool()}), "s", "x").stop_reason, "max_calls_per_step");
}
TEST(adk, tool_result_size_cap) {
Rig r;
auto big = std::make_shared<FunctionTool>("big", "", Json(), [](const Json&, ToolContext&) {
Json o = Json::object();
o.set("blob", Json(std::string(AdkCaps::kMaxToolResultBytes + 10, 'x')));
return o;
});
r.model->push(call_reply("big", "{}"));
r.model->push(text_reply("ok"));
Runner runner = r.runner();
runner.run(llm("root", {big}), "s", "x");
auto seen = r.model->seen();
ASSERT_TRUE(seen[1].contents.back().parts[0].function_response->response.dump().find(
"over 32768 bytes") != std::string::npos);
}
TEST(adk, sequential_shares_state_and_templates_instructions) {
Rig r;
auto seq = std::make_shared<SequentialAgent>("pipeline", "");
seq->add_sub_agent(llm("writer", {}, "Write.", "draft"));
seq->add_sub_agent(llm("editor", {}, "Edit this: {draft} (missing {nokey})"));
r.model->push(text_reply("first draft"));
r.model->push(text_reply("final text"));
Runner runner = r.runner();
RunResult res = runner.run(seq, "s", "topic");
ASSERT_EQ(res.text, "final text");
ASSERT_EQ(res.author, "editor");
ASSERT_EQ(res.state.find("draft")->as_string(), "first draft");
auto seen = r.model->seen();
ASSERT_EQ(seen[1].system->parts[0].text, "Edit this: first draft (missing {nokey})");
}
TEST(adk, parallel_runs_all_branches_and_merges) {
Rig r;
auto par = std::make_shared<ParallelAgent>("fanout", "");
par->add_sub_agent(llm("a", {}, "A", "ka"));
par->add_sub_agent(llm("b", {}, "B", "kb"));
r.model->repeat(text_reply("same"));
Runner runner = r.runner();
RunResult res = runner.run(par, "s", "go");
ASSERT_EQ(r.model->calls(), 2u);
ASSERT_EQ(res.text, "a: same\n\nb: same");
ASSERT_TRUE(res.state.has("ka") && res.state.has("kb"));
ASSERT_THROW(par->add_sub_agent(llm("a")), AdkError); // duplicate name
}
TEST(adk, loop_exits_on_tool_and_on_cap) {
{
Rig r;
auto loop = std::make_shared<LoopAgent>("refine", "", 5);
loop->add_sub_agent(llm("worker", {make_exit_loop_tool()}));
r.model->push(text_reply("try 1"));
r.model->push(call_reply("exit_loop", "{}"));
r.model->push(text_reply("good enough"));
Runner runner = r.runner();
RunResult res = runner.run(loop, "s", "go");
ASSERT_EQ(res.text, "good enough");
ASSERT_EQ(r.model->calls(), 3u);
}
{
Rig r;
auto loop = std::make_shared<LoopAgent>("refine", "", 3);
loop->add_sub_agent(llm("worker"));
r.model->repeat(text_reply("again"));
Runner runner = r.runner();
runner.run(loop, "s", "go");
ASSERT_EQ(r.model->calls(), 3u);
}
ASSERT_THROW(LoopAgent("l", "", 0), AdkError);
ASSERT_THROW(LoopAgent("l", "", AdkCaps::kMaxLoopIterations + 1), AdkError);
}
TEST(adk, transfer_to_sub_agent_and_caps) {
Rig r;
auto root = llm("router", {}, "Route.");
root->add_sub_agent(llm("billing"));
root->add_sub_agent(llm("support"));
r.model->push(call_reply("transfer_to_agent", "{\"agent_name\":\"billing\"}"));
r.model->push(text_reply("billing answer"));
Runner runner = r.runner();
RunResult res = runner.run(root, "s", "invoice question");
ASSERT_EQ(res.text, "billing answer");
ASSERT_EQ(res.author, "billing");
auto seen = r.model->seen();
// The router offered the transfer function with both targets; the sub-agent
// got the original user message.
ASSERT_EQ(seen[0].tools[0].functions[0].name, "transfer_to_agent");
ASSERT_EQ(seen[1].contents.back().text(), "invoice question");
}
TEST(adk, unknown_transfer_target_is_a_tool_error_and_pingpong_is_capped) {
{
Rig r;
auto root = llm("router");
root->add_sub_agent(llm("billing"));
r.model->push(call_reply("transfer_to_agent", "{\"agent_name\":\"ghost\"}"));
r.model->push(text_reply("handled myself"));
Runner runner = r.runner();
ASSERT_EQ(runner.run(root, "s", "x").text, "handled myself");
}
{
Rig r;
auto root = llm("a");
root->add_sub_agent(llm("b"));
// a hands to b, b hands back to its parent a, forever.
r.model->repeat(call_reply("transfer_to_agent", "{\"agent_name\":\"b\"}"));
RunLimits l;
Runner runner = r.runner(l);
RunResult res = runner.run(root, "s", "x");
ASSERT_TRUE(res.stop_reason == "max_transfers" || res.stop_reason == "max_steps");
}
}
TEST(adk, graph_shape_caps) {
auto root = llm("root");
for (std::size_t i = 0; i < AdkCaps::kMaxSubAgents; ++i)
root->add_sub_agent(llm("s" + std::to_string(i)));
ASSERT_THROW(root->add_sub_agent(llm("one_too_many")), AdkError);
// Depth: a chain deeper than kMaxAgentDepth is refused at run time.
Rig r;
r.model->repeat(text_reply("x"));
std::shared_ptr<BaseAgent> top = std::make_shared<SequentialAgent>("d0", "");
BaseAgent* cur = top.get();
for (int i = 1; i <= AdkCaps::kMaxAgentDepth; ++i) {
auto next = std::make_shared<SequentialAgent>("d" + std::to_string(i), "");
BaseAgent* raw = next.get();
cur->add_sub_agent(next);
cur = raw;
}
Runner runner = r.runner();
ASSERT_THROW(runner.run(top, "s", "x"), AdkError);
}
TEST(adk, session_history_persists_and_is_bounded) {
Rig r;
r.model->repeat(text_reply("ok"));
Runner runner = r.runner();
auto a = llm("root");
runner.run(a, "s", "first");
runner.run(a, "s", "second");
auto seen = r.model->seen();
// Turn two sees: user "first", model "ok", user "second".
ASSERT_EQ(seen[1].contents.size(), 3u);
ASSERT_EQ(seen[1].contents[0].text(), "first");
ASSERT_EQ(seen[1].contents[1].role, "model");
InMemorySessionService svc;
for (std::size_t i = 0; i < AdkCaps::kMaxSessions + 5; ++i)
svc.create("id" + std::to_string(i), "u");
ASSERT_EQ(svc.size(), AdkCaps::kMaxSessions);
ASSERT_FALSE(svc.get("id0").has_value()); // oldest evicted
Session s = *svc.get("id10");
for (std::size_t i = 0; i < AdkCaps::kMaxEventsPerSession + 20; ++i)
s.events.push_back({"user", Content::user("m"), false});
svc.save(s);
ASSERT_EQ(svc.get("id10")->events.size(), AdkCaps::kMaxEventsPerSession);
s.state.set("big", Json(std::string(AdkCaps::kMaxStateValueBytes + 1, 'x')));
ASSERT_THROW(svc.save(s), AdkError);
ASSERT_THROW(svc.create("id10", "u"), AdkError);
ASSERT_THROW(svc.create("bad id", "u"), AdkError);
}
TEST(adk, memory_service_ranks_and_scopes_by_user) {
Rig r;
r.model->repeat(text_reply("Your favourite colour is green."));
Runner runner = r.runner();
auto a = llm("root");
runner.run(a, "m1", "My favourite colour is green", "alice");
runner.remember("m1");
runner.run(a, "m2", "Unrelated pasta recipe", "bob");
runner.remember("m2");
auto hits = r.memory->search("alice", "what colour do I like", 5);
ASSERT_TRUE(!hits.empty());
ASSERT_TRUE(hits[0].text.find("green") != std::string::npos);
ASSERT_TRUE(r.memory->search("alice", "pasta recipe", 5).empty());
ASSERT_TRUE(!r.memory->search("bob", "pasta recipe", 5).empty());
// The load_memory tool reaches the same data.
r.model->push(call_reply("load_memory", "{\"query\":\"favourite colour\"}"));
r.model->push(text_reply("green"));
runner.run(llm("mem", {make_load_memory_tool(r.memory, "alice")}), "m3", "what do I like?", "alice");
auto seen = r.model->seen();
ASSERT_TRUE(seen.back().contents.back().parts[0].function_response->response.dump().find(
"green") != std::string::npos);
}
+443
View File
@@ -0,0 +1,443 @@
// ADK: Agent Studio definitions, Garden catalog, AP2 types, triggers,
// DirectModel request construction, MCP / A2A protocol clients, live checks.
// MCP and A2A are not Google APIs: their scripted peers follow the primary
// specs (see adk/SPEC.md Sources). No scripted Google replies appear here.
#include <cstdlib>
#include <iostream>
#include <memory>
#include "framework.h"
#include "fake_model.h"
#include "clients/transports/http_transport.h"
#include "clients/transports/mock_transport.h"
#include "google/adk/a2a.h"
#include "google/adk/error.h"
#include "google/adk/ap2.h"
#include "google/adk/direct_model.h"
#include "google/adk/garden.h"
#include "google/adk/mcp.h"
#include "google/adk/runner.h"
#include "google/adk/studio.h"
#include "google/adk/trigger.h"
#include "google/credentials.h"
#include "google/generative.h"
using namespace molo::google;
using namespace molo::google::adk;
using AdkTool = molo::google::adk::Tool;
using adk_test::call_reply;
using adk_test::FakeModel;
using adk_test::text_reply;
using molo::clients::ClientResponse;
using molo::clients::HeaderMap;
using molo::clients::Method;
using molo::clients::body::Json;
using molo::clients::transports::MockTransport;
namespace {
ClientResponse ok_json(const std::string& body, const char* ctype = "application/json") {
HeaderMap h;
h.set("Content-Type", ctype);
return ClientResponse(200, h, body);
}
struct Peer {
MockTransport* mock;
std::shared_ptr<RemoteHttp> http;
Peer() {
auto t = std::make_unique<MockTransport>();
mock = t.get();
http = std::make_shared<RemoteHttp>(
std::make_shared<molo::clients::Client>(std::move(t)));
}
};
std::shared_ptr<Agent> llm(const std::string& name, std::vector<std::shared_ptr<AdkTool>> tools = {}) {
Agent::Config c;
c.name = name;
c.model = "m";
c.instruction = "Do the thing.";
c.tools = std::move(tools);
return std::make_shared<Agent>(std::move(c));
}
std::shared_ptr<AdkTool> echo_tool(const std::string& name) {
return std::make_shared<FunctionTool>(name, "echo", Json(), [](const Json&, ToolContext&) {
return Json::object();
});
}
} // namespace
// ---- Studio -----------------------------------------------------------------
TEST(adk_studio, export_import_round_trip) {
ToolRegistry reg;
reg.add(echo_tool("lookup"));
auto root = llm("root", {reg.find("lookup")});
auto seq = std::make_shared<SequentialAgent>("flow", "runs in order");
seq->add_sub_agent(llm("a"));
auto loop = std::make_shared<LoopAgent>("loop", "", 4);
loop->add_sub_agent(llm("b", {reg.find("exit_loop")}));
seq->add_sub_agent(loop);
root->add_sub_agent(seq);
Json doc = AgentDefinition::to_json(*root);
ASSERT_EQ(doc.find("agent_class")->as_string(), "LlmAgent");
ASSERT_EQ(doc.find("tools")->as_array()[0].find("name")->as_string(), "lookup");
auto copy = AgentDefinition::from_text(doc.dump(), reg);
ASSERT_EQ(AgentDefinition::to_json(*copy).dump(), doc.dump());
ASSERT_TRUE(copy->find("b") != nullptr);
ASSERT_EQ(dynamic_cast<LoopAgent*>(copy->find("loop"))->max_iterations(), 4);
ASSERT_TRUE(AgentDefinition::to_yaml(*root).find("agent_class") != std::string::npos);
}
TEST(adk_studio, rejects_bad_definitions_loudly) {
ToolRegistry reg;
ASSERT_THROW(AgentDefinition::from_text("not json", reg), AdkError);
ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"x\",\"agent_class\":\"EvilAgent\"}", reg), AdkError);
ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"bad name\"}", reg), AdkError);
ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"x\",\"tools\":[{\"name\":\"ghost\"}]}", reg), AdkError);
ASSERT_THROW(AgentDefinition::from_text(
"{\"name\":\"x\",\"sub_agents\":[{\"config_path\":\"y.yaml\"}]}", reg), AdkError);
ASSERT_THROW(AgentDefinition::from_text("{\"name\":\"l\",\"agent_class\":\"LoopAgent\",\"max_iterations\":99}", reg),
AdkError);
ASSERT_THROW(AgentDefinition::from_text(std::string(AdkCaps::kMaxDefinitionBytes + 1, ' '), reg), AdkError);
}
// ---- Garden -----------------------------------------------------------------
TEST(adk_garden, four_templates_instantiate_with_or_without_tools) {
ASSERT_EQ(AgentGarden::templates().size(), 4u);
for (const char* id : {"code_modernization", "financial_analysis", "economic_research", "invoice_processing"})
ASSERT_TRUE(AgentGarden::find(id) != nullptr);
ToolRegistry reg;
std::vector<std::string> missing;
auto bare = AgentGarden::instantiate("invoice_processing", reg, &missing);
ASSERT_EQ(missing.size(), 1u);
ASSERT_TRUE(dynamic_cast<Agent*>(bare.get())->config().tools.empty());
reg.add(echo_tool("validate_invoice"));
auto full = AgentGarden::instantiate("invoice_processing", reg);
ASSERT_EQ(dynamic_cast<Agent*>(full.get())->config().tools.size(), 1u);
ASSERT_THROW(AgentGarden::instantiate("nope", reg), AdkError);
ASSERT_EQ(AgentGarden::catalog_json().find("templates")->as_array().size(), 4u);
}
// ---- AP2 --------------------------------------------------------------------
TEST(adk_ap2, mandate_chain_validation) {
ap2::IntentMandate intent;
intent.id = "int-1";
intent.description = "Buy a laptop sleeve";
intent.merchants = {"shop.example"};
intent.max_amount_minor = 5000;
intent.currency = "EUR";
intent.validate();
ap2::CartMandate cart;
cart.id = "cart-1";
cart.intent_id = "int-1";
cart.merchant = "shop.example";
cart.items = {{"sku1", "Sleeve", 2, 1500}};
cart.total_minor = 3000;
cart.currency = "EUR";
cart.validate_against(intent);
ap2::PaymentMandate pay;
pay.id = "pay-1";
pay.cart_id = "cart-1";
pay.payment_method_token = "tok_abc";
pay.amount_minor = 3000;
pay.currency = "EUR";
pay.validate_against(cart);
ap2::CartMandate round = ap2::CartMandate::from_json(Json::parse(cart.to_json().dump()));
ASSERT_EQ(round.to_json().dump(), cart.to_json().dump());
cart.total_minor = 2999;
ASSERT_THROW(cart.validate(), AdkError); // total != item sum
cart.total_minor = 3000;
cart.merchant = "evil.example";
ASSERT_THROW(cart.validate_against(intent), AdkError);
cart.merchant = "shop.example";
intent.max_amount_minor = 2000;
ASSERT_THROW(cart.validate_against(intent), AdkError);
pay.amount_minor = 1;
ASSERT_THROW(pay.validate_against(cart), AdkError);
intent.currency = "eur";
ASSERT_THROW(intent.validate(), AdkError);
}
// ---- Triggers ---------------------------------------------------------------
TEST(adk_trigger, batch_and_event_dispatch_with_caps) {
auto model = std::make_shared<FakeModel>();
model->repeat(text_reply("handled"));
auto runner = std::make_shared<Runner>(model, std::make_shared<InMemorySessionService>());
TriggerDispatcher dispatcher(runner, llm("worker"));
BatchTrigger batch({{"job1", "a"}, {"job2", "b"}, {"bad id!", "c"}});
auto out = dispatcher.dispatch(batch, 10);
ASSERT_EQ(out.size(), 3u);
ASSERT_TRUE(out[0].ok && out[1].ok);
ASSERT_FALSE(out[2].ok); // a bad id fails alone, the rest ran
ASSERT_EQ(out[0].result.text, "handled");
QueueTrigger queue;
for (std::size_t i = 0; i < AdkCaps::kMaxTriggerQueue; ++i) ASSERT_TRUE(queue.push({"e" + std::to_string(i), "x"}));
ASSERT_FALSE(queue.push({"overflow", "x"}));
ASSERT_EQ(queue.dropped(), 1u);
auto first = dispatcher.dispatch(queue, 100000); // capped to kMaxTriggerBatch
ASSERT_EQ(first.size(), AdkCaps::kMaxTriggerBatch);
}
// ---- DirectModel (request construction only) --------------------------------
TEST(adk_direct, validates_before_network_and_fields_match_declared_table) {
auto transport = std::make_unique<MockTransport>();
MockTransport* mock = transport.get();
auto client = std::make_shared<GoogleClient>(std::move(transport), Credentials::api_key("k"));
DirectModel model(client, "gemini-test");
GenerateRequest bad;
bad.model = "../evil";
bad.contents.push_back(Content::user("hi"));
ASSERT_THROW(model.generate(bad), GoogleError);
ASSERT_EQ(mock->send_count(), 0u);
ASSERT_THROW(DirectModel(client, "a/b"), GoogleError);
// Every top-level key the request builder can emit is a declared field
// (tools/check_discovery.py proves those exist in Google's schemas).
GenerateRequest full;
full.system = Content::user("sys");
full.contents.push_back(Content::user("hi"));
molo::google::Tool t;
t.functions.push_back({"f", "d", Json()});
full.tools.push_back(t);
full.tool_mode = "AUTO";
full.config.temperature = 0.5;
full.safety.push_back({"HARM_CATEGORY_HARASSMENT", "BLOCK_NONE"});
Json body = full.to_json();
for (const auto& [key, v] : body.as_object()) {
bool declared = false;
for (const char* f : kDirectRequestFields) declared = declared || key == f;
ASSERT_TRUE(declared);
}
ASSERT_EQ(body.as_object().size(), 6u);
}
// ---- MCP --------------------------------------------------------------------
TEST(adk_mcp, handshake_list_call_and_tool_adapter) {
Peer p;
p.mock->expect_response(Method::kPost, "/mcp",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}}}"));
p.mock->expect_status(Method::kPost, "/mcp", 202);
p.mock->expect_response(Method::kPost, "/mcp",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"tools\":[{\"name\":\"get-weather\",\"description\":\"d\","
"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"location\":{\"type\":\"string\"}},"
"\"required\":[\"location\"]}}],\"nextCursor\":\"p2\"}}"));
p.mock->expect_response(Method::kPost, "/mcp",
ok_json("data: {\"jsonrpc\":\"2.0\",\"id\":3,\"result\":{\"tools\":[{\"name\":\"ping\",\"inputSchema\":{\"type\":\"object\"}}]}}\n\n",
"text/event-stream"));
p.mock->expect_response(Method::kPost, "/mcp",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":4,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"72F\"}],\"isError\":false}}"));
p.mock->expect_response(Method::kPost, "/mcp",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":5,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"boom\"}],\"isError\":true}}"));
auto mcp = std::make_shared<McpClient>(p.http, "https://mcp.example.com/mcp");
mcp->initialize();
auto tools = mcp->tools();
ASSERT_EQ(tools.size(), 2u);
ASSERT_EQ(tools[0]->name(), "get_weather"); // sanitized for Gemini
ASSERT_EQ(tools[0]->declaration().parameters.find("required")->as_array().size(), 1u);
bool esc = false;
Json state = Json::object();
ToolContext tc{state, "a", esc};
Json args = Json::object();
args.set("location", Json("NYC"));
ASSERT_EQ(tools[0]->call(args, tc).find("text")->as_string(), "72F");
ASSERT_THROW(tools[0]->call(args, tc), AdkError); // isError -> tool error
ASSERT_THROW(tools[0]->call(Json::object(), tc), AdkError); // schema check, no request
auto seen = p.mock->seen();
ASSERT_EQ(seen.size(), 6u);
ASSERT_TRUE(seen[0].body.find("\"method\":\"initialize\"") != std::string::npos);
ASSERT_TRUE(seen[2].body.find("\"method\":\"tools/list\"") != std::string::npos);
ASSERT_TRUE(seen[3].body.find("\"cursor\":\"p2\"") != std::string::npos);
ASSERT_TRUE(seen[4].body.find("\"name\":\"get-weather\"") != std::string::npos);
ASSERT_EQ(seen[2].headers.get_or("MCP-Protocol-Version", ""), "2025-06-18");
}
TEST(adk_mcp, errors_and_url_validation) {
Peer p;
ASSERT_THROW(McpClient(p.http, "ftp://x"), AdkError);
ASSERT_THROW(McpClient(p.http, "not a url"), AdkError);
p.mock->expect_response(Method::kPost, "/mcp",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32602,\"message\":\"Unknown tool\"}}"));
McpClient mcp(p.http, "https://mcp.example.com/mcp");
ASSERT_THROW(mcp.call_tool("x", Json::object()), AdkError);
p.mock->expect_status(Method::kPost, "/mcp", 403, "no");
try {
mcp.list_tools();
FAIL("403 must throw");
} catch (const AdkError& e) {
ASSERT_EQ(e.code(), "upstream");
}
}
// ---- A2A --------------------------------------------------------------------
TEST(adk_a2a, card_send_get_in_both_dialects) {
{
Peer p;
p.mock->expect_response(Method::kGet, "/.well-known/agent-card.json",
ok_json("{\"name\":\"Invoicer\",\"description\":\"d\",\"version\":\"1\","
"\"supportedInterfaces\":[{\"url\":\"https://a2a.example.com/rpc\",\"protocolBinding\":\"JSONRPC\"}],"
"\"capabilities\":{\"streaming\":true},\"skills\":[{\"id\":\"s1\",\"name\":\"Extract\"}]}"));
p.mock->expect_response(Method::kPost, "/rpc",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"task\":{\"id\":\"t1\",\"contextId\":\"c1\","
"\"status\":{\"state\":\"TASK_STATE_COMPLETED\"},"
"\"artifacts\":[{\"parts\":[{\"text\":\"total 42\"}]}]}}}"));
p.mock->expect_response(Method::kPost, "/rpc",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"id\":\"t1\",\"status\":{\"state\":\"TASK_STATE_INPUT_REQUIRED\","
"\"message\":{\"parts\":[{\"text\":\"which currency?\"}]}}}}"));
auto a2a = std::make_shared<A2aClient>(p.http, "https://a2a.example.com/");
A2aCard card = a2a->fetch_card();
ASSERT_EQ(card.name, "Invoicer");
ASSERT_TRUE(card.streaming);
ASSERT_EQ(card.skills.size(), 1u);
ASSERT_EQ(a2a->endpoint(), "https://a2a.example.com/rpc");
A2aTask t = a2a->send_message("invoice please");
ASSERT_EQ(t.state, "completed");
ASSERT_TRUE(t.terminal());
ASSERT_EQ(t.text, "total 42");
A2aTask g = a2a->get_task("t1");
ASSERT_EQ(g.state, "input-required");
ASSERT_EQ(g.text, "which currency?");
auto seen = p.mock->seen();
ASSERT_TRUE(seen[1].body.find("\"method\":\"SendMessage\"") != std::string::npos);
ASSERT_TRUE(seen[1].body.find("ROLE_USER") != std::string::npos);
ASSERT_TRUE(seen[2].body.find("\"method\":\"GetTask\"") != std::string::npos);
}
{
Peer p;
p.mock->expect_response(Method::kPost, "/",
ok_json("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"kind\":\"message\",\"role\":\"agent\","
"\"messageId\":\"m\",\"parts\":[{\"kind\":\"text\",\"text\":\"hello\"}]}}"));
auto a2a = std::make_shared<A2aClient>(p.http, "https://old.example.com", A2aDialect::kV03);
A2aTask t = a2a->send_message("hi");
ASSERT_EQ(t.state, "message");
ASSERT_EQ(t.text, "hello");
auto seen = p.mock->seen();
ASSERT_TRUE(seen[0].body.find("\"method\":\"message/send\"") != std::string::npos);
ASSERT_TRUE(seen[0].body.find("\"kind\":\"text\"") != std::string::npos);
}
}
TEST(adk_a2a, validation_and_tool_adapter) {
Peer p;
auto a2a = std::make_shared<A2aClient>(p.http, "https://a2a.example.com");
ASSERT_THROW(a2a->send_message(""), AdkError);
ASSERT_THROW(a2a->send_message(std::string(AdkCaps::kMaxA2aTextChars + 1, 'x')), AdkError);
ASSERT_THROW(a2a->get_task(""), AdkError);
ASSERT_THROW(a2a->as_tool("bad name", "d"), AdkError);
ASSERT_THROW(A2aClient(p.http, "javascript:alert(1)"), AdkError);
ASSERT_EQ(p.mock->send_count(), 0u);
auto tool = a2a->as_tool("remote_invoicer", "Remote agent");
ASSERT_EQ(tool->declaration().name, "remote_invoicer");
}
// ---- Live (opt-in) ----------------------------------------------------------
// MOLO_LIVE_NET=1 plus GOOGLE_API_KEY. An express key (AQ.) uses the Vertex
// publisher endpoint, anything else the Gemini API. Calls are few and small.
namespace {
bool live_ready(const char* name) {
if (!std::getenv("MOLO_LIVE_NET") || Credentials::env().empty()) {
std::cout << "SKIP " << name << " (set MOLO_LIVE_NET=1 and GOOGLE_API_KEY)\n";
return false;
}
return true;
}
std::shared_ptr<DirectModel> live_model() {
auto client = std::make_shared<GoogleClient>(
std::make_unique<molo::clients::transports::HttpTransport>(),
Credentials::from_env());
bool express = Credentials::env().rfind("AQ.", 0) == 0;
return std::make_shared<DirectModel>(
client, Generative::default_model(),
express ? endpoints::vertex_generative() : endpoints::generative());
}
std::shared_ptr<Agent> live_agent(const std::string& name, const std::string& instruction,
std::vector<std::shared_ptr<AdkTool>> tools) {
Agent::Config c;
c.name = name;
c.instruction = instruction;
c.tools = std::move(tools);
c.generate.thinking_budget = 0;
c.generate.max_output_tokens = 200;
return std::make_shared<Agent>(std::move(c));
}
} // namespace
TEST(adk_live, function_calling_loop_against_the_real_model) {
if (!live_ready("adk_live.function_calling_loop_against_the_real_model")) return;
int calls = 0;
Json city = Json::object();
city.set("type", Json("string"));
Json props = Json::object();
props.set("city", city);
Json req = Json::array();
req.push(Json("city"));
Json schema = Json::object();
schema.set("type", Json("object"));
schema.set("properties", props);
schema.set("required", req);
auto tool = std::make_shared<FunctionTool>("get_weather", "Current weather for a city", schema,
[&calls](const Json&, ToolContext&) {
++calls;
Json o = Json::object();
o.set("temp_c", Json(17));
o.set("sky", Json("drizzle"));
return o;
});
Runner runner(live_model(), std::make_shared<InMemorySessionService>());
RunResult r = runner.run(
live_agent("weather", "Use get_weather for weather questions; answer in one sentence.", {tool}),
"live1", "What is the weather in Utrecht right now?");
std::cout << " live answer (" << r.steps << " steps, " << r.tool_calls << " tool calls): " << r.text << "\n";
ASSERT_EQ(r.stop_reason, "completed");
ASSERT_EQ(calls, 1);
ASSERT_TRUE(r.text.find("17") != std::string::npos);
}
TEST(adk_live, transfer_between_agents_against_the_real_model) {
if (!live_ready("adk_live.transfer_between_agents_against_the_real_model")) return;
auto root = live_agent("router",
"You only route. For any question about numbers call transfer_to_agent with agent_name math_helper.", {});
root->add_sub_agent(live_agent("math_helper", "Answer the math question with just the number.", {}));
Runner runner(live_model(), std::make_shared<InMemorySessionService>());
RunResult r = runner.run(root, "live2", "What is 12 times 12?");
std::cout << " live answer by " << r.author << ": " << r.text << "\n";
ASSERT_EQ(r.stop_reason, "completed");
ASSERT_EQ(r.author, "math_helper");
ASSERT_FALSE(r.text.empty()); // The arithmetic itself is the model's, not asserted.
}
TEST(adk_live, mcp_client_against_a_public_server) {
if (!std::getenv("MOLO_LIVE_NET")) {
std::cout << "SKIP adk_live.mcp_client_against_a_public_server (set MOLO_LIVE_NET=1)\n";
return;
}
// DeepWiki's public, unauthenticated, read-only MCP endpoint (replies as SSE).
auto http = std::make_shared<RemoteHttp>(std::make_shared<molo::clients::Client>(
std::make_unique<molo::clients::transports::HttpTransport>()));
auto mcp = std::make_shared<McpClient>(http, "https://mcp.deepwiki.com/mcp");
mcp->initialize();
auto tools = mcp->tools();
std::cout << " live MCP tools: " << tools.size() << " first: "
<< (tools.empty() ? "" : tools[0]->name()) << "\n";
ASSERT_TRUE(!tools.empty());
ASSERT_TRUE(!tools[0]->declaration().parameters.is_null());
}