From 9b3b505c9675e497836b78f9be61997d805a595f Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Wed, 2 Dec 2026 23:11:27 +0800 Subject: [PATCH 01/22] feat(a2a): upgrade to a2a-sdk 1.4.0 with dual-stack v0.3/v1.0 support - depend on a2a-sdk[http-server]>=1.4.0,<1.5.0 and agentkit-sdk-python>=0.9.3 - advertise both 0.3 and 1.0 JSON-RPC interfaces and serve both card paths from VeA2AServer, init_app and to_a2a - keep v0.3 JSON-RPC compatibility via enable_v0_3_compat - add CloudMessage/CloudPart so CloudApp.message_send keeps the historical parts[0].root.text access while supporting a2a 1.x flat parts - fix CloudApp httpx client lifecycle and add aclose/close/context manager - migrate TaskStore, executor, identity auth processor, hub client and remote agents to a2a 1.x APIs - require VEADK_A2A_PUBLIC_URL in the FaaS template and enable MCP routes with the fastmcp 3.x API - add tests/a2a/test_a2a_sdk_14.py covering the migration contract --- pyproject.toml | 6 +- tests/a2a/test_a2a_sdk_14.py | 908 ++++++++++++++++++ tests/agents/test_remote_sandbox_agent.py | 13 +- tests/test_cloud.py | 21 +- veadk/a2a/agent_card.py | 64 +- veadk/a2a/hub/a2a_hub_client.py | 3 +- veadk/a2a/remote_ve_agent.py | 30 +- veadk/a2a/utils/agent_to_a2a.py | 253 +++-- veadk/a2a/ve_a2a_server.py | 106 +- veadk/a2a/ve_agent_executor.py | 4 +- veadk/a2a/ve_task_store.py | 22 +- veadk/agents/_remote_sandbox/skill.py | 205 ++-- veadk/cloud/cloud_app.py | 309 ++++-- .../{{cookiecutter.local_dir_name}}/deploy.py | 12 +- .../src/app.py | 15 +- .../ve_identity/auth_processor.py | 6 +- 16 files changed, 1641 insertions(+), 336 deletions(-) create mode 100644 tests/a2a/test_a2a_sdk_14.py diff --git a/pyproject.toml b/pyproject.toml index 88c881d7d..46bd24f2f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,7 +18,7 @@ authors = [ dependencies = [ "async-timeout>=5,<6; python_version < '3.11'", # asyncio.timeout backport "pydantic-settings==2.10.1", # Config management - "a2a-sdk>=0.3.7,<1.0.0", # For Google Agent2Agent protocol + "a2a-sdk[http-server]>=1.4.0,<1.5.0", # For Google Agent2Agent protocol "deprecated==1.2.18", "google-adk>=2.7.0,<2.15.0", # For basic agent architecture # litellm and sqlalchemy are required by code paths veadk always uses @@ -55,7 +55,7 @@ dependencies = [ "python-docx>=1.1.0,<2", # Read and write Word documents in document_parse/doc_generate "openpyxl>=3.1.0,<4", # Read and write Excel workbooks in document_parse/doc_generate "vikingdb-python-sdk>=0.1.32", # For Viking DB - "agentkit-sdk-python>=0.8.5", + "agentkit-sdk-python>=0.9.3", "websockets>=15,<16", # Stream temporary AgentKit Sandbox conversations "openviking-sdk>=0.1.9", "python-frontmatter==1.1.0", @@ -136,7 +136,7 @@ harness = [ "headroom", ] harness-sidecar = [ - "agentkit-sdk-python>=0.8.5", + "agentkit-sdk-python>=0.9.3", ] cli = [] sandbox = [ diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py new file mode 100644 index 000000000..007902b1f --- /dev/null +++ b/tests/a2a/test_a2a_sdk_14.py @@ -0,0 +1,908 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit and contract tests for the a2a-sdk 1.4.0 migration.""" + +from __future__ import annotations + +import asyncio +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock, patch + +import httpx +import pytest +from a2a.types import ( + AgentCard, + AgentCapabilities, + AgentInterface, + AgentSkill, + ListTasksRequest, + Message, + Part, + Role, + StreamResponse, + Task, + TaskStatus, + TaskStatusUpdateEvent, + TaskState, +) +from fastapi.testclient import TestClient +from google.adk.agents import BaseAgent +from google.adk.events import Event +from google.genai import types + +from veadk.a2a.agent_card import get_agent_card +from veadk.a2a.hub.a2a_hub_client import A2AHubClient +from veadk.a2a.remote_ve_agent import ( + RemoteVeAgent, + _convert_agent_card_dict_to_obj, + _rewrite_interface_urls, +) +from veadk.a2a.utils.agent_to_a2a import ( + _augment_agent_card, + _load_agent_card, + to_a2a, +) +from veadk.a2a.ve_a2a_server import ( + A2AServerConfig, + VeA2AServer, + _resolve_public_url, + init_app, +) +from veadk.a2a.ve_task_store import VeTaskStore +from veadk.cloud.cloud_app import CloudApp, CloudMessage, CloudPart, get_message_id + + +class EchoAgent(BaseAgent): + async def _run_async_impl(self, context): + yield Event( + author=self.name, + content=types.Content(role="model", parts=[types.Part(text="pong")]), + ) + + +class FakeExecutor: + def __init__(self, **kwargs): + self.kwargs = kwargs + + +class FakeRunner: + def __init__(self, **kwargs): + self.kwargs = kwargs + + +def _agent(name="agent", description="description"): + return SimpleNamespace(name=name, description=description) + + +def _card(url="https://example.com", versions=("0.3", "1.0")): + return AgentCard( + name="card", + description="card", + version="1.0.0", + capabilities=AgentCapabilities(), + default_input_modes=["text"], + default_output_modes=["text"], + skills=[AgentSkill(id="0", name="chat", description="chat", tags=["chat"])], + supported_interfaces=[ + AgentInterface( + url=url, protocol_binding="JSONRPC", protocol_version=version + ) + for version in versions + ], + ) + + +# --------------------------------------------------------------------------- +# agent_card +# --------------------------------------------------------------------------- + + +def test_get_agent_card_is_dual_stack_by_default(): + card = get_agent_card(_agent(), "https://example.com/") + assert [i.protocol_version for i in card.supported_interfaces] == ["0.3", "1.0"] + assert card.supported_interfaces[0].url == "https://example.com" + assert card.skills[0].id == "0" + + +def test_get_agent_card_can_disable_v0_3(): + card = get_agent_card(_agent(), "https://example.com", compat_v0_3=False) + assert [i.protocol_version for i in card.supported_interfaces] == ["1.0"] + + +def test_get_agent_card_warns_on_bind_address(caplog): + with caplog.at_level("WARNING"): + card = get_agent_card(_agent(), "0.0.0.0:8000") + assert card.supported_interfaces[0].url == "0.0.0.0:8000" + assert "bind address" in caplog.text + + +# --------------------------------------------------------------------------- +# ve_a2a_server +# --------------------------------------------------------------------------- + + +def test_resolve_public_url_prefers_server_url(): + assert _resolve_public_url("https://direct.example") == "https://direct.example" + + +def test_resolve_public_url_falls_back_to_veadk_env(monkeypatch): + monkeypatch.setenv("VEADK_A2A_PUBLIC_URL", "https://env.example/") + monkeypatch.delenv("A2A_PUBLIC_URL", raising=False) + assert _resolve_public_url("0.0.0.0") == "https://env.example" + + +def test_resolve_public_url_falls_back_to_legacy_env(monkeypatch): + monkeypatch.delenv("VEADK_A2A_PUBLIC_URL", raising=False) + monkeypatch.setenv("A2A_PUBLIC_URL", "https://legacy.example/") + assert _resolve_public_url("0.0.0.0") == "https://legacy.example" + + +def test_resolve_public_url_warns_when_unavailable(monkeypatch, caplog): + monkeypatch.delenv("VEADK_A2A_PUBLIC_URL", raising=False) + monkeypatch.delenv("A2A_PUBLIC_URL", raising=False) + with caplog.at_level("WARNING"): + assert _resolve_public_url("0.0.0.0") == "0.0.0.0" + assert "empty or 0.0.0.0" in caplog.text + + +def _patch_server_dependencies(monkeypatch): + monkeypatch.setattr("veadk.a2a.ve_a2a_server.A2aAgentExecutor", FakeExecutor) + monkeypatch.setattr("veadk.a2a.ve_a2a_server.Runner", FakeRunner) + + +def test_ve_a2a_server_serves_both_card_paths(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + ) + client = TestClient(server.build()) + assert client.get("/.well-known/agent-card.json").status_code == 200 + assert client.get("/.well-known/agent.json").status_code == 200 + + +def test_ve_a2a_server_can_disable_v0_3(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + config=A2AServerConfig(compat_v0_3=False), + ) + client = TestClient(server.build()) + assert client.get("/.well-known/agent-card.json").status_code == 200 + assert client.get("/.well-known/agent.json").status_code == 404 + + +def test_ve_a2a_server_can_enable_openapi(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + config=A2AServerConfig(docs_enabled=True), + ) + client = TestClient(server.build()) + response = client.get("/openapi.json") + assert response.status_code == 200 + assert "/.well-known/agent-card.json" in response.json()["paths"] + + +def test_init_app_uses_env_public_url(monkeypatch): + captured = {} + + class FakeServer: + def __init__(self, **kwargs): + captured.update(kwargs) + + def build(self): + return "app" + + monkeypatch.setattr("veadk.a2a.ve_a2a_server.VeA2AServer", FakeServer) + monkeypatch.setenv("VEADK_A2A_PUBLIC_URL", "https://env.example") + app = init_app("0.0.0.0", "app", _agent(), object()) + assert app == "app" + assert captured["url"] == "https://env.example" + + +# --------------------------------------------------------------------------- +# ve_task_store +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_ve_task_store_implements_all_abstract_methods(): + store = VeTaskStore() + assert await store.save(object(), None) is None + assert await store.get("missing", None) is None + assert await store.list(ListTasksRequest(), None) is not None + assert await store.delete("missing", None) is None + + +@pytest.mark.asyncio +async def test_ve_task_store_allows_omitted_context(): + store = VeTaskStore() + assert await store.save(object()) is None + assert await store.get("missing") is None + assert await store.delete("missing") is None + assert await store.list(ListTasksRequest()) is not None + + +# --------------------------------------------------------------------------- +# agent_to_a2a +# --------------------------------------------------------------------------- + + +def test_augment_agent_card_adds_v0_3_to_v1_only_card(): + card = _card(versions=("1.0",)) + augmented = _augment_agent_card(card, "https://fallback.example") + assert [i.protocol_version for i in augmented.supported_interfaces] == [ + "0.3", + "1.0", + ] + assert augmented.supported_interfaces[0].url == "https://example.com" + # The caller's card is not mutated. + assert [i.protocol_version for i in card.supported_interfaces] == ["1.0"] + + +def test_augment_agent_card_adds_v1_to_v0_3_only_card(): + card = _card(versions=("0.3",)) + augmented = _augment_agent_card(card, "https://fallback.example") + assert [i.protocol_version for i in augmented.supported_interfaces] == [ + "0.3", + "1.0", + ] + + +def test_augment_agent_card_keeps_existing_both(): + card = _card(versions=("0.3", "1.0")) + augmented = _augment_agent_card(card, "https://fallback.example") + assert [i.protocol_version for i in augmented.supported_interfaces] == [ + "0.3", + "1.0", + ] + + +def test_load_agent_card_from_path(tmp_path): + path = tmp_path / "card.json" + path.write_text( + json.dumps( + { + "name": "legacy", + "description": "legacy", + "version": "1", + "url": "https://legacy.example", + "preferredTransport": "JSONRPC", + "protocolVersion": "0.3", + "capabilities": {}, + "skills": [], + } + ) + ) + card = _load_agent_card(str(path)) + assert card.supported_interfaces[0].protocol_version == "0.3" + + +def test_load_agent_card_passes_through_object(): + card = _card() + assert _load_agent_card(card) is card + + +def test_to_a2a_serves_dual_stack_card(): + app = to_a2a(EchoAgent(name="echo"), host="127.0.0.1", port=8000) + with TestClient(app) as client: + card = client.get("/.well-known/agent-card.json") + assert card.status_code == 200 + body = card.json() + assert {i["protocolVersion"] for i in body["supportedInterfaces"]} == { + "0.3", + "1.0", + } + assert body["url"] == "http://127.0.0.1:8000" + assert client.get("/.well-known/agent.json").status_code == 200 + + +def test_to_a2a_accepts_custom_v0_3_card(tmp_path): + path = tmp_path / "card.json" + path.write_text( + json.dumps( + { + "name": "custom", + "description": "custom", + "version": "1.2.3", + "url": "https://custom.example/a2a", + "preferredTransport": "JSONRPC", + "protocolVersion": "0.3", + "capabilities": {}, + "skills": [], + } + ) + ) + app = to_a2a( + EchoAgent(name="echo"), host="127.0.0.1", port=8000, agent_card=str(path) + ) + with TestClient(app) as client: + body = client.get("/.well-known/agent-card.json").json() + assert body["version"] == "1.2.3" + assert {i["protocolVersion"] for i in body["supportedInterfaces"]} == { + "0.3", + "1.0", + } + + +# --------------------------------------------------------------------------- +# CloudMessage / CloudApp +# --------------------------------------------------------------------------- + + +def _message(text="pong", role=Role.ROLE_AGENT): + return Message(message_id="m-1", role=role, parts=[Part(text=text)]) + + +def test_cloud_message_supports_root_and_flat_access(): + message = CloudMessage.from_message(_message("pong")) + assert message.parts[0].root.text == "pong" + assert message.parts[0].text == "pong" + assert message.messageId == "m-1" + assert message.message_id == "m-1" + assert str(message) == "pong" + + +def test_cloud_message_role_is_user(): + message = CloudMessage.from_message(_message("hi", Role.ROLE_USER)) + assert message.role == "user" + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_returns_message(): + async def stream(): + yield StreamResponse(message=_message("pong")) + + result = await CloudMessage.from_stream(stream()) + assert result is not None + assert result.text == "pong" + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_extracts_task_history(): + task = Task( + id="t-1", + context_id="c-1", + status={"state": TaskState.TASK_STATE_COMPLETED}, + history=[_message("user", Role.ROLE_USER), _message("agent")], + ) + + async def stream(): + yield StreamResponse(task=task) + + result = await CloudMessage.from_stream(stream()) + assert result is not None + assert result.text == "agent" + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_returns_none_without_agent_history(): + task = Task( + id="t-1", + context_id="c-1", + status={"state": TaskState.TASK_STATE_COMPLETED}, + history=[_message("user", Role.ROLE_USER)], + ) + + async def stream(): + yield StreamResponse(task=task) + + assert await CloudMessage.from_stream(stream()) is None + + +@pytest.mark.asyncio +async def test_cloud_message_from_stream_returns_none_on_empty_stream(): + async def stream(): + return + yield # pragma: no cover + + assert await CloudMessage.from_stream(stream()) is None + + +def test_get_message_id_supports_both_api_shapes(): + assert get_message_id(CloudMessage(message_id="abc")) == "abc" + assert get_message_id(Message(message_id="def")) == "def" + + +@pytest.mark.asyncio +async def test_cloud_app_default_mode_does_not_fetch_card(monkeypatch): + captured = {} + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, card): + captured["card"] = card + return "client" + + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(side_effect=AssertionError("should not fetch")) + monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", FakeFactory) + monkeypatch.setattr("veadk.cloud.cloud_app.A2ACardResolver", lambda **kw: resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + client = await app._get_a2a_client() + await app.aclose() + + assert client == "client" + assert [i.protocol_version for i in captured["card"].supported_interfaces] == [ + "0.3" + ] + + +@pytest.mark.asyncio +async def test_cloud_app_card_mode_fetches_card(monkeypatch): + card = _card() + captured = {} + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, resolved_card): + captured["card"] = resolved_card + return "client" + + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(return_value=card) + monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", FakeFactory) + monkeypatch.setattr("veadk.cloud.cloud_app.A2ACardResolver", lambda **kw: resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1", use_agent_card=True) + client = await app._get_a2a_client() + await app.aclose() + + assert client == "client" + assert captured["card"] is card + resolver.get_agent_card.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_cloud_app_message_send_returns_cloud_message(monkeypatch): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + + async def stream(*args, **kwargs): + yield StreamResponse(message=_message("pong")) + + client = MagicMock() + client.send_message = stream + monkeypatch.setattr(app, "_get_a2a_client", AsyncMock(return_value=client)) + + result = await app.message_send("ping", "s", "u") + await app.aclose() + + assert result is not None + assert result.parts[0].root.text == "pong" + + +@pytest.mark.asyncio +async def test_cloud_app_message_send_passes_timeout(monkeypatch): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + captured = {} + + async def stream(*args, **kwargs): + captured["context"] = kwargs.get("context") + yield StreamResponse(message=_message("pong")) + + client = MagicMock() + client.send_message = stream + monkeypatch.setattr(app, "_get_a2a_client", AsyncMock(return_value=client)) + + await app.message_send("ping", "s", "u", timeout=12.5) + await app.aclose() + + assert captured["context"].timeout == 12.5 + + +@pytest.mark.asyncio +async def test_cloud_app_message_send_returns_none_on_error(monkeypatch): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + monkeypatch.setattr( + app, "_get_a2a_client", AsyncMock(side_effect=RuntimeError("boom")) + ) + assert await app.message_send("ping", "s", "u") is None + await app.aclose() + + +@pytest.mark.asyncio +async def test_cloud_app_context_manager_closes_client(): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + async with app as entered: + assert entered is app + assert app.httpx_client.is_closed + + +# --------------------------------------------------------------------------- +# RemoteVeAgent +# --------------------------------------------------------------------------- + + +def test_convert_agent_card_dict_parses_v0_3_card(): + card = _convert_agent_card_dict_to_obj( + { + "name": "legacy", + "description": "legacy", + "version": "1", + "url": "https://legacy.example", + "preferredTransport": "JSONRPC", + "protocolVersion": "0.3", + "capabilities": {}, + "skills": [], + } + ) + assert card.supported_interfaces[0].protocol_version == "0.3" + + +def test_rewrite_interface_urls_preserves_caller_query(): + card = _card(url="http://card.example/a2a") + rewritten = _rewrite_interface_urls(card, "https://caller.example/base?token=1") + assert rewritten.supported_interfaces[0].url == ( + "https://caller.example/a2a?token=1" + ) + + +def test_rewrite_interface_urls_leaves_non_http_interfaces(): + card = AgentCard( + name="x", + description="x", + version="1", + skills=[], + supported_interfaces=[ + AgentInterface(url="grpc://card.example:443", protocol_binding="GRPC") + ], + ) + rewritten = _rewrite_interface_urls(card, "https://caller.example") + assert rewritten.supported_interfaces[0].url == "grpc://card.example:443" + + +# --------------------------------------------------------------------------- +# A2AHubClient +# --------------------------------------------------------------------------- + + +def test_a2a_hub_client_registers_card_as_camel_case_dict(): + with ( + patch( + "veadk.a2a.hub.a2a_hub_client.requests.get", + return_value=MagicMock(status_code=200), + ), + patch( + "veadk.a2a.hub.a2a_hub_client.requests.post", + return_value=MagicMock(status_code=200), + ) as post, + ): + client = A2AHubClient("hub.example", 8000) + client.register_agent("group", "agent", _card()) + payload = post.call_args.kwargs["json"]["agent_card"] + assert payload["supportedInterfaces"][0]["protocolVersion"] == "0.3" + assert payload["url"] == "https://example.com" + + +# --------------------------------------------------------------------------- +# auth_processor changed lines +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_auth_processor_updates_task_with_working_state(): + from veadk.integrations.ve_identity.auth_processor import AuthRequestProcessor + from veadk.integrations.ve_identity.models import AuthRequestConfig + + oauth2 = SimpleNamespace( + auth_uri="https://auth.example", + __pydantic_fields__={"access_token": None}, + __dict__={"access_token": None}, + ) + auth_config = SimpleNamespace( + exchanged_auth_credential=SimpleNamespace(oauth2=oauth2, resource_ref=None), + model_dump=MagicMock(return_value={"exchanged_auth_credential": {}}), + ) + poller = SimpleNamespace( + poll_for_auth=AsyncMock(return_value=SimpleNamespace(access_token="token")) + ) + config = AuthRequestConfig( + oauth2_auth_poller=lambda uri, request_dict: poller, + identity_client=MagicMock(), + ) + processor = AuthRequestProcessor(config=config) + task_updater = AsyncMock() + + result = await processor.process_auth_request("event-1", auth_config, task_updater) + + assert result is not None + task_updater.update_status.assert_awaited_once() + state = task_updater.update_status.await_args.args[0] + message = task_updater.update_status.await_args.kwargs["message"] + assert state == TaskState.TASK_STATE_WORKING + assert message.parts[0].text == "Authorization received, continuing..." + + +# --------------------------------------------------------------------------- +# extra branch coverage for changed lines +# --------------------------------------------------------------------------- + + +def test_get_agent_card_accepts_empty_url(): + card = get_agent_card(_agent(), "") + assert [interface.url for interface in card.supported_interfaces] == ["", ""] + + +def test_cloud_part_str_returns_text(): + assert str(CloudPart(text="hello")) == "hello" + + +@pytest.mark.asyncio +async def test_cloud_app_close_alias_closes_client(): + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + await app.close() + assert app.httpx_client.is_closed + + +def test_rewrite_interface_urls_skips_empty_interface_url(): + card = _card() + card.supported_interfaces[0].url = "" + rewritten = _rewrite_interface_urls(card, "https://caller.example/base?token=1") + assert rewritten.supported_interfaces[0].url == "" + + +def test_remote_ve_agent_rewrites_fetched_card_interfaces(monkeypatch): + payload = { + "name": "remote", + "description": "d", + "version": "1", + "supportedInterfaces": [ + {"url": "", "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}, + { + "url": "http://card.example/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0", + }, + ], + "capabilities": {"streaming": False}, + "defaultInputModes": ["text"], + "defaultOutputModes": ["text"], + "skills": [], + } + monkeypatch.setattr( + "veadk.a2a.remote_ve_agent.requests.get", + lambda *args, **kwargs: MagicMock(json=lambda: payload), + ) + agent = RemoteVeAgent(name="remote", url="https://caller.example/base?token=1") + try: + interfaces = agent._agent_card.supported_interfaces + assert interfaces[0].url == "" + assert interfaces[1].url == "https://caller.example/a2a?token=1" + finally: + asyncio.run(agent._httpx_client.aclose()) + + +@pytest.mark.asyncio +async def test_ve_agent_executor_enqueues_final_output(monkeypatch): + from veadk.a2a.ve_agent_executor import VeAgentExecutor + + monkeypatch.setattr("veadk.a2a.ve_agent_executor.Runner", FakeRunner) + executor = VeAgentExecutor( + app_name="app", agent=_agent(), short_term_memory=object() + ) + executor.runner = SimpleNamespace(user_id="", run=AsyncMock(return_value="final")) + context = SimpleNamespace( + metadata={"user_id": "u", "session_id": "s"}, get_user_input=lambda: "hi" + ) + queue = SimpleNamespace(enqueue_event=AsyncMock()) + + await executor.execute(context, queue) + + message = queue.enqueue_event.await_args.args[0] + assert message.parts[0].text == "final" + assert await executor.cancel(context, queue) is None + + +def _skill_card_payload(): + return { + "name": "skill", + "description": "d", + "version": "1", + "supportedInterfaces": [ + {"url": "", "protocolBinding": "JSONRPC", "protocolVersion": "0.3"}, + { + "url": "http://127.0.0.1:1/a2a", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0", + }, + ], + "capabilities": {"streaming": False}, + "defaultInputModes": ["text"], + "defaultOutputModes": ["text"], + "skills": [], + } + + +def _patch_skill_transport(monkeypatch, client): + from veadk.agents._remote_sandbox import skill as skill_module + + class FakeHttp: + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return None + + async def get(self, url): + return SimpleNamespace(status_code=200, json=lambda: _skill_card_payload()) + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, card): + return client + + monkeypatch.setattr( + skill_module, + "httpx", + SimpleNamespace( + AsyncClient=lambda **kwargs: FakeHttp(), + Timeout=httpx.Timeout, + URL=httpx.URL, + TransportError=httpx.TransportError, + ), + ) + monkeypatch.setattr(skill_module, "ClientFactory", FakeFactory) + return skill_module + + +def _skill_arguments(): + agent = SimpleNamespace( + name="sandbox", ready_timeout=5, request_timeout=5, expiry_buffer=0 + ) + ctx = SimpleNamespace( + user_id="u", + session=SimpleNamespace(id="s"), + invocation_id="inv", + branch=None, + ) + return dict( + agent=agent, + ctx=ctx, + endpoint="http://127.0.0.1:1/?route=fixture", + headers={}, + binding=None, + turn_key="turn-1", + task="ping", + context={}, + lease=None, + ) + + +@pytest.mark.asyncio +async def test_skill_events_consumes_status_message_and_empty_chunks(monkeypatch): + from veadk.agents.agentkit_remote_sandbox_agent import SandboxAgentError # noqa: F401 + + chunks = [ + StreamResponse( + status_update=TaskStatusUpdateEvent( + task_id="t-1", + context_id="ctx-1", + status=TaskStatus( + state=TaskState.TASK_STATE_COMPLETED, + message=_message("done"), + ), + ) + ), + StreamResponse( + message=Message( + message_id="m-1", + role=Role.ROLE_AGENT, + parts=[Part(text="hello")], + context_id="ctx-1", + ) + ), + StreamResponse(), + ] + + class FakeClient: + def __init__(self): + self.closed = False + + async def send_message(self, request): + for chunk in chunks: + yield chunk + + async def close(self): + self.closed = True + + async def cancel_task(self, request): + return None + + client = FakeClient() + skill_module = _patch_skill_transport(monkeypatch, client) + + events = [event async for event in skill_module.skill_events(**_skill_arguments())] + + texts = [part.text for event in events for part in event.content.parts if part.text] + assert "done" in texts + assert "hello" in texts + assert client.closed + + +@pytest.mark.asyncio +async def test_skill_events_transport_error_before_task_raises(monkeypatch): + from veadk.agents.agentkit_remote_sandbox_agent import SandboxAgentError + + class FakeClient: + def __init__(self): + self.closed = False + + async def send_message(self, request): + raise httpx.ConnectError("boom") + yield # unreachable: keeps this an async generator + + async def close(self): + self.closed = True + + async def cancel_task(self, request): + return None + + client = FakeClient() + skill_module = _patch_skill_transport(monkeypatch, client) + + with pytest.raises(SandboxAgentError): + async for _ in skill_module.skill_events(**_skill_arguments()): + pass + + assert client.closed + + +@pytest.mark.asyncio +async def test_skill_events_accepts_message_only_response(monkeypatch): + class FakeClient: + def __init__(self): + self.closed = False + + async def send_message(self, request): + yield StreamResponse( + message=Message( + message_id="m-only", + role=Role.ROLE_AGENT, + parts=[Part(text="direct-answer")], + context_id="ctx-only", + ) + ) + + async def close(self): + self.closed = True + + async def cancel_task(self, request): + return None + + client = FakeClient() + skill_module = _patch_skill_transport(monkeypatch, client) + + events = [event async for event in skill_module.skill_events(**_skill_arguments())] + + texts = [part.text for event in events for part in event.content.parts if part.text] + assert "direct-answer" in texts + assert client.closed diff --git a/tests/agents/test_remote_sandbox_agent.py b/tests/agents/test_remote_sandbox_agent.py index 1e3550f8a..09db41339 100644 --- a/tests/agents/test_remote_sandbox_agent.py +++ b/tests/agents/test_remote_sandbox_agent.py @@ -309,13 +309,14 @@ async def test_discovery_cache_is_user_scoped(): @pytest.mark.parametrize("streaming", [True, False]) async def test_skill_a2a_preserves_tool_parts_and_context(streaming): from google.adk.a2a.converters.part_converter import convert_genai_part_to_a2a_part + from a2a.compat.v0_3.conversions import to_compat_part release = asyncio.Event() contexts = [] methods = [] def wire(part): - return convert_genai_part_to_a2a_part(part).model_dump( + return to_compat_part(convert_genai_part_to_a2a_part(part)).model_dump( mode="json", by_alias=True, exclude_none=True ) @@ -549,17 +550,23 @@ async def generate_content_async(self, llm_request, stream=False): with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] - from a2a.types import AgentCard, AgentCapabilities + from a2a.types import AgentCard, AgentCapabilities, AgentInterface card = AgentCard( name="native_skill", description="fixture", version="1", - url=f"http://127.0.0.1:{port}/", capabilities=AgentCapabilities(streaming=streaming), default_input_modes=["text/plain"], default_output_modes=["text/plain"], skills=[], + supported_interfaces=[ + AgentInterface( + url=f"http://127.0.0.1:{port}/", + protocol_binding="JSONRPC", + protocol_version="1.0", + ) + ], ) application = to_a2a(remote, host="127.0.0.1", port=port, agent_card=card) server = uvicorn.Server( diff --git a/tests/test_cloud.py b/tests/test_cloud.py index bb45f3ea0..f6e8cc127 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -1027,13 +1027,21 @@ async def test_cloud(): mock_vefaas_service.delete.assert_called_with("app-123") # Test CloudApp message_send functionality - mock_response = Mock() - mock_message = Mock() - mock_response.root.result = mock_message + from a2a.types import Message, Part, Role, StreamResponse + + mock_message = Message( + message_id="m-1", + role=Role.ROLE_AGENT, + parts=[Part(text="pong-from-mock")], + ) + mock_stream_response = StreamResponse(message=mock_message) + + async def _stream(*args, **kwargs): + yield mock_stream_response with patch.object(cloud_app, "_get_a2a_client") as mock_get_client: mock_client = AsyncMock() - mock_client.send_message = AsyncMock(return_value=mock_response) + mock_client.send_message = _stream mock_get_client.return_value = mock_client # Test message sending to cloud agent @@ -1044,8 +1052,9 @@ async def test_cloud(): ) # Verify message sending result - assert result == mock_message - mock_client.send_message.assert_called_once() + assert result is not None + assert result.parts[0].root.text == "pong-from-mock" + assert result.parts[0].text == "pong-from-mock" # Test CloudApp delete_self functionality with patch("builtins.input", return_value="y"): diff --git a/veadk/a2a/agent_card.py b/veadk/a2a/agent_card.py index 8e815d1de..2758c2c34 100644 --- a/veadk/a2a/agent_card.py +++ b/veadk/a2a/agent_card.py @@ -12,15 +12,50 @@ # See the License for the specific language governing permissions and # limitations under the License. -from a2a.types import AgentCapabilities, AgentCard, AgentProvider, AgentSkill +from a2a.types import ( + AgentCapabilities, + AgentCard, + AgentInterface, + AgentProvider, + AgentSkill, +) from veadk import Agent +from veadk.utils.logger import get_logger from veadk.version import VERSION +logger = get_logger(__name__) + + +def _normalize_public_url(url: str) -> str: + """Return a URL suitable for ``AgentInterface.url``. + + ``0.0.0.0`` is a bind address, not a public URL. Existing callers may + still pass it (the FaaS template used to), so keep the process alive and + only warn; the deployment flow is responsible for injecting a real public + URL via ``VEADK_A2A_PUBLIC_URL``. + """ + normalized = (url or "").strip().rstrip("/") + if not normalized: + return "" + if normalized.startswith("0.0.0.0"): + logger.warning( + "AgentCard URL %r is a bind address, not a public URL. " + "A2A clients will not be able to reach the agent; configure " + "VEADK_A2A_PUBLIC_URL or pass a public URL.", + normalized, + ) + return normalized + def get_agent_card( - agent: Agent, url: str, version: str = VERSION, provider: str = "veadk" + agent: Agent, + url: str, + version: str = VERSION, + provider: str = "veadk", + compat_v0_3: bool = True, ) -> AgentCard: + public_url = _normalize_public_url(url) agent_provider = AgentProvider(organization=provider, url="") agent_capabilities = AgentCapabilities() agent_skills = [ @@ -31,15 +66,34 @@ def get_agent_card( tags=["chat", "talk"], ) ] + supported_interfaces = [] + if compat_v0_3: + # Keep the legacy interface first: clients that do not implement the + # SDK's version preference (including hand-written v0.3 clients) read + # the first entry. The SDK client itself always prefers 1.0. + supported_interfaces.append( + AgentInterface( + url=public_url, + protocol_binding="JSONRPC", + protocol_version="0.3", + ) + ) + supported_interfaces.append( + AgentInterface( + url=public_url, + protocol_binding="JSONRPC", + protocol_version="1.0", + ) + ) agent_card = AgentCard( capabilities=agent_capabilities, description=agent.description, name=agent.name, - defaultInputModes=["text"], - defaultOutputModes=["text"], + default_input_modes=["text"], + default_output_modes=["text"], provider=agent_provider, skills=agent_skills, - url=url, + supported_interfaces=supported_interfaces, version=version, ) return agent_card diff --git a/veadk/a2a/hub/a2a_hub_client.py b/veadk/a2a/hub/a2a_hub_client.py index bdc77c104..a9f13f470 100644 --- a/veadk/a2a/hub/a2a_hub_client.py +++ b/veadk/a2a/hub/a2a_hub_client.py @@ -14,6 +14,7 @@ import requests from a2a.types import AgentCard +from a2a.server.request_handlers.response_helpers import agent_card_to_dict class A2AHubClient: @@ -55,7 +56,7 @@ def register_agent(self, group_id: str, agent_id: str, agent_card: AgentCard): json={ "group_id": group_id, "agent_id": agent_id, - "agent_card": agent_card.model_dump(), + "agent_card": agent_card_to_dict(agent_card), }, ) diff --git a/veadk/a2a/remote_ve_agent.py b/veadk/a2a/remote_ve_agent.py index 1eddedaa9..a34a363fa 100644 --- a/veadk/a2a/remote_ve_agent.py +++ b/veadk/a2a/remote_ve_agent.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -import json import functools from typing import AsyncGenerator, Literal, Optional from a2a.client.base_client import BaseClient +from a2a.client.card_resolver import parse_agent_card import httpx import requests from a2a.types import AgentCard @@ -36,9 +36,27 @@ def _convert_agent_card_dict_to_obj(agent_card_dict: dict) -> AgentCard: - agent_card_json_str = json.dumps(agent_card_dict, ensure_ascii=False, indent=2) - agent_card_object = AgentCard.model_validate_json(str(agent_card_json_str)) - return agent_card_object + return parse_agent_card(agent_card_dict) + + +def _rewrite_interface_urls(card: AgentCard, effective_url: str) -> AgentCard: + """Point every HTTP interface at the caller's origin. + + ``parse_agent_card`` ignores the legacy top-level ``url`` as soon as the + card contains ``supportedInterfaces``. A gateway or port-forward would + otherwise send the client back to the address registered inside the card, + so preserve each interface path but replace scheme/host/port with the URL + the caller actually provided. + """ + base = httpx.URL(effective_url) + for interface in card.supported_interfaces: + if not interface.url: + continue + target = httpx.URL(interface.url) + if target.scheme not in ("http", "https"): + continue + interface.url = str(base.copy_with(path=target.path or "/", fragment=None)) + return card class RemoteVeAgent(RemoteA2aAgent): @@ -173,10 +191,8 @@ def __init__( headers=req_headers, params=req_params, ).json() - # replace agent_card_url with actual host - agent_card_dict["url"] = effective_url - agent_card_object = _convert_agent_card_dict_to_obj(agent_card_dict) + agent_card_object = _rewrite_interface_urls(agent_card_object, effective_url) logger.debug(f"Agent card of {name}: {agent_card_object}") diff --git a/veadk/a2a/utils/agent_to_a2a.py b/veadk/a2a/utils/agent_to_a2a.py index ebd104edf..523d8ece1 100644 --- a/veadk/a2a/utils/agent_to_a2a.py +++ b/veadk/a2a/utils/agent_to_a2a.py @@ -13,19 +13,108 @@ # limitations under the License. from __future__ import annotations -from typing import Literal, Optional, Union -from a2a.types import AgentCard +import copy +import json +from contextlib import asynccontextmanager +from pathlib import Path +from typing import AsyncIterator, Literal, Optional, Union + +from a2a.client.card_resolver import parse_agent_card +from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes +from a2a.server.tasks import InMemoryTaskStore +from a2a.types import AgentCard, AgentInterface +from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor +from google.adk.a2a.utils.agent_card_builder import AgentCardBuilder from google.adk.agents import BaseAgent -from starlette.applications import Starlette -from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService -from google.adk.sessions.in_memory_session_service import InMemorySessionService +from google.adk.artifacts.in_memory_artifact_service import ( + InMemoryArtifactService, +) +from google.adk.auth.credential_service.in_memory_credential_service import ( + InMemoryCredentialService, +) from google.adk.memory.in_memory_memory_service import InMemoryMemoryService -from google.adk.a2a.utils.agent_to_a2a import to_a2a as google_adk_to_a2a +from google.adk.runners import Runner as AdkRunner +from google.adk.sessions.in_memory_session_service import InMemorySessionService +from starlette.applications import Starlette + from veadk import Runner from veadk.a2a.ve_middlewares import build_a2a_auth_middleware from veadk.auth.ve_credential_service import VeCredentialService from veadk.consts import DEFAULT_AGENT_NAME +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + +_AGENT_CARD_WELL_KNOWN_PATH = "/.well-known/agent-card.json" +_PREV_AGENT_CARD_WELL_KNOWN_PATH = "/.well-known/agent.json" + + +def _load_agent_card(agent_card: Union[AgentCard, str, None]) -> Optional[AgentCard]: + """Load a caller-provided AgentCard from an object or a JSON path.""" + if agent_card is None: + return None + if isinstance(agent_card, str): + with Path(agent_card).open("r", encoding="utf-8") as f: + return parse_agent_card(json.load(f)) + return agent_card + + +def _has_protocol_version(card: AgentCard, prefix: str) -> bool: + return any( + (interface.protocol_version or "").startswith(prefix) + for interface in card.supported_interfaces + ) + + +def _augment_agent_card(card: AgentCard, rpc_url: str) -> AgentCard: + """Ensure the card advertises both a v0.3 and a v1.0 JSON-RPC interface. + + ADK's ``AgentCardBuilder`` only emits a 1.0 interface under a2a-sdk 1.x. + A 1.0-only card has no legacy top-level ``url``, so a2a-sdk 0.3.x clients + fail discovery before they reach the v0.3-compatible RPC route. Keep the + caller's card untouched and return an augmented copy. + """ + augmented = copy.deepcopy(card) + interfaces = list(augmented.supported_interfaces) + base_url = next( + (interface.url for interface in interfaces if interface.url), rpc_url + ) + + if not _has_protocol_version(augmented, "0.3"): + interfaces.insert( + 0, + AgentInterface( + url=base_url, + protocol_binding="JSONRPC", + protocol_version="0.3", + ), + ) + if not _has_protocol_version(augmented, "1."): + interfaces.append( + AgentInterface( + url=base_url, + protocol_binding="JSONRPC", + protocol_version="1.0", + ), + ) + + del augmented.supported_interfaces[:] + augmented.supported_interfaces.extend(interfaces) + return augmented + + +def _create_default_runner(agent: BaseAgent) -> AdkRunner: + """Create the same in-memory runner ADK's ``to_a2a`` uses by default.""" + return AdkRunner( + app_name=agent.name or "adk_agent", + agent=agent, + artifact_service=InMemoryArtifactService(), + session_service=InMemorySessionService(), + memory_service=InMemoryMemoryService(), + credential_service=InMemoryCredentialService(), + ) def to_a2a( @@ -39,105 +128,49 @@ def to_a2a( enable_auth: bool = False, auth_method: Literal["header", "querystring"] = "header", ) -> Starlette: - """Convert an ADK agent to a A2A Starlette application with optional VeADK enhancements. + """Convert an ADK agent to a dual-stack A2A Starlette application. - This function wraps Google ADK's to_a2a utility and optionally adds: - - VeCredentialService for authentication management - - A2A authentication middleware for token validation + The public signature is intentionally unchanged. The implementation no + longer delegates to ``google.adk.a2a.utils.agent_to_a2a`` because that + helper only advertises a 1.0 interface under a2a-sdk 1.x. This wrapper + builds the same ``A2aAgentExecutor`` + ``DefaultRequestHandler`` stack, + augments the ADK-built card with a 0.3 interface, and serves both + well-known card paths so a2a-sdk 0.3.x and 1.x clients can discover and + call the agent. Args: - agent: The ADK agent to convert to A2A server - host: The host for the A2A RPC URL (default: "localhost") - port: The port for the A2A RPC URL (default: 8000) - protocol: The protocol for the A2A RPC URL (default: "http") - agent_card: Optional pre-built AgentCard object or path to agent card - JSON. If not provided, will be built automatically from the - agent. + agent: The ADK agent to convert to an A2A server. + host: The host for the A2A RPC URL (default: "localhost"). + port: The port for the A2A RPC URL (default: 8000). + protocol: The protocol for the A2A RPC URL (default: "http"). + agent_card: Optional pre-built AgentCard object or path to an agent + card JSON file. If not provided, the card is built from the agent. runner: Optional pre-built Runner object. If not provided, a default - runner will be created using in-memory services. - When enable_auth=True: - - If runner is provided and has a credential_service, it must be - a VeCredentialService instance (raises TypeError otherwise) - - If runner is provided without credential_service, a new - VeCredentialService will be created and set - - If runner is not provided, a new runner with VeCredentialService - will be created - auth_method: Authentication method for A2A requests (only used when - enable_auth=True). Options: - - "header": Extract token from Authorization header (default) - - "querystring": Extract token from query parameter + runner will be created using in-memory services. enable_auth: Whether to enable VeADK authentication features. - When True, enables credential service and auth middleware. - When False, uses standard Google ADK behavior. - Default: False + auth_method: Authentication method for A2A requests (only used when + enable_auth=True). Options: "header" or "querystring". Returns: - A Starlette application that can be run with uvicorn - - Raises: - TypeError: If enable_auth=True and runner has a credential_service - that is not a VeCredentialService instance - - Example: - Basic usage (without VeADK auth): - ```python - from veadk import Agent - from veadk.a2a.utils.agent_to_a2a import to_a2a - - agent = Agent(name="my_agent", tools=[...]) - app = to_a2a(agent, host="localhost", port=8000) - # Run with: uvicorn module:app --host localhost --port 8000 - ``` - - With VeADK authentication enabled: - ```python - app = to_a2a(agent, enable_auth=True) - ``` - - With custom runner and VeADK auth: - ```python - from veadk import Agent, Runner - from veadk.memory.short_term_memory import ShortTermMemory - from veadk.auth.ve_credential_service import VeCredentialService - - agent = Agent(name="my_agent") - runner = Runner( - agent=agent, - short_term_memory=ShortTermMemory(), - app_name="my_app", - credential_service=VeCredentialService() # Optional - ) - app = to_a2a(agent, runner=runner, enable_auth=True) - ``` - - With querystring authentication: - ```python - app = to_a2a(agent, enable_auth=True, auth_method="querystring") - ``` + A Starlette application that can be run with uvicorn. """ app_name = agent.name or DEFAULT_AGENT_NAME - middleware = None # May need support multiple middlewares in the future + middleware = None - # Handle VeADK authentication setup if enable_auth: - # Create credential service if not provided credential_service = VeCredentialService() if runner is not None: - # Check if runner has credential_service if runner.credential_service is not None: - # Validate that it's a VeCredentialService if not isinstance(runner.credential_service, VeCredentialService): raise TypeError( - f"When enable_auth=True, runner.credential_service must be " - f"a VeCredentialService instance, got {type(runner.credential_service).__name__}" + "When enable_auth=True, runner.credential_service must " + "be a VeCredentialService instance, got " + f"{type(runner.credential_service).__name__}" ) - # Use existing credential service credential_service = runner.credential_service else: - # Add credential_service to runner runner.credential_service = credential_service else: - # Create runner with credential_service runner = Runner( app_name=app_name, agent=agent, @@ -153,17 +186,49 @@ def to_a2a( auth_method=auth_method, ) - # Convert agent to A2A Starlette app using Google ADK utility - app: Starlette = google_adk_to_a2a( - agent=agent, - host=host, - port=port, - protocol=protocol, - agent_card=agent_card, - runner=runner, - ) + if runner is None: + runner = _create_default_runner(agent) + + provided_card = _load_agent_card(agent_card) + rpc_url = f"{protocol}://{host}:{port}/" + card_builder = AgentCardBuilder(agent=agent, rpc_url=rpc_url) + agent_executor = A2aAgentExecutor(runner=runner) + task_store = InMemoryTaskStore() + + async def setup_a2a(app: Starlette) -> None: + if provided_card is not None: + final_card = _augment_agent_card(provided_card, rpc_url) + else: + final_card = _augment_agent_card(await card_builder.build(), rpc_url) + + handler = DefaultRequestHandler( + agent_executor=agent_executor, + task_store=task_store, + agent_card=final_card, + ) + app.routes.extend( + [ + *create_agent_card_routes( + final_card, card_url=_AGENT_CARD_WELL_KNOWN_PATH + ), + *create_agent_card_routes( + final_card, card_url=_PREV_AGENT_CARD_WELL_KNOWN_PATH + ), + *create_jsonrpc_routes( + handler, + rpc_url="/", + enable_v0_3_compat=True, + ), + ] + ) + + @asynccontextmanager + async def _lifespan(app: Starlette) -> AsyncIterator[None]: + await setup_a2a(app) + yield + + app = Starlette(lifespan=_lifespan) - # Add VeADK authentication middleware only if enabled if middleware: app.add_middleware(middleware) diff --git a/veadk/a2a/ve_a2a_server.py b/veadk/a2a/ve_a2a_server.py index f5fb54388..d4fe8afab 100644 --- a/veadk/a2a/ve_a2a_server.py +++ b/veadk/a2a/ve_a2a_server.py @@ -12,21 +12,73 @@ # See the License for the specific language governing permissions and # limitations under the License. -from a2a.server.apps.jsonrpc.fastapi_app import A2AFastAPIApplication -from a2a.server.request_handlers.default_request_handler import DefaultRequestHandler -from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore +import os +from dataclasses import dataclass + +from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.routes import ( + add_a2a_routes_to_fastapi, + create_agent_card_routes, + create_jsonrpc_routes, +) +from a2a.server.tasks import InMemoryTaskStore from fastapi import FastAPI from veadk import Agent from veadk.a2a.agent_card import get_agent_card from veadk.runner import Runner from veadk.memory.short_term_memory import ShortTermMemory +from veadk.utils.logger import get_logger from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor from google.adk.auth.credential_service.base_credential_service import ( BaseCredentialService, ) +logger = get_logger(__name__) + + +@dataclass +class A2AServerConfig: + """Configuration for the veadk A2A server. + + ``compat_v0_3`` keeps the legacy JSON-RPC methods and the historical + ``/.well-known/agent.json`` card path enabled. ``docs_enabled`` registers + the A2A routes through ``add_a2a_routes_to_fastapi`` so they appear in the + generated OpenAPI schema; it is opt-in and does not change runtime RPC + behavior. + """ + + compat_v0_3: bool = True + docs_enabled: bool = False + + +def _resolve_public_url(server_url: str) -> str: + """Resolve the public URL advertised in the AgentCard. + + The FaaS template historically passed ``0.0.0.0`` (a bind address). Keep + that process alive: prefer the deployment-injected + ``VEADK_A2A_PUBLIC_URL``, then the existing MPA/CLI convention + ``A2A_PUBLIC_URL``, and only warn when neither is available. + """ + candidates = ( + server_url, + os.getenv("VEADK_A2A_PUBLIC_URL", ""), + os.getenv("A2A_PUBLIC_URL", ""), + ) + for candidate in candidates: + normalized = (candidate or "").strip().rstrip("/") + if normalized and not normalized.startswith("0.0.0.0"): + return normalized + + logger.warning( + "A2A public URL is empty or 0.0.0.0; AgentCard clients will not be " + "able to reach the agent. Set VEADK_A2A_PUBLIC_URL or pass a public " + "URL. Falling back to %r.", + server_url, + ) + return (server_url or "").rstrip("/") + class VeA2AServer: def __init__( @@ -36,8 +88,14 @@ def __init__( app_name: str, short_term_memory: ShortTermMemory, credential_service: BaseCredentialService | None = None, + config: A2AServerConfig | None = None, ): - self.agent_card = get_agent_card(agent, url) + self.config = config or A2AServerConfig() + self.agent_card = get_agent_card( + agent, + _resolve_public_url(url), + compat_v0_3=self.config.compat_v0_3, + ) self.agent_executor = A2aAgentExecutor( runner=Runner( @@ -51,17 +109,38 @@ def __init__( self.task_store = InMemoryTaskStore() self.request_handler = DefaultRequestHandler( - agent_executor=self.agent_executor, task_store=self.task_store + agent_executor=self.agent_executor, + task_store=self.task_store, + agent_card=self.agent_card, ) def build(self) -> FastAPI: - app_application = A2AFastAPIApplication( - agent_card=self.agent_card, - http_handler=self.request_handler, + card_routes = [*create_agent_card_routes(self.agent_card)] + if self.config.compat_v0_3: + # a2a-sdk 0.3.x served both paths; keep the historical one so + # existing discovery code keeps working after the upgrade. + card_routes.extend( + create_agent_card_routes( + self.agent_card, + card_url="/.well-known/agent.json", + ) + ) + rpc_routes = create_jsonrpc_routes( + self.request_handler, + rpc_url="/", + enable_v0_3_compat=self.config.compat_v0_3, ) - app = app_application.build() # build routes - return app + if self.config.docs_enabled: + app = FastAPI() + add_a2a_routes_to_fastapi( + app, + agent_card_routes=card_routes, + jsonrpc_routes=rpc_routes, + ) + return app + + return FastAPI(routes=[*card_routes, *rpc_routes]) def init_app( @@ -70,6 +149,7 @@ def init_app( agent: Agent, short_term_memory: ShortTermMemory, credential_service: BaseCredentialService | None = None, + config: A2AServerConfig | None = None, ) -> FastAPI: """Init the fastapi application in terms of VeADK agent. @@ -78,6 +158,9 @@ def init_app( app_name: str, the name of the app agent: Agent, the agent of the app short_term_memory: ShortTermMemory, the short term memory of the app + credential_service: optional credential service used by the runner + config: optional server configuration; defaults to dual-stack v0.3 + + v1.0 with the legacy card path enabled Returns: FastAPI, the fastapi app @@ -85,9 +168,10 @@ def init_app( server = VeA2AServer( agent=agent, - url=server_url, + url=_resolve_public_url(server_url), app_name=app_name, short_term_memory=short_term_memory, credential_service=credential_service, + config=config, ) return server.build() diff --git a/veadk/a2a/ve_agent_executor.py b/veadk/a2a/ve_agent_executor.py index f9e84ce3a..db0a16d21 100644 --- a/veadk/a2a/ve_agent_executor.py +++ b/veadk/a2a/ve_agent_executor.py @@ -15,7 +15,7 @@ from a2a.server.agent_execution.agent_executor import AgentExecutor from a2a.server.agent_execution.context import RequestContext from a2a.server.events.event_queue import EventQueue -from a2a.utils import new_agent_text_message +from a2a.helpers import new_text_message from typing_extensions import override from veadk import Agent @@ -71,7 +71,7 @@ async def execute(self, context: RequestContext, event_queue: EventQueue) -> Non logger.debug(f"Final output: {final_output}") - await event_queue.enqueue_event(new_agent_text_message(final_output)) + await event_queue.enqueue_event(new_text_message(final_output)) @override async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None: diff --git a/veadk/a2a/ve_task_store.py b/veadk/a2a/ve_task_store.py index 0c1555dda..6f0e3a62b 100644 --- a/veadk/a2a/ve_task_store.py +++ b/veadk/a2a/ve_task_store.py @@ -12,8 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +from a2a.server.context import ServerCallContext from a2a.server.tasks import TaskStore -from a2a.types import Task +from a2a.types import ListTasksRequest, ListTasksResponse, Task from typing_extensions import override @@ -22,16 +23,29 @@ def __init__(self): super().__init__() @override - async def save(self, task: Task) -> None: + async def save(self, task: Task, context: ServerCallContext | None = None) -> None: """Saves or updates a task in the store.""" return None @override - async def get(self, task_id: str) -> Task | None: + async def get( + self, task_id: str, context: ServerCallContext | None = None + ) -> Task | None: """Retrieves a task from the store by ID.""" return None @override - async def delete(self, task_id: str) -> None: + async def list( + self, + params: ListTasksRequest, + context: ServerCallContext | None = None, + ) -> ListTasksResponse: + """Retrieves a list of tasks from the store.""" + return ListTasksResponse() + + @override + async def delete( + self, task_id: str, context: ServerCallContext | None = None + ) -> None: """Deletes a task from the store by ID.""" return None diff --git a/veadk/agents/_remote_sandbox/skill.py b/veadk/agents/_remote_sandbox/skill.py index ffb276b2c..713ef891b 100644 --- a/veadk/agents/_remote_sandbox/skill.py +++ b/veadk/agents/_remote_sandbox/skill.py @@ -23,16 +23,17 @@ import httpx from a2a.client import ClientConfig, ClientFactory -from a2a.client.errors import A2AClientHTTPError, A2AClientTimeoutError +from a2a.client.card_resolver import parse_agent_card +from a2a.client.errors import A2AClientError from a2a.types import ( - AgentCard, + CancelTaskRequest, + GetTaskRequest, Message, Part, - TaskArtifactUpdateEvent, - TaskIdParams, - TaskQueryParams, + Role, + SendMessageRequest, + Task, TaskState, - TextPart, ) from google.adk.a2a.converters.part_converter import convert_a2a_part_to_genai_part from google.genai import types @@ -41,7 +42,7 @@ from veadk.agents._remote_sandbox.code import check_lease, event_for, observation from veadk.agents.agentkit_remote_sandbox_agent import SandboxAgentError -_ACTIVE = {TaskState.submitted, TaskState.working} +_ACTIVE = {TaskState.TASK_STATE_SUBMITTED, TaskState.TASK_STATE_WORKING} def endpoint_path(endpoint, path): @@ -51,6 +52,14 @@ def endpoint_path(endpoint, path): return url.copy_with(path=url.path.rstrip("/") + "/" + path.lstrip("/")) +def _is_text(part: Part) -> bool: + return part.WhichOneof("content") == "text" + + +def _text_of(parts) -> str: + return "".join(part.text for part in parts or [] if _is_text(part)) + + async def skill_events( *, agent, ctx, endpoint, headers, binding, turn_key, task, context, lease ): @@ -64,7 +73,7 @@ async def skill_events( endpoint_path(endpoint, "/.well-known/agent-card.json") ) if response.status_code == 200: - card = AgentCard.model_validate(response.json()) + card = parse_agent_card(response.json()) break if response.status_code not in {502, 503, 504}: raise SandboxAgentError( @@ -75,15 +84,18 @@ async def skill_events( await asyncio.sleep(1) check_lease(agent, lease) # Keep the platform authority/query, using only the Card's RPC path. - card = card.model_copy(deep=True) - card.url = str(endpoint_path(endpoint, httpx.URL(card.url).path)) - card.additional_interfaces = None + base = httpx.URL(endpoint) + for interface in card.supported_interfaces: + if not interface.url: + continue + target = httpx.URL(interface.url) + interface.url = str(base.copy_with(path=target.path or "/", fragment=None)) client = ClientFactory( ClientConfig( httpx_client=http, streaming=bool(card.capabilities.streaming), polling=True, - supported_transports=["JSONRPC"], + supported_protocol_bindings=["JSONRPC"], use_client_preference=True, ) ).create(card) @@ -99,11 +111,18 @@ async def skill_events( invocations[turn_key] = {"status": "submitting"} message = Message( message_id=turn_key, - role="user", - parts=[Part(root=TextPart(text=task))], + role=Role.ROLE_USER, + parts=[Part(text=task)], context_id=context.get("context_id"), ) - remote_task = None + request = SendMessageRequest( + message=message, + metadata={ + "user_id": ctx.user_id, + "session_id": ctx.session.id, + }, + ) + remote_task: Task | None = None completed = False emitted = set() final_text = "" @@ -157,81 +176,107 @@ def convert(parts, *, source): ) return result - def consume(response): - nonlocal remote_task, final_text, completed - if isinstance(response, Message): - completed = True - if response.context_id: - context["context_id"] = response.context_id - final_text = "\n".join( - p.root.text for p in response.parts if isinstance(p.root, TextPart) - ) - return convert(response.parts, source=response.message_id) - remote_task, update = response + def consume_message(message: Message): + nonlocal final_text, completed + # A direct Message response is a terminal result, exactly like a + # completed Task. Keep that pre-1.4 behavior so message-only + # Skill servers do not fail the "no terminal task" check below. + completed = True + if message.context_id: + context["context_id"] = message.context_id + final_text = "\n".join( + part.text for part in message.parts if _is_text(part) + ) + return convert(message.parts, source=message.message_id) + + def consume_task(task: Task): + nonlocal remote_task, final_text + remote_task = task invocations[turn_key] = { - "status": remote_task.status.state.value, - "task_id": remote_task.id, + "status": TaskState.Name(task.status.state), + "task_id": task.id, } - if remote_task.context_id: - context["context_id"] = remote_task.context_id - if isinstance(update, TaskArtifactUpdateEvent): - artifact = update.artifact - text = "".join( - p.root.text for p in artifact.parts if isinstance(p.root, TextPart) - ) - snapshots[artifact.artifact_id] = ( - (snapshots.get(artifact.artifact_id, "") + text) - if update.append - else text - ) - return convert(artifact.parts, source=artifact.artifact_id) + if task.context_id: + context["context_id"] = task.context_id events = [] - messages = list(remote_task.history or []) if update is None else [] - if remote_task.status.message: - messages.append(remote_task.status.message) + messages = list(task.history or []) + if task.status.message: + messages.append(task.status.message) for msg in messages: - if msg.role == "user" or msg.message_id in emitted: + if msg.role == Role.ROLE_USER or msg.message_id in emitted: continue emitted.add(msg.message_id) events.extend(convert(msg.parts, source=msg.message_id)) + if task.status.state not in _ACTIVE: + text = _text_of(msg.parts) + if text: + final_text = text + # Final/polled snapshots provide authoritative artifacts. + for artifact in task.artifacts or []: + snapshots[artifact.artifact_id] = _text_of(artifact.parts) + tool_parts = [part for part in artifact.parts if not _is_text(part)] + events.extend(convert(tool_parts, source=artifact.artifact_id)) + return events + + def consume_status_update(update): + nonlocal remote_task, final_text + if remote_task is None: + remote_task = Task( + id=update.task_id, + context_id=update.context_id, + status=update.status, + ) + else: + if update.task_id: + remote_task.id = update.task_id + if update.context_id: + remote_task.context_id = update.context_id + remote_task.status.CopyFrom(update.status) + invocations[turn_key] = { + "status": TaskState.Name(remote_task.status.state), + "task_id": remote_task.id, + } + if remote_task.context_id: + context["context_id"] = remote_task.context_id + events = [] + message = update.status.message + if message and message.message_id not in emitted: + emitted.add(message.message_id) + events.extend(convert(message.parts, source=message.message_id)) if remote_task.status.state not in _ACTIVE: - text = "\n".join( - p.root.text for p in msg.parts if isinstance(p.root, TextPart) - ) + text = _text_of(message.parts) if text: final_text = text - # Final/polled snapshots provide authoritative artifacts. Streaming - # artifact deltas were already shown; only extract tools on final. - if update is None or remote_task.status.state not in _ACTIVE: - for artifact in remote_task.artifacts or []: - snapshots[artifact.artifact_id] = "".join( - p.root.text - for p in artifact.parts - if isinstance(p.root, TextPart) - ) - tool_parts = [ - p for p in artifact.parts if not isinstance(p.root, TextPart) - ] - events.extend(convert(tool_parts, source=artifact.artifact_id)) return events + def consume_artifact_update(update): + artifact = update.artifact + text = _text_of(artifact.parts) + snapshots[artifact.artifact_id] = ( + (snapshots.get(artifact.artifact_id, "") + text) + if update.append + else text + ) + return convert(artifact.parts, source=artifact.artifact_id) + + def consume(chunk): + if chunk.HasField("message"): + return consume_message(chunk.message) + if chunk.HasField("task"): + return consume_task(chunk.task) + if chunk.HasField("status_update"): + return consume_status_update(chunk.status_update) + if chunk.HasField("artifact_update"): + return consume_artifact_update(chunk.artifact_update) + return [] + try: async with timeout(agent.request_timeout): try: - async for response in client.send_message( - message, - request_metadata={ - "user_id": ctx.user_id, - "session_id": ctx.session.id, - }, - ): - for event in consume(response): + async for chunk in client.send_message(request): + for event in consume(chunk): yield event - except ( - httpx.TransportError, - A2AClientHTTPError, - A2AClientTimeoutError, - ): + except (httpx.TransportError, A2AClientError): # An accepted Task can be queried; never send the message twice. if remote_task is None: raise SandboxAgentError( @@ -240,15 +285,16 @@ def consume(response): while remote_task and remote_task.status.state in _ACTIVE: await asyncio.sleep(1) queried = await client.get_task( - TaskQueryParams(id=remote_task.id, history_length=20) + GetTaskRequest(id=remote_task.id, history_length=20) ) - for event in consume((queried, None)): + for event in consume_task(queried): yield event if remote_task: completed = remote_task.status.state not in _ACTIVE - if remote_task.status.state != TaskState.completed: + if remote_task.status.state != TaskState.TASK_STATE_COMPLETED: raise SandboxAgentError( - f"Skill task ended with state {remote_task.status.state.value}" + "Skill task ended with state " + f"{TaskState.Name(remote_task.status.state)}" ) if not completed: raise SandboxAgentError( @@ -274,6 +320,7 @@ def consume(response): if remote_task and not completed: with suppress(Exception): await asyncio.wait_for( - client.cancel_task(TaskIdParams(id=remote_task.id)), timeout=10 + client.cancel_task(CancelTaskRequest(id=remote_task.id)), + timeout=10, ) await client.close() diff --git a/veadk/cloud/cloud_app.py b/veadk/cloud/cloud_app.py index b308d6b25..5640f113c 100644 --- a/veadk/cloud/cloud_app.py +++ b/veadk/cloud/cloud_app.py @@ -15,12 +15,23 @@ import json import os import time -from typing import Any +from dataclasses import dataclass, field +from typing import Any, AsyncIterator from uuid import uuid4 import httpx -from a2a.client import A2ACardResolver, A2AClient -from a2a.types import AgentCard, Message, MessageSendParams, SendMessageRequest +from a2a.client import A2ACardResolver, ClientCallContext, ClientConfig, ClientFactory +from a2a.types import ( + AgentCard, + AgentCapabilities, + AgentInterface, + Message, + Part, + Role, + SendMessageRequest, + StreamResponse, +) +from google.protobuf.json_format import MessageToDict from veadk.config import getenv from veadk.utils.logger import get_logger @@ -29,6 +40,106 @@ logger = get_logger(__name__) +@dataclass +class CloudPart: + """Lightweight A2A text part that keeps the historical ``.root`` access.""" + + text: str = "" + raw: bytes = b"" + url: str = "" + metadata: dict[str, Any] | None = None + filename: str = "" + media_type: str = "" + + @property + def root(self) -> "CloudPart": + return self + + def __str__(self) -> str: + return self.text + + +@dataclass +class CloudMessage: + """VeADK-owned response wrapper for :meth:`CloudApp.message_send`. + + a2a-sdk 1.x exposes a flat Protobuf ``Part`` and no Pydantic ``.root``. + The official tutorial and the FaaS template use ``parts[0].root.text``, + so this wrapper exposes both the historical and the new access style: + ``parts[0].root.text`` and ``parts[0].text``. + """ + + message_id: str = "" + role: str = "agent" + parts: list[CloudPart] = field(default_factory=list) + context_id: str = "" + task_id: str = "" + metadata: dict[str, Any] | None = None + reference_task_ids: list[str] = field(default_factory=list) + + @property + def messageId(self) -> str: + return self.message_id + + @property + def text(self) -> str: + return "".join(part.text for part in self.parts) + + def __str__(self) -> str: + return self.text + + @classmethod + def from_message(cls, message: Message) -> "CloudMessage": + return cls( + message_id=message.message_id, + role="agent" if message.role == Role.ROLE_AGENT else "user", + parts=[ + CloudPart( + text=part.text, + raw=part.raw, + url=part.url, + metadata=( + MessageToDict(part.metadata) + if part.HasField("metadata") + else None + ), + filename=part.filename, + media_type=part.media_type, + ) + for part in message.parts + ], + context_id=message.context_id, + task_id=message.task_id, + metadata=( + MessageToDict(message.metadata) + if message.HasField("metadata") + else None + ), + reference_task_ids=list(message.reference_task_ids), + ) + + @classmethod + async def from_stream( + cls, stream: AsyncIterator[StreamResponse] + ) -> "CloudMessage | None": + """Reduce a non-streaming ``StreamResponse`` to the historical shape. + + ``message_send`` has always used non-streaming ``message/send``: a + ``Message`` is returned directly, while a ``Task`` is reduced to the + last agent message in its history (or ``None`` when there is none). + """ + async for chunk in stream: + if chunk.HasField("message"): + return cls.from_message(chunk.message) + if chunk.HasField("task"): + task = chunk.task + agent_messages = [ + msg for msg in reversed(task.history) if msg.role == Role.ROLE_AGENT + ] + return cls.from_message(agent_messages[0]) if agent_messages else None + return None + + class CloudApp: """Represents a deployed cloud agent application on Volcengine FaaS platform. @@ -224,38 +335,49 @@ def _get_vefaas_application_id_by_name(self) -> str: ) return vefaas_application_id - async def _get_a2a_client(self) -> A2AClient: + async def _get_a2a_client(self): """Constructs an A2A client configured for this cloud app. - If use_agent_card, resolves agent card and uses its URL; otherwise uses direct endpoint. - - Args: - self: The CloudApp instance. + If use_agent_card, resolves the agent card and lets the SDK select the + matching interface; otherwise constructs a minimal v0.3-only card and + sends ``message/send`` directly to the configured endpoint. The + default mode deliberately does not fetch the card: that was the + pre-1.4 behavior and avoids an extra network round-trip. Returns: - A2AClient: Ready-to-use A2A client. + A ready-to-use a2a client. Note: - Manages httpx_client context. - For card mode, fetches from base_url/ (public card). + The shared ``httpx_client`` is passed through ``ClientConfig``; + the SDK marks it shared and never closes it. Callers close it via + :meth:`aclose` or ``async with``. """ if self.use_agent_card: - async with self.httpx_client as httpx_client: - resolver = A2ACardResolver( - httpx_client=httpx_client, base_url=self.vefaas_endpoint - ) - - final_agent_card_to_use: AgentCard | None = None - _public_card = ( - await resolver.get_agent_card() - ) # Fetches from default public path - final_agent_card_to_use = _public_card - - return A2AClient( - httpx_client=self.httpx_client, agent_card=final_agent_card_to_use - ) + resolver = A2ACardResolver( + httpx_client=self.httpx_client, base_url=self.vefaas_endpoint + ) + card = await resolver.get_agent_card() else: - return A2AClient(httpx_client=self.httpx_client, url=self.vefaas_endpoint) + card = AgentCard( + name="cloud_app", + description="CloudApp default endpoint", + version="1.0.0", + supported_interfaces=[ + AgentInterface( + url=self.vefaas_endpoint, + protocol_binding="JSONRPC", + protocol_version="0.3", + ) + ], + capabilities=AgentCapabilities(), + default_input_modes=["text"], + default_output_modes=["text"], + skills=[], + ) + + return ClientFactory( + ClientConfig(httpx_client=self.httpx_client, streaming=False) + ).create(card) def update_self( self, @@ -374,10 +496,12 @@ def delete_self( async def message_send( self, message: str, session_id: str, user_id: str, timeout: float = 600.0 - ) -> Message | None: + ) -> CloudMessage | None: """Sends a user message to the cloud agent and retrieves the response. - Constructs A2A SendMessageRequest and executes via client. + The public signature is unchanged. The return value is a VeADK-owned + ``CloudMessage`` wrapper that supports both the historical + ``parts[0].root.text`` and the a2a 1.x ``parts[0].text`` access. Args: message (str): Text content of the user message. @@ -386,102 +510,75 @@ async def message_send( timeout (float): Maximum wait time in seconds. Defaults to 600.0. Returns: - Message | None: Assistant response message or None if error occurs. - - Raises: - Exception: Communication or processing errors; error is printed. + CloudMessage | None: Assistant response message or None if an + error occurs. Note: - Uses UUID for message and request IDs. - Payload includes role 'user' and text part. - Debug logs the full response. - Ignores type checks for result as it may not be Task. + Uses a non-streaming ``message/send``. A ``Task`` response is + reduced to the last agent message in its history, matching the + pre-1.4 behavior. Examples: ```python response = await app.message_send("What is AI?", "chat-1", "user-1", timeout=300) - print(response.content) + print(response.parts[0].root.text) ``` """ - a2a_client = await self._get_a2a_client() - - async with self.httpx_client: - send_message_payload: dict[str, Any] = { - "message": { - "role": "user", - "parts": [{"type": "text", "text": message}], - "messageId": uuid4().hex, - }, - "metadata": { - "user_id": user_id, - "session_id": session_id, - }, - } - try: - message_send_request = SendMessageRequest( - id=uuid4().hex, - params=MessageSendParams(**send_message_payload), - ) + try: + a2a_client = await self._get_a2a_client() + message_send_request = SendMessageRequest( + message=Message( + message_id=uuid4().hex, + role=Role.ROLE_USER, + parts=[Part(text=message)], + ), + metadata={"user_id": user_id, "session_id": session_id}, + ) - res = await a2a_client.send_message( + result = await CloudMessage.from_stream( + a2a_client.send_message( message_send_request, - http_kwargs={"timeout": httpx.Timeout(timeout)}, + context=ClientCallContext(timeout=timeout), ) + ) - logger.debug( - f"Message sent to cloud app {self.vefaas_application_name} with response: {res}" - ) + logger.debug( + f"Message sent to cloud app {self.vefaas_application_name} " + f"with response: {result}" + ) + return result + except Exception as e: + logger.error(f"Failed to send message to cloud app. Error: {e}") + return None - # we ignore type checking here, because the response - # from CloudApp will not be `Task` type - result = res.root.result # type: ignore - try: - from a2a.types import Task - except ImportError: - return result - - if isinstance(result, Task): - if result.history: # type: ignore - return next( - ( - msg - for msg in reversed(result.history) # type: ignore - if msg.role == "agent" - ), - None, - ) - else: - return None - else: - return result - except Exception as e: - logger.error(f"Failed to send message to cloud app. Error: {e}") - return None - - -def get_message_id(message: Message): - """Extracts the unique ID from an A2A Message object. - - Checks for both legacy 'messageId' and current 'message_id' attributes. + async def aclose(self) -> None: + """Close the shared HTTP client if it is still open.""" + if not self.httpx_client.is_closed: + await self.httpx_client.aclose() + + async def close(self) -> None: + """Alias of :meth:`aclose` for callers that use ``close()``.""" + await self.aclose() + + async def __aenter__(self) -> "CloudApp": + return self + + async def __aexit__(self, exc_type, exc, tb) -> None: + await self.aclose() + + +def get_message_id(message: Message | CloudMessage): + """Extracts the unique ID from an A2A message or CloudMessage. + + Checks for both the legacy 'messageId' and the current 'message_id'. Args: - message (Message): The A2A message instance. + message: The A2A message or CloudMessage instance. Returns: str: The message identifier. - - Note: - Ensures compatibility with a2a-python versions before and after 0.3.0. - Prefers 'message_id' if available, falls back to 'messageId'. - - Examples: - ```python - mid = get_message_id(response_message) - print(mid) - ``` """ if getattr(message, "messageId", None): - # Compatible with the messageId of the old a2a-python version (<0.3.0) in cloud app + # Compatible with the messageId of the old a2a-python version (<0.3.0) return message.messageId # type: ignore - else: - return message.message_id + return message.message_id diff --git a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py index 51abebe15..64edbde0e 100644 --- a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py +++ b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/deploy.py @@ -15,7 +15,6 @@ import asyncio from pathlib import Path -from a2a.types import TextPart from fastmcp.client import Client from veadk.cloud.cloud_agent_engine import CloudAgentEngine @@ -38,14 +37,9 @@ async def _send_msg_with_a2a(cloud_app: CloudApp, message: str) -> None: print(f"Message ID: {get_message_id(response_message)}") - if isinstance(response_message.parts[0].root, TextPart): - print( - f"Response from {cloud_app.vefaas_endpoint}: {response_message.parts[0].root.text}" - ) - else: - print( - f"Response from {cloud_app.vefaas_endpoint}: {response_message.parts[0].root}" - ) + print( + f"Response from {cloud_app.vefaas_endpoint}: {response_message.parts[0].text}" + ) async def _send_msg_with_mcp(cloud_app: CloudApp, message: str) -> None: diff --git a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py index 9807c944e..1fa478c5b 100644 --- a/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py +++ b/veadk/integrations/ve_faas/template/{{cookiecutter.local_dir_name}}/src/app.py @@ -26,6 +26,7 @@ from starlette.routing import Route from google.adk.a2a.utils.agent_card_builder import AgentCardBuilder +from a2a.server.request_handlers.response_helpers import agent_card_to_dict from a2a.types import AgentProvider from veadk.a2a.ve_a2a_server import init_app @@ -117,7 +118,7 @@ async def run_agent( async def agent_card() -> dict: agent_card = await agent_card_builder.build() - return agent_card.model_dump() + return agent_card_to_dict(agent_card) async def get_cozeloop_space_id() -> dict: return {"space_id": os.getenv("OBSERVABILITY_OPENTELEMETRY_COZELOOP_SERVICE_NAME", default="")} @@ -127,8 +128,15 @@ async def get_cozeloop_space_id() -> dict: # Build a run_agent function for building MCP server run_agent_func = build_mcp_run_agent_func() +public_url = os.getenv("VEADK_A2A_PUBLIC_URL", "").strip().rstrip("/") +if not public_url: + raise RuntimeError( + "VEADK_A2A_PUBLIC_URL is required; it must be the public JSON-RPC URL " + "injected at deploy time, not 0.0.0.0" + ) + a2a_app = init_app( - server_url="0.0.0.0", + server_url=public_url, app_name=app_name, agent=agent, short_term_memory=short_term_memory, @@ -140,7 +148,8 @@ async def get_cozeloop_space_id() -> dict: # === Build mcp server === -mcp = FastMCP.from_fastapi(app=a2a_app, name=app_name, include_tags={"mcp"}) +mcp = FastMCP.from_fastapi(app=a2a_app, name=app_name) +mcp.enable(tags={"mcp"}, only=True) # Create MCP ASGI app mcp_app = mcp.http_app(path="/", transport="streamable-http") diff --git a/veadk/integrations/ve_identity/auth_processor.py b/veadk/integrations/ve_identity/auth_processor.py index 2dea7cec2..f3a967cac 100644 --- a/veadk/integrations/ve_identity/auth_processor.py +++ b/veadk/integrations/ve_identity/auth_processor.py @@ -33,7 +33,7 @@ get_function_call_id, is_pending_auth_event, ) -from a2a.utils import new_agent_text_message +from a2a.helpers import new_text_message from veadk.utils.logger import get_logger from a2a.server.tasks import TaskUpdater @@ -240,8 +240,8 @@ async def process_auth_request( updated_oauth2_auth = await active_poller.poll_for_auth() if task_updater: await task_updater.update_status( - TaskState.working, - message=new_agent_text_message("Authorization received, continuing..."), + TaskState.TASK_STATE_WORKING, + message=new_text_message("Authorization received, continuing..."), ) for k, v in updated_oauth2_auth.__dict__.items(): if ( From 3e88e52667b663d8248ad633d47ac1be8d65257f Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Wed, 2 Dec 2026 23:24:59 +0800 Subject: [PATCH 02/22] feat(faas): inject VEADK_A2A_PUBLIC_URL after deploy - add VeFaaS.merge_function_envs_and_release, which preserves the function's existing env vars and is idempotent - inject the public URL after a new deploy and after a code update so the AgentCard advertises a reachable endpoint instead of 0.0.0.0 - cover merge, skip and platform-env preservation with unit tests --- tests/test_cloud.py | 44 +++++++++++++++++++ veadk/cloud/cloud_agent_engine.py | 13 ++++++ veadk/integrations/ve_faas/ve_faas.py | 62 +++++++++++++++++++++++++++ 3 files changed, 119 insertions(+) diff --git a/tests/test_cloud.py b/tests/test_cloud.py index f6e8cc127..27f179f58 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -74,6 +74,49 @@ def test_vefaas_create_function_uses_configured_project() -> None: assert request.memory_mb == 2048 +def test_vefaas_merge_function_envs_preserves_existing_and_releases() -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace( + envs=[ + SimpleNamespace(key="_FAAS_FUNC_ID", value="fn-1"), + SimpleNamespace(key="APP_REGION", value="cn-beijing"), + ] + ) + service.client.get_release_status.return_value = SimpleNamespace(status="Success") + + with patch("time.sleep") as sleep: + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + request = service.client.update_function.call_args.args[0] + envs = {item.key: item.value for item in request.envs} + assert envs["_FAAS_FUNC_ID"] == "fn-1" + assert envs["APP_REGION"] == "cn-beijing" + assert envs["VEADK_A2A_PUBLIC_URL"] == "https://example.com" + service.client.release.assert_called_once() + sleep.assert_not_called() + + +def test_vefaas_merge_function_envs_skips_when_already_present() -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace( + envs=[ + SimpleNamespace(key="VEADK_A2A_PUBLIC_URL", value="https://example.com"), + SimpleNamespace(key="APP_REGION", value="cn-beijing"), + ] + ) + + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + service.client.update_function.assert_not_called() + service.client.release.assert_not_called() + + @pytest.mark.parametrize("provider", ["volcengine", "byteplus"]) @pytest.mark.parametrize("existing", [False, True]) @pytest.mark.parametrize("studio_resources", [False, True]) @@ -109,6 +152,7 @@ def test_cloud_deploy_function_resources( ) ) service._upload_and_mount_code = Mock() + service.merge_function_envs_and_release = Mock() service._create_application = Mock(return_value="application-id") service._release_application = Mock(return_value="https://studio.example") service.ensure_application_route_methods = Mock() diff --git a/veadk/cloud/cloud_agent_engine.py b/veadk/cloud/cloud_agent_engine.py index 00bf34a60..c562ebf5a 100644 --- a/veadk/cloud/cloud_agent_engine.py +++ b/veadk/cloud/cloud_agent_engine.py @@ -346,6 +346,13 @@ def deploy( ) _ = function_id # for future use + # 方案 B:公网地址只有在首次发布后才知道,把它注入函数环境变量 + # 并重新发布,供 AgentCard 使用。重复部署时该值不变,会跳过更新。 + self._vefaas_service.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": vefaas_application_url}, + ) + veapig_gateway_id, _, veapig_route_id = ( self._vefaas_service.get_application_route(app_id=app_id) ) @@ -555,6 +562,12 @@ def update_function_code( path=path, ) ) + # The code update preserves the function env list, but an app + # created before this feature may not carry the public URL yet. + self._vefaas_service.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": vefaas_application_url}, + ) return CloudApp( vefaas_application_name=application_name, diff --git a/veadk/integrations/ve_faas/ve_faas.py b/veadk/integrations/ve_faas/ve_faas.py index e7fef939c..01df68d93 100644 --- a/veadk/integrations/ve_faas/ve_faas.py +++ b/veadk/integrations/ve_faas/ve_faas.py @@ -1087,6 +1087,68 @@ def update_function_envs_and_release( time.sleep(5) logger.warning("Function re-release did not settle within timeout.") + def merge_function_envs_and_release( + self, function_id: str, extra_envs: dict + ) -> None: + """Merge ``extra_envs`` into the function's current env vars and release. + + Unlike :meth:`update_function_envs_and_release`, this preserves the + env vars already configured on the function (including + platform-provided values such as ``_FAAS_FUNC_ID`` and ``APP_REGION``) + instead of replacing the whole list with local ``veadk_environments``. + It is idempotent: when the values are already present no update or + release is issued. + + Used by :class:`veadk.cloud.cloud_agent_engine.CloudAgentEngine` to + inject ``VEADK_A2A_PUBLIC_URL`` after the public endpoint is known. + """ + import time + + from volcenginesdkvefaas import ( + EnvForUpdateFunctionInput, + GetFunctionRequest, + GetReleaseStatusRequest, + ReleaseRequest, + UpdateFunctionRequest, + ) + + function = self.client.get_function(GetFunctionRequest(id=function_id)) + environment = { + item.key: item.value for item in (getattr(function, "envs", None) or []) + } + if all(environment.get(key) == value for key, value in extra_envs.items()): + logger.debug( + "Function %s already has envs %s; skipping release.", + function_id, + sorted(extra_envs), + ) + return + + environment.update(extra_envs) + self.client.update_function( + UpdateFunctionRequest( + id=function_id, + envs=[ + EnvForUpdateFunctionInput(key=key, value=value) + for key, value in environment.items() + ], + ) + ) + # revision_number=0 releases the latest revision. + self.client.release(ReleaseRequest(function_id=function_id, revision_number=0)) + + for _ in range(60): + status = self.client.get_release_status( + GetReleaseStatusRequest(function_id=function_id) + ) + state = str(getattr(status, "status", "") or "").lower() + if "succ" in state or state == "done": + return + if "fail" in state or "error" in state: + raise RuntimeError(f"Function re-release failed: {state}") + time.sleep(5) + logger.warning("Function re-release did not settle within timeout.") + def deploy( self, name: str, From 46abcea5b4711fc44c658ece6587f547a00c3580 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Wed, 2 Dec 2026 23:38:58 +0800 Subject: [PATCH 03/22] fix(faas): seed public URL before first release The template validates VEADK_A2A_PUBLIC_URL at import time, but the real public URL is only known after the first release. Seed a placeholder env on function creation so the first release can boot, then replace it with the real URL and release again. This closes the chicken-and-egg gap in the two-phase FaaS deploy. --- tests/test_cloud.py | 3 +++ veadk/integrations/ve_faas/ve_faas.py | 32 +++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 27f179f58..4536ce2f5 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -279,6 +279,7 @@ def test_vefaas_update_code_uses_resource_updating_bundle_path( ) service._replace_application_code_bundle = Mock() service._release_application = Mock(return_value="https://studio.example") + service.merge_function_envs_and_release = Mock() service._set_function_min_instance = Mock() service.ensure_application_route_methods = Mock() @@ -326,6 +327,7 @@ def test_vefaas_deploy_updates_existing_application_in_place() -> None: service.update_application_code_bundle = Mock( return_value="https://studio.example.com" ) + service.merge_function_envs_and_release = Mock() service._create_function = Mock() service._create_application = Mock() @@ -498,6 +500,7 @@ def test_vefaas_deploy_can_disable_gateway_cors() -> None: service._create_function = Mock(return_value=("studio-app-fn", "function-id")) service._create_application = Mock(return_value="application-id") service._release_application = Mock(return_value="https://studio.example.com") + service.merge_function_envs_and_release = Mock() service._set_function_min_instance = Mock() service.ensure_application_route_methods = Mock() diff --git a/veadk/integrations/ve_faas/ve_faas.py b/veadk/integrations/ve_faas/ve_faas.py index 01df68d93..2a26a838c 100644 --- a/veadk/integrations/ve_faas/ve_faas.py +++ b/veadk/integrations/ve_faas/ve_faas.py @@ -378,10 +378,17 @@ def _create_function( *, cpu_milli: int | None = None, memory_mb: int | None = None, + extra_envs: dict[str, str] | None = None, ): # Read envs envs = [] - for key, value in veadk.config.veadk_environments.items(): + merged_envs = { + key: value + for key, value in veadk.config.veadk_environments.items() + if value is not None + } + merged_envs.update(extra_envs or {}) + for key, value in merged_envs.items(): envs.append(EnvForCreateFunctionInput(key=key, value=value)) logger.info( f"Fetch {len(envs)} environment variables.", @@ -875,6 +882,10 @@ def _update_function_code( f"VeFaaS application {application_name} with ID {app_id} released." ) logger.info(f"VeFaaS application {application_name} updated on {url}.") + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": url}, + ) return url, app_id, function_id finally: @@ -1225,6 +1236,10 @@ def deploy( logger.info( f"VeFaaS application {name} with ID {existing_app_id} updated on {url}." ) + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": url}, + ) return url, existing_app_id, function_id # Give default names @@ -1256,8 +1271,17 @@ def deploy( f"Start to create VeFaaS function {function_name} with path {path}. Gateway: {gateway_name}, Gateway Service: {gateway_service_name}, Gateway Upstream: {gateway_upstream_name}." ) try: + # The template validates VEADK_A2A_PUBLIC_URL at import time, but + # the real public URL is only known after the first release. Seed + # a syntactically valid placeholder so the first release can boot, + # then replace it with the real URL and release again below. + pending_public_url = "http://veadk-a2a-public-url-pending.invalid" function_name, function_id = self._create_function( - function_name, path, cpu_milli=cpu_milli, memory_mb=memory_mb + function_name, + path, + cpu_milli=cpu_milli, + memory_mb=memory_mb, + extra_envs={"VEADK_A2A_PUBLIC_URL": pending_public_url}, ) logger.info( f"VeFaaS function {function_name} with ID {function_id} created." @@ -1277,6 +1301,10 @@ def deploy( logger.info(f"VeFaaS application {name} with ID {app_id} created.") logger.info(f"Start to release VeFaaS application {app_id}.") url = self._release_application(app_id) + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": url}, + ) self._set_function_min_instance(function_id, max_instance=max_instance) self.ensure_application_route_methods( app_id, From e0aecb110167a8c386b3266af36ddc86f885245b Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Wed, 2 Dec 2026 23:48:11 +0800 Subject: [PATCH 04/22] fix(runner): keep run_async signature introspectable ADK 2.14.x's A2A executor calls inspect.signature on the bound runner.run_async. The interceptor wrapper exposes keyword-only parameters, which Python rejects for a bound method with 'invalid method signature'. Wrap the interceptor with a positional *args/**kwargs function so the signature is introspectable while preserving the interceptor contract. --- tests/a2a/test_a2a_sdk_14.py | 12 ++++++++++++ veadk/runner.py | 15 +++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py index 007902b1f..a5e4104fa 100644 --- a/tests/a2a/test_a2a_sdk_14.py +++ b/tests/a2a/test_a2a_sdk_14.py @@ -17,6 +17,7 @@ from __future__ import annotations import asyncio +import inspect import json from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch @@ -650,6 +651,17 @@ def test_get_agent_card_accepts_empty_url(): assert [interface.url for interface in card.supported_interfaces] == ["", ""] +def test_runner_run_async_signature_is_introspectable(): + """ADK 2.14.x's A2A executor calls inspect.signature on the bound method.""" + from veadk import Runner + + runner = Runner(agent=EchoAgent(name="echo"), app_name="app", user_id="u") + params = inspect.signature(runner.run_async).parameters + assert any( + parameter.kind == inspect.Parameter.VAR_KEYWORD for parameter in params.values() + ) + + def test_cloud_part_str_returns_text(): assert str(CloudPart(text="hello")) == "hello" diff --git a/veadk/runner.py b/veadk/runner.py index 0b79c02a8..c31a26350 100644 --- a/veadk/runner.py +++ b/veadk/runner.py @@ -517,10 +517,21 @@ def __init__( **kwargs, ) - self.run_async = MethodType( - intercept_new_message(_upload_image_to_tos)(super().run_async), self + intercepted_run_async = intercept_new_message(_upload_image_to_tos)( + super().run_async ) + def _run_async_with_interceptor(self, *args, **kwargs): + # ADK 2.14.x's A2A executor calls inspect.signature() on the bound + # ``runner.run_async``. The interceptor wrapper has keyword-only + # parameters, which Python's inspect rejects for a bound method + # ("invalid method signature"). Expose a positional ``*args`` + # wrapper so the signature is introspectable while preserving the + # interceptor and the underlying keyword-only contract. + return intercepted_run_async(self, *args, **kwargs) + + self.run_async = MethodType(_run_async_with_interceptor, self) + async def run( self, messages: RunnerMessage, From 55d5a75acfd10a1612c004321131fc9ab5abf663 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Wed, 2 Dec 2026 23:58:51 +0800 Subject: [PATCH 05/22] fix(faas): update rendered src projects in place CloudAgentEngine.update_function_code is called with the rendered `src` directory by the template's deploy.py, but _update_function_code assumed a project root and nested it under src/. That broke relative requirements paths such as local wheels. Detect the rendered src layout and copy it over the template src directory instead. --- tests/test_cloud.py | 75 ++++++++++++++++++++++++++- veadk/integrations/ve_faas/ve_faas.py | 32 ++++++++---- 2 files changed, 95 insertions(+), 12 deletions(-) diff --git a/tests/test_cloud.py b/tests/test_cloud.py index 4536ce2f5..b26043c1b 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -277,7 +277,17 @@ def test_vefaas_update_code_uses_resource_updating_bundle_path( }, ) ) - service._replace_application_code_bundle = Mock() + captured: dict[str, object] = {} + + def _capture(**kwargs: object) -> None: + uploaded = Path(str(kwargs["path"])) + captured["files"] = { + path.relative_to(uploaded).as_posix(): path.read_text() + for path in uploaded.rglob("*") + if path.is_file() + } + + service._replace_application_code_bundle = Mock(side_effect=_capture) service._release_application = Mock(return_value="https://studio.example") service.merge_function_envs_and_release = Mock() service._set_function_min_instance = Mock() @@ -310,6 +320,69 @@ def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: service._set_function_min_instance.assert_called_once_with("function-id") +def test_vefaas_update_code_uses_rendered_src_in_place( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + src = tmp_path / "src" + (src / "a2a14_smoke").mkdir(parents=True) + (src / "app.py").write_text("app = None\n") + (src / "requirements.txt").write_text("./a2a14_smoke/x.whl\n") + (src / "a2a14_smoke" / "x.whl").write_text("wheel") + + service = object.__new__(VeFaaS) + service.find_app_id_by_name = Mock(return_value="application-id") + service._get_application_status = Mock( + return_value=( + "deploy_success", + { + "Result": { + "CloudResource": '{"framework":{"function":' + '{"Id":"function-id","Name":"studio-app-fn"}}}' + } + }, + ) + ) + captured: dict[str, object] = {} + + def _capture(**kwargs: object) -> None: + uploaded = Path(str(kwargs["path"])) + captured["files"] = { + path.relative_to(uploaded).as_posix(): path.read_text() + for path in uploaded.rglob("*") + if path.is_file() + } + + service._replace_application_code_bundle = Mock(side_effect=_capture) + service._release_application = Mock(return_value="https://studio.example") + service.merge_function_envs_and_release = Mock() + service._set_function_min_instance = Mock() + service.ensure_application_route_methods = Mock() + + def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: + package = Path(output_dir) / str(extra_context["local_dir_name"]) + (package / "src").mkdir(parents=True) + + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.tempfile.gettempdir", + lambda: str(tmp_path), + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.cookiecutter", _cookiecutter + ) + + result = service._update_function_code("studio-app", str(src)) + + assert result == ("https://studio.example", "application-id", "function-id") + files = captured["files"] + assert files["app.py"] == "app = None\n" + assert files["requirements.txt"] == "./a2a14_smoke/x.whl\n" + assert files["a2a14_smoke/x.whl"] == "wheel" + + def test_vefaas_deploy_updates_existing_application_in_place() -> None: service = object.__new__(VeFaaS) service.find_app_id_by_name = Mock(return_value="application-id") diff --git a/veadk/integrations/ve_faas/ve_faas.py b/veadk/integrations/ve_faas/ve_faas.py index 2a26a838c..1952f6beb 100644 --- a/veadk/integrations/ve_faas/ve_faas.py +++ b/veadk/integrations/ve_faas/ve_faas.py @@ -853,18 +853,28 @@ def _update_function_code( tmp_path = temp_base / tmp_dir_name try: - agent_dir = tmp_path / "src" / user_proj_path.name.replace("-", "_") - if agent_dir.exists(): - shutil.rmtree(agent_dir) - agent_dir.mkdir(parents=True, exist_ok=True) - shutil.copytree(user_proj_path, agent_dir, dirs_exist_ok=True) - user_requirements = user_proj_path / "requirements.txt" - - if user_requirements.exists(): - logger.debug("Using user-provided requirements.txt") - shutil.copy(user_requirements, tmp_path / "src" / "requirements.txt") + if (user_proj_path / "app.py").exists(): + # `veadk init` projects pass the rendered `src` directory to + # deploy(). Update that directory in place instead of nesting + # it under `src/`, which would break relative + # requirements paths such as local wheels. + logger.debug("Updating an already-rendered src directory in place") + shutil.copytree(user_proj_path, tmp_path / "src", dirs_exist_ok=True) else: - logger.warning("No requirements.txt found, using template default") + agent_dir = tmp_path / "src" / user_proj_path.name.replace("-", "_") + if agent_dir.exists(): + shutil.rmtree(agent_dir) + agent_dir.mkdir(parents=True, exist_ok=True) + shutil.copytree(user_proj_path, agent_dir, dirs_exist_ok=True) + user_requirements = user_proj_path / "requirements.txt" + + if user_requirements.exists(): + logger.debug("Using user-provided requirements.txt") + shutil.copy( + user_requirements, tmp_path / "src" / "requirements.txt" + ) + else: + logger.warning("No requirements.txt found, using template default") self._replace_application_code_bundle( function_id=function_id, From ccae68d83a34629f0bded7d1daf02b886228b09a Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 00:07:42 +0800 Subject: [PATCH 06/22] test: cover FaaS update and runner interceptor branches --- tests/a2a/test_a2a_sdk_14.py | 26 +++++++++++ tests/test_cloud.py | 89 +++++++++++++++++++++++++++++++++++- 2 files changed, 114 insertions(+), 1 deletion(-) diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py index a5e4104fa..2e10440ec 100644 --- a/tests/a2a/test_a2a_sdk_14.py +++ b/tests/a2a/test_a2a_sdk_14.py @@ -662,6 +662,32 @@ def test_runner_run_async_signature_is_introspectable(): ) +@pytest.mark.asyncio +async def test_runner_run_async_interceptor_executes(): + from google.adk.sessions import InMemorySessionService + from google.genai import types + + from veadk import Runner + + sessions = InMemorySessionService() + await sessions.create_session(app_name="app", user_id="u", session_id="s") + runner = Runner( + agent=EchoAgent(name="echo"), + app_name="app", + session_service=sessions, + user_id="u", + ) + events = [ + event + async for event in runner.run_async( + user_id="u", + session_id="s", + new_message=types.Content(role="user", parts=[types.Part(text="ping")]), + ) + ] + assert events[-1].content.parts[0].text == "pong" + + def test_cloud_part_str_returns_text(): assert str(CloudPart(text="hello")) == "hello" diff --git a/tests/test_cloud.py b/tests/test_cloud.py index b26043c1b..d7346a6a9 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -117,6 +117,38 @@ def test_vefaas_merge_function_envs_skips_when_already_present() -> None: service.client.release.assert_not_called() +def test_vefaas_merge_function_envs_raises_on_failed_release() -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace(envs=[]) + service.client.get_release_status.return_value = SimpleNamespace(status="Failed") + + with pytest.raises(RuntimeError, match="re-release failed"): + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + +def test_vefaas_merge_function_envs_warns_on_timeout(caplog) -> None: + service = VeFaaS(access_key="ak", secret_key="sk") + service.client = Mock() + service.client.get_function.return_value = SimpleNamespace(envs=[]) + service.client.get_release_status.side_effect = lambda *args, **kwargs: ( + SimpleNamespace(status="Deploying") + ) + + with ( + patch("time.sleep") as sleep, + caplog.at_level("WARNING"), + ): + service.merge_function_envs_and_release( + "fn-1", {"VEADK_A2A_PUBLIC_URL": "https://example.com"} + ) + + assert "did not settle within timeout" in caplog.text + assert sleep.call_count == 60 + + @pytest.mark.parametrize("provider", ["volcengine", "byteplus"]) @pytest.mark.parametrize("existing", [False, True]) @pytest.mark.parametrize("studio_resources", [False, True]) @@ -262,6 +294,7 @@ def test_vefaas_update_code_uses_resource_updating_bundle_path( ) -> None: project = tmp_path / "agent" project.mkdir() + (project / "requirements.txt").write_text("requests\n") service = object.__new__(VeFaaS) service.find_app_id_by_name = Mock(return_value="application-id") service._get_application_status = Mock( @@ -295,7 +328,8 @@ def _capture(**kwargs: object) -> None: def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: package = Path(output_dir) / str(extra_context["local_dir_name"]) - (package / "src").mkdir(parents=True) + (package / "src" / "agent").mkdir(parents=True) + (package / "src" / "agent" / "old.py").write_text("old = True\n") monkeypatch.setattr( "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" @@ -317,6 +351,10 @@ def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: environment_overrides=None, request_timeout=1800, ) + files = captured["files"] + assert files["requirements.txt"] == "requests\n" + assert files["agent/requirements.txt"] == "requests\n" + assert "agent/old.py" not in files service._set_function_min_instance.assert_called_once_with("function-id") @@ -383,6 +421,55 @@ def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: assert files["a2a14_smoke/x.whl"] == "wheel" +def test_vefaas_update_code_warns_without_requirements( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + caplog, +) -> None: + project = tmp_path / "agent" + project.mkdir() + (project / "agent.py").write_text("agent = None\n") + + service = object.__new__(VeFaaS) + service.find_app_id_by_name = Mock(return_value="application-id") + service._get_application_status = Mock( + return_value=( + "deploy_success", + { + "Result": { + "CloudResource": '{"framework":{"function":' + '{"Id":"function-id","Name":"studio-app-fn"}}}' + } + }, + ) + ) + service._replace_application_code_bundle = Mock() + service._release_application = Mock(return_value="https://studio.example") + service.merge_function_envs_and_release = Mock() + service._set_function_min_instance = Mock() + service.ensure_application_route_methods = Mock() + + def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: + package = Path(output_dir) / str(extra_context["local_dir_name"]) + (package / "src").mkdir(parents=True) + + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.tempfile.gettempdir", + lambda: str(tmp_path), + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.cookiecutter", _cookiecutter + ) + + with caplog.at_level("WARNING"): + service._update_function_code("studio-app", str(project)) + + assert "No requirements.txt found" in caplog.text + + def test_vefaas_deploy_updates_existing_application_in_place() -> None: service = object.__new__(VeFaaS) service.find_app_id_by_name = Mock(return_value="application-id") From 9f74107702f2b41b7d377954e0b79a8c7ea34f0f Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 11:53:16 +0800 Subject: [PATCH 07/22] chore(lock): resolve a2a-sdk 1.4.0 and agentkit 0.9.3 --- uv.lock | 67 +++++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 56 insertions(+), 11 deletions(-) diff --git a/uv.lock b/uv.lock index 3a878b27b..710353c99 100644 --- a/uv.lock +++ b/uv.lock @@ -16,18 +16,27 @@ resolution-markers = [ [[package]] name = "a2a-sdk" -version = "0.3.26" +version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ + { name = "culsans", marker = "python_full_version < '3.13'" }, { name = "google-api-core" }, + { name = "googleapis-common-protos" }, { name = "httpx" }, - { name = "httpx-sse" }, + { name = "json-rpc" }, + { name = "packaging" }, { name = "protobuf" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/be/97/a6840e01795b182ce751ca165430d46459927cde9bfab838087cbb24aef7/a2a_sdk-0.3.26.tar.gz", hash = "sha256:44068e2d037afbb07ab899267439e9bc7eaa7ac2af94f1e8b239933c993ad52d", size = 274598, upload-time = "2026-04-09T15:21:13.902Z" } +sdist = { url = "https://files.pythonhosted.org/packages/01/3d/215dbe548f197c3d87dcb334569c5e0c16219e546e767966e234e7f5d377/a2a_sdk-1.4.0.tar.gz", hash = "sha256:14f642a58374badc9054b668fd9bc0915eb4a60454a35854de7712f852e45770", size = 466558, upload-time = "2026-11-30T11:00:58.135Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/dd/d5/51f4ee1bf3b736add42a542d3c8a3fd3fa85f3d36c17972127defc46c26f/a2a_sdk-0.3.26-py3-none-any.whl", hash = "sha256:754e0573f6d33b225c1d8d51f640efa69cbbed7bdfb06ce9c3540ea9f58d4a91", size = 151016, upload-time = "2026-04-09T15:21:12.35Z" }, + { url = "https://files.pythonhosted.org/packages/6a/d3/e5b1e3ccd8e1ed8a6ac4be5ae585ce16df4b5a77cccc5955f04539e2f839/a2a_sdk-1.4.0-py3-none-any.whl", hash = "sha256:9b814f6bc62b62de044f4c38342b2ed024fa2eac288bf2f1006194657ebcce3e", size = 310052, upload-time = "2026-11-30T11:00:56.647Z" }, +] + +[package.optional-dependencies] +http-server = [ + { name = "sse-starlette" }, + { name = "starlette" }, ] [[package]] @@ -77,7 +86,7 @@ wheels = [ [[package]] name = "agentkit-sdk-python" -version = "0.8.9" +version = "0.9.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "a2a-sdk" }, @@ -106,9 +115,9 @@ dependencies = [ { name = "volcengine" }, { name = "websocket-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/24/1e/e6fef2ff0a54fc8cb854e48b4dd82ee27a7aa5570ca5cb1b15716746f500/agentkit_sdk_python-0.8.9.tar.gz", hash = "sha256:226d868f340b77d3c0113c57a7c55c83a8719d5e13195ef939d12bd810905af5", size = 610207, upload-time = "2026-10-13T02:34:30.875Z" } +sdist = { url = "https://files.pythonhosted.org/packages/c5/27/60815e26bdd089f2f88fd5778c5d9a3da13d2f1b06a2dc0f5f6bac2d8488/agentkit_sdk_python-0.9.3.tar.gz", hash = "sha256:36e55d44f2550dca7461c5c0d7d8cba5120dd8b211ab432ef05a068ec8556121", size = 633954, upload-time = "2026-12-03T03:49:06.568Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/60/93/2417a81bf1a23a938594c99072ae178dbf5fd568e749cb8419b4a85228fa/agentkit_sdk_python-0.8.9-py3-none-any.whl", hash = "sha256:5bf428303615da6c730c6e84f2e4d3de1dd2accab554301a457ab307ed7c5c4f", size = 818571, upload-time = "2026-10-13T02:34:28.96Z" }, + { url = "https://files.pythonhosted.org/packages/63/4d/835da28f0d4d18d88fb0f897a90c2a1e17e6577b64eca9d98dc81e167c61/agentkit_sdk_python-0.9.3-py3-none-any.whl", hash = "sha256:6c46757666617a09bfa0ad5c574f99f94a361c5769fcf8856dee8f74b2a46917", size = 854551, upload-time = "2026-12-03T03:49:05.015Z" }, ] [[package]] @@ -244,6 +253,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ea/c0/649856ee655a843c8f8664592cfccb73ac80ede6a8c8db33a25d810c12db/aiohttp-3.13.4-cp313-cp313-win_amd64.whl", hash = "sha256:74a2eb058da44fa3a877a49e2095b591d4913308bb424c418b77beb160c55ce3", size = 459778, upload-time = "2026-03-28T17:17:21.964Z" }, ] +[[package]] +name = "aiologic" +version = "0.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "sniffio" }, + { name = "typing-extensions" }, + { name = "wrapt" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/7a/d51f2fde1e8ae8a83431f8e97b7a71e9358cdb1d4d2ce6be387fa44d68de/aiologic-0.17.1.tar.gz", hash = "sha256:2e1b93b9e88ced318c2a63ad7b382688f40cbfe40e3d42258d49dc9c5aea179d", size = 252354, upload-time = "2026-06-27T20:41:33.25Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/d3/2d310b1b839014034dba0cba685e492df8a5c7ad32c19cab7e979eed6554/aiologic-0.17.1-py3-none-any.whl", hash = "sha256:c66b319830fedb7ca3d2b2125fa6f5b653f89418c2a27ea76f259ec5f00943c0", size = 161331, upload-time = "2026-06-27T20:41:31.877Z" }, +] + [[package]] name = "aiomysql" version = "0.3.2" @@ -1064,6 +1087,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/44/711e61f7d014be825ef79b285b047292d1bf893732ac1bc030a351fb517f/cryptography-50.0.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:693c99b49bd37d0d096e4334c10232c77248c415b98d35236094cdf96d57258b", size = 3824006, upload-time = "2026-08-25T19:45:37.281Z" }, ] +[[package]] +name = "culsans" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiologic" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d9/e3/49afa1bc180e0d28008ec6bcdf82a4072d1c7a41032b5b759b60814ca4b0/culsans-0.11.0.tar.gz", hash = "sha256:0b43d0d05dce6106293d114c86e3fb4bfc63088cfe8ff08ed3fe36891447fe33", size = 107546, upload-time = "2025-12-31T23:15:38.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/5d/9fb19fb38f6d6120422064279ea5532e22b84aa2be8831d49607194feda3/culsans-0.11.0-py3-none-any.whl", hash = "sha256:278d118f63fc75b9db11b664b436a1b83cc30d9577127848ba41420e66eb5a47", size = 21811, upload-time = "2025-12-31T23:15:37.189Z" }, +] + [[package]] name = "cyclopts" version = "4.23.3" @@ -2600,6 +2636,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/c5/82addfd375e5ee6520644e0553e4aadde92d668c4fc99cc716d337fe7bb3/joserfc-1.7.5-py3-none-any.whl", hash = "sha256:add2c2c84e8373b084d526a8b53daba5d7a513a118cd2dcd9fc9f979d0922159", size = 71269, upload-time = "2026-08-29T13:05:40.718Z" }, ] +[[package]] +name = "json-rpc" +version = "1.15.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/74/2d/3942cd7052da88f0ef3eacdc185b8fdc82becdb81768dea5249ea878740e/json_rpc-1.15.2.tar.gz", hash = "sha256:e0e12cd1327d9c743eacc21aeedf432ba31b25792d46a749d850c76dc99c97d4", size = 37294, upload-time = "2026-11-29T23:57:15.795Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3b/36/ddf8b0662258925505bf4c0645af62628a8ca0f3b28063bc852ab844a70c/json_rpc-1.15.2-py2.py3-none-any.whl", hash = "sha256:01c1246f66542b70a8aa1979ddf45b6ded94fc1949ecb53b9f027fcf2bdf712f", size = 49559, upload-time = "2026-11-29T23:57:14.375Z" }, +] + [[package]] name = "jsonpickle" version = "4.1.2" @@ -6058,7 +6103,7 @@ wheels = [ name = "veadk-python" source = { editable = "." } dependencies = [ - { name = "a2a-sdk" }, + { name = "a2a-sdk", extra = ["http-server"] }, { name = "agent-pilot-sdk" }, { name = "agentkit-sdk-python" }, { name = "aiomysql" }, @@ -6179,11 +6224,11 @@ dev = [ [package.metadata] requires-dist = [ - { name = "a2a-sdk", specifier = ">=0.3.7,<1.0.0" }, + { name = "a2a-sdk", extras = ["http-server"], specifier = ">=1.4.0,<1.5.0" }, { name = "a2ui-agent-sdk", marker = "extra == 'a2ui'", specifier = ">=0.2.1" }, { name = "agent-pilot-sdk", specifier = "==0.1.2" }, - { name = "agentkit-sdk-python", specifier = ">=0.8.5" }, - { name = "agentkit-sdk-python", marker = "extra == 'harness-sidecar'", specifier = ">=0.8.5" }, + { name = "agentkit-sdk-python", specifier = ">=0.9.3" }, + { name = "agentkit-sdk-python", marker = "extra == 'harness-sidecar'", specifier = ">=0.9.3" }, { name = "aiomysql", specifier = "==0.3.2" }, { name = "anthropic", marker = "extra == 'sandbox'", specifier = ">=0.40.0" }, { name = "async-timeout", marker = "python_full_version < '3.11'", specifier = ">=5,<6" }, From 758010c1d992f122c567930ba15f2478b4c04bf8 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 12:06:21 +0800 Subject: [PATCH 08/22] test: align agentkit baseline assertions with 0.9.3 The runtime, studio TOS and sidecar wheel metadata tests still asserted the historical agentkit-sdk-python>=0.8.5 floor. veadk now requires >=0.9.3 so that a2a-sdk 1.4.0 resolves, so the assertions are updated to the new floor while still proving the TOS-capable lower bound is preserved. --- tests/cli/test_studio_tos_sdk_dependency.py | 4 +++- tests/extensions/harness/test_sidecar_wheel.py | 4 ++-- tests/test_runtime_dependency_compatibility.py | 6 +++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/cli/test_studio_tos_sdk_dependency.py b/tests/cli/test_studio_tos_sdk_dependency.py index b5af55f72..adb3a4be5 100644 --- a/tests/cli/test_studio_tos_sdk_dependency.py +++ b/tests/cli/test_studio_tos_sdk_dependency.py @@ -32,5 +32,7 @@ def test_studio_requires_agentkit_sdk_with_tos_credential_type() -> None: if Requirement(value).name == "agentkit-sdk-python" ) - assert requirement.specifier.contains("0.8.5") + # TOS credential type landed in agentkit-sdk-python 0.8.5; the declared floor + # must stay at or above it while still admitting the currently required line. + assert requirement.specifier.contains("0.9.3") assert not requirement.specifier.contains("0.8.4") diff --git a/tests/extensions/harness/test_sidecar_wheel.py b/tests/extensions/harness/test_sidecar_wheel.py index 915c3ead4..292b40ac4 100644 --- a/tests/extensions/harness/test_sidecar_wheel.py +++ b/tests/extensions/harness/test_sidecar_wheel.py @@ -110,7 +110,7 @@ def test_wheel_metadata_keeps_sidecar_optional_and_sdk_constraints_aligned( if canonicalize_name(item.name) == "agentkit-sdk-python" ] assert any( - item.marker is None and ">=0.8.5" in str(item.specifier) + item.marker is None and ">=0.9.3" in str(item.specifier) for item in sdk_requirements ) sidecar_extra = [ @@ -119,7 +119,7 @@ def test_wheel_metadata_keeps_sidecar_optional_and_sdk_constraints_aligned( if item.marker is not None and "harness-sidecar" in str(item.marker) ] assert len(sidecar_extra) == 1 - assert ">=0.8.5" in str(sidecar_extra[0].specifier) + assert ">=0.9.3" in str(sidecar_extra[0].specifier) forbidden = { "agentkit-harness-sidecar-integration", diff --git a/tests/test_runtime_dependency_compatibility.py b/tests/test_runtime_dependency_compatibility.py index d54c3bd16..c43dd63f8 100644 --- a/tests/test_runtime_dependency_compatibility.py +++ b/tests/test_runtime_dependency_compatibility.py @@ -24,7 +24,7 @@ ROOT = Path(__file__).resolve().parents[1] GOOGLE_ADK_BASELINE = "google-adk>=2.7.0,<2.15.0" GOOGLE_ADK_EVAL_BASELINE = "google-adk[eval]>=2.7.0,<2.15.0" -AGENTKIT_BASELINE = "agentkit-sdk-python>=0.8.5" +AGENTKIT_BASELINE = "agentkit-sdk-python>=0.9.3" OPENTELEMETRY_EXPORTER_BASELINE = "opentelemetry-exporter-otlp>=1.37.0,<1.43" OPENTELEMETRY_EXPORTER_LOCK_BASELINE = ( '{ name = "opentelemetry-exporter-otlp", specifier = ">=1.37.0,<1.43" }' @@ -50,10 +50,10 @@ def test_project_dependency_metadata_uses_runtime_compatibility_baseline() -> No def test_lock_metadata_matches_project_dependency_baseline() -> None: lock = (ROOT / "uv.lock").read_text(encoding="utf-8") - assert '{ name = "agentkit-sdk-python", specifier = ">=0.8.5" }' in lock + assert '{ name = "agentkit-sdk-python", specifier = ">=0.9.3" }' in lock assert ( '{ name = "agentkit-sdk-python", marker = "extra == ' - '\'harness-sidecar\'", specifier = ">=0.8.5" }' + '\'harness-sidecar\'", specifier = ">=0.9.3" }' ) in lock assert '{ name = "google-adk", specifier = ">=2.7.0,<2.15.0" }' in lock assert ( From 62d2908e40e9c92b30860ed2c7ad98af776e096d Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 14:41:17 +0800 Subject: [PATCH 09/22] fix(a2a): advertise streaming and auto-resolve CloudApp cards VeA2AServer serves message/stream for both the 0.3 and 1.0 JSON-RPC bindings, but its AgentCard advertised streaming=false. A 1.0 client that honours the card could therefore downgrade to non-streaming message/send. Advertise the capability that the server actually has. CloudApp's default mode built a v0.3-only synthetic card, so it could not reach a 1.0-only peer. Default to auto card resolution instead: try /.well-known/agent-card.json, then the legacy /.well-known/agent.json, and let the SDK pick the best interface. If neither path publishes a card, fall back to the historical v0.3-only card so existing deployments keep working. use_agent_card=False preserves the old no-fetch behavior; True requires a card. A successful resolution is cached per instance. Verified against real servers: dual-stack veadk (1.0), 1.0-only (1.0), 0.3-only with the legacy card path (0.3), and a no-card endpoint (0.3). --- tests/a2a/test_a2a_sdk_14.py | 134 +++++++++++++++++++++++++++-------- veadk/a2a/agent_card.py | 6 +- veadk/cloud/cloud_app.py | 123 ++++++++++++++++++++++++-------- 3 files changed, 203 insertions(+), 60 deletions(-) diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py index 2e10440ec..57555d86b 100644 --- a/tests/a2a/test_a2a_sdk_14.py +++ b/tests/a2a/test_a2a_sdk_14.py @@ -116,6 +116,7 @@ def test_get_agent_card_is_dual_stack_by_default(): assert [i.protocol_version for i in card.supported_interfaces] == ["0.3", "1.0"] assert card.supported_interfaces[0].url == "https://example.com" assert card.skills[0].id == "0" + assert card.capabilities.streaming is True def test_get_agent_card_can_disable_v0_3(): @@ -173,8 +174,14 @@ def test_ve_a2a_server_serves_both_card_paths(monkeypatch): short_term_memory=object(), ) client = TestClient(server.build()) - assert client.get("/.well-known/agent-card.json").status_code == 200 - assert client.get("/.well-known/agent.json").status_code == 200 + for path in ("/.well-known/agent-card.json", "/.well-known/agent.json"): + response = client.get(path) + assert response.status_code == 200 + payload = response.json() + assert payload["capabilities"]["streaming"] is True + assert [ + interface["protocolVersion"] for interface in payload["supportedInterfaces"] + ] == ["0.3", "1.0"] def test_ve_a2a_server_can_disable_v0_3(monkeypatch): @@ -427,60 +434,127 @@ def test_get_message_id_supports_both_api_shapes(): assert get_message_id(Message(message_id="def")) == "def" -@pytest.mark.asyncio -async def test_cloud_app_default_mode_does_not_fetch_card(monkeypatch): - captured = {} +class _FakeClientFactory: + """Capture the card handed to ClientFactory and return a sentinel client.""" - class FakeFactory: - def __init__(self, config): - self.config = config + def __init__(self, config): + self.config = config + self.captured = None - def create(self, card): - captured["card"] = card - return "client" + def create(self, card): + self.captured = card + return "client" - resolver = MagicMock() - resolver.get_agent_card = AsyncMock(side_effect=AssertionError("should not fetch")) - monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", FakeFactory) + +def _patch_card_resolution(monkeypatch, resolver): + factory_holder = {} + + def factory(config): + factory_holder["factory"] = _FakeClientFactory(config) + return factory_holder["factory"] + + monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", factory) monkeypatch.setattr("veadk.cloud.cloud_app.A2ACardResolver", lambda **kw: resolver) + return factory_holder + + +@pytest.mark.asyncio +async def test_cloud_app_auto_mode_resolves_card_from_new_path(monkeypatch): + card = _card() + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(return_value=card) + holder = _patch_card_resolution(monkeypatch, resolver) app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") client = await app._get_a2a_client() await app.aclose() assert client == "client" - assert [i.protocol_version for i in captured["card"].supported_interfaces] == [ - "0.3" - ] + assert holder["factory"].captured is card + resolver.get_agent_card.assert_awaited_once_with( + relative_card_path="/.well-known/agent-card.json" + ) @pytest.mark.asyncio -async def test_cloud_app_card_mode_fetches_card(monkeypatch): +async def test_cloud_app_auto_mode_falls_back_to_legacy_card_path(monkeypatch): card = _card() - captured = {} + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(side_effect=[RuntimeError("404"), card]) + holder = _patch_card_resolution(monkeypatch, resolver) - class FakeFactory: - def __init__(self, config): - self.config = config + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + client = await app._get_a2a_client() + await app.aclose() + + assert client == "client" + assert holder["factory"].captured is card + assert [ + call.kwargs["relative_card_path"] + for call in resolver.get_agent_card.await_args_list + ] == ["/.well-known/agent-card.json", "/.well-known/agent.json"] - def create(self, resolved_card): - captured["card"] = resolved_card - return "client" +@pytest.mark.asyncio +async def test_cloud_app_auto_mode_falls_back_to_synthetic_v0_3_card(monkeypatch): resolver = MagicMock() - resolver.get_agent_card = AsyncMock(return_value=card) - monkeypatch.setattr("veadk.cloud.cloud_app.ClientFactory", FakeFactory) - monkeypatch.setattr("veadk.cloud.cloud_app.A2ACardResolver", lambda **kw: resolver) + resolver.get_agent_card = AsyncMock(side_effect=RuntimeError("404")) + holder = _patch_card_resolution(monkeypatch, resolver) - app = CloudApp(vefaas_endpoint="http://127.0.0.1:1", use_agent_card=True) + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") client = await app._get_a2a_client() await app.aclose() assert client == "client" - assert captured["card"] is card + assert [ + interface.protocol_version + for interface in holder["factory"].captured.supported_interfaces + ] == ["0.3"] + + +@pytest.mark.asyncio +async def test_cloud_app_auto_mode_caches_resolved_card(monkeypatch): + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(return_value=_card()) + _patch_card_resolution(monkeypatch, resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") + await app._get_a2a_client() + await app._get_a2a_client() + await app.aclose() + resolver.get_agent_card.assert_awaited_once() +@pytest.mark.asyncio +async def test_cloud_app_explicit_false_never_fetches_card(monkeypatch): + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(side_effect=AssertionError("should not fetch")) + holder = _patch_card_resolution(monkeypatch, resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1", use_agent_card=False) + client = await app._get_a2a_client() + await app.aclose() + + assert client == "client" + assert [ + interface.protocol_version + for interface in holder["factory"].captured.supported_interfaces + ] == ["0.3"] + + +@pytest.mark.asyncio +async def test_cloud_app_card_mode_raises_when_no_card(monkeypatch): + resolver = MagicMock() + resolver.get_agent_card = AsyncMock(side_effect=RuntimeError("404")) + _patch_card_resolution(monkeypatch, resolver) + + app = CloudApp(vefaas_endpoint="http://127.0.0.1:1", use_agent_card=True) + with pytest.raises(ValueError, match="Could not resolve an agent card"): + await app._get_a2a_client() + await app.aclose() + + @pytest.mark.asyncio async def test_cloud_app_message_send_returns_cloud_message(monkeypatch): app = CloudApp(vefaas_endpoint="http://127.0.0.1:1") diff --git a/veadk/a2a/agent_card.py b/veadk/a2a/agent_card.py index 2758c2c34..508878db7 100644 --- a/veadk/a2a/agent_card.py +++ b/veadk/a2a/agent_card.py @@ -57,7 +57,11 @@ def get_agent_card( ) -> AgentCard: public_url = _normalize_public_url(url) agent_provider = AgentProvider(organization=provider, url="") - agent_capabilities = AgentCapabilities() + # ``VeA2AServer`` always runs ``A2aAgentExecutor``, whose + # ``DefaultRequestHandler`` serves ``message/stream`` for both the 0.3 and + # 1.0 JSON-RPC bindings. Advertise it so 1.0 clients that honour the card + # do not silently downgrade to non-streaming ``message/send``. + agent_capabilities = AgentCapabilities(streaming=True) agent_skills = [ AgentSkill( id="0", diff --git a/veadk/cloud/cloud_app.py b/veadk/cloud/cloud_app.py index 5640f113c..0389b678d 100644 --- a/veadk/cloud/cloud_app.py +++ b/veadk/cloud/cloud_app.py @@ -39,6 +39,11 @@ logger = get_logger(__name__) +_AGENT_CARD_PATHS = ( + "/.well-known/agent-card.json", + "/.well-known/agent.json", +) + @dataclass class CloudPart: @@ -152,7 +157,11 @@ class CloudApp: vefaas_application_name (str): Name of the VeFaaS application. Defaults to "". vefaas_endpoint (str): URL for accessing the application. Resolved if not provided. vefaas_application_id (str): Unique identifier of the application. Defaults to "". - use_agent_card (bool): Flag to resolve endpoint via agent card. Defaults to False. + use_agent_card (bool | None): Card resolution mode. ``None`` (default) + resolves the card from both well-known paths and lets the SDK pick + the best interface (preferring 1.0), falling back to the historical + v0.3-only card when no card is served. ``True`` requires a card; + ``False`` never fetches one. httpx_client (httpx.AsyncClient): Async HTTP client for requests. Note: @@ -176,7 +185,7 @@ def __init__( vefaas_application_name: str = "", vefaas_endpoint: str = "", vefaas_application_id: str = "", - use_agent_card: bool = False, + use_agent_card: bool | None = None, ): """Initializes the CloudApp with VeFaaS application details. @@ -186,7 +195,9 @@ def __init__( vefaas_application_name (str, optional): Application name for lookup. Defaults to "". vefaas_endpoint (str, optional): Direct endpoint URL. Defaults to "". vefaas_application_id (str, optional): Application ID for lookup. Defaults to "". - use_agent_card (bool): Use agent card to determine invocation URL. Defaults to False. + use_agent_card (bool | None): Card resolution mode. ``None`` (default) + resolves the card and falls back to the historical v0.3-only + card; ``True`` requires a card; ``False`` never fetches one. Returns: None @@ -207,6 +218,7 @@ def __init__( self.vefaas_application_id = vefaas_application_id self.vefaas_application_name = vefaas_application_name self.use_agent_card = use_agent_card + self._resolved_card: AgentCard | None = None # vefaas must be set one of three if ( @@ -232,7 +244,7 @@ def __init__( if use_agent_card: logger.info( - "Use agent card to invoke agent. The agent endpoint will use the `url` in agent card." + "Use agent card to invoke agent. The agent endpoint will use the `url` in the agent card." ) scheme = httpx.URL(self.vefaas_endpoint).scheme @@ -335,14 +347,77 @@ def _get_vefaas_application_id_by_name(self) -> str: ) return vefaas_application_id + def _legacy_v0_3_card(self) -> AgentCard: + """Return the historical minimal v0.3 card. + + This is the pre-1.4 default-mode card. It is kept as the fallback so + endpoints that do not publish an agent card keep working exactly as + before. + """ + return AgentCard( + name="cloud_app", + description="CloudApp default endpoint", + version="1.0.0", + supported_interfaces=[ + AgentInterface( + url=self.vefaas_endpoint, + protocol_binding="JSONRPC", + protocol_version="0.3", + ) + ], + capabilities=AgentCapabilities(), + default_input_modes=["text"], + default_output_modes=["text"], + skills=[], + ) + + async def _resolve_agent_card(self) -> AgentCard | None: + """Resolve the agent card from both well-known paths. + + a2a-sdk 1.x publishes ``/.well-known/agent-card.json`` while 0.3.x + used ``/.well-known/agent.json``. Try the current path first, then the + legacy one, so a v0.3-only peer is still discovered. A successful + resolution is cached on the instance; failures are not cached so a + transient error can recover on the next call. + """ + if self._resolved_card is not None: + return self._resolved_card + + resolver = A2ACardResolver( + httpx_client=self.httpx_client, base_url=self.vefaas_endpoint + ) + errors: list[str] = [] + for path in _AGENT_CARD_PATHS: + try: + card = await resolver.get_agent_card(relative_card_path=path) + except Exception as e: # noqa: BLE001 - fall back to the next path + errors.append(f"{path}: {e}") + continue + self._resolved_card = card + return card + + logger.debug( + "Agent card resolution failed for %s: %s", + self.vefaas_endpoint, + errors, + ) + return None + async def _get_a2a_client(self): """Constructs an A2A client configured for this cloud app. - If use_agent_card, resolves the agent card and lets the SDK select the - matching interface; otherwise constructs a minimal v0.3-only card and - sends ``message/send`` directly to the configured endpoint. The - default mode deliberately does not fetch the card: that was the - pre-1.4 behavior and avoids an extra network round-trip. + ``use_agent_card`` controls card resolution: + + * ``None`` (default, "auto"): resolve the card from both well-known + paths and let the SDK select the best interface. The SDK prefers + 1.0, so a dual-stack or 1.0-only peer is reached over 1.0 while a + v0.3-only peer is reached over 0.3. If no card is published, fall + back to the historical v0.3-only card so existing deployments keep + working. + * ``True``: require a card. Both paths are tried; if neither works a + ``ValueError`` is raised. + * ``False``: never fetch a card; always use the historical v0.3-only + card. Returns: A ready-to-use a2a client. @@ -352,28 +427,18 @@ async def _get_a2a_client(self): the SDK marks it shared and never closes it. Callers close it via :meth:`aclose` or ``async with``. """ - if self.use_agent_card: - resolver = A2ACardResolver( - httpx_client=self.httpx_client, base_url=self.vefaas_endpoint - ) - card = await resolver.get_agent_card() + if self.use_agent_card is False: + card = self._legacy_v0_3_card() else: - card = AgentCard( - name="cloud_app", - description="CloudApp default endpoint", - version="1.0.0", - supported_interfaces=[ - AgentInterface( - url=self.vefaas_endpoint, - protocol_binding="JSONRPC", - protocol_version="0.3", + card = await self._resolve_agent_card() + if card is None: + if self.use_agent_card is True: + raise ValueError( + "Could not resolve an agent card from " + f"{self.vefaas_endpoint}; set use_agent_card=False to " + "force the legacy v0.3 card." ) - ], - capabilities=AgentCapabilities(), - default_input_modes=["text"], - default_output_modes=["text"], - skills=[], - ) + card = self._legacy_v0_3_card() return ClientFactory( ClientConfig(httpx_client=self.httpx_client, streaming=False) From 3b76065f633b19e219e20beae184d45f2f0f2228 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 16:24:41 +0800 Subject: [PATCH 10/22] feat(a2a): add declarative config and AgentCard JWS signing Introduce A2AServerConfig with opt-in knobs for the 1.x capabilities and an AgentCard signer supporting local JWK/PEM keys and Volcano Engine KMS asymmetric keys. The signer produces a detached JWS over the JCS-canonicalised card and can publish the matching JWKS to TOS. Signed-off-by: Codex --- veadk/a2a/config.py | 233 ++++++++++++++++++++++++++++++++++++++++ veadk/a2a/signing.py | 246 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 479 insertions(+) create mode 100644 veadk/a2a/config.py create mode 100644 veadk/a2a/signing.py diff --git a/veadk/a2a/config.py b/veadk/a2a/config.py new file mode 100644 index 000000000..a4423d2d0 --- /dev/null +++ b/veadk/a2a/config.py @@ -0,0 +1,233 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Declarative configuration for the VeADK A2A server. + +Every knob is opt-in and has a backward-compatible default, so existing +``VeA2AServer`` / ``init_app`` callers keep their current behaviour. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from a2a.types import ( + APIKeySecurityScheme, + AuthorizationCodeOAuthFlow, + HTTPAuthSecurityScheme, + MutualTlsSecurityScheme, + OAuth2SecurityScheme, + OAuthFlows, + OpenIdConnectSecurityScheme, + SecurityRequirement, + SecurityScheme, + StringList, +) + +_API_KEY = "apiKey" +_HTTP = "http" +_OAUTH2 = "oauth2" +_OIDC = "openIdConnect" +_MTLS = "mutualTLS" + + +@dataclass(frozen=True) +class A2ASecurityScheme: + """One AgentCard ``securitySchemes`` entry. + + ``type`` selects the A2A security-scheme flavour and the remaining fields + are only meaningful for that flavour: + + * ``apiKey``: ``name``, ``location`` (``header``/``query``/``cookie``) + * ``http``: ``scheme``, ``bearer_format`` + * ``oauth2``: ``authorization_url``, ``token_url``, ``refresh_url``, + ``scopes``, ``pkce_required``, ``oauth2_metadata_url`` + * ``openIdConnect``: ``open_id_connect_url`` + * ``mutualTLS``: description only + """ + + scheme_id: str + type: str + description: str = "" + name: str = "" + location: str = "" + scheme: str = "" + bearer_format: str = "" + authorization_url: str = "" + token_url: str = "" + refresh_url: str = "" + open_id_connect_url: str = "" + oauth2_metadata_url: str = "" + scopes: dict[str, str] = field(default_factory=dict) + pkce_required: bool = True + + def __post_init__(self) -> None: + if self.type not in {_API_KEY, _HTTP, _OAUTH2, _OIDC, _MTLS}: + raise ValueError(f"Unsupported A2A security scheme type: {self.type!r}") + + def to_proto(self) -> SecurityScheme: + """Convert the declarative scheme to the AgentCard protobuf type.""" + if self.type == _API_KEY: + return SecurityScheme( + api_key_security_scheme=APIKeySecurityScheme( + description=self.description, + location=self.location, + name=self.name, + ) + ) + if self.type == _HTTP: + return SecurityScheme( + http_auth_security_scheme=HTTPAuthSecurityScheme( + description=self.description, + scheme=self.scheme, + bearer_format=self.bearer_format, + ) + ) + if self.type == _OAUTH2: + return SecurityScheme( + oauth2_security_scheme=OAuth2SecurityScheme( + description=self.description, + oauth2_metadata_url=self.oauth2_metadata_url, + flows=OAuthFlows( + authorization_code=AuthorizationCodeOAuthFlow( + authorization_url=self.authorization_url, + token_url=self.token_url, + refresh_url=self.refresh_url, + scopes=self.scopes, + pkce_required=self.pkce_required, + ) + ), + ) + ) + if self.type == _OIDC: + return SecurityScheme( + open_id_connect_security_scheme=OpenIdConnectSecurityScheme( + description=self.description, + open_id_connect_url=self.open_id_connect_url, + ) + ) + return SecurityScheme( + mtls_security_scheme=MutualTlsSecurityScheme(description=self.description) + ) + + +@dataclass(frozen=True) +class A2ASigningConfig: + """AgentCard JWS signing configuration. + + ``provider="local"`` signs with a local key (PEM/JWK). ``provider="kms"`` + signs with Volcano Engine KMS asymmetric keys; the private key never + leaves KMS. ``jku`` is published in the protected header so verifiers can + fetch the JWKS. + """ + + provider: str = "local" + kid: str = "veadk-a2a-1" + alg: str = "ES256" + jku: str = "" + private_key: str = "" + # KMS + kms_key_id: str = "" + kms_keyring_name: str = "" + kms_algorithm: str = "ECDSA_SHA_256" + region: str = "cn-beijing" + access_key: str = "" + secret_key: str = "" + session_token: str = "" + # JWKS publishing + jwks_bucket: str = "" + jwks_object_key: str = ".well-known/jwks.json" + + def __post_init__(self) -> None: + if self.provider not in {"local", "kms"}: + raise ValueError(f"Unsupported A2A signing provider: {self.provider!r}") + + +@dataclass +class A2AServerConfig: + """Configuration for the veadk A2A server. + + ``compat_v0_3`` keeps the legacy JSON-RPC methods and the historical + ``/.well-known/agent.json`` card path enabled. ``docs_enabled`` registers + the A2A routes through ``add_a2a_routes_to_fastapi`` so they appear in the + generated OpenAPI schema. + + The remaining fields are opt-in capabilities from A2A 1.0/1.4: + + * ``rest_enabled`` / ``rest_path_prefix`` mount the HTTP+JSON transport. + * ``otel_enabled`` registers the SDK OpenTelemetry plugin. + * ``validate_input_modes`` / ``validate_required_extensions`` turn on the + server-side policy checks. + * ``extensions`` declares (and, with validation on, requires) extensions. + * ``extended_card_skills`` builds the authenticated extended card. + * ``signing`` signs the AgentCard (local key or KMS). + * ``security_schemes`` / ``security_requirements`` declare auth metadata. + * ``oidc_*`` / ``require_auth`` enforce bearer-token authentication. + * ``database_url`` enables multi-replica cluster mode. + * ``push_*`` enables push notifications. + * ``tenant_header`` is the fallback tenant carrier for transports that do + not set ``ServerCallContext.tenant``. + """ + + compat_v0_3: bool = True + docs_enabled: bool = False + # HTTP+JSON transport + rest_enabled: bool = False + rest_path_prefix: str = "/v1" + # observability + otel_enabled: bool = False + # request validation + validate_input_modes: bool = False + validate_required_extensions: bool = False + extensions: tuple[str, ...] = () + # extended card + extended_card_skills: tuple[Any, ...] = () + # card signing + signing: A2ASigningConfig | None = None + # security metadata + security_schemes: tuple[A2ASecurityScheme, ...] = () + security_requirements: tuple[dict[str, tuple[str, ...]], ...] = () + # authentication + oidc_issuer: str | None = None + oidc_jwks_uri: str | None = None + oidc_audience: str | None = None + require_auth: bool = False + # cluster mode + database_url: str | None = None + # push notifications + push_webhook_url: str | None = None + push_encryption_key: str | None = None + push_allow_private_url: bool = False + # tenant routing + tenant_header: str = "x-a2a-tenant" + + @property + def push_enabled(self) -> bool: + return bool(self.push_webhook_url) + + +def security_requirements_to_proto( + requirements: tuple[dict[str, tuple[str, ...]], ...], +) -> list[SecurityRequirement]: + """Convert declarative security requirements to protobuf.""" + return [ + SecurityRequirement( + schemes={ + scheme_id: StringList(list=list(scopes)) + for scheme_id, scopes in requirement.items() + } + ) + for requirement in requirements + ] diff --git a/veadk/a2a/signing.py b/veadk/a2a/signing.py new file mode 100644 index 000000000..f0b196c1f --- /dev/null +++ b/veadk/a2a/signing.py @@ -0,0 +1,246 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AgentCard JWS signing (A2A specification section 6.6). + +The signer produces a detached JWS over the JCS-canonicalised AgentCard and +appends an ``AgentCardSignature``. Verification is intentionally left to the +standard ``a2a.utils.signing.create_signature_verifier`` so clients can use any +JWKS-compatible key source. +""" + +from __future__ import annotations + +import base64 +import json +from typing import Any + +from a2a.types import AgentCard, AgentCardSignature +from a2a.utils.signing import create_agent_card_signer +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec +from jwt import PyJWK + +from veadk.a2a.config import A2ASigningConfig +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + + +def _b64url_uint(value: int) -> str: + """Encode an unsigned integer as unpadded base64url.""" + raw = value.to_bytes((value.bit_length() + 7) // 8, "big") + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") + + +def generate_es256_jwk(kid: str = "veadk-a2a-1") -> tuple[dict, dict]: + """Generate an ES256 key pair as (private JWK, public JWK).""" + private_key = ec.generate_private_key(ec.SECP256R1()) + public_numbers = private_key.public_key().public_numbers() + private_numbers = private_key.private_numbers() + public_jwk = { + "kty": "EC", + "crv": "P-256", + "x": _b64url_uint(public_numbers.x), + "y": _b64url_uint(public_numbers.y), + "kid": kid, + "alg": "ES256", + "use": "sig", + } + private_jwk = { + **public_jwk, + "d": _b64url_uint(private_numbers.private_value), + } + return private_jwk, public_jwk + + +def public_jwk_from_der(der: bytes, kid: str, alg: str = "ES256") -> dict[str, Any]: + """Convert a DER SubjectPublicKeyInfo blob to a public JWK. + + Volcano Engine KMS ``GetPublicKey`` returns DER SPKI. EC and RSA keys are + the two families KMS exposes for ``SIGN_VERIFY``. + """ + key = serialization.load_der_public_key(der) + if isinstance(key, ec.EllipticCurvePublicKey): + numbers = key.public_numbers() + curve = numbers.curve.name + crv = {"secp256r1": "P-256", "secp384r1": "P-384"}.get(curve) + if crv is None: + raise ValueError(f"Unsupported EC curve: {curve}") + return { + "kty": "EC", + "crv": crv, + "x": _b64url_uint(numbers.x), + "y": _b64url_uint(numbers.y), + "kid": kid, + "alg": alg, + "use": "sig", + } + numbers = key.public_numbers() + return { + "kty": "RSA", + "n": _b64url_uint(numbers.n), + "e": _b64url_uint(numbers.e), + "kid": kid, + "alg": alg, + "use": "sig", + } + + +class LocalAgentCardSigner: + """Signs an AgentCard with a local JWK or PEM key.""" + + def __init__(self, config: A2ASigningConfig) -> None: + if not config.private_key: + raise ValueError("local signing requires A2ASigningConfig.private_key") + material = config.private_key.strip() + key: PyJWK | str + if material.startswith("{"): + key = PyJWK.from_dict(json.loads(material)) + else: + key = material + self._signer = create_agent_card_signer( + signing_key=key, + protected_header={ + "alg": config.alg, + "kid": config.kid, + **({"jku": config.jku} if config.jku else {}), + }, + ) + + def __call__(self, card: AgentCard) -> AgentCard: + return self._signer(card) + + +class KmsAgentCardSigner: + """Signs an AgentCard with a Volcano Engine KMS asymmetric key. + + The private key never leaves KMS: only the JWS signing input is sent to + ``AsymmetricSign``. Requires the KMS service to be activated for the + account and a key with ``KeyUsage=SIGN_VERIFY``. + """ + + def __init__(self, config: A2ASigningConfig) -> None: + if not config.kms_key_id: + raise ValueError("kms signing requires A2ASigningConfig.kms_key_id") + self._config = config + self._api = self._build_api() + + def _build_api(self): + import volcenginesdkcore + import volcenginesdkkms + + cfg = volcenginesdkcore.Configuration() + cfg.ak = self._config.access_key or "" + cfg.sk = self._config.secret_key or "" + cfg.session_token = self._config.session_token + cfg.region = self._config.region + cfg.host = "open.volcengineapi.com" + return volcenginesdkkms.KMSApi( + api_client=volcenginesdkcore.ApiClient(configuration=cfg) + ) + + def _sign(self, signing_input: bytes) -> str: + import base64 as b64 + + from volcenginesdkkms.models.asymmetric_sign_request import ( + AsymmetricSignRequest, + ) + + response = self._api.asymmetric_sign( + AsymmetricSignRequest( + key_id=self._config.kms_key_id, + algorithm=self._config.kms_algorithm, + message=b64.b64encode(signing_input).decode("ascii"), + message_type="RAW", + ) + ) + signature = base64.b64decode(response.signature or "") + return base64.urlsafe_b64encode(signature).rstrip(b"=").decode("ascii") + + def __call__(self, card: AgentCard) -> AgentCard: + from a2a.utils.signing import _canonicalize_agent_card + + payload = _canonicalize_agent_card(card).encode("utf-8") + protected_header = { + "alg": self._config.alg, + "kid": self._config.kid, + **({"jku": self._config.jku} if self._config.jku else {}), + } + protected = ( + base64.urlsafe_b64encode( + json.dumps(protected_header, separators=(",", ":")).encode() + ) + .rstrip(b"=") + .decode("ascii") + ) + encoded_payload = base64.urlsafe_b64encode(payload).rstrip(b"=").decode("ascii") + signature = self._sign(f"{protected}.{encoded_payload}".encode()) + card.signatures.append( + AgentCardSignature( + protected=protected, + signature=signature, + ) + ) + return card + + +def build_agent_card_signer(config: A2ASigningConfig | None): + """Build a signer from config, or ``None`` when signing is disabled.""" + if config is None: + return None + if config.provider == "kms": + return KmsAgentCardSigner(config) + return LocalAgentCardSigner(config) + + +def jwks_document(keys: list[dict[str, Any]]) -> dict[str, Any]: + """Build a JWKS document from public JWKs.""" + return {"keys": keys} + + +def publish_jwks_to_tos( + jwks: dict[str, Any], + bucket: str, + object_key: str, + *, + region: str = "cn-beijing", +) -> str: + """Publish a JWKS document to TOS and return its public URL. + + The bucket must already exist and allow public reads. This helper is + intentionally blocking; call it from a startup hook, not a request path. + """ + from veadk.integrations.ve_tos.ve_tos import VeTOS + + client = VeTOS(region=region, bucket_name=bucket) + try: + client.create_bucket(bucket) + client.upload_bytes( + data=json.dumps(jwks, separators=(",", ":")).encode("utf-8"), + bucket_name=bucket, + object_key=object_key, + ) + # JWKS must be readable without credentials so verifiers can fetch it. + # ``VeTOS`` does not expose object ACLs, so call the underlying client. + import tos + + client._client.put_object_acl( # noqa: SLF001 + bucket=bucket, + key=object_key, + acl=tos.ACLType.ACL_Public_Read, + ) + finally: + client.close() + return f"https://{bucket}.tos-{region}.volces.com/{object_key.lstrip('/')}" From 67db75727c681232b03ddb5b30de340555cb404a Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 16:24:46 +0800 Subject: [PATCH 11/22] feat(a2a): add OIDC bearer auth, tenant routing and scoped stores Add a bearer-token middleware that validates JWTs against an OIDC issuer/JWKS, a tenant transport decorator for clients, and task/event/push stores that scope data by caller and tenant. In-memory mode keeps the historical single-process behaviour while enforcing per-owner isolation; database mode uses the SDK's versioned SQLAlchemy stores for multi-replica deployments. Signed-off-by: Codex --- veadk/a2a/security.py | 170 +++++++++++++++++++++++++++++ veadk/a2a/stores.py | 242 ++++++++++++++++++++++++++++++++++++++++++ veadk/a2a/tenant.py | 38 +++++++ 3 files changed, 450 insertions(+) create mode 100644 veadk/a2a/security.py create mode 100644 veadk/a2a/stores.py create mode 100644 veadk/a2a/tenant.py diff --git a/veadk/a2a/security.py b/veadk/a2a/security.py new file mode 100644 index 000000000..9a2b4545c --- /dev/null +++ b/veadk/a2a/security.py @@ -0,0 +1,170 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Bearer-token authentication for the A2A server. + +Implements the server half of A2A specification section 7.3: the AgentCard +declares ``securitySchemes`` and the server validates the credential the +client injects. Token issuance stays with the identity provider (Volcano +Engine Identity Service exposes OIDC discovery and JWKS). +""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any + +import jwt +from a2a.auth.user import User +from starlette.types import ASGIApp, Receive, Scope, Send + +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + +_DEFAULT_ALGORITHMS = ("RS256",) + + +class A2AUser(User): + """Authenticated A2A caller derived from a verified access token.""" + + def __init__(self, claims: dict[str, Any]) -> None: + self._claims = claims + + @property + def is_authenticated(self) -> bool: + return True + + @property + def user_name(self) -> str: + for key in ("sub", "client_id", "username", "uid"): + value = self._claims.get(key) + if value: + return str(value) + return "unknown" + + @property + def display_name(self) -> str: + """Starlette-compatible alias used by the default context builder.""" + return self.user_name + + @property + def claims(self) -> dict[str, Any]: + return dict(self._claims) + + +class BearerJWTVerifier: + """Verify bearer JWTs against an OIDC issuer / JWKS endpoint.""" + + def __init__( + self, + *, + issuer: str, + jwks_uri: str | None = None, + audience: str | None = None, + algorithms: tuple[str, ...] = _DEFAULT_ALGORITHMS, + ) -> None: + self.issuer = issuer + self.audience = audience + self.algorithms = list(algorithms) + if jwks_uri: + self._jwks_client: jwt.PyJWKClient | None = jwt.PyJWKClient( + jwks_uri, cache_keys=True + ) + else: + self._jwks_client = None + + def _verify_sync(self, token: str) -> dict[str, Any]: + if self._jwks_client is not None: + signing_key = self._jwks_client.get_signing_key_from_jwt(token) + key = signing_key.key + else: + raise ValueError("BearerJWTVerifier requires a JWKS URI") + return jwt.decode( + token, + key=key, + algorithms=self.algorithms, + audience=self.audience, + issuer=self.issuer, + ) + + async def verify(self, token: str) -> dict[str, Any]: + """Verify a token and return its claims.""" + return await asyncio.to_thread(self._verify_sync, token) + + +async def _send_unauthorized(send: Send, error: str, description: str) -> None: + """Send a 401 response with a Bearer challenge.""" + body = json.dumps({"error": error, "error_description": description}).encode() + response_headers = [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode()), + (b"www-authenticate", b'Bearer realm="a2a"'), + ] + await send( + { + "type": "http.response.start", + "status": 401, + "headers": response_headers, + } + ) + await send({"type": "http.response.body", "body": body}) + + +class A2AAuthMiddleware: + """Require a valid bearer token on every non-public route.""" + + def __init__( + self, + app: ASGIApp, + verifier: BearerJWTVerifier, + public_paths: tuple[str, ...] = (), + ) -> None: + self.app = app + self.verifier = verifier + self.public_paths = tuple(public_paths) + + def _is_public(self, path: str) -> bool: + if path in self.public_paths: + return True + return path.startswith("/.well-known/") + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self.app(scope, receive, send) + return + path = scope.get("path", "") + if self._is_public(path): + await self.app(scope, receive, send) + return + + headers = { + key.decode("latin-1").lower(): value.decode("latin-1") + for key, value in scope.get("headers", []) + } + authorization = headers.get("authorization", "") + if not authorization.lower().startswith("bearer "): + await _send_unauthorized(send, "invalid_request", "Missing bearer token") + return + token = authorization[7:].strip() + try: + claims = await self.verifier.verify(token) + except Exception as exc: # noqa: BLE001 - any validation failure is 401 + logger.warning("Rejected A2A bearer token: %s", exc) + await _send_unauthorized(send, "invalid_token", "Token validation failed") + return + + scope["user"] = A2AUser(claims) + await self.app(scope, receive, send) diff --git a/veadk/a2a/stores.py b/veadk/a2a/stores.py new file mode 100644 index 000000000..347f63e0f --- /dev/null +++ b/veadk/a2a/stores.py @@ -0,0 +1,242 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Task, event and push-config stores for the VeADK A2A server. + +Without ``database_url`` the server uses in-memory stores, which is the +historical single-process behaviour. With ``database_url`` the server uses the +SDK's versioned SQLAlchemy stores, which give multi-replica task visibility and +cross-replica streaming. Volcano Engine AIDAP Serverless PostgreSQL is the +default backing service (``postgresql+asyncpg``). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from a2a.server.cluster import ( + DatabaseTaskEventStream, + TaskEventStream, + VersionedTaskStore, + VersionedDatabaseTaskStore, +) +from a2a.server.context import ServerCallContext +from a2a.server.owner_resolver import OwnerResolver +from a2a.server.routes.common import DefaultServerCallContextBuilder +from a2a.server.tasks import ( + DatabasePushNotificationConfigStore, + InMemoryPushNotificationConfigStore, + InMemoryTaskStore, + PushNotificationConfigStore, + TaskStore, +) +from a2a.types import ListTasksRequest, ListTasksResponse, Task +from starlette.requests import Request + +from veadk.a2a.config import A2AServerConfig +from veadk.a2a.push import DefaultingPushNotificationConfigStore +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + + +def normalize_database_url(url: str) -> str: + """Normalise an AIDAP connection string for ``asyncpg``. + + AIDAP returns ``...?sslmode=require&channel_binding=require``. ``asyncpg`` + does not accept ``channel_binding`` and SQLAlchemy expects ``ssl`` rather + than ``sslmode``, so rewrite both. + """ + from sqlalchemy.engine import make_url + + parsed = make_url(url) + query = dict(parsed.query) + query.pop("channel_binding", None) + if "sslmode" in query: + query["ssl"] = query.pop("sslmode") + return parsed.set(query=query).render_as_string(hide_password=False) + + +def make_owner_resolver(tenant_header: str = "") -> OwnerResolver: + """Build an owner resolver that scopes tasks by caller and tenant.""" + + def resolve(context: ServerCallContext) -> str: + user = getattr(context.user, "user_name", "") or "" + tenant = context.tenant or "" + if not tenant and tenant_header: + headers = context.state.get("headers") or {} + tenant = headers.get(tenant_header, "") + if tenant: + return f"{user}|{tenant}" + return user + + return resolve + + +class VeServerCallContextBuilder(DefaultServerCallContextBuilder): + """Context builder that falls back to a tenant header. + + JSON-RPC and REST set ``ServerCallContext.tenant`` from the request. A + plain header fallback keeps tenant routing available to clients that cannot + set the field (for example older proxies). + """ + + def __init__(self, tenant_header: str = "") -> None: + super().__init__() + self.tenant_header = tenant_header + + def build(self, request: Request) -> ServerCallContext: + context = super().build(request) + if not context.tenant and self.tenant_header: + context.tenant = request.headers.get(self.tenant_header, "") + return context + + +class OwnerScopedInMemoryTaskStore(TaskStore): + """In-memory store that enforces per-owner task isolation. + + ``InMemoryTaskStore`` is a shared dictionary, so without this wrapper any + caller could read any task. The owner key is the value returned by the + configured resolver (user plus tenant); unauthenticated callers all share + the empty owner, preserving the historical single-tenant behaviour. + """ + + def __init__(self, owner_resolver: OwnerResolver) -> None: + self._inner = InMemoryTaskStore() + self._owners: dict[str, str] = {} + self._owner_resolver = owner_resolver + + def _owner(self, context: ServerCallContext | None) -> str: + if context is None: + return "" + return self._owner_resolver(context) + + @staticmethod + def _context(context: ServerCallContext | None) -> ServerCallContext: + return context or ServerCallContext() + + async def save(self, task: Task, context: ServerCallContext | None = None) -> None: + await self._inner.save(task, self._context(context)) + self._owners[task.id] = self._owner(context) + + async def get( + self, task_id: str, context: ServerCallContext | None = None + ) -> Task | None: + owner = self._owner(context) + if self._owners.get(task_id, owner) != owner: + return None + return await self._inner.get(task_id, self._context(context)) + + async def list( + self, + params: ListTasksRequest, + context: ServerCallContext | None = None, + ) -> ListTasksResponse: + owner = self._owner(context) + response = await self._inner.list(params, self._context(context)) + owned = [ + task for task in response.tasks if self._owners.get(task.id, owner) == owner + ] + result = ListTasksResponse() + result.CopyFrom(response) + del result.tasks[:] + result.tasks.extend(owned) + return result + + async def delete( + self, task_id: str, context: ServerCallContext | None = None + ) -> None: + owner = self._owner(context) + if self._owners.get(task_id, owner) != owner: + return + await self._inner.delete(task_id, self._context(context)) + self._owners.pop(task_id, None) + + +@dataclass +class A2AStores: + """Stores required by one ``VeA2AServer`` instance.""" + + task_store: TaskStore | VersionedTaskStore + event_stream: TaskEventStream | None = None + push_config_store: PushNotificationConfigStore | None = None + engine: Any | None = None + _initialized: bool = field(default=False, repr=False) + + async def initialize(self) -> None: + if self._initialized: + return + if self.engine is not None: + await self.task_store.initialize() + if self.event_stream is not None: + await self.event_stream.initialize() + if self.push_config_store is not None: + await self.push_config_store.initialize() + self._initialized = True + + async def close(self) -> None: + if self.engine is not None: + await self.engine.dispose() + self.engine = None + + +def build_stores(config: A2AServerConfig) -> A2AStores: + """Build task/event/push stores from config.""" + owner_resolver = make_owner_resolver(config.tenant_header) + if not config.database_url: + task_store: TaskStore | VersionedTaskStore = OwnerScopedInMemoryTaskStore( + owner_resolver + ) + push_store: PushNotificationConfigStore | None = None + if config.push_enabled: + push_store = DefaultingPushNotificationConfigStore( + InMemoryPushNotificationConfigStore(), + config.push_webhook_url or "", + ) + return A2AStores( + task_store=task_store, + event_stream=None, + push_config_store=push_store, + ) + + from veadk.integrations.mpa.managed.database import postgres_engine + + engine = postgres_engine(normalize_database_url(config.database_url)) + task_store = VersionedDatabaseTaskStore( + engine=engine, + create_table=True, + owner_resolver=owner_resolver, + ) + event_stream: TaskEventStream | None = DatabaseTaskEventStream( + engine=engine, + create_table=True, + ) + push_store = None + if config.push_enabled: + push_store = DefaultingPushNotificationConfigStore( + DatabasePushNotificationConfigStore( + engine=engine, + create_table=True, + encryption_key=config.push_encryption_key, + owner_resolver=owner_resolver, + ), + config.push_webhook_url or "", + ) + return A2AStores( + task_store=task_store, + event_stream=event_stream, + push_config_store=push_store, + engine=engine, + ) diff --git a/veadk/a2a/tenant.py b/veadk/a2a/tenant.py new file mode 100644 index 000000000..88abb9066 --- /dev/null +++ b/veadk/a2a/tenant.py @@ -0,0 +1,38 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Client-side tenant routing for A2A.""" + +from __future__ import annotations + +from typing import TypeVar + +from a2a.client.transports.tenant_decorator import TenantTransportDecorator + +T = TypeVar("T") + + +def apply_tenant(client: T, tenant: str) -> T: + """Attach a tenant to every request made by an A2A client. + + ``tenant`` is an opaque routing identifier in A2A 1.0 (spec 4.4.6); the + server decides how to use it. An empty tenant leaves the client untouched. + """ + if not tenant: + return client + transport = getattr(client, "_transport", None) + if transport is None: + raise ValueError("The A2A client does not expose a transport to decorate") + client._transport = TenantTransportDecorator(transport, tenant) # noqa: SLF001 + return client From beb7fbe1cd7595d166c4944f5bb7547bf4e46324 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 16:24:53 +0800 Subject: [PATCH 12/22] feat(a2a): add push delivery and OpenTelemetry plugin wiring Add a push sender with the SDK's SSRF screen, a store wrapper that applies a server-wide default webhook while honouring per-task overrides, and the OpenTelemetry plugin manager. All are opt-in through A2AServerConfig. Signed-off-by: Codex --- veadk/a2a/plugins.py | 38 +++++++++++++ veadk/a2a/push.py | 132 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 170 insertions(+) create mode 100644 veadk/a2a/plugins.py create mode 100644 veadk/a2a/push.py diff --git a/veadk/a2a/plugins.py b/veadk/a2a/plugins.py new file mode 100644 index 000000000..e0376143e --- /dev/null +++ b/veadk/a2a/plugins.py @@ -0,0 +1,38 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Plugin manager wiring for the VeADK A2A server.""" + +from __future__ import annotations + +from a2a.plugins import PluginManager, SequentialPluginManager +from a2a.plugins.otel import OpenTelemetryPlugin + +from veadk.a2a.config import A2AServerConfig +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + + +def build_plugin_manager(config: A2AServerConfig) -> PluginManager | None: + """Build the A2A plugin manager. + + Only the OpenTelemetry plugin is wired today; the manager is the extension + point for future request/task hooks. The application owns the OTel tracer + provider and exporter; the plugin only creates spans. + """ + if not config.otel_enabled: + return None + logger.info("A2A OpenTelemetry plugin enabled") + return SequentialPluginManager(OpenTelemetryPlugin()) diff --git a/veadk/a2a/push.py b/veadk/a2a/push.py new file mode 100644 index 000000000..ec1b7e6c3 --- /dev/null +++ b/veadk/a2a/push.py @@ -0,0 +1,132 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Push-notification delivery for the VeADK A2A server. + +The A2A spec marks push-URL screening as SHOULD: a client can ask the server to +POST to an arbitrary URL, so the default validator rejects loopback, private +and link-local targets. Set ``push_allow_private_url`` only in tests. +""" + +from __future__ import annotations + + +import httpx +from a2a.plugins.manager import PluginManager +from a2a.server.context import ServerCallContext +from a2a.server.tasks import ( + BasePushNotificationSender, + PushNotificationConfigStore, +) +from a2a.types import TaskPushNotificationConfig +from a2a.utils.push_url_validator import validate_push_notification_url + +from veadk.a2a.config import A2AServerConfig +from veadk.utils.logger import get_logger + +logger = get_logger(__name__) + +_PUSH_TIMEOUT_SECONDS = 10.0 + + +def build_push_url_validator(config: A2AServerConfig): + """Build the async push-URL validator. + + The SDK ships an RFC-6598-aware SSRF screen. ``push_allow_private_url`` + disables it so local webhook receivers can be used in tests; production + should leave it off. + """ + if not config.push_enabled: + return None + if config.push_allow_private_url: + return None + return validate_push_notification_url + + +class DefaultingPushNotificationConfigStore(PushNotificationConfigStore): + """Wrap a config store and add a server-wide default webhook. + + A2A clients normally register one webhook per task. VeADK deployments + usually want every task delivered to one operations endpoint, so this + wrapper returns the default config when the task has no explicit one. + Explicit per-task configs always win. + """ + + def __init__( + self, + inner: PushNotificationConfigStore, + default_url: str, + token: str = "", + ) -> None: + self._inner = inner + self._default_url = default_url + self._token = token + + async def set_info( + self, + task_id: str, + notification_config: TaskPushNotificationConfig, + context: ServerCallContext, + ) -> TaskPushNotificationConfig | None: + return await self._inner.set_info(task_id, notification_config, context) + + async def get_info( + self, task_id: str, context: ServerCallContext + ) -> list[TaskPushNotificationConfig]: + return await self._inner.get_info(task_id, context) + + async def get_info_for_dispatch( + self, task_id: str + ) -> list[TaskPushNotificationConfig]: + infos = await self._inner.get_info_for_dispatch(task_id) + if infos: + return infos + if not self._default_url: + return [] + return [ + TaskPushNotificationConfig( + id=f"veadk-default-{task_id[:8]}", + task_id=task_id, + url=self._default_url, + token=self._token, + ) + ] + + async def delete_info( + self, + task_id: str, + context: ServerCallContext, + config_id: str | None = None, + ) -> None: + await self._inner.delete_info(task_id, context, config_id) + + +def build_push_sender( + config: A2AServerConfig, + config_store: PushNotificationConfigStore | None, + plugins: PluginManager | None, +) -> BasePushNotificationSender | None: + """Build the SDK push sender, or ``None`` when push is off.""" + if not config.push_enabled or config_store is None: + return None + client = httpx.AsyncClient( + timeout=_PUSH_TIMEOUT_SECONDS, + follow_redirects=False, + ) + return BasePushNotificationSender( + httpx_client=client, + config_store=config_store, + push_url_validator=build_push_url_validator(config), + plugins=plugins, + ) From d74133962638d46888215c5af0c0a8493ae23e1b Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 16:25:01 +0800 Subject: [PATCH 13/22] feat(a2a): wire 1.x capabilities into VeA2AServer Wire REST, OpenTelemetry, input-mode and required-extension validation, extended card, signing, security schemes, OIDC auth, cluster stores, push delivery and tenant routing into VeA2AServer. Everything is opt-in and the default configuration keeps the dual-stack v0.3 + v1.0 behaviour, so existing callers and VeFaaS deployments are unchanged. Also attach the tenant to CloudApp and RemoteVeAgent so client-side routing works with the same server configuration. Signed-off-by: Codex --- veadk/a2a/agent_card.py | 33 ++++++++- veadk/a2a/remote_ve_agent.py | 15 ++++ veadk/a2a/ve_a2a_server.py | 133 +++++++++++++++++++++++++++++------ veadk/cloud/cloud_app.py | 11 ++- 4 files changed, 169 insertions(+), 23 deletions(-) diff --git a/veadk/a2a/agent_card.py b/veadk/a2a/agent_card.py index 508878db7..8d4698ef6 100644 --- a/veadk/a2a/agent_card.py +++ b/veadk/a2a/agent_card.py @@ -15,12 +15,17 @@ from a2a.types import ( AgentCapabilities, AgentCard, + AgentExtension, AgentInterface, AgentProvider, AgentSkill, ) from veadk import Agent +from veadk.a2a.config import ( + A2ASecurityScheme, + security_requirements_to_proto, +) from veadk.utils.logger import get_logger from veadk.version import VERSION @@ -54,6 +59,13 @@ def get_agent_card( version: str = VERSION, provider: str = "veadk", compat_v0_3: bool = True, + *, + push_notifications: bool = False, + extensions: tuple[str, ...] = (), + extended_card: bool = False, + security_schemes: tuple[A2ASecurityScheme, ...] = (), + security_requirements: tuple[dict[str, tuple[str, ...]], ...] = (), + signer=None, ) -> AgentCard: public_url = _normalize_public_url(url) agent_provider = AgentProvider(organization=provider, url="") @@ -61,7 +73,20 @@ def get_agent_card( # ``DefaultRequestHandler`` serves ``message/stream`` for both the 0.3 and # 1.0 JSON-RPC bindings. Advertise it so 1.0 clients that honour the card # do not silently downgrade to non-streaming ``message/send``. - agent_capabilities = AgentCapabilities(streaming=True) + agent_capabilities = AgentCapabilities( + streaming=True, + push_notifications=push_notifications, + extended_agent_card=extended_card, + extensions=[ + AgentExtension( + uri=uri, + description="VeADK A2A extension", + required=True, + params={}, + ) + for uri in extensions + ], + ) agent_skills = [ AgentSkill( id="0", @@ -99,5 +124,11 @@ def get_agent_card( skills=agent_skills, supported_interfaces=supported_interfaces, version=version, + security_schemes={ + scheme.scheme_id: scheme.to_proto() for scheme in security_schemes + }, + security_requirements=security_requirements_to_proto(security_requirements), ) + if signer is not None: + agent_card = signer(agent_card) return agent_card diff --git a/veadk/a2a/remote_ve_agent.py b/veadk/a2a/remote_ve_agent.py index a34a363fa..06fdb670c 100644 --- a/veadk/a2a/remote_ve_agent.py +++ b/veadk/a2a/remote_ve_agent.py @@ -156,7 +156,18 @@ def __init__( auth_token: Optional[str] = None, auth_method: Literal["header", "querystring"] | None = None, httpx_client: Optional[httpx.AsyncClient] = None, + tenant: str = "", ): + """Initialize the remote VeADK agent. + + Args: + name: Unique name for this agent instance. + url: Base URL of the remote agent. + auth_token: Optional static bearer token. + auth_method: How to attach ``auth_token``. + httpx_client: Optional pre-configured HTTP client. + tenant: Optional A2A tenant identifier attached to every request. + """ # Determine the effective URL for the agent and handle conflicts. effective_url = url if httpx_client and httpx_client.base_url: @@ -225,6 +236,10 @@ def __init__( super().__init__( name=name, agent_card=agent_card_object, httpx_client=client_to_use ) + if tenant: + from veadk.a2a.tenant import apply_tenant + + apply_tenant(self._a2a_client, tenant) # The parent class sets _httpx_client_needs_cleanup based on whether # the httpx_client it received was None. Since we always pass a diff --git a/veadk/a2a/ve_a2a_server.py b/veadk/a2a/ve_a2a_server.py index d4fe8afab..558fb4459 100644 --- a/veadk/a2a/ve_a2a_server.py +++ b/veadk/a2a/ve_a2a_server.py @@ -13,21 +13,29 @@ # limitations under the License. import os -from dataclasses import dataclass +from contextlib import asynccontextmanager from a2a.server.request_handlers import DefaultRequestHandler from a2a.server.routes import ( add_a2a_routes_to_fastapi, create_agent_card_routes, create_jsonrpc_routes, + create_rest_routes, ) -from a2a.server.tasks import InMemoryTaskStore +from a2a.types import AgentCard, AgentSkill +from a2a.utils.errors import UnsupportedOperationError from fastapi import FastAPI from veadk import Agent from veadk.a2a.agent_card import get_agent_card -from veadk.runner import Runner +from veadk.a2a.config import A2AServerConfig +from veadk.a2a.plugins import build_plugin_manager +from veadk.a2a.push import build_push_sender +from veadk.a2a.security import A2AAuthMiddleware, BearerJWTVerifier +from veadk.a2a.signing import build_agent_card_signer +from veadk.a2a.stores import VeServerCallContextBuilder, build_stores from veadk.memory.short_term_memory import ShortTermMemory +from veadk.runner import Runner from veadk.utils.logger import get_logger from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor @@ -37,20 +45,14 @@ logger = get_logger(__name__) +_PUBLIC_PATHS = ( + "/docs", + "/redoc", + "/openapi.json", + "/healthz", +) -@dataclass -class A2AServerConfig: - """Configuration for the veadk A2A server. - - ``compat_v0_3`` keeps the legacy JSON-RPC methods and the historical - ``/.well-known/agent.json`` card path enabled. ``docs_enabled`` registers - the A2A routes through ``add_a2a_routes_to_fastapi`` so they appear in the - generated OpenAPI schema; it is opt-in and does not change runtime RPC - behavior. - """ - - compat_v0_3: bool = True - docs_enabled: bool = False +__all__ = ["A2AServerConfig", "VeA2AServer", "init_app"] def _resolve_public_url(server_url: str) -> str: @@ -91,11 +93,24 @@ def __init__( config: A2AServerConfig | None = None, ): self.config = config or A2AServerConfig() + self.stores = build_stores(self.config) + self.plugins = build_plugin_manager(self.config) + self.push_sender = build_push_sender( + self.config, self.stores.push_config_store, self.plugins + ) + self.signer = build_agent_card_signer(self.config.signing) self.agent_card = get_agent_card( agent, _resolve_public_url(url), compat_v0_3=self.config.compat_v0_3, + push_notifications=self.config.push_enabled, + extensions=self.config.extensions, + extended_card=bool(self.config.extended_card_skills), + security_schemes=self.config.security_schemes, + security_requirements=self.config.security_requirements, + signer=self.signer, ) + self.extended_agent_card = self._build_extended_card() self.agent_executor = A2aAgentExecutor( runner=Runner( @@ -106,14 +121,60 @@ def __init__( ) ) - self.task_store = InMemoryTaskStore() + self.task_store = self.stores.task_store self.request_handler = DefaultRequestHandler( agent_executor=self.agent_executor, - task_store=self.task_store, + task_store=self.stores.task_store, agent_card=self.agent_card, + push_config_store=self.stores.push_config_store, + push_sender=self.push_sender, + extended_agent_card=self.extended_agent_card, + extended_card_modifier=self._extended_card_modifier, + validate_input_modes=self.config.validate_input_modes, + event_stream=self.stores.event_stream, + plugins=self.plugins, + validate_required_extensions=self.config.validate_required_extensions, ) + def _build_extended_card(self) -> AgentCard | None: + if not self.config.extended_card_skills: + return None + extended = AgentCard() + extended.CopyFrom(self.agent_card) + extended.capabilities.extended_agent_card = True + # The base signature does not cover the extra skills, so re-sign the + # extended card instead of inheriting an invalid signature. + del extended.signatures[:] + for skill in self.config.extended_card_skills: + extended.skills.append( + skill if isinstance(skill, AgentSkill) else AgentSkill(**skill) + ) + if self.signer is not None: + extended = self.signer(extended) + return extended + + @staticmethod + async def _extended_card_modifier(card: AgentCard, context) -> AgentCard: + if not context.user.is_authenticated: + raise UnsupportedOperationError( + message="Authentication required for the extended AgentCard" + ) + return card + + @asynccontextmanager + async def _lifespan(self, _app: FastAPI): + await self.stores.initialize() + try: + yield + finally: + await self.request_handler.aclose() + if self.push_sender is not None: + client = getattr(self.push_sender, "_client", None) + if client is not None: + await client.aclose() + await self.stores.close() + def build(self) -> FastAPI: card_routes = [*create_agent_card_routes(self.agent_card)] if self.config.compat_v0_3: @@ -125,22 +186,52 @@ def build(self) -> FastAPI: card_url="/.well-known/agent.json", ) ) + context_builder = VeServerCallContextBuilder(self.config.tenant_header) rpc_routes = create_jsonrpc_routes( self.request_handler, rpc_url="/", enable_v0_3_compat=self.config.compat_v0_3, + context_builder=context_builder, ) + rest_routes = [] + if self.config.rest_enabled: + rest_routes = create_rest_routes( + self.request_handler, + context_builder=context_builder, + # REST is a 1.0 binding. The v0.3 REST adapter reuses the same + # ``/v1/...`` paths and would shadow the 1.0 routes, so v0.3 + # peers keep using the JSON-RPC endpoint. + enable_v0_3_compat=False, + path_prefix=self.config.rest_path_prefix, + ) if self.config.docs_enabled: - app = FastAPI() + app = FastAPI(lifespan=self._lifespan) add_a2a_routes_to_fastapi( app, agent_card_routes=card_routes, jsonrpc_routes=rpc_routes, + rest_routes=rest_routes, + ) + else: + app = FastAPI( + routes=[*card_routes, *rpc_routes, *rest_routes], + lifespan=self._lifespan, ) - return app - return FastAPI(routes=[*card_routes, *rpc_routes]) + if self.config.require_auth: + if not self.config.oidc_issuer or not self.config.oidc_jwks_uri: + raise ValueError("require_auth needs oidc_issuer and oidc_jwks_uri") + app.add_middleware( + A2AAuthMiddleware, + verifier=BearerJWTVerifier( + issuer=self.config.oidc_issuer, + jwks_uri=self.config.oidc_jwks_uri, + audience=self.config.oidc_audience, + ), + public_paths=_PUBLIC_PATHS, + ) + return app def init_app( diff --git a/veadk/cloud/cloud_app.py b/veadk/cloud/cloud_app.py index 0389b678d..b465e3eed 100644 --- a/veadk/cloud/cloud_app.py +++ b/veadk/cloud/cloud_app.py @@ -186,6 +186,7 @@ def __init__( vefaas_endpoint: str = "", vefaas_application_id: str = "", use_agent_card: bool | None = None, + tenant: str = "", ): """Initializes the CloudApp with VeFaaS application details. @@ -198,6 +199,8 @@ def __init__( use_agent_card (bool | None): Card resolution mode. ``None`` (default) resolves the card and falls back to the historical v0.3-only card; ``True`` requires a card; ``False`` never fetches one. + tenant (str): Optional A2A tenant identifier attached to every + request. Empty (default) sends no tenant. Returns: None @@ -218,6 +221,7 @@ def __init__( self.vefaas_application_id = vefaas_application_id self.vefaas_application_name = vefaas_application_name self.use_agent_card = use_agent_card + self.tenant = tenant self._resolved_card: AgentCard | None = None # vefaas must be set one of three @@ -440,9 +444,14 @@ async def _get_a2a_client(self): ) card = self._legacy_v0_3_card() - return ClientFactory( + client = ClientFactory( ClientConfig(httpx_client=self.httpx_client, streaming=False) ).create(card) + if self.tenant: + from veadk.a2a.tenant import apply_tenant + + client = apply_tenant(client, self.tenant) + return client def update_self( self, From 918136368091daafae594acf850f2b502abee49e Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 16:25:07 +0800 Subject: [PATCH 14/22] test(a2a): cover 1.x server capabilities and push delivery Add unit and HTTP contract tests for the config surface, REST transport, OpenTelemetry spans, input-mode and extension validation, extended card, signing, tenant scoping, owner isolation and push delivery (default webhook, SSRF rejection and per-task override). Signed-off-by: Codex --- tests/a2a/conftest.py | 127 ++++ tests/a2a/test_a2a_push.py | 218 ++++++ tests/a2a/test_a2a_server_capabilities.py | 844 ++++++++++++++++++++++ 3 files changed, 1189 insertions(+) create mode 100644 tests/a2a/conftest.py create mode 100644 tests/a2a/test_a2a_push.py create mode 100644 tests/a2a/test_a2a_server_capabilities.py diff --git a/tests/a2a/conftest.py b/tests/a2a/conftest.py new file mode 100644 index 000000000..f6c6b5acb --- /dev/null +++ b/tests/a2a/conftest.py @@ -0,0 +1,127 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared fixtures for the A2A server tests.""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +import pytest +from a2a.types import ( + Artifact, + Part, + Task, + TaskArtifactUpdateEvent, + TaskState, + TaskStatus, + TaskStatusUpdateEvent, +) + +import veadk.a2a.ve_a2a_server as server_module +from veadk.a2a.ve_a2a_server import VeA2AServer + + +class StubExecutor: + """Deterministic agent executor used by the A2A server tests.""" + + text = "pong" + delay = 0.0 + artifact = False + + def __init__(self, **kwargs): + self.kwargs = kwargs + + async def execute(self, context, event_queue) -> None: + task = Task( + id=context.task_id, + context_id=context.context_id, + status=TaskStatus(state=TaskState.TASK_STATE_WORKING), + ) + await event_queue.enqueue_event(task) + if self.delay: + await asyncio.sleep(self.delay) + if self.artifact: + await event_queue.enqueue_event( + TaskArtifactUpdateEvent( + task_id=context.task_id, + context_id=context.context_id, + artifact=Artifact( + artifact_id="a-1", + name="answer", + parts=[Part(text=self.text)], + ), + last_chunk=True, + ) + ) + await event_queue.enqueue_event( + TaskStatusUpdateEvent( + task_id=context.task_id, + context_id=context.context_id, + status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED), + ) + ) + + async def cancel(self, context, event_queue) -> None: + return None + + +@pytest.fixture +def stub_executor(monkeypatch): + """Patch the server to use ``StubExecutor`` instead of ADK.""" + monkeypatch.setattr(server_module, "A2aAgentExecutor", StubExecutor) + monkeypatch.setattr(server_module, "Runner", lambda **kwargs: None) + return StubExecutor + + +@pytest.fixture +def agent(): + return SimpleNamespace(name="agent", description="A test agent") + + +@pytest.fixture +def make_server(stub_executor, agent): + """Build a ``VeA2AServer`` with the stub executor.""" + + def _make(config=None): + return VeA2AServer( + agent=agent, + url="http://testserver", + app_name="app", + short_term_memory=object(), + config=config, + ) + + return _make + + +def send_message_body(text="hi", method="SendMessage", message_id="m-1"): + """Build a 1.0 JSON-RPC ``SendMessage`` body.""" + return { + "jsonrpc": "2.0", + "id": 1, + "method": method, + "params": { + "message": { + "messageId": message_id, + "role": "ROLE_USER", + "parts": [{"text": text}], + }, + "configuration": {}, + }, + } + + +V1 = {"A2A-Version": "1.0"} diff --git a/tests/a2a/test_a2a_push.py b/tests/a2a/test_a2a_push.py new file mode 100644 index 000000000..4667b82e1 --- /dev/null +++ b/tests/a2a/test_a2a_push.py @@ -0,0 +1,218 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Push-notification tests for the A2A server.""" + +from __future__ import annotations + +import json +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest +from fastapi.testclient import TestClient + +from tests.a2a.conftest import V1, send_message_body +from veadk.a2a.config import A2AServerConfig +from veadk.a2a.push import DefaultingPushNotificationConfigStore + + +class _Receiver: + def __init__(self): + self.records = [] + self.lock = threading.Lock() + + def handler(self): + receiver = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("content-length", "0")) + body = self.rfile.read(length) + with receiver.lock: + receiver.records.append( + { + "path": self.path, + "body": json.loads(body or b"{}"), + "headers": dict(self.headers), + } + ) + self.send_response(200) + self.send_header("content-length", "2") + self.end_headers() + self.wfile.write(b"{}") + + def log_message(self, *args): + return + + return Handler + + +def _start_receiver(path): + receiver = _Receiver() + server = ThreadingHTTPServer(("127.0.0.1", 0), receiver.handler()) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, receiver, f"http://127.0.0.1:{server.server_port}{path}" + + +@pytest.fixture +def webhook(): + server, receiver, url = _start_receiver("/webhook") + try: + yield url, receiver + finally: + server.shutdown() + server.server_close() + + +def _wait_for(records, count, timeout=5.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if len(records) >= count: + return records + time.sleep(0.05) + return records + + +def test_default_webhook_receives_task_and_status(make_server, webhook): + url, receiver = webhook + client = TestClient( + make_server( + A2AServerConfig( + push_webhook_url=url, + push_allow_private_url=True, + ) + ).build() + ) + card = client.get("/.well-known/agent-card.json").json() + assert card["capabilities"]["pushNotifications"] is True + + response = client.post("/", headers=V1, json=send_message_body()) + assert response.status_code == 200 + + records = _wait_for(receiver.records, 2) + assert len(records) == 2 + assert records[0]["body"]["task"]["status"]["state"] == "TASK_STATE_WORKING" + assert ( + records[1]["body"]["statusUpdate"]["status"]["state"] == "TASK_STATE_COMPLETED" + ) + + +def test_private_webhook_is_rejected_by_default(make_server, webhook): + url, receiver = webhook + client = TestClient(make_server(A2AServerConfig(push_webhook_url=url)).build()) + response = client.post("/", headers=V1, json=send_message_body()) + assert response.status_code == 200 + time.sleep(0.5) + assert receiver.records == [] + + +def test_explicit_config_overrides_default_webhook(make_server, webhook, stub_executor): + default_url, default_receiver = webhook + override_server, override_receiver, override_url = _start_receiver("/override") + try: + client = TestClient( + make_server( + A2AServerConfig( + push_webhook_url=default_url, + push_allow_private_url=True, + ) + ).build() + ) + stub_executor.delay = 3.0 + result = {} + + def send(): + result["response"] = client.post( + "/", headers=V1, json=send_message_body("slow") + ) + + thread = threading.Thread(target=send) + thread.start() + task_id = None + deadline = time.monotonic() + 5 + while time.monotonic() < deadline and task_id is None: + tasks = client.post( + "/", + headers=V1, + json={ + "jsonrpc": "2.0", + "id": 8, + "method": "ListTasks", + "params": {}, + }, + ).json()["result"]["tasks"] + if tasks: + task_id = tasks[-1]["id"] + else: + time.sleep(0.05) + assert task_id is not None + registered = client.post( + "/", + headers=V1, + json={ + "jsonrpc": "2.0", + "id": 11, + "method": "CreateTaskPushNotificationConfig", + "params": {"taskId": task_id, "url": override_url}, + }, + ) + assert registered.status_code == 200, registered.text + assert "result" in registered.json(), registered.text + thread.join() + stub_executor.delay = 0 + assert result["response"].status_code == 200, result["response"].text + _wait_for(override_receiver.records, 2) + # The initial "working" event fired before the override was registered + # and therefore went to the default webhook; the terminal event must + # use the per-task override. + assert len(default_receiver.records) == 1 + assert ( + default_receiver.records[0]["body"]["task"]["status"]["state"] + == "TASK_STATE_WORKING" + ) + assert len(override_receiver.records) == 1 + assert ( + override_receiver.records[0]["body"]["statusUpdate"]["status"]["state"] + == "TASK_STATE_COMPLETED" + ) + finally: + stub_executor.delay = 0 + override_server.shutdown() + override_server.server_close() + + +def test_defaulting_store_prefers_explicit_config(): + import asyncio + + from a2a.server.context import ServerCallContext + from a2a.server.tasks import InMemoryPushNotificationConfigStore + from a2a.types import TaskPushNotificationConfig + + async def run(): + inner = InMemoryPushNotificationConfigStore() + store = DefaultingPushNotificationConfigStore(inner, "https://default") + context = ServerCallContext() + explicit = TaskPushNotificationConfig( + id="cfg-1", task_id="t-1", url="https://explicit" + ) + await store.set_info("t-1", explicit, context) + infos = await store.get_info_for_dispatch("t-1") + assert [info.url for info in infos] == ["https://explicit"] + + defaults = await store.get_info_for_dispatch("t-2") + assert [info.url for info in defaults] == ["https://default"] + + asyncio.run(run()) diff --git a/tests/a2a/test_a2a_server_capabilities.py b/tests/a2a/test_a2a_server_capabilities.py new file mode 100644 index 000000000..f34b900fa --- /dev/null +++ b/tests/a2a/test_a2a_server_capabilities.py @@ -0,0 +1,844 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unit and HTTP contract tests for the A2A 1.x capabilities.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest +from a2a.types import ( + ListTasksRequest, + Task, + TaskState, + TaskStatus, +) +from a2a.utils.signing import create_signature_verifier +from fastapi.testclient import TestClient +from jwt import PyJWK + +from tests.a2a.conftest import V1, send_message_body +from veadk.a2a.agent_card import get_agent_card +from veadk.a2a.config import ( + A2ASecurityScheme, + A2AServerConfig, + A2ASigningConfig, + security_requirements_to_proto, +) +from veadk.a2a.security import A2AAuthMiddleware, A2AUser, BearerJWTVerifier +from veadk.a2a.signing import ( + LocalAgentCardSigner, + KmsAgentCardSigner, + build_agent_card_signer, + generate_es256_jwk, + jwks_document, + public_jwk_from_der, +) +from veadk.a2a.stores import ( + OwnerScopedInMemoryTaskStore, + make_owner_resolver, + normalize_database_url, +) +from veadk.a2a.tenant import apply_tenant + +EXTENSION_URI = "https://veadk.volcengine.com/a2a/extensions/veadk-agent/v1" + + +# --------------------------------------------------------------------------- +# config +# --------------------------------------------------------------------------- + + +def test_server_config_defaults_are_backward_compatible(): + config = A2AServerConfig() + assert config.compat_v0_3 is True + assert config.docs_enabled is False + assert config.rest_enabled is False + assert config.otel_enabled is False + assert config.validate_input_modes is False + assert config.validate_required_extensions is False + assert config.signing is None + assert config.security_schemes == () + assert config.database_url is None + assert config.push_enabled is False + + +@pytest.mark.parametrize( + ("scheme", "expected_field"), + [ + ( + A2ASecurityScheme( + scheme_id="key", + type="apiKey", + name="X-Api-Key", + location="header", + ), + "api_key_security_scheme", + ), + ( + A2ASecurityScheme( + scheme_id="bearer", + type="http", + scheme="bearer", + bearer_format="JWT", + ), + "http_auth_security_scheme", + ), + ( + A2ASecurityScheme( + scheme_id="oauth", + type="oauth2", + authorization_url="https://idp/authorize", + token_url="https://idp/token", + scopes={"openid": "openid"}, + ), + "oauth2_security_scheme", + ), + ( + A2ASecurityScheme( + scheme_id="oidc", + type="openIdConnect", + open_id_connect_url="https://idp/.well-known/openid-configuration", + ), + "open_id_connect_security_scheme", + ), + ( + A2ASecurityScheme(scheme_id="mtls", type="mutualTLS"), + "mtls_security_scheme", + ), + ], +) +def test_security_scheme_to_proto(scheme, expected_field): + proto = scheme.to_proto() + assert proto.HasField(expected_field) + + +def test_security_scheme_rejects_unknown_type(): + with pytest.raises(ValueError): + A2ASecurityScheme(scheme_id="x", type="unknown") + + +def test_security_requirements_to_proto(): + reqs = security_requirements_to_proto(({"oauth2": ("openid",)},)) + assert reqs[0].schemes["oauth2"].list == ["openid"] + + +def test_signing_config_rejects_unknown_provider(): + with pytest.raises(ValueError): + A2ASigningConfig(provider="hsm") + + +# --------------------------------------------------------------------------- +# REST transport +# --------------------------------------------------------------------------- + + +def test_rest_disabled_by_default(make_server): + client = TestClient(make_server().build()) + response = client.post("/v1/message:send", headers=V1, json={"message": {}}) + assert response.status_code == 404 + + +def test_rest_send_get_and_list(make_server): + client = TestClient(make_server(A2AServerConfig(rest_enabled=True)).build()) + sent = client.post( + "/v1/message:send", + headers=V1, + json={ + "message": { + "messageId": "m-1", + "role": "ROLE_USER", + "parts": [{"text": "hi"}], + } + }, + ) + assert sent.status_code == 200 + task_id = sent.json()["task"]["id"] + + fetched = client.get(f"/v1/tasks/{task_id}", headers=V1) + assert fetched.status_code == 200 + assert fetched.json()["status"]["state"] == "TASK_STATE_COMPLETED" + + listed = client.get("/v1/tasks", headers=V1) + assert listed.status_code == 200 + assert listed.json()["tasks"][0]["id"] == task_id + + +def test_rest_requires_version_header(make_server): + client = TestClient(make_server(A2AServerConfig(rest_enabled=True)).build()) + response = client.post("/v1/message:send", json={"message": {}}) + assert response.status_code == 400 + assert response.json()["error"]["message"].startswith("A2A version '0.3'") + + +def test_rest_stream(make_server): + client = TestClient(make_server(A2AServerConfig(rest_enabled=True)).build()) + with client.stream( + "POST", + "/v1/message:stream", + headers={**V1, "Accept": "text/event-stream"}, + json={ + "message": { + "messageId": "m-1", + "role": "ROLE_USER", + "parts": [{"text": "hi"}], + } + }, + ) as response: + assert response.status_code == 200 + body = "".join(response.iter_text()) + assert "TASK_STATE_COMPLETED" in body + + +# --------------------------------------------------------------------------- +# observability +# --------------------------------------------------------------------------- + + +def test_otel_plugin_exports_spans(make_server): + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + trace.set_tracer_provider(provider) + + client = TestClient(make_server(A2AServerConfig(otel_enabled=True)).build()) + response = client.post("/", headers=V1, json=send_message_body()) + assert response.status_code == 200 + + spans = exporter.get_finished_spans() + assert spans + assert spans[0].attributes["a2a.protocol.version"] == "1.0" + assert spans[0].attributes["a2a.task.state"] == "TASK_STATE_COMPLETED" + + +def test_otel_plugin_can_be_disabled(make_server): + client = TestClient(make_server().build()) + assert client.post("/", headers=V1, json=send_message_body()).status_code == 200 + + +# --------------------------------------------------------------------------- +# request validation +# --------------------------------------------------------------------------- + + +def test_input_mode_validation_rejects_undeclared_media_type(make_server): + client = TestClient(make_server(A2AServerConfig(validate_input_modes=True)).build()) + body = send_message_body() + body["params"]["message"]["parts"] = [{"text": "hi", "mediaType": "image/png"}] + response = client.post("/", headers=V1, json=body) + assert response.json()["error"]["code"] == -32005 + assert "image/png" in response.json()["error"]["message"] + + +def test_input_mode_validation_accepts_declared_text(make_server): + client = TestClient(make_server(A2AServerConfig(validate_input_modes=True)).build()) + response = client.post("/", headers=V1, json=send_message_body()) + assert response.json()["result"]["task"]["status"]["state"] == ( + "TASK_STATE_COMPLETED" + ) + + +def test_required_extension_is_declared_and_enforced(make_server): + config = A2AServerConfig( + extensions=(EXTENSION_URI,), + validate_required_extensions=True, + ) + client = TestClient(make_server(config).build()) + + card = client.get("/.well-known/agent-card.json").json() + assert card["capabilities"]["extensions"][0]["uri"] == EXTENSION_URI + assert card["capabilities"]["extensions"][0]["required"] is True + + rejected = client.post("/", headers=V1, json=send_message_body()) + assert rejected.json()["error"]["code"] == -32008 + + accepted = client.post( + "/", + headers={**V1, "A2A-Extensions": EXTENSION_URI}, + json=send_message_body(), + ) + assert accepted.json()["result"]["task"]["status"]["state"] == ( + "TASK_STATE_COMPLETED" + ) + + +def test_extension_declaration_without_validation_does_not_block(make_server): + config = A2AServerConfig(extensions=(EXTENSION_URI,)) + client = TestClient(make_server(config).build()) + response = client.post("/", headers=V1, json=send_message_body()) + assert response.json()["result"]["task"]["status"]["state"] == ( + "TASK_STATE_COMPLETED" + ) + + +# --------------------------------------------------------------------------- +# extended card +# --------------------------------------------------------------------------- + + +def test_extended_card_is_advertised_and_gated(make_server): + config = A2AServerConfig( + extended_card_skills=( + { + "id": "secret", + "name": "secret", + "description": "only for authenticated callers", + "tags": ["secret"], + }, + ) + ) + client = TestClient(make_server(config).build()) + card = client.get("/.well-known/agent-card.json").json() + assert card["capabilities"]["extendedAgentCard"] is True + assert [skill["id"] for skill in card["skills"]] == ["0"] + + response = client.post( + "/", + headers=V1, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "GetExtendedAgentCard", + "params": {}, + }, + ) + assert "error" in response.json() + + +def test_extended_card_modifier_returns_extra_skills_for_authenticated_user( + make_server, +): + config = A2AServerConfig( + extended_card_skills=( + { + "id": "secret", + "name": "secret", + "description": "only for authenticated callers", + "tags": ["secret"], + }, + ) + ) + server = make_server(config) + extended = server.extended_agent_card + assert [skill.id for skill in extended.skills] == ["0", "secret"] + assert extended.capabilities.extended_agent_card is True + + +def test_extended_card_is_resigned(make_server): + private_jwk, public_jwk = generate_es256_jwk("kid-1") + server = make_server( + A2AServerConfig( + signing=A2ASigningConfig( + private_key=json.dumps(private_jwk), + kid="kid-1", + alg="ES256", + ), + extended_card_skills=( + { + "id": "secret", + "name": "secret", + "description": "d", + "tags": ["t"], + }, + ), + ) + ) + assert len(server.agent_card.signatures) == 1 + assert len(server.extended_agent_card.signatures) == 1 + assert ( + server.agent_card.signatures[0].signature + != server.extended_agent_card.signatures[0].signature + ) + verifier = create_signature_verifier( + key_provider=lambda kid, jku: PyJWK.from_dict(public_jwk), + algorithms=["ES256"], + ) + verifier(server.extended_agent_card) + + +# --------------------------------------------------------------------------- +# signing +# --------------------------------------------------------------------------- + + +def test_local_signer_produces_verifiable_signature(): + private_jwk, public_jwk = generate_es256_jwk("kid-1") + signer = LocalAgentCardSigner( + A2ASigningConfig( + private_key=json.dumps(private_jwk), + kid="kid-1", + alg="ES256", + jku="https://example.com/.well-known/jwks.json", + ) + ) + card = signer( + get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + ) + ) + assert len(card.signatures) == 1 + protected = json.loads( + __import__("base64").urlsafe_b64decode(card.signatures[0].protected + "==") + ) + assert protected["kid"] == "kid-1" + assert protected["jku"].endswith("jwks.json") + + verifier = create_signature_verifier( + key_provider=lambda kid, jku: PyJWK.from_dict(public_jwk), + algorithms=["ES256"], + ) + verifier(card) + + +def test_local_signer_accepts_pem_key(): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + + key = ec.generate_private_key(ec.SECP256R1()) + pem = key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ).decode() + signer = LocalAgentCardSigner( + A2ASigningConfig(private_key=pem, kid="kid-2", alg="ES256") + ) + card = signer( + get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + ) + ) + assert card.signatures + + +def test_signer_rejects_invalid_jwk(): + with pytest.raises(Exception): + LocalAgentCardSigner( + A2ASigningConfig(private_key="not-a-key", kid="x", alg="ES256") + )( + get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + ) + ) + + +def test_kms_signer_builds_protected_header_and_calls_kms(monkeypatch): + signer = KmsAgentCardSigner( + A2ASigningConfig( + provider="kms", + kms_key_id="key-1", + kms_algorithm="ECDSA_SHA_256", + kid="kid-1", + jku="https://example.com/jwks.json", + access_key="ak", + secret_key="sk", + ) + ) + captured = {} + + def fake_sign(signing_input: bytes) -> str: + captured["input"] = signing_input + return "c2ln" + + monkeypatch.setattr(signer, "_sign", fake_sign) + card = signer( + get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + ) + ) + assert card.signatures[0].signature == "c2ln" + protected = captured["input"].decode().split(".")[0] + assert protected + + +def test_kms_signer_requires_key_id(): + with pytest.raises(ValueError): + KmsAgentCardSigner(A2ASigningConfig(provider="kms")) + + +def test_build_signer_returns_none_when_disabled(): + assert build_agent_card_signer(None) is None + + +def test_public_jwk_from_der_converts_ec_key(): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + + key = ec.generate_private_key(ec.SECP256R1()) + der = key.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + jwk = public_jwk_from_der(der, "kid-1") + assert jwk["kty"] == "EC" + assert jwk["crv"] == "P-256" + assert jwks_document([jwk])["keys"] == [jwk] + + +def test_public_jwk_from_der_rejects_unknown_curve(): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + + key = ec.generate_private_key(ec.SECP256K1()) + der = key.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + with pytest.raises(ValueError): + public_jwk_from_der(der, "kid-1") + + +def test_public_jwk_from_der_converts_rsa_key(): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import rsa + + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + der = key.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + jwk = public_jwk_from_der(der, "rsa-kid", alg="RS256") + assert jwk["kty"] == "RSA" + assert jwk["n"] + assert jwk["e"] == "AQAB" + + +def test_local_signer_requires_private_key(): + with pytest.raises(ValueError): + LocalAgentCardSigner(A2ASigningConfig()) + + +def test_kms_sign_method_encodes_message_and_signature(monkeypatch): + signer = KmsAgentCardSigner( + A2ASigningConfig( + provider="kms", + kms_key_id="key-1", + kms_algorithm="ECDSA_SHA_256", + access_key="ak", + secret_key="sk", + ) + ) + + class FakeResponse: + signature = "c2ln" + + captured = {} + + def fake_asymmetric_sign(request): + captured["request"] = request + return FakeResponse() + + monkeypatch.setattr(signer._api, "asymmetric_sign", fake_asymmetric_sign) + signature = signer._sign(b"signing-input") + assert signature == "c2ln" + assert captured["request"].key_id == "key-1" + assert captured["request"].algorithm == "ECDSA_SHA_256" + assert captured["request"].message_type == "RAW" + + +def test_build_signer_creates_kms_signer(): + signer = build_agent_card_signer( + A2ASigningConfig( + provider="kms", + kms_key_id="key-1", + access_key="ak", + secret_key="sk", + ) + ) + assert isinstance(signer, KmsAgentCardSigner) + + +# --------------------------------------------------------------------------- +# stores / tenant / owner scoping +# --------------------------------------------------------------------------- + + +def test_normalize_database_url_rewrites_asyncpg_parameters(): + url = normalize_database_url( + "mysql://db.invalid/app?sslmode=require&channel_binding=require" + ) + assert "channel_binding" not in url + assert "ssl=require" in url + + +def test_owner_resolver_combines_user_and_tenant(): + from a2a.server.context import ServerCallContext + + resolve = make_owner_resolver("x-a2a-tenant") + context = ServerCallContext( + user=A2AUser({"sub": "alice"}), + tenant="tenant-a", + ) + assert resolve(context) == "alice|tenant-a" + + header_only = ServerCallContext( + user=A2AUser({"sub": "bob"}), + state={"headers": {"x-a2a-tenant": "tenant-b"}}, + ) + assert resolve(header_only) == "bob|tenant-b" + + +def test_owner_scoped_store_handles_missing_context(): + import asyncio + + store = OwnerScopedInMemoryTaskStore(make_owner_resolver()) + assert store._owner(None) == "" + assert asyncio.run(store.get("missing")) is None + + +def test_a2a_user_defaults_and_claims(): + user = A2AUser({"sub": "alice"}) + assert user.claims == {"sub": "alice"} + assert user.display_name == "alice" + assert A2AUser({}).user_name == "unknown" + + +def test_auth_middleware_passes_through_non_http_scope(): + called = [] + + async def app(scope, receive, send): + called.append(scope["type"]) + + middleware = A2AAuthMiddleware(app, BearerJWTVerifier(issuer="https://idp")) + import asyncio + + asyncio.run(middleware({"type": "lifespan"}, None, None)) + assert called == ["lifespan"] + + +def test_auth_middleware_treats_well_known_paths_as_public(): + middleware = A2AAuthMiddleware(None, BearerJWTVerifier(issuer="https://idp")) + assert middleware._is_public("/.well-known/agent-card.json") + assert middleware._is_public("/docs") is False + + +def test_get_agent_card_applies_signer(): + calls = [] + + def signer(card): + calls.append(card.name) + return card + + card = get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + signer=signer, + ) + assert calls == ["a"] + assert card.name == "a" + + +def test_build_stores_without_push_has_no_push_store(): + from veadk.a2a.stores import build_stores + + stores = build_stores(A2AServerConfig()) + assert stores.push_config_store is None + assert stores.event_stream is None + import asyncio + + asyncio.run(stores.initialize()) + asyncio.run(stores.close()) + + +def test_build_stores_with_push_wraps_default_store(): + from veadk.a2a.push import DefaultingPushNotificationConfigStore + from veadk.a2a.stores import build_stores + + stores = build_stores(A2AServerConfig(push_webhook_url="https://example.com/hook")) + assert isinstance(stores.push_config_store, DefaultingPushNotificationConfigStore) + + +def test_require_auth_without_oidc_config_raises(make_server): + with pytest.raises(ValueError): + make_server(A2AServerConfig(require_auth=True)).build() + + +def test_push_sender_is_closed_on_lifespan_shutdown(make_server): + config = A2AServerConfig( + push_webhook_url="https://example.com/hook", + push_allow_private_url=True, + ) + server = make_server(config) + with TestClient(server.build()) as client: + assert client.get("/.well-known/agent-card.json").status_code == 200 + + +def test_defaulting_store_delegates_reads_and_deletes(): + import asyncio + + from a2a.server.context import ServerCallContext + from a2a.server.tasks import InMemoryPushNotificationConfigStore + from a2a.types import TaskPushNotificationConfig + from veadk.a2a.push import DefaultingPushNotificationConfigStore + + async def run(): + store = DefaultingPushNotificationConfigStore( + InMemoryPushNotificationConfigStore(), "" + ) + context = ServerCallContext() + assert await store.get_info("t-1", context) == [] + assert await store.get_info_for_dispatch("t-1") == [] + config = TaskPushNotificationConfig(id="c-1", task_id="t-1", url="https://x") + await store.set_info("t-1", config, context) + assert len(await store.get_info("t-1", context)) == 1 + await store.delete_info("t-1", context) + assert await store.get_info("t-1", context) == [] + + asyncio.run(run()) + + +def test_push_validator_is_none_when_push_disabled(): + from veadk.a2a.push import build_push_url_validator + + assert build_push_url_validator(A2AServerConfig()) is None + assert ( + build_push_url_validator( + A2AServerConfig( + push_webhook_url="https://x", + push_allow_private_url=True, + ) + ) + is None + ) + + +def test_owner_scoped_in_memory_store_isolates_tasks(): + from a2a.server.context import ServerCallContext + + resolve = make_owner_resolver() + store = OwnerScopedInMemoryTaskStore(resolve) + alice = ServerCallContext(user=A2AUser({"sub": "alice"})) + bob = ServerCallContext(user=A2AUser({"sub": "bob"})) + task = Task( + id="t-1", + context_id="c-1", + status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED), + ) + + import asyncio + + async def run(): + await store.save(task, alice) + assert await store.get("t-1", alice) is not None + assert await store.get("t-1", bob) is None + assert [t.id for t in (await store.list(ListTasksRequest(), alice)).tasks] == [ + "t-1" + ] + assert not (await store.list(ListTasksRequest(), bob)).tasks + await store.delete("t-1", bob) + assert await store.get("t-1", alice) is not None + await store.delete("t-1", alice) + assert await store.get("t-1", alice) is None + + asyncio.run(run()) + + +def test_apply_tenant_wraps_transport(): + class FakeTransport: + pass + + class FakeClient: + _transport = FakeTransport() + + client = apply_tenant(FakeClient(), "tenant-a") + assert client._transport._tenant == "tenant-a" + assert apply_tenant(FakeClient(), "")._transport.__class__ is FakeTransport + + +def test_apply_tenant_requires_transport(): + with pytest.raises(ValueError): + apply_tenant(object(), "tenant-a") + + +def test_remote_ve_agent_applies_tenant(monkeypatch): + import veadk.a2a.remote_ve_agent as module + + card = { + "name": "remote", + "description": "remote", + "version": "1.0.0", + "capabilities": {}, + "defaultInputModes": ["text"], + "defaultOutputModes": ["text"], + "skills": [], + "supportedInterfaces": [ + { + "url": "https://example.com", + "protocolBinding": "JSONRPC", + "protocolVersion": "1.0", + } + ], + } + monkeypatch.setattr( + module.requests, + "get", + lambda *args, **kwargs: SimpleNamespace(json=lambda: card), + ) + + class FakeParent: + def __init__(self, **kwargs): + self._a2a_client = SimpleNamespace(_transport=object()) + + monkeypatch.setattr(module.RemoteA2aAgent, "__init__", FakeParent.__init__) + agent = module.RemoteVeAgent( + name="remote", url="https://example.com", tenant="tenant-a" + ) + assert agent._a2a_client._transport._tenant == "tenant-a" + + +def test_cloud_app_applies_tenant(monkeypatch): + import asyncio + + import veadk.cloud.cloud_app as module + + class FakeClient: + def __init__(self): + self._transport = object() + + class FakeFactory: + def __init__(self, config): + self.config = config + + def create(self, card): + return FakeClient() + + monkeypatch.setattr(module, "ClientFactory", FakeFactory) + app = module.CloudApp( + vefaas_endpoint="https://example.com", + use_agent_card=False, + tenant="tenant-a", + ) + client = asyncio.run(app._get_a2a_client()) + assert client._transport._tenant == "tenant-a" + + +def test_bearer_verifier_requires_jwks_uri(): + import asyncio + + verifier = BearerJWTVerifier(issuer="https://idp") + with pytest.raises(ValueError): + asyncio.run(verifier.verify("token")) From dbb1b5c481aae8e360dae2055ccffb04607a6d49 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 16:25:15 +0800 Subject: [PATCH 15/22] test(a2a): add real-cloud E2E for AIDAP, Identity Service and TOS Cover multi-replica task visibility and cross-replica streaming on AIDAP Serverless PostgreSQL, database-backed push delivery, OIDC client-credentials auth with the real Identity Service JWKS, tenant isolation, and AgentCard signature verification against a TOS-hosted JWKS. The KMS path is included but skipped until the account activates the KMS service. Signed-off-by: Codex --- tests/a2a/test_a2a_cloud_e2e.py | 461 ++++++++++++++++++++++++++++++++ 1 file changed, 461 insertions(+) create mode 100644 tests/a2a/test_a2a_cloud_e2e.py diff --git a/tests/a2a/test_a2a_cloud_e2e.py b/tests/a2a/test_a2a_cloud_e2e.py new file mode 100644 index 000000000..1177d2f08 --- /dev/null +++ b/tests/a2a/test_a2a_cloud_e2e.py @@ -0,0 +1,461 @@ +# Copyright (c) 2025 Beijing Volcano Engine Technology Co., Ltd. and/or its affiliates. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Real-cloud end-to-end tests for the A2A 1.x capabilities. + +These tests create no resources themselves; they consume resources the +operator provisioned for the run and are skipped when the corresponding +environment variables are absent. + +* ``VEADK_TEST_AIDAP_URL``: AIDAP Serverless PostgreSQL connection string. +* ``VEADK_TEST_TOS_BUCKET`` / ``VEADK_TEST_TOS_REGION``: JWKS hosting bucket. +* ``VEADK_TEST_OIDC_ISSUER`` / ``VEADK_TEST_OIDC_JWKS_URI`` / + ``VEADK_TEST_OIDC_AUDIENCE``: Identity Service OIDC metadata. +* ``VEADK_TEST_OIDC_TOKEN_ENDPOINT`` / ``VEADK_TEST_OIDC_CLIENT_ID`` / + ``VEADK_TEST_OIDC_CLIENT_SECRET``: client-credentials token source. +* ``VEADK_TEST_KMS_KEY_ID``: optional KMS asymmetric signing key. +""" + +from __future__ import annotations + +import json +import os +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from types import SimpleNamespace + +import pytest +import requests +from a2a.utils.signing import ( + InvalidSignaturesError, + create_signature_verifier, +) +from fastapi.testclient import TestClient +from jwt import PyJWK + +from tests.a2a.conftest import V1, send_message_body +from veadk.a2a.agent_card import get_agent_card +from veadk.a2a.config import ( + A2ASecurityScheme, + A2AServerConfig, + A2ASigningConfig, +) +from veadk.a2a.signing import ( + LocalAgentCardSigner, + generate_es256_jwk, + jwks_document, + publish_jwks_to_tos, +) +from veadk.a2a.stores import normalize_database_url + +AIDAP_URL = os.getenv("VEADK_TEST_AIDAP_URL", "") +TOS_BUCKET = os.getenv("VEADK_TEST_TOS_BUCKET", "") +TOS_REGION = os.getenv("VEADK_TEST_TOS_REGION", "cn-beijing") +OIDC_ISSUER = os.getenv("VEADK_TEST_OIDC_ISSUER", "") +OIDC_JWKS = os.getenv("VEADK_TEST_OIDC_JWKS_URI", "") +OIDC_AUDIENCE = os.getenv("VEADK_TEST_OIDC_AUDIENCE", "") +OIDC_TOKEN_URL = os.getenv("VEADK_TEST_OIDC_TOKEN_ENDPOINT", "") +OIDC_CLIENT_ID = os.getenv("VEADK_TEST_OIDC_CLIENT_ID", "") +OIDC_CLIENT_SECRET = os.getenv("VEADK_TEST_OIDC_CLIENT_SECRET", "") +KMS_KEY_ID = os.getenv("VEADK_TEST_KMS_KEY_ID", "") + +requires_aidap = pytest.mark.skipif( + not AIDAP_URL, reason="VEADK_TEST_AIDAP_URL is not set" +) +requires_tos = pytest.mark.skipif( + not TOS_BUCKET, reason="VEADK_TEST_TOS_BUCKET is not set" +) +requires_oidc = pytest.mark.skipif( + not all( + [ + OIDC_ISSUER, + OIDC_JWKS, + OIDC_AUDIENCE, + OIDC_TOKEN_URL, + OIDC_CLIENT_ID, + OIDC_CLIENT_SECRET, + ] + ), + reason="Identity Service OIDC environment is not set", +) +requires_kms = pytest.mark.skipif( + not KMS_KEY_ID, reason="VEADK_TEST_KMS_KEY_ID is not set" +) + + +def _bearer_token() -> str: + response = requests.post( + OIDC_TOKEN_URL, + data={"grant_type": "client_credentials"}, + auth=(OIDC_CLIENT_ID, OIDC_CLIENT_SECRET), + timeout=20, + ) + response.raise_for_status() + return response.json()["access_token"] + + +def _security_scheme() -> A2ASecurityScheme: + return A2ASecurityScheme( + scheme_id="oauth2", + type="oauth2", + description="Volcano Engine Identity Service", + authorization_url=f"{OIDC_ISSUER}/authorize", + token_url=OIDC_TOKEN_URL, + scopes={"openid": "openid"}, + pkce_required=True, + oauth2_metadata_url=f"{OIDC_ISSUER}/.well-known/openid-configuration", + ) + + +def _auth_config(**kwargs) -> A2AServerConfig: + return A2AServerConfig( + require_auth=True, + oidc_issuer=OIDC_ISSUER, + oidc_jwks_uri=OIDC_JWKS, + oidc_audience=OIDC_AUDIENCE, + security_schemes=(_security_scheme(),), + security_requirements=({"oauth2": ("openid",)},), + **kwargs, + ) + + +class _Webhook: + def __init__(self): + self.records = [] + self.lock = threading.Lock() + + def handler(self): + receiver = self + + class Handler(BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("content-length", "0")) + with receiver.lock: + receiver.records.append( + json.loads(self.rfile.read(length) or b"{}") + ) + self.send_response(200) + self.send_header("content-length", "2") + self.end_headers() + self.wfile.write(b"{}") + + def log_message(self, *args): + return + + return Handler + + +def _start_webhook(): + receiver = _Webhook() + server = ThreadingHTTPServer(("127.0.0.1", 0), receiver.handler()) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, receiver, f"http://127.0.0.1:{server.server_port}/hook" + + +def _wait_for_records(records, count, timeout=10.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if len(records) >= count: + return records + time.sleep(0.05) + return records + + +# --------------------------------------------------------------------------- +# Cluster mode on AIDAP +# --------------------------------------------------------------------------- + + +@requires_aidap +def test_cluster_task_visibility_and_cross_replica_streaming( + make_server, stub_executor +): + stub_executor.delay = 3.0 + config = A2AServerConfig( + database_url=normalize_database_url(AIDAP_URL), + rest_enabled=True, + ) + replica_a = make_server(config) + replica_b = make_server(config) + + with ( + TestClient(replica_a.build()) as client_a, + TestClient(replica_b.build()) as client_b, + ): + existing_working = { + task["id"] + for task in client_b.get("/v1/tasks", headers=V1).json()["tasks"] + if task["status"]["state"] == "TASK_STATE_WORKING" + } + result = {} + + def send(): + result["response"] = client_a.post( + "/", headers=V1, json=send_message_body("cluster") + ) + + thread = threading.Thread(target=send) + thread.start() + + task_id = None + deadline = time.monotonic() + 10 + while time.monotonic() < deadline and task_id is None: + tasks = client_b.get("/v1/tasks", headers=V1).json()["tasks"] + working = [ + task + for task in tasks + if task["status"]["state"] == "TASK_STATE_WORKING" + and task["id"] not in existing_working + ] + if working: + task_id = working[-1]["id"] + else: + time.sleep(0.1) + assert task_id is not None + + fetched = client_b.get(f"/v1/tasks/{task_id}", headers=V1) + assert fetched.status_code == 200 + assert fetched.json()["status"]["state"] == "TASK_STATE_WORKING" + + events = [] + with client_b.stream( + "GET", f"/v1/tasks/{task_id}:subscribe", headers=V1 + ) as response: + assert response.status_code == 200 + for line in response.iter_lines(): + if line: + events.append(line) + if "TASK_STATE_COMPLETED" in line: + break + + thread.join() + stub_executor.delay = 0 + assert result["response"].status_code == 200 + assert any("TASK_STATE_COMPLETED" in event for event in events) + + +@requires_aidap +def test_cluster_push_uses_database_config_store(make_server, stub_executor): + stub_executor.delay = 3.0 + server, receiver, webhook_url = _start_webhook() + try: + config = A2AServerConfig( + database_url=normalize_database_url(AIDAP_URL), + push_webhook_url=webhook_url, + push_allow_private_url=True, + ) + client = TestClient(make_server(config).build()) + response = client.post("/", headers=V1, json=send_message_body("push")) + assert response.status_code == 200 + records = _wait_for_records(receiver.records, 2) + assert len(records) == 2 + assert records[0]["task"]["status"]["state"] == "TASK_STATE_WORKING" + assert records[1]["statusUpdate"]["status"]["state"] == "TASK_STATE_COMPLETED" + finally: + stub_executor.delay = 0 + server.shutdown() + server.server_close() + + +# --------------------------------------------------------------------------- +# Identity Service auth + tenant isolation +# --------------------------------------------------------------------------- + + +@requires_oidc +def test_oidc_auth_and_extended_card(make_server): + token = _bearer_token() + config = _auth_config( + extended_card_skills=( + { + "id": "secret", + "name": "secret", + "description": "authenticated-only skill", + "tags": ["secret"], + }, + ) + ) + client = TestClient(make_server(config).build()) + + card = client.get("/.well-known/agent-card.json") + assert card.status_code == 200 + assert card.json()["capabilities"]["extendedAgentCard"] is True + assert "oauth2" in card.json()["securitySchemes"] + + missing = client.post("/", headers=V1, json=send_message_body()) + assert missing.status_code == 401 + assert missing.json()["error"] == "invalid_request" + + invalid = client.post( + "/", + headers={**V1, "Authorization": "Bearer not-a-jwt"}, + json=send_message_body(), + ) + assert invalid.status_code == 401 + assert invalid.json()["error"] == "invalid_token" + + authorized = client.post( + "/", + headers={**V1, "Authorization": f"Bearer {token}"}, + json=send_message_body(), + ) + assert authorized.status_code == 200 + assert ( + authorized.json()["result"]["task"]["status"]["state"] == "TASK_STATE_COMPLETED" + ) + + extended = client.post( + "/", + headers={**V1, "Authorization": f"Bearer {token}"}, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "GetExtendedAgentCard", + "params": {}, + }, + ) + assert extended.status_code == 200 + assert "secret" in [skill["id"] for skill in extended.json()["result"]["skills"]] + + unauthenticated = client.post( + "/", + headers=V1, + json={ + "jsonrpc": "2.0", + "id": 3, + "method": "GetExtendedAgentCard", + "params": {}, + }, + ) + assert unauthenticated.status_code == 401 + + +@requires_oidc +@requires_aidap +def test_tenant_isolation_with_real_identity(make_server): + token = _bearer_token() + config = _auth_config( + database_url=normalize_database_url(AIDAP_URL), + tenant_header="x-a2a-tenant", + ) + with TestClient(make_server(config).build()) as client: + headers = {**V1, "Authorization": f"Bearer {token}"} + + created = client.post( + "/", + headers={**headers, "x-a2a-tenant": "tenant-a"}, + json=send_message_body(), + ) + task_id = created.json()["result"]["task"]["id"] + + other_tenant = client.post( + "/", + headers={**headers, "x-a2a-tenant": "tenant-b"}, + json={ + "jsonrpc": "2.0", + "id": 2, + "method": "GetTask", + "params": {"id": task_id}, + }, + ) + assert other_tenant.json()["error"]["code"] == -32001 + + same_tenant = client.post( + "/", + headers={**headers, "x-a2a-tenant": "tenant-a"}, + json={ + "jsonrpc": "2.0", + "id": 3, + "method": "GetTask", + "params": {"id": task_id}, + }, + ) + assert same_tenant.json()["result"]["id"] == task_id + + other_list = client.post( + "/", + headers={**headers, "x-a2a-tenant": "tenant-b"}, + json={"jsonrpc": "2.0", "id": 4, "method": "ListTasks", "params": {}}, + ) + assert other_list.json()["result"]["tasks"] == [] + + +# --------------------------------------------------------------------------- +# AgentCard signing with a real TOS-hosted JWKS +# --------------------------------------------------------------------------- + + +@requires_tos +def test_signed_card_verifies_against_tos_jwks(): + private_jwk, public_jwk = generate_es256_jwk("veadk-e2e-kid") + jwks = jwks_document([public_jwk]) + jwks_url = publish_jwks_to_tos( + jwks, + bucket=TOS_BUCKET, + object_key=".well-known/jwks.json", + region=TOS_REGION, + ) + + fetched = requests.get(jwks_url, timeout=20) + assert fetched.status_code == 200 + assert fetched.json()["keys"][0]["kid"] == "veadk-e2e-kid" + + signer = LocalAgentCardSigner( + A2ASigningConfig( + private_key=json.dumps(private_jwk), + kid="veadk-e2e-kid", + alg="ES256", + jku=jwks_url, + ) + ) + card = signer( + get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + ) + ) + + verifier = create_signature_verifier( + key_provider=lambda kid, jku: PyJWK.from_dict(public_jwk), + algorithms=["ES256"], + ) + verifier(card) + + card.name = "tampered" + with pytest.raises(InvalidSignaturesError): + verifier(card) + + +@requires_kms +def test_kms_signed_card_verifies(): + from veadk.a2a.signing import KmsAgentCardSigner + + signer = KmsAgentCardSigner( + A2ASigningConfig( + provider="kms", + kms_key_id=KMS_KEY_ID, + kid="veadk-kms-kid", + alg="ES256", + access_key=os.getenv("VOLCENGINE_ACCESS_KEY", ""), + secret_key=os.getenv("VOLCENGINE_SECRET_KEY", ""), + ) + ) + card = signer( + get_agent_card( + SimpleNamespace(name="a", description="d"), + "https://example.com", + ) + ) + assert card.signatures From bd5a4ac4dbe4dbfedf0ce0e8895757cf06095292 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 18:02:35 +0800 Subject: [PATCH 16/22] fix(a2a): convert KMS ECDSA DER signatures to JWS raw Volcano Engine KMS returns ASN.1 DER SEQUENCE(r, s) for ECDSA, while JWS ES256 requires the fixed-width r||s concatenation. Convert the signature before base64url encoding so KMS-signed cards verify with standard JWKS. Extend the unit test to assert the request shape and the 64-byte raw signature, and make the real-cloud KMS test fetch the public key and verify both a valid and a tampered card. Signed-off-by: Codex --- tests/a2a/test_a2a_cloud_e2e.py | 35 ++++++++++++++++++++++- tests/a2a/test_a2a_server_capabilities.py | 30 ++++++++++++++++--- veadk/a2a/signing.py | 9 ++++++ 3 files changed, 69 insertions(+), 5 deletions(-) diff --git a/tests/a2a/test_a2a_cloud_e2e.py b/tests/a2a/test_a2a_cloud_e2e.py index 1177d2f08..f5a231a5b 100644 --- a/tests/a2a/test_a2a_cloud_e2e.py +++ b/tests/a2a/test_a2a_cloud_e2e.py @@ -440,12 +440,21 @@ def test_signed_card_verifies_against_tos_jwks(): @requires_kms def test_kms_signed_card_verifies(): - from veadk.a2a.signing import KmsAgentCardSigner + import base64 + + import volcenginesdkcore + import volcenginesdkkms + from volcenginesdkkms.models.get_public_key_request import ( + GetPublicKeyRequest, + ) + + from veadk.a2a.signing import KmsAgentCardSigner, public_jwk_from_der signer = KmsAgentCardSigner( A2ASigningConfig( provider="kms", kms_key_id=KMS_KEY_ID, + kms_algorithm="ECDSA_SHA_256", kid="veadk-kms-kid", alg="ES256", access_key=os.getenv("VOLCENGINE_ACCESS_KEY", ""), @@ -459,3 +468,27 @@ def test_kms_signed_card_verifies(): ) ) assert card.signatures + + cfg = volcenginesdkcore.Configuration() + cfg.ak = os.getenv("VOLCENGINE_ACCESS_KEY", "") + cfg.sk = os.getenv("VOLCENGINE_SECRET_KEY", "") + cfg.region = "cn-beijing" + cfg.host = "open.volcengineapi.com" + api = volcenginesdkkms.KMSApi( + api_client=volcenginesdkcore.ApiClient(configuration=cfg) + ) + public_key = api.get_public_key(GetPublicKeyRequest(key_id=KMS_KEY_ID)) + jwk = public_jwk_from_der( + base64.b64decode(public_key.public_key), + kid="veadk-kms-kid", + alg="ES256", + ) + verifier = create_signature_verifier( + key_provider=lambda kid, jku: PyJWK.from_dict(jwk), + algorithms=["ES256"], + ) + verifier(card) + + card.name = "tampered" + with pytest.raises(InvalidSignaturesError): + verifier(card) diff --git a/tests/a2a/test_a2a_server_capabilities.py b/tests/a2a/test_a2a_server_capabilities.py index f34b900fa..60dd9bf3a 100644 --- a/tests/a2a/test_a2a_server_capabilities.py +++ b/tests/a2a/test_a2a_server_capabilities.py @@ -532,7 +532,15 @@ def test_local_signer_requires_private_key(): LocalAgentCardSigner(A2ASigningConfig()) -def test_kms_sign_method_encodes_message_and_signature(monkeypatch): +def test_kms_sign_encodes_request_and_converts_der_to_jws_raw(monkeypatch): + import base64 + + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.hazmat.primitives.asymmetric.utils import ( + encode_dss_signature, + ) + signer = KmsAgentCardSigner( A2ASigningConfig( provider="kms", @@ -542,9 +550,12 @@ def test_kms_sign_method_encodes_message_and_signature(monkeypatch): secret_key="sk", ) ) + key = ec.generate_private_key(ec.SECP256R1()) + der = key.sign(b"signing-input", ec.ECDSA(hashes.SHA256())) + assert der[0] == 0x30 # ASN.1 SEQUENCE class FakeResponse: - signature = "c2ln" + signature = base64.b64encode(der).decode("ascii") captured = {} @@ -553,11 +564,22 @@ def fake_asymmetric_sign(request): return FakeResponse() monkeypatch.setattr(signer._api, "asymmetric_sign", fake_asymmetric_sign) - signature = signer._sign(b"signing-input") - assert signature == "c2ln" + encoded = signer._sign(b"signing-input") assert captured["request"].key_id == "key-1" assert captured["request"].algorithm == "ECDSA_SHA_256" assert captured["request"].message_type == "RAW" + assert base64.b64decode(captured["request"].message) == b"signing-input" + raw = base64.urlsafe_b64decode(encoded + "==") + assert len(raw) == 64 + # The JWS signature must verify as a raw r||s ECDSA signature. + key.public_key().verify( + encode_dss_signature( + int.from_bytes(raw[:32], "big"), + int.from_bytes(raw[32:], "big"), + ), + b"signing-input", + ec.ECDSA(hashes.SHA256()), + ) def test_build_signer_creates_kms_signer(): diff --git a/veadk/a2a/signing.py b/veadk/a2a/signing.py index f0b196c1f..de8a00d97 100644 --- a/veadk/a2a/signing.py +++ b/veadk/a2a/signing.py @@ -167,6 +167,15 @@ def _sign(self, signing_input: bytes) -> str: ) ) signature = base64.b64decode(response.signature or "") + if self._config.kms_algorithm.upper().startswith("ECDSA"): + # KMS returns an ASN.1 DER ``SEQUENCE(r, s)``. JWS ES256 expects + # the fixed-width ``r || s`` concatenation, so convert it. + from cryptography.hazmat.primitives.asymmetric.utils import ( + decode_dss_signature, + ) + + r, s = decode_dss_signature(signature) + signature = r.to_bytes(32, "big") + s.to_bytes(32, "big") return base64.urlsafe_b64encode(signature).rstrip(b"=").decode("ascii") def __call__(self, card: AgentCard) -> AgentCard: From f4edab9ace79daab73e1599f213e3c81da1fa9bb Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Thu, 3 Dec 2026 20:07:39 +0800 Subject: [PATCH 17/22] fix(a2a): address review findings for push, tenant and FaaS updates - Forward initialize() in DefaultingPushNotificationConfigStore so a server with both database_url and push_webhook_url starts instead of raising AttributeError during lifespan startup. - Apply the RemoteVeAgent tenant inside _ensure_resolved, after the ADK client exists, instead of in __init__ where _a2a_client is still None. - Unwrap TenantTransportDecorator before auth-header injection so TIP and bearer credentials are still applied when tenant routing is enabled. - Pass the tenant-aware owner resolver into InMemoryTaskStore so tasks are filtered before pagination, not after. - Seed the placeholder VEADK_A2A_PUBLIC_URL before releasing an updated code bundle, so apps created before the env existed can boot the new template. All five findings are covered by unit tests; the DB+push startup path was also verified against a real AIDAP workspace. Signed-off-by: Codex --- tests/a2a/test_a2a_server_capabilities.py | 201 +++++++++++++++++++++- tests/cli/test_studio_update.py | 4 + tests/test_cloud.py | 78 ++++++++- veadk/a2a/push.py | 6 + veadk/a2a/remote_ve_agent.py | 44 +++-- veadk/a2a/stores.py | 18 +- veadk/a2a/tenant.py | 6 +- veadk/integrations/ve_faas/ve_faas.py | 25 ++- 8 files changed, 345 insertions(+), 37 deletions(-) diff --git a/tests/a2a/test_a2a_server_capabilities.py b/tests/a2a/test_a2a_server_capabilities.py index 60dd9bf3a..105baf38b 100644 --- a/tests/a2a/test_a2a_server_capabilities.py +++ b/tests/a2a/test_a2a_server_capabilities.py @@ -694,6 +694,33 @@ def test_build_stores_with_push_wraps_default_store(): assert isinstance(stores.push_config_store, DefaultingPushNotificationConfigStore) +def test_a2a_stores_initialize_initializes_push_config_store(): + import asyncio + + from veadk.a2a.stores import A2AStores + + class Initializable: + def __init__(self): + self.initialized = False + + async def initialize(self): + self.initialized = True + + task_store = Initializable() + event_stream = Initializable() + push_store = Initializable() + stores = A2AStores( + task_store=task_store, + event_stream=event_stream, + push_config_store=push_store, + engine=object(), + ) + asyncio.run(stores.initialize()) + assert task_store.initialized is True + assert event_stream.initialized is True + assert push_store.initialized is True + + def test_require_auth_without_oidc_config_raises(make_server): with pytest.raises(ValueError): make_server(A2AServerConfig(require_auth=True)).build() @@ -733,6 +760,60 @@ async def run(): asyncio.run(run()) +def test_defaulting_store_forwards_initialize(): + import asyncio + + from veadk.a2a.push import DefaultingPushNotificationConfigStore + + class Inner: + initialized = False + + async def initialize(self): + self.initialized = True + + inner = Inner() + store = DefaultingPushNotificationConfigStore(inner, "https://default") + asyncio.run(store.initialize()) + assert inner.initialized is True + + +def test_owner_scoped_store_filters_tenant_before_pagination(): + import asyncio + + from a2a.server.context import ServerCallContext + from a2a.types import ListTasksRequest, Task, TaskState, TaskStatus + + resolve = make_owner_resolver("x-a2a-tenant") + store = OwnerScopedInMemoryTaskStore(resolve) + tenant_a = ServerCallContext(user=A2AUser({"sub": "alice"}), tenant="a") + tenant_b = ServerCallContext(user=A2AUser({"sub": "alice"}), tenant="b") + + async def run(): + for index in range(60): + await store.save( + Task( + id=f"b-{index}", + context_id="c", + status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED), + ), + tenant_b, + ) + await store.save( + Task( + id="a-1", + context_id="c", + status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED), + ), + tenant_a, + ) + + page = await store.list(ListTasksRequest(page_size=10), tenant_a) + assert [task.id for task in page.tasks] == ["a-1"] + assert page.next_page_token == "" + + asyncio.run(run()) + + def test_push_validator_is_none_when_push_disabled(): from veadk.a2a.push import build_push_url_validator @@ -796,10 +877,8 @@ def test_apply_tenant_requires_transport(): apply_tenant(object(), "tenant-a") -def test_remote_ve_agent_applies_tenant(monkeypatch): - import veadk.a2a.remote_ve_agent as module - - card = { +def _remote_card(): + return { "name": "remote", "description": "remote", "version": "1.0.0", @@ -815,10 +894,17 @@ def test_remote_ve_agent_applies_tenant(monkeypatch): } ], } + + +def test_remote_ve_agent_applies_tenant(monkeypatch): + import asyncio + + import veadk.a2a.remote_ve_agent as module + monkeypatch.setattr( module.requests, "get", - lambda *args, **kwargs: SimpleNamespace(json=lambda: card), + lambda *args, **kwargs: SimpleNamespace(json=lambda: _remote_card()), ) class FakeParent: @@ -826,10 +912,113 @@ def __init__(self, **kwargs): self._a2a_client = SimpleNamespace(_transport=object()) monkeypatch.setattr(module.RemoteA2aAgent, "__init__", FakeParent.__init__) + + async def fake_resolved(self, ctx=None): + return self._a2a_client + + monkeypatch.setattr(module.RemoteA2aAgent, "_ensure_resolved", fake_resolved) agent = module.RemoteVeAgent( name="remote", url="https://example.com", tenant="tenant-a" ) - assert agent._a2a_client._transport._tenant == "tenant-a" + client = asyncio.run(agent._ensure_resolved()) + assert client._transport._tenant == "tenant-a" + + +def test_remote_ve_agent_tenant_constructs_before_client_exists(monkeypatch): + import veadk.a2a.remote_ve_agent as module + + monkeypatch.setattr( + module.requests, + "get", + lambda *args, **kwargs: SimpleNamespace(json=lambda: _remote_card()), + ) + + class LazyParent: + def __init__(self, **kwargs): + # ADK leaves the client None until _ensure_resolved runs. + self._a2a_client = None + + monkeypatch.setattr(module.RemoteA2aAgent, "__init__", LazyParent.__init__) + agent = module.RemoteVeAgent( + name="remote", url="https://example.com", tenant="tenant-a" + ) + assert agent._tenant == "tenant-a" + assert agent._a2a_client is None + + +def test_remote_ve_agent_httpx_client_unwraps_tenant_decorator(monkeypatch): + import httpx + from a2a.client.transports.tenant_decorator import TenantTransportDecorator + + import veadk.a2a.remote_ve_agent as module + + monkeypatch.setattr( + module.requests, + "get", + lambda *args, **kwargs: SimpleNamespace(json=lambda: _remote_card()), + ) + httpx_client = httpx.AsyncClient() + + class FakeParent: + def __init__(self, **kwargs): + self._a2a_client = SimpleNamespace( + _transport=TenantTransportDecorator( + SimpleNamespace(httpx_client=httpx_client), "tenant-a" + ) + ) + + monkeypatch.setattr(module.RemoteA2aAgent, "__init__", FakeParent.__init__) + agent = module.RemoteVeAgent(name="remote", url="https://example.com") + assert agent._httpx_client() is httpx_client + + +def test_inject_auth_token_works_through_tenant_decorator(monkeypatch): + import asyncio + + import httpx + from a2a.client.transports.tenant_decorator import TenantTransportDecorator + + import veadk.a2a.remote_ve_agent as module + + monkeypatch.setattr( + module.requests, + "get", + lambda *args, **kwargs: SimpleNamespace(json=lambda: _remote_card()), + ) + + class FakeClient: + def __init__(self): + self.httpx_client = httpx.AsyncClient() + self._transport = TenantTransportDecorator( + SimpleNamespace(httpx_client=self.httpx_client), "tenant-a" + ) + + monkeypatch.setattr(module, "BaseClient", FakeClient) + monkeypatch.setattr( + "google.adk.agents.callback_context.CallbackContext", + lambda ctx: SimpleNamespace(ctx=ctx), + ) + + class LazyParent: + def __init__(self, **kwargs): + self._a2a_client = FakeClient() + + monkeypatch.setattr(module.RemoteA2aAgent, "__init__", LazyParent.__init__) + agent = module.RemoteVeAgent(name="remote", url="https://example.com") + + tip = SimpleNamespace(api_key="tip-token") + credential_service = SimpleNamespace( + load_credential=__import__("unittest.mock", fromlist=["AsyncMock"]).AsyncMock( + side_effect=[tip, None] + ) + ) + ctx = SimpleNamespace(credential_service=credential_service) + + asyncio.run(agent._inject_auth_token(ctx)) + assert ( + agent._a2a_client.httpx_client.headers[module.VE_TIP_TOKEN_HEADER] + == "tip-token" + ) def test_cloud_app_applies_tenant(monkeypatch): diff --git a/tests/cli/test_studio_update.py b/tests/cli/test_studio_update.py index 9b16fe28d..2741dda7b 100644 --- a/tests/cli/test_studio_update.py +++ b/tests/cli/test_studio_update.py @@ -1671,6 +1671,7 @@ def test_update_application_code_bundle_merges_only_explicit_environment( resource_requests: list[Any] = [] service = object.__new__(VeFaaS) service.session_token = "" + monkeypatch.setattr(service, "merge_function_envs_and_release", Mock()) cast(Any, service).client = SimpleNamespace( get_function=lambda _: SimpleNamespace( command="./run.sh", @@ -2192,6 +2193,7 @@ def test_update_application_code_bundle_preserves_unspecified_sandbox_tool( updated_requests: list[Any] = [] service = object.__new__(VeFaaS) service.session_token = "" + monkeypatch.setattr(service, "merge_function_envs_and_release", Mock()) cast(Any, service).client = SimpleNamespace( get_function=lambda _: SimpleNamespace( envs=[ @@ -2226,6 +2228,7 @@ def test_update_application_code_bundle_does_not_read_or_replace_environment( updated_requests: list[Any] = [] service = object.__new__(VeFaaS) service.session_token = "" + monkeypatch.setattr(service, "merge_function_envs_and_release", Mock()) cast(Any, service).client = SimpleNamespace( get_function=lambda _: pytest.fail("environment should not be read"), update_function=updated_requests.append, @@ -2253,6 +2256,7 @@ def test_studio_update_preserves_custom_function_command( updated_requests: list[Any] = [] service = object.__new__(VeFaaS) service.session_token = "" + monkeypatch.setattr(service, "merge_function_envs_and_release", Mock()) cast(Any, service).client = SimpleNamespace( get_function=lambda _: SimpleNamespace( command="python3 custom_server.py", diff --git a/tests/test_cloud.py b/tests/test_cloud.py index d7346a6a9..a912ca026 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -31,7 +31,7 @@ from veadk.cloud.cloud_agent_engine import CloudAgentEngine from veadk.integrations.ve_apig.ve_apig import APIGateway from veadk.integrations.ve_code_pipeline.ve_code_pipeline import VeCodePipeline -from veadk.integrations.ve_faas.ve_faas import VeFaaS +from veadk.integrations.ve_faas.ve_faas import PENDING_PUBLIC_URL, VeFaaS from veadk.utils.cloud_provider import ( CloudProvider, agentkit_openapi_base, @@ -470,6 +470,82 @@ def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: assert "No requirements.txt found" in caplog.text +def test_vefaas_update_code_seeds_public_url_before_release( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + project = tmp_path / "agent" + project.mkdir() + (project / "requirements.txt").write_text("requests\n") + service = object.__new__(VeFaaS) + service.find_app_id_by_name = Mock(return_value="application-id") + service._get_application_status = Mock( + return_value=( + "deploy_success", + { + "Result": { + "CloudResource": ( + '{"framework":{"function":{"Name":"studio-app-fn",' + '"Id":"function-id"}}}' + ) + } + }, + ) + ) + service._replace_application_code_bundle = Mock() + service._release_application = Mock(return_value="https://studio.example") + order: list[str] = [] + service.merge_function_envs_and_release = Mock( + side_effect=lambda **kwargs: order.append( + kwargs["extra_envs"]["VEADK_A2A_PUBLIC_URL"] + ) + ) + service._set_function_min_instance = Mock() + service.ensure_application_route_methods = Mock() + + def _cookiecutter(*, output_dir: str, extra_context: dict, **_: object) -> None: + package = Path(output_dir) / str(extra_context["local_dir_name"]) + (package / "src" / "agent").mkdir(parents=True) + + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.formatted_timestamp", lambda: "stamp" + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.tempfile.gettempdir", + lambda: str(tmp_path), + ) + monkeypatch.setattr( + "veadk.integrations.ve_faas.ve_faas.cookiecutter", _cookiecutter + ) + + service._update_function_code("studio-app", str(project)) + + assert order == [PENDING_PUBLIC_URL, "https://studio.example"] + + +def test_vefaas_update_bundle_seeds_public_url_before_release() -> None: + service = object.__new__(VeFaaS) + service._replace_application_code_bundle = Mock() + service._release_application = Mock(return_value="https://studio.example") + order: list[str] = [] + service.merge_function_envs_and_release = Mock( + side_effect=lambda **kwargs: order.append( + kwargs["extra_envs"]["VEADK_A2A_PUBLIC_URL"] + ) + ) + service._set_function_min_instance = Mock() + service.ensure_application_route_methods = Mock() + + result = service.update_application_code_bundle( + application_id="application-id", + function_id="function-id", + path=".", + ) + + assert result == "https://studio.example" + assert order == [PENDING_PUBLIC_URL] + + def test_vefaas_deploy_updates_existing_application_in_place() -> None: service = object.__new__(VeFaaS) service.find_app_id_by_name = Mock(return_value="application-id") diff --git a/veadk/a2a/push.py b/veadk/a2a/push.py index ec1b7e6c3..0c243b978 100644 --- a/veadk/a2a/push.py +++ b/veadk/a2a/push.py @@ -73,6 +73,12 @@ def __init__( self._default_url = default_url self._token = token + async def initialize(self) -> None: + """Initialize the wrapped store when it supports initialization.""" + initializer = getattr(self._inner, "initialize", None) + if initializer is not None: + await initializer() + async def set_info( self, task_id: str, diff --git a/veadk/a2a/remote_ve_agent.py b/veadk/a2a/remote_ve_agent.py index 06fdb670c..7247662c7 100644 --- a/veadk/a2a/remote_ve_agent.py +++ b/veadk/a2a/remote_ve_agent.py @@ -236,10 +236,10 @@ def __init__( super().__init__( name=name, agent_card=agent_card_object, httpx_client=client_to_use ) - if tenant: - from veadk.a2a.tenant import apply_tenant - - apply_tenant(self._a2a_client, tenant) + # ``RemoteA2aAgent`` creates ``_a2a_client`` lazily inside + # ``_ensure_resolved``; applying the tenant here would fail because the + # client does not exist yet. ``_ensure_resolved`` below applies it. + self._tenant = tenant # The parent class sets _httpx_client_needs_cleanup based on whether # the httpx_client it received was None. Since we always pass a @@ -257,6 +257,21 @@ def __init__( # and authentication logic always executes, even if users override _run_async_impl self._wrap_run_async_impl() + async def _ensure_resolved(self, ctx: Optional[InvocationContext] = None): + """Resolve the A2A client, then attach the configured tenant.""" + client = await super()._ensure_resolved(ctx) + if self._tenant: + from veadk.a2a.tenant import apply_tenant + + apply_tenant(client, self._tenant) + return client + + def _httpx_client(self) -> Optional[httpx.AsyncClient]: + """Return the underlying HTTP client, unwrapping a tenant decorator.""" + transport = getattr(self._a2a_client, "_transport", None) + base = getattr(transport, "_base", transport) + return getattr(base, "httpx_client", None) + def _wrap_run_async_impl(self) -> None: """Wrap _run_async_impl with a decorator that ensures pre-run logic executes. @@ -343,15 +358,10 @@ async def _inject_auth_token(self, ctx: InvocationContext) -> None: ) return - # Skip if transport is not available - if not hasattr(self._a2a_client, "_transport"): - logger.debug( - "A2A client transport not available, skipping auth token injection" - ) - return - - # Skip if httpx_client is not available - if not hasattr(self._a2a_client._transport, "httpx_client"): + # Skip if the underlying HTTP client is not available. A tenant + # decorator wraps the transport, so unwrap ``_base`` first. + httpx_client = self._httpx_client() + if httpx_client is None: logger.debug( "A2A client httpx_client not available, skipping auth token injection" ) @@ -374,7 +384,7 @@ async def _inject_auth_token(self, ctx: InvocationContext) -> None: ) if tip_credential: - self._a2a_client._transport.httpx_client.headers.update( + httpx_client.headers.update( {VE_TIP_TOKEN_HEADER: tip_credential.api_key} ) logger.debug( @@ -404,15 +414,15 @@ async def _inject_auth_token(self, ctx: InvocationContext) -> None: if self.auth_method == "querystring": # Extract API key api_key = credential.api_key - new_params = dict(self._a2a_client._transport.httpx_client.params) + new_params = dict(httpx_client.params) new_params.update({"token": api_key}) - self._a2a_client._transport.httpx_client.params = new_params + httpx_client.params = new_params logger.debug( f"Injected auth token via querystring for app={ctx.app_name}, user={ctx.user_id}" ) else: if headers := generate_headers(credential): - self._a2a_client._transport.httpx_client.headers.update(headers) + httpx_client.headers.update(headers) logger.debug( f"Injected auth token via header for app={ctx.app_name}, user={ctx.user_id}" ) diff --git a/veadk/a2a/stores.py b/veadk/a2a/stores.py index 347f63e0f..3ecad2120 100644 --- a/veadk/a2a/stores.py +++ b/veadk/a2a/stores.py @@ -114,7 +114,11 @@ class OwnerScopedInMemoryTaskStore(TaskStore): """ def __init__(self, owner_resolver: OwnerResolver) -> None: - self._inner = InMemoryTaskStore() + # The inner store must use the same tenant-aware resolver so it + # filters by owner *before* paginating. Filtering after pagination + # would return an empty first page (with a next-page token) when the + # caller has more than ``page_size`` tasks in another tenant. + self._inner = InMemoryTaskStore(owner_resolver=owner_resolver) self._owners: dict[str, str] = {} self._owner_resolver = owner_resolver @@ -144,16 +148,8 @@ async def list( params: ListTasksRequest, context: ServerCallContext | None = None, ) -> ListTasksResponse: - owner = self._owner(context) - response = await self._inner.list(params, self._context(context)) - owned = [ - task for task in response.tasks if self._owners.get(task.id, owner) == owner - ] - result = ListTasksResponse() - result.CopyFrom(response) - del result.tasks[:] - result.tasks.extend(owned) - return result + # The inner store already scopes and paginates by owner. + return await self._inner.list(params, self._context(context)) async def delete( self, task_id: str, context: ServerCallContext | None = None diff --git a/veadk/a2a/tenant.py b/veadk/a2a/tenant.py index 88abb9066..d94eedd09 100644 --- a/veadk/a2a/tenant.py +++ b/veadk/a2a/tenant.py @@ -34,5 +34,9 @@ def apply_tenant(client: T, tenant: str) -> T: transport = getattr(client, "_transport", None) if transport is None: raise ValueError("The A2A client does not expose a transport to decorate") - client._transport = TenantTransportDecorator(transport, tenant) # noqa: SLF001 + # Unwrap any previous decorator so repeated resolution does not nest + # decorators (the shared client is cached and ``_ensure_resolved`` runs + # for every invocation). + base = getattr(transport, "_base", transport) + client._transport = TenantTransportDecorator(base, tenant) # noqa: SLF001 return client diff --git a/veadk/integrations/ve_faas/ve_faas.py b/veadk/integrations/ve_faas/ve_faas.py index 1952f6beb..f34046904 100644 --- a/veadk/integrations/ve_faas/ve_faas.py +++ b/veadk/integrations/ve_faas/ve_faas.py @@ -60,6 +60,11 @@ logger = get_logger(__name__) +# The FaaS template validates ``VEADK_A2A_PUBLIC_URL`` at import time, but the +# real public URL is only known after a release. Update paths seed this +# placeholder so a pre-existing app without the env can boot the new bundle. +PENDING_PUBLIC_URL = "http://veadk-a2a-public-url-pending.invalid" + _LARGE_CODE_BUNDLE_BYTES = 64 * 1024 * 1024 _STANDARD_CODE_UPLOAD_TIMEOUT_SECONDS = 300 _LARGE_CODE_UPLOAD_TIMEOUT_SECONDS = 1800 @@ -654,6 +659,19 @@ def _list_application(self, app_id: str = None, app_name: str = None): ) return all_items + def _ensure_public_url_env(self, function_id: str) -> None: + """Seed ``VEADK_A2A_PUBLIC_URL`` before releasing a new code bundle. + + ``merge_function_envs_and_release`` is idempotent: when the env is + already present it skips the update and the release. For an app + created before this env existed, it sets a syntactically valid + placeholder and releases once so the new code can boot. + """ + self.merge_function_envs_and_release( + function_id=function_id, + extra_envs={"VEADK_A2A_PUBLIC_URL": PENDING_PUBLIC_URL}, + ) + def update_application_code_bundle( self, *, @@ -698,6 +716,10 @@ def update_application_code_bundle( cpu_milli=cpu_milli, memory_mb=memory_mb, ) + # The template validates VEADK_A2A_PUBLIC_URL at import time. An app + # created before this env existed has no value, so the first release + # of the new code would crash before the real URL can be merged. + self._ensure_public_url_env(function_id) url = self._release_application(application_id) self._set_function_min_instance(function_id, max_instance=max_instance) if disable_gateway_cors: @@ -885,6 +907,7 @@ def _update_function_code( logger.info( f"VeFaaS function {function_name} with ID {function_id} updated." ) + self._ensure_public_url_env(function_id) url = self._release_application(app_id) self._set_function_min_instance(function_id) self.ensure_application_route_methods(app_id) @@ -1285,7 +1308,7 @@ def deploy( # the real public URL is only known after the first release. Seed # a syntactically valid placeholder so the first release can boot, # then replace it with the real URL and release again below. - pending_public_url = "http://veadk-a2a-public-url-pending.invalid" + pending_public_url = PENDING_PUBLIC_URL function_name, function_id = self._create_function( function_name, path, From 63902c4a0a1523d329770d6679016e67ed5a3c23 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 4 Dec 2026 11:14:18 +0800 Subject: [PATCH 18/22] fix(a2a): serve 1.x card at standard path for A2A Center --- tests/a2a/test_a2a_sdk_14.py | 28 ++++++++++++++++++++++ veadk/a2a/ve_a2a_server.py | 45 +++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py index 57555d86b..ac1623071 100644 --- a/tests/a2a/test_a2a_sdk_14.py +++ b/tests/a2a/test_a2a_sdk_14.py @@ -184,6 +184,34 @@ def test_ve_a2a_server_serves_both_card_paths(monkeypatch): ] == ["0.3", "1.0"] +def test_ve_a2a_server_standard_card_is_a2a_center_compatible(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + ) + client = TestClient(server.build()) + + # AgentKit A2A Center rejects a card that carries both the legacy + # top-level protocolVersion and the 1.x supportedInterfaces. + standard = client.get("/.well-known/agent-card.json") + assert standard.status_code == 200 + payload = standard.json() + assert "protocolVersion" not in payload + assert {i["protocolVersion"] for i in payload["supportedInterfaces"]} == { + "0.3", + "1.0", + } + assert payload["url"] == "https://example.com" + + # 0.3 clients keep the historical shape on the legacy path. + legacy = client.get("/.well-known/agent.json") + assert legacy.status_code == 200 + assert legacy.json()["protocolVersion"] == "0.3" + + def test_ve_a2a_server_can_disable_v0_3(monkeypatch): _patch_server_dependencies(monkeypatch) server = VeA2AServer( diff --git a/veadk/a2a/ve_a2a_server.py b/veadk/a2a/ve_a2a_server.py index 558fb4459..abdcb2a93 100644 --- a/veadk/a2a/ve_a2a_server.py +++ b/veadk/a2a/ve_a2a_server.py @@ -12,10 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +import hashlib +import json import os from contextlib import asynccontextmanager from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.request_handlers.response_helpers import agent_card_to_dict from a2a.server.routes import ( add_a2a_routes_to_fastapi, create_agent_card_routes, @@ -25,6 +28,9 @@ from a2a.types import AgentCard, AgentSkill from a2a.utils.errors import UnsupportedOperationError from fastapi import FastAPI +from starlette.requests import Request +from starlette.responses import Response +from starlette.routing import Route from veadk import Agent from veadk.a2a.agent_card import get_agent_card @@ -55,6 +61,20 @@ __all__ = ["A2AServerConfig", "VeA2AServer", "init_app"] +def _agent_card_1x_payload(agent_card: AgentCard) -> dict: + """Return a 1.x-shaped AgentCard payload accepted by AgentKit A2A Center. + + a2a-sdk's compatibility layer injects a top-level ``protocolVersion`` next + to ``supportedInterfaces``. AgentKit A2A Center rejects that combination + with ``protocolVersion and supportedInterfaces cannot be used together``. + Keep the legacy shape at ``/.well-known/agent.json`` and serve this 1.x + shape at the standard card path. + """ + payload = agent_card_to_dict(agent_card) + payload.pop("protocolVersion", None) + return payload + + def _resolve_public_url(server_url: str) -> str: """Resolve the public URL advertised in the AgentCard. @@ -176,7 +196,18 @@ async def _lifespan(self, _app: FastAPI): await self.stores.close() def build(self) -> FastAPI: - card_routes = [*create_agent_card_routes(self.agent_card)] + # The standard card path must be 1.x-shaped for AgentKit A2A Center + # registration. a2a-sdk's create_agent_card_routes always merges the + # legacy ``protocolVersion`` back in, which the center rejects when + # ``supportedInterfaces`` is also present. Serve the 1.x payload directly + # and keep the merged legacy card on the historical path below. + card_routes = [ + Route( + "/.well-known/agent-card.json", + endpoint=self._serve_1x_agent_card, + methods=["GET"], + ) + ] if self.config.compat_v0_3: # a2a-sdk 0.3.x served both paths; keep the historical one so # existing discovery code keeps working after the upgrade. @@ -233,6 +264,18 @@ def build(self) -> FastAPI: ) return app + async def _serve_1x_agent_card(self, request: Request) -> Response: + payload = _agent_card_1x_payload(self.agent_card) + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + etag = f'"{hashlib.sha256(body.encode("utf-8")).hexdigest()[:32]}"' + if request.headers.get("if-none-match") == etag: + return Response(status_code=304, headers={"ETag": etag}) + return Response( + content=body, + media_type="application/json", + headers={"ETag": etag}, + ) + def init_app( server_url: str, From 16c90b36200fa9921051ac6c726ebc7de6d00322 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 4 Dec 2026 11:26:31 +0800 Subject: [PATCH 19/22] fix(a2a): allow overriding AgentCard version for A2A Center --- tests/a2a/test_a2a_sdk_14.py | 14 ++++++++++++++ veadk/a2a/config.py | 5 +++++ veadk/a2a/ve_a2a_server.py | 2 ++ 3 files changed, 21 insertions(+) diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py index ac1623071..7e1e4ec47 100644 --- a/tests/a2a/test_a2a_sdk_14.py +++ b/tests/a2a/test_a2a_sdk_14.py @@ -212,6 +212,20 @@ def test_ve_a2a_server_standard_card_is_a2a_center_compatible(monkeypatch): assert legacy.json()["protocolVersion"] == "0.3" +def test_ve_a2a_server_can_override_card_version(monkeypatch): + _patch_server_dependencies(monkeypatch) + server = VeA2AServer( + agent=_agent(), + url="https://example.com", + app_name="app", + short_term_memory=object(), + config=A2AServerConfig(card_version="1.2.3"), + ) + client = TestClient(server.build()) + assert client.get("/.well-known/agent-card.json").json()["version"] == "1.2.3" + assert client.get("/.well-known/agent.json").json()["version"] == "1.2.3" + + def test_ve_a2a_server_can_disable_v0_3(monkeypatch): _patch_server_dependencies(monkeypatch) server = VeA2AServer( diff --git a/veadk/a2a/config.py b/veadk/a2a/config.py index a4423d2d0..bcfa83951 100644 --- a/veadk/a2a/config.py +++ b/veadk/a2a/config.py @@ -172,6 +172,9 @@ class A2AServerConfig: server-side policy checks. * ``extensions`` declares (and, with validation on, requires) extensions. * ``extended_card_skills`` builds the authenticated extended card. + * ``card_version`` overrides the AgentCard version; use a valid semver + (for example ``1.0.0``) when the package version is a local/dev build, + because AgentKit A2A Center rejects non-semver card versions. * ``signing`` signs the AgentCard (local key or KMS). * ``security_schemes`` / ``security_requirements`` declare auth metadata. * ``oidc_*`` / ``require_auth`` enforce bearer-token authentication. @@ -183,6 +186,8 @@ class A2AServerConfig: compat_v0_3: bool = True docs_enabled: bool = False + # AgentCard version override (must be a valid semantic version) + card_version: str | None = None # HTTP+JSON transport rest_enabled: bool = False rest_path_prefix: str = "/v1" diff --git a/veadk/a2a/ve_a2a_server.py b/veadk/a2a/ve_a2a_server.py index abdcb2a93..16792c2ea 100644 --- a/veadk/a2a/ve_a2a_server.py +++ b/veadk/a2a/ve_a2a_server.py @@ -43,6 +43,7 @@ from veadk.memory.short_term_memory import ShortTermMemory from veadk.runner import Runner from veadk.utils.logger import get_logger +from veadk.version import VERSION from google.adk.a2a.executor.a2a_agent_executor import A2aAgentExecutor from google.adk.auth.credential_service.base_credential_service import ( @@ -122,6 +123,7 @@ def __init__( self.agent_card = get_agent_card( agent, _resolve_public_url(url), + version=self.config.card_version or VERSION, compat_v0_3=self.config.compat_v0_3, push_notifications=self.config.push_enabled, extensions=self.config.extensions, From f0c83cd9a0d6d2167d5ae521f0d4f19e6dcc768b Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 4 Dec 2026 12:30:15 +0800 Subject: [PATCH 20/22] chore: require agentkit-sdk-python>=0.9.5 --- pyproject.toml | 4 ++-- uv.lock | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 46bd24f2f..e9322966e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,7 +55,7 @@ dependencies = [ "python-docx>=1.1.0,<2", # Read and write Word documents in document_parse/doc_generate "openpyxl>=3.1.0,<4", # Read and write Excel workbooks in document_parse/doc_generate "vikingdb-python-sdk>=0.1.32", # For Viking DB - "agentkit-sdk-python>=0.9.3", + "agentkit-sdk-python>=0.9.5", "websockets>=15,<16", # Stream temporary AgentKit Sandbox conversations "openviking-sdk>=0.1.9", "python-frontmatter==1.1.0", @@ -136,7 +136,7 @@ harness = [ "headroom", ] harness-sidecar = [ - "agentkit-sdk-python>=0.9.3", + "agentkit-sdk-python>=0.9.5", ] cli = [] sandbox = [ diff --git a/uv.lock b/uv.lock index 710353c99..88f3b9ee6 100644 --- a/uv.lock +++ b/uv.lock @@ -86,7 +86,7 @@ wheels = [ [[package]] name = "agentkit-sdk-python" -version = "0.9.3" +version = "0.9.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "a2a-sdk" }, @@ -115,9 +115,9 @@ dependencies = [ { name = "volcengine" }, { name = "websocket-client" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c5/27/60815e26bdd089f2f88fd5778c5d9a3da13d2f1b06a2dc0f5f6bac2d8488/agentkit_sdk_python-0.9.3.tar.gz", hash = "sha256:36e55d44f2550dca7461c5c0d7d8cba5120dd8b211ab432ef05a068ec8556121", size = 633954, upload-time = "2026-12-03T03:49:06.568Z" } +sdist = { url = "https://files.pythonhosted.org/packages/eb/0b/75d3aab892d79d62ce07f9e55e72cb2f36e8bcec99ea09bda6bae852b8a8/agentkit_sdk_python-0.9.5.tar.gz", hash = "sha256:5d70e46359e4389468ffb5faa25479a0a96653b5be6509202c52e2b875aae37b", size = 634307, upload-time = "2026-12-04T04:24:30.144Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/63/4d/835da28f0d4d18d88fb0f897a90c2a1e17e6577b64eca9d98dc81e167c61/agentkit_sdk_python-0.9.3-py3-none-any.whl", hash = "sha256:6c46757666617a09bfa0ad5c574f99f94a361c5769fcf8856dee8f74b2a46917", size = 854551, upload-time = "2026-12-03T03:49:05.015Z" }, + { url = "https://files.pythonhosted.org/packages/bb/14/67c4aa2e05d75e155e01972de35c5566af403910409343461aa93cef5988/agentkit_sdk_python-0.9.5-py3-none-any.whl", hash = "sha256:878b82d8474b28c5bbaba6d50c8d9cee2d09e37b9febc3f5a377d207940a2eb5", size = 855086, upload-time = "2026-12-04T04:24:28.528Z" }, ] [[package]] @@ -6227,8 +6227,8 @@ requires-dist = [ { name = "a2a-sdk", extras = ["http-server"], specifier = ">=1.4.0,<1.5.0" }, { name = "a2ui-agent-sdk", marker = "extra == 'a2ui'", specifier = ">=0.2.1" }, { name = "agent-pilot-sdk", specifier = "==0.1.2" }, - { name = "agentkit-sdk-python", specifier = ">=0.9.3" }, - { name = "agentkit-sdk-python", marker = "extra == 'harness-sidecar'", specifier = ">=0.9.3" }, + { name = "agentkit-sdk-python", specifier = ">=0.9.5" }, + { name = "agentkit-sdk-python", marker = "extra == 'harness-sidecar'", specifier = ">=0.9.5" }, { name = "aiomysql", specifier = "==0.3.2" }, { name = "anthropic", marker = "extra == 'sandbox'", specifier = ">=0.40.0" }, { name = "async-timeout", marker = "python_full_version < '3.11'", specifier = ">=5,<6" }, From 8a6855aebf6662205ee0bbcdfd31c0d9ee923537 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 4 Dec 2026 12:40:45 +0800 Subject: [PATCH 21/22] test: update agentkit-sdk-python baseline to 0.9.5 --- tests/cli/test_studio_tos_sdk_dependency.py | 4 +++- tests/extensions/harness/test_sidecar_wheel.py | 4 ++-- tests/test_runtime_dependency_compatibility.py | 6 +++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/cli/test_studio_tos_sdk_dependency.py b/tests/cli/test_studio_tos_sdk_dependency.py index adb3a4be5..04651f75b 100644 --- a/tests/cli/test_studio_tos_sdk_dependency.py +++ b/tests/cli/test_studio_tos_sdk_dependency.py @@ -34,5 +34,7 @@ def test_studio_requires_agentkit_sdk_with_tos_credential_type() -> None: # TOS credential type landed in agentkit-sdk-python 0.8.5; the declared floor # must stay at or above it while still admitting the currently required line. - assert requirement.specifier.contains("0.9.3") + # 0.9.5 is the first release with the A2A Center card compatibility fix. + assert requirement.specifier.contains("0.9.5") + assert not requirement.specifier.contains("0.9.3") assert not requirement.specifier.contains("0.8.4") diff --git a/tests/extensions/harness/test_sidecar_wheel.py b/tests/extensions/harness/test_sidecar_wheel.py index 292b40ac4..574813aae 100644 --- a/tests/extensions/harness/test_sidecar_wheel.py +++ b/tests/extensions/harness/test_sidecar_wheel.py @@ -110,7 +110,7 @@ def test_wheel_metadata_keeps_sidecar_optional_and_sdk_constraints_aligned( if canonicalize_name(item.name) == "agentkit-sdk-python" ] assert any( - item.marker is None and ">=0.9.3" in str(item.specifier) + item.marker is None and ">=0.9.5" in str(item.specifier) for item in sdk_requirements ) sidecar_extra = [ @@ -119,7 +119,7 @@ def test_wheel_metadata_keeps_sidecar_optional_and_sdk_constraints_aligned( if item.marker is not None and "harness-sidecar" in str(item.marker) ] assert len(sidecar_extra) == 1 - assert ">=0.9.3" in str(sidecar_extra[0].specifier) + assert ">=0.9.5" in str(sidecar_extra[0].specifier) forbidden = { "agentkit-harness-sidecar-integration", diff --git a/tests/test_runtime_dependency_compatibility.py b/tests/test_runtime_dependency_compatibility.py index c43dd63f8..b2c268b7b 100644 --- a/tests/test_runtime_dependency_compatibility.py +++ b/tests/test_runtime_dependency_compatibility.py @@ -24,7 +24,7 @@ ROOT = Path(__file__).resolve().parents[1] GOOGLE_ADK_BASELINE = "google-adk>=2.7.0,<2.15.0" GOOGLE_ADK_EVAL_BASELINE = "google-adk[eval]>=2.7.0,<2.15.0" -AGENTKIT_BASELINE = "agentkit-sdk-python>=0.9.3" +AGENTKIT_BASELINE = "agentkit-sdk-python>=0.9.5" OPENTELEMETRY_EXPORTER_BASELINE = "opentelemetry-exporter-otlp>=1.37.0,<1.43" OPENTELEMETRY_EXPORTER_LOCK_BASELINE = ( '{ name = "opentelemetry-exporter-otlp", specifier = ">=1.37.0,<1.43" }' @@ -50,10 +50,10 @@ def test_project_dependency_metadata_uses_runtime_compatibility_baseline() -> No def test_lock_metadata_matches_project_dependency_baseline() -> None: lock = (ROOT / "uv.lock").read_text(encoding="utf-8") - assert '{ name = "agentkit-sdk-python", specifier = ">=0.9.3" }' in lock + assert '{ name = "agentkit-sdk-python", specifier = ">=0.9.5" }' in lock assert ( '{ name = "agentkit-sdk-python", marker = "extra == ' - '\'harness-sidecar\'", specifier = ">=0.9.3" }' + '\'harness-sidecar\'", specifier = ">=0.9.5" }' ) in lock assert '{ name = "google-adk", specifier = ">=2.7.0,<2.15.0" }' in lock assert ( From ed3de7f9cc2c853a5f120eee1c0ff47db3677d69 Mon Sep 17 00:00:00 2001 From: "wujiaming.ai" Date: Fri, 4 Dec 2026 13:07:35 +0800 Subject: [PATCH 22/22] fix(a2a): serve 1.x card from to_a2a standard path --- tests/a2a/test_a2a_sdk_14.py | 15 ++++++++---- veadk/a2a/utils/agent_to_a2a.py | 42 +++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/tests/a2a/test_a2a_sdk_14.py b/tests/a2a/test_a2a_sdk_14.py index 7e1e4ec47..71565ff07 100644 --- a/tests/a2a/test_a2a_sdk_14.py +++ b/tests/a2a/test_a2a_sdk_14.py @@ -358,15 +358,22 @@ def test_load_agent_card_passes_through_object(): def test_to_a2a_serves_dual_stack_card(): app = to_a2a(EchoAgent(name="echo"), host="127.0.0.1", port=8000) with TestClient(app) as client: - card = client.get("/.well-known/agent-card.json") - assert card.status_code == 200 - body = card.json() + standard = client.get("/.well-known/agent-card.json") + assert standard.status_code == 200 + body = standard.json() assert {i["protocolVersion"] for i in body["supportedInterfaces"]} == { "0.3", "1.0", } assert body["url"] == "http://127.0.0.1:8000" - assert client.get("/.well-known/agent.json").status_code == 200 + + # AgentKit A2A Center rejects a card that carries both the legacy + # top-level protocolVersion and the 1.x supportedInterfaces. + assert "protocolVersion" not in body + + legacy = client.get("/.well-known/agent.json") + assert legacy.status_code == 200 + assert legacy.json()["protocolVersion"] == "0.3" def test_to_a2a_accepts_custom_v0_3_card(tmp_path): diff --git a/veadk/a2a/utils/agent_to_a2a.py b/veadk/a2a/utils/agent_to_a2a.py index 523d8ece1..b2701ce16 100644 --- a/veadk/a2a/utils/agent_to_a2a.py +++ b/veadk/a2a/utils/agent_to_a2a.py @@ -15,6 +15,7 @@ from __future__ import annotations import copy +import hashlib import json from contextlib import asynccontextmanager from pathlib import Path @@ -22,6 +23,7 @@ from a2a.client.card_resolver import parse_agent_card from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.request_handlers.response_helpers import agent_card_to_dict from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes from a2a.server.tasks import InMemoryTaskStore from a2a.types import AgentCard, AgentInterface @@ -38,6 +40,9 @@ from google.adk.runners import Runner as AdkRunner from google.adk.sessions.in_memory_session_service import InMemorySessionService from starlette.applications import Starlette +from starlette.requests import Request +from starlette.responses import Response +from starlette.routing import Route from veadk import Runner from veadk.a2a.ve_middlewares import build_a2a_auth_middleware @@ -51,6 +56,24 @@ _PREV_AGENT_CARD_WELL_KNOWN_PATH = "/.well-known/agent.json" +def _agent_card_1x_payload(card: AgentCard) -> dict: + """Return a 1.x-shaped AgentCard payload accepted by AgentKit A2A Center. + + a2a-sdk's compatibility layer injects a top-level ``protocolVersion`` next + to ``supportedInterfaces``. AgentKit A2A Center rejects that combination + with ``protocolVersion and supportedInterfaces cannot be used together``. + Keep the merged 0.3 card on the legacy path and serve this 1.x payload on + the standard card path. + """ + payload = agent_card_to_dict(card) + payload.pop("protocolVersion", None) + # Keep the legacy ``url`` for clients that do not understand + # ``supportedInterfaces`` yet (for example a 1.0-only card). + if not payload.get("url") and payload.get("supportedInterfaces"): + payload["url"] = payload["supportedInterfaces"][0]["url"] + return payload + + def _load_agent_card(agent_card: Union[AgentCard, str, None]) -> Optional[AgentCard]: """Load a caller-provided AgentCard from an object or a JSON path.""" if agent_card is None: @@ -206,10 +229,25 @@ async def setup_a2a(app: Starlette) -> None: task_store=task_store, agent_card=final_card, ) + + async def _serve_1x_card(request: Request) -> Response: + payload = _agent_card_1x_payload(final_card) + body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + etag = f'"{hashlib.sha256(body.encode("utf-8")).hexdigest()[:32]}"' + if request.headers.get("if-none-match") == etag: + return Response(status_code=304, headers={"ETag": etag}) + return Response( + content=body, + media_type="application/json", + headers={"ETag": etag}, + ) + app.routes.extend( [ - *create_agent_card_routes( - final_card, card_url=_AGENT_CARD_WELL_KNOWN_PATH + Route( + _AGENT_CARD_WELL_KNOWN_PATH, + endpoint=_serve_1x_card, + methods=["GET"], ), *create_agent_card_routes( final_card, card_url=_PREV_AGENT_CARD_WELL_KNOWN_PATH