Skip to content

Agent Mesh

sdk/python: accept A2A for the agent, stop publishing services

Antonio Ojea20866aaf3a70
diff --git a/sdk/python/examples/agent.py b/sdk/python/examples/agent.py
new file mode 100644
index 00000000..86677d88
--- /dev/null
+++ b/sdk/python/examples/agent.py
@@ -0,0 +1,50 @@
+"""An agent on the mesh: joins, then answers A2A requests from other members
+until stopped. It publishes nothing. There is no service name to look up; a
+caller reaches the agent by its peer ID, through a router, as `a2a://agent`.
+The mesh policy decides which members may call; the SDK turns the others away
+before anything reaches this code.
+
+ python agent.py # answered by the handler below
+ python agent.py http://127.0.0.1:9999 # forwarded to an A2A server beside it
+
+SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
+SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or SAM_JWT_PATH
+(a workload identity token your platform issues, such as a Kubernetes
+projected service account token), and keeps the identity and credential in
+SAM_STATE_DIR; later runs resume from there, as the same peer, without it.
+"""
+
+import json
+import os
+import sys
+
+import trio
+from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, VerifiedBiscuit
+
+backend_url = sys.argv[1] if len(sys.argv) > 1 else None
+
+mesh = AgentMesh.enroll(
+ os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
+ bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
+ jwt_path=os.environ.get("SAM_JWT_PATH"),
+ state_dir=os.environ.get("SAM_STATE_DIR", "~/.config/sam-mesh/agent"),
+ # A plaintext http:// control plane is otherwise accepted only on loopback.
+ allow_insecure=os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "true",
+)
+
+
+async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
+ """Answers every path with who was asked and who asked; a real agent runs
+ an A2A server here, or beside this process at backend_url."""
+ body = json.dumps({"name": "agent", "path": request.path, "caller": caller.peer_id})
+ return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
+
+
+async def main() -> None:
+ async with mesh.join() as session:
+ target = await session.accept_a2a(backend_url or card)
+ print(f"accepting {target} as {session.peer_id}", flush=True)
+ await trio.sleep_forever()
+
+
+trio.run(main)
diff --git a/sdk/python/examples/call.py b/sdk/python/examples/call.py
index 8a1ca068..43a2ef05 100644
--- a/sdk/python/examples/call.py
+++ b/sdk/python/examples/call.py
@@ -1,9 +1,10 @@
-"""Finds a service on the mesh and calls it: a tool of an MCP service, or a
-path of an inference or A2A service.
+"""Calls something on the mesh: a tool of an MCP service or a path of an
+inference or A2A service someone published, found by name, or an agent that
+published nothing, reached by its peer ID.
python call.py mcp://greeter greet '{"name": "Ada"}'
- python call.py a2a://greeter /card
python call.py inference://ollama /v1/models
+ python call.py 12D3KooW... a2a://agent /card
SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or SAM_JWT_PATH
@@ -20,8 +21,12 @@ import trio
from agent_mesh import AgentMesh
argv = sys.argv[1:]
-service = argv[0] if len(argv) > 0 else "mcp://greeter"
-tool_or_path = argv[1] if len(argv) > 1 else "greet"
+# A first argument that is not a service target is the peer ID of an agent.
+peer_id = None
+if argv and "://" not in argv[0]:
+ peer_id, argv = argv[0], argv[1:]
+service = argv[0] if len(argv) > 0 else ("a2a://agent" if peer_id else "mcp://greeter")
+tool_or_path = argv[1] if len(argv) > 1 else ("/card" if peer_id else "greet")
args = json.loads(argv[2]) if len(argv) > 2 else {"name": "world"}
mesh = AgentMesh.enroll(
@@ -38,19 +43,25 @@ async def main() -> None:
async with mesh.join() as session:
print(f"on the mesh as {session.peer_id}")
- providers = await session.discover(service)
- if not providers:
- raise SystemExit(f"no member of the mesh serves {service}")
- # A provider record can outlive its member; the first that answers is used.
- for provider in providers:
- try:
- await session.connect(provider)
- break
- except (ConnectionError, PermissionError) as err:
- print(f"{provider.peer_id}: {err}", file=sys.stderr)
+ if peer_id:
+ # An agent is not in the discovery table; the SDK finds the path
+ # to its peer ID through the routers.
+ await session.connect(peer_id)
+ provider = peer_id
else:
- raise SystemExit(f"no provider of {service} is reachable")
- print(f"{service} is served by {provider.peer_id}")
+ providers = await session.discover(service)
+ if not providers:
+ raise SystemExit(f"no member of the mesh serves {service}")
+ # A provider record can outlive its member; the first that answers is used.
+ for provider in providers:
+ try:
+ await session.connect(provider)
+ break
+ except (ConnectionError, PermissionError) as err:
+ print(f"{provider.peer_id}: {err}", file=sys.stderr)
+ else:
+ raise SystemExit(f"no provider of {service} is reachable")
+ print(f"{service} is served by {peer_id or provider.peer_id}")
if service.startswith("mcp://"):
tools = await session.list_tools(provider, service)
diff --git a/sdk/python/examples/serve.py b/sdk/python/examples/serve.py
deleted file mode 100644
index 6821732a..00000000
--- a/sdk/python/examples/serve.py
+++ /dev/null
@@ -1,64 +0,0 @@
-"""Publishes services on the mesh and answers callers until stopped: an MCP
-tool, an A2A endpoint and, when OLLAMA_URL is set, the Ollama server running
-beside this program as an inference service. The mesh policy decides which
-members may call; the SDK turns the others away before anything reaches this
-code or Ollama.
-
- python serve.py # publishes mcp://greeter and a2a://greeter
- python serve.py greeter-2 # the same under another name
-
-SAM_CONTROL_PLANE_URL names the mesh. The first run enrolls with the file
-SAM_BOOTSTRAP_TOKEN_PATH (a token the mesh operator gave you) or SAM_JWT_PATH
-(a workload identity token your platform issues, such as a Kubernetes
-projected service account token), and keeps the identity and credential in
-SAM_STATE_DIR; later runs resume from there without it.
-"""
-
-import json
-import os
-import sys
-
-import trio
-from agent_mesh import AgentMesh, HTTPRequest, HTTPResponse, HTTPService, MCPService, VerifiedBiscuit
-from mcp.server.mcpserver import MCPServer
-
-service_name = sys.argv[1] if len(sys.argv) > 1 else "greeter"
-
-mesh = AgentMesh.enroll(
- os.environ.get("SAM_CONTROL_PLANE_URL", "https://mesh.example.com"),
- bootstrap_token_path=os.environ.get("SAM_BOOTSTRAP_TOKEN_PATH"),
- jwt_path=os.environ.get("SAM_JWT_PATH"),
- state_dir=os.environ.get("SAM_STATE_DIR", f"~/.config/sam-mesh/{service_name}"),
- # A plaintext http:// control plane is otherwise accepted only on loopback.
- allow_insecure=os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "true",
-)
-
-
-def create_server() -> MCPServer:
- server = MCPServer(service_name)
-
- @server.tool(description="Greets someone by name")
- def greet(name: str) -> str:
- return f"hello {name}"
-
- return server
-
-
-async def card(request: HTTPRequest, caller: VerifiedBiscuit) -> HTTPResponse:
- body = json.dumps({"name": service_name, "path": request.path, "caller": caller.peer_id})
- return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
-
-
-async def main() -> None:
- async with mesh.join() as session:
- await session.serve(MCPService(name=service_name, create_server=create_server))
- await session.serve(HTTPService(type="a2a", name=service_name, target=card))
- if "OLLAMA_URL" in os.environ:
- await session.serve(HTTPService(type="inference", name="ollama", target=os.environ["OLLAMA_URL"]))
-
- served = ", ".join(f"{t}://{n}" for t, n, _ in session.services.list())
- print(f"serving {served} as {session.peer_id}", flush=True)
- await trio.sleep_forever()
-
-
-trio.run(main)
diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.py
index 3fdf0c1e..08979a2a 100644
--- a/sdk/python/src/agent_mesh/__init__.py
+++ b/sdk/python/src/agent_mesh/__init__.py
@@ -30,30 +30,33 @@ from .controlplane import (
verify_keys_response,
)
from .credential import MeshCredential, decode_auth_response, encode_auth_frame
-from .discovery import DHT_PROTOCOL, DiscoveredProvider, find_providers, parse_service_target, provide, service_key
+from .discovery import DHT_PROTOCOL, DiscoveredProvider, find_providers, parse_service_target, service_key
+from .httpx_transport import MESH_PATH_PREFIX, MeshTransport, split_mesh_url
from .identity import Identity, canonical_peer_id, libp2p_public_key, peer_id_from_public_key, verify_ed25519
-from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, ToolInfo, open_mcp_session, require_labels
-from .mesh import AgentMesh, ControlPlaneSync
-from .relay import dial_through_relay, reserve_relay
-from .serve import (
+from .libp2p_http import (
+ DEFAULT_A2A_NAME,
HTTP_PROTOCOL,
+ A2AEndpoint,
HTTPHandler,
HTTPRequest,
HTTPResponse,
- HTTPService,
- MCPService,
ProviderOptions,
- ServiceRegistry,
+ StreamedResponse,
http_ingress_handler,
http_request_over_stream,
- mcp_stream_handler,
+ mesh_http_target,
+ open_http_request,
)
+from .mcp_client import LabelsNotSatisfiedError, ToolCallResult, ToolInfo, open_mcp_session, require_labels
+from .mesh import AgentMesh, ControlPlaneSync
+from .relay import dial_through_relay, reserve_relay
from .session import AdmittedRouter, MeshSession, Peer
from .sync import GOSSIP_EVENTS_TOPIC, BanSet, verify_mesh_event
__version__ = "0.1.0"
__all__ = [
+ "A2AEndpoint",
"AUTH_PROTOCOL",
"AdmittedRouter",
"AgentMesh",
@@ -66,6 +69,7 @@ __all__ = [
"ControlPlaneClient",
"ControlPlaneError",
"ControlPlaneSync",
+ "DEFAULT_A2A_NAME",
"DHT_PROTOCOL",
"DiscoveredProvider",
"Enrollment",
@@ -75,21 +79,21 @@ __all__ = [
"HTTPHandler",
"HTTPRequest",
"HTTPResponse",
- "HTTPService",
"Identity",
"InsecureControlPlaneURLError",
"LabelsNotSatisfiedError",
"MCP_PROTOCOL",
- "MCPService",
+ "MESH_PATH_PREFIX",
"MeshCredential",
"MeshSession",
+ "MeshTransport",
"Peer",
"ProviderAuthorizerOptions",
"ProviderOptions",
"ROLE_NODE",
"ROLE_ROUTER",
"RefreshResult",
- "ServiceRegistry",
+ "StreamedResponse",
"ToolCallResult",
"ToolInfo",
"VerifiedBiscuit",
@@ -106,17 +110,18 @@ __all__ = [
"http_ingress_handler",
"http_request_over_stream",
"libp2p_public_key",
- "mcp_stream_handler",
+ "mesh_http_target",
+ "open_http_request",
"open_mcp_session",
"parse_service_target",
"peer_id_from_public_key",
- "provide",
"refresh_challenge",
"register_challenge",
"require_labels",
"require_role",
"reserve_relay",
"service_key",
+ "split_mesh_url",
"validate_control_plane_url",
"verify_ed25519",
"verify_keys_response",
diff --git a/sdk/python/src/agent_mesh/conformance_join.py b/sdk/python/src/agent_mesh/conformance_join.py
index 046cce10..cd69fabd 100644
--- a/sdk/python/src/agent_mesh/conformance_join.py
+++ b/sdk/python/src/agent_mesh/conformance_join.py
@@ -25,14 +25,12 @@ then takes JSON commands on stdin, one per line, until stdin closes:
list a provider's tools
{"cmd": "call", "addr": "<multiaddr>", "service": "mcp://calc",
"tool": "add", "args": {...}} call one tool
- {"cmd": "serve", "type": "mcp", "name": "echo"}
- publish an MCP service with an echo
- tool served in this process
- {"cmd": "serve", "type": "inference", "name": "llm", "target": "<url>"}
- publish an HTTP service; without
- target, a fake in this process
- {"cmd": "http", "addr": "<multiaddr>", "service": "inference://llm",
- "path": "/v1/models", "method": "GET", "body": "..."}
+ {"cmd": "accept", "name": "agent", "target": "<url>"}
+ accept A2A requests for this
+ member's agent; without target, a
+ handler in this process answers
+ {"cmd": "http", "addr": "<multiaddr>", "service": "a2a://agent",
+ "path": "/card", "method": "GET", "body": "..."}
call an HTTP service over the mesh
{"cmd": "peers"} peers that authenticated to us
{"cmd": "sync"} pull keys, bans and routers from
@@ -52,10 +50,9 @@ import sys
import traceback
import trio
-from mcp.server.mcpserver import MCPServer
+from .libp2p_http import DEFAULT_A2A_NAME, HTTPRequest, HTTPResponse
from .mesh import AgentMesh
-from .serve import HTTPRequest, HTTPResponse, HTTPService, MCPService
from .session import MeshSession
@@ -118,34 +115,17 @@ async def _handle(session: MeshSession, command: dict) -> dict:
}
if cmd == "banned":
return {"cmd": cmd, "ok": True, "banned": session.banned.peers(), "authenticated_peers": sorted(session.authenticated_peers)}
- if cmd == "serve":
- name = command.get("name", "")
- service_type = command.get("type")
- if service_type == "mcp":
-
- def create_server() -> MCPServer:
- server = MCPServer(name)
-
- @server.tool()
- def echo(text: str) -> str:
- return f"python:{text}"
-
- return server
-
- await session.serve(MCPService(name=name, create_server=create_server, description="echo served by the python SDK"))
- elif service_type in ("inference", "a2a"):
- target = command.get("target")
- if not target:
-
- async def fake(request: HTTPRequest, caller) -> HTTPResponse: # type: ignore[no-untyped-def]
- body = json.dumps({"sdk": "python", "peer": caller.peer_id, "method": request.method, "path": request.path.split("?")[0]})
- return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
-
- target = fake
- await session.serve(HTTPService(type=service_type, name=name, target=target, description=f"{service_type} served by the python SDK"))
- else:
- return {"cmd": cmd, "ok": False, "error": f"unknown service type {service_type!r}"}
- return {"cmd": cmd, "ok": True, "services": [f"{t}://{n}" for t, n, _ in session.services.list()]}
+ if cmd == "accept":
+ target = command.get("target")
+ if not target:
+
+ async def fake(request: HTTPRequest, caller) -> HTTPResponse: # type: ignore[no-untyped-def]
+ body = json.dumps({"sdk": "python", "peer": caller.peer_id, "method": request.method, "path": request.path.split("?")[0]})
+ return HTTPResponse(status=200, headers={"content-type": "application/json"}, body=body.encode())
+
+ target = fake
+ service = await session.accept_a2a(target, name=command.get("name", DEFAULT_A2A_NAME))
+ return {"cmd": cmd, "ok": True, "service": service}
if cmd == "http":
with trio.fail_after(15):
res = await session.request(
diff --git a/sdk/python/src/agent_mesh/controlplane.py b/sdk/python/src/agent_mesh/controlplane.py
index b9c53a41..ce063dc0 100644
--- a/sdk/python/src/agent_mesh/controlplane.py
+++ b/sdk/python/src/agent_mesh/controlplane.py
@@ -288,19 +288,6 @@ class ControlPlaneClient:
raise ValueError("control plane predates datalog_rules in its policy response; upgrade the control plane")
return list(resp.datalog_rules)
- def report_catalog(self, biscuit: bytes, services: Sequence[tuple[str, str, str]]) -> None:
- """POST /nodes/catalog: this member's published services as (type, name,
- description), for the console. Display only; the control plane takes
- the reporting peer from the biscuit."""
- types = {"mcp": pb.SERVICE_TYPE_MCP, "inference": pb.SERVICE_TYPE_INFERENCE, "a2a": pb.SERVICE_TYPE_A2A}
- report = pb.NodeCatalogReport(services=[pb.ServiceInfo(type=types[t], name=n, description=d) for t, n, d in services])
- self._request(
- "POST",
- "/nodes/catalog",
- report.SerializeToString(),
- headers={"Authorization": "Bearer " + base64.b64encode(biscuit).decode()},
- )
-
def _request(self, method: str, path: str, body: Optional[bytes] = None, headers: Optional[Mapping[str, str]] = None) -> bytes:
all_headers = {"Accept": PROTOBUF_CONTENT_TYPE, **(headers or {})}
if body is not None:
diff --git a/sdk/python/src/agent_mesh/discovery.py b/sdk/python/src/agent_mesh/discovery.py
index fa39c87b..9a97292f 100644
--- a/sdk/python/src/agent_mesh/discovery.py
+++ b/sdk/python/src/agent_mesh/discovery.py
@@ -16,14 +16,14 @@
record in the mesh DHT under a key derived from the service. The lookup is a
bounded Kademlia GET_PROVIDERS walk spoken directly on go-libp2p-kad-dht's
protocol: py-libp2p 0.7's DHT client hardcodes the /ipfs prefix and the mesh
-uses /sam."""
+uses /sam. An SDK member only looks records up; it announces none."""
from __future__ import annotations
import hashlib
import logging
from dataclasses import dataclass, field
-from typing import Iterable, Literal, Sequence
+from typing import Iterable, Literal
import multiaddr
import trio
@@ -143,56 +143,3 @@ async def find_providers(host: IHost, key: bytes, seeds: Iterable[ID], limit: in
if found:
break
return list(found.values())
-
-
-async def _add_provider(host: IHost, peer_id: ID, key: bytes, addrs: Sequence[multiaddr.Multiaddr]) -> bool:
- """Sends one ADD_PROVIDER for key naming ourselves. go-libp2p-kad-dht
- stores the record only when the sender is the provider and lists at
- least one address, and answers nothing."""
- try:
- stream = await open_stream(host, peer_id, DHT_PROTOCOL, _QUERY_TIMEOUT)
- except Exception as err: # noqa: BLE001 - a peer that does not serve the DHT is skipped
- logger.debug("dht: %s does not answer %s: %s", peer_id, DHT_PROTOCOL, err)
- return False
- try:
- with trio.fail_after(_QUERY_TIMEOUT):
- msg = kad.Message(type=kad.Message.ADD_PROVIDER, key=key)
- provider = msg.providerPeers.add()
- provider.id = host.get_id().to_bytes()
- provider.addrs.extend(ma.to_bytes() for ma in addrs)
- await stream.write(encode_varint_prefixed(msg.SerializeToString()))
- except Exception as err: # noqa: BLE001
- logger.debug("dht: add_provider to %s failed: %s", peer_id, err)
- return False
- finally:
- await stream.close()
- return True
-
-
-async def provide(host: IHost, key: bytes, seeds: Iterable[ID], addrs: Sequence[multiaddr.Multiaddr]) -> int:
- """Announces this host as a provider of key, as sam-node's DHT provide:
- the record goes to the seed peers (the routers, which serve the DHT) and
- to the closer peers they name for the key. Returns how many accepted a
- stream; the DHT does not acknowledge the record itself."""
- self_id = host.get_id()
- targets: list[ID] = [p for p in seeds if p != self_id]
- for seed in list(targets):
- resp = await _get_providers(host, seed, key)
- if resp is None:
- continue
- for info in _peer_infos(resp.closerPeers):
- if info.peer_id == self_id or info.peer_id in targets:
- continue
- if info.peer_id not in host.get_connected_peers():
- try:
- await host.connect(info)
- except Exception: # noqa: BLE001 - unreachable closer peers are skipped
- continue
- targets.append(info.peer_id)
- if len(targets) >= _MAX_PEERS_PER_ROUND:
- break
- sent = 0
- for peer_id in targets[:_MAX_PEERS_PER_ROUND]:
- if await _add_provider(host, peer_id, key, addrs):
- sent += 1
- return sent
diff --git a/sdk/python/src/agent_mesh/httpx_transport.py b/sdk/python/src/agent_mesh/httpx_transport.py
new file mode 100644
index 00000000..d945e3fd
--- /dev/null
+++ b/sdk/python/src/agent_mesh/httpx_transport.py
@@ -0,0 +1,97 @@
+# Copyright 2026 Google LLC
+#
+# 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.
+
+"""The mesh as an httpx transport, so a client built on httpx, such as the
+official A2A SDK, reaches a member's service or agent without knowing about
+libp2p:
+
+ client = httpx.AsyncClient(transport=MeshTransport(session))
+ await client.post("http://mesh/sam/<peer-id>/a2a/agent", json=...)
+
+The URL has the shape sam-node's egress proxy takes, /sam/<peer-id>/<type>/
+<name>/<path>, so an agent card a sam-node rewrote for the mesh works here as
+it is. The host is ignored: httpx lowercases it, and a peer ID is not
+case-insensitive. Response bodies stream, so `message/stream` works."""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, AsyncIterator
+
+import httpx
+
+from .libp2p_http import StreamedResponse, open_http_request
+
+if TYPE_CHECKING:
+ from .session import MeshSession
+
+MESH_PATH_PREFIX = "/sam/"
+_REQUEST_TIMEOUT = 60.0
+
+
+def split_mesh_url(url: httpx.URL) -> tuple[str, str]:
+ """(peer ID, request target) of a mesh URL; the target is the
+ /<type>/<name>/<path>?<query> the peer's ingress takes."""
+ raw = url.raw_path.decode("latin-1")
+ path, _, query = raw.partition("?")
+ if not path.startswith(MESH_PATH_PREFIX):
+ raise httpx.UnsupportedProtocol(f"a mesh URL looks like http://mesh{MESH_PATH_PREFIX}<peer-id>/<type>/<name>/..., got {url}")
+ peer_id, _, rest = path[len(MESH_PATH_PREFIX) :].partition("/")
+ parts = rest.split("/")
+ if not peer_id or len(parts) < 2 or not parts[0] or not parts[1]:
+ raise httpx.UnsupportedProtocol(f"a mesh URL names a peer, a service type and a name, got {url}")
+ return peer_id, "/" + rest + (f"?{query}" if query else "")
+
+
+class _BodyStream(httpx.AsyncByteStream):
+ def __init__(self, response: StreamedResponse) -> None:
+ self._response = response
+
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ async for chunk in self._response.iter_body():
+ yield chunk
+
+ async def aclose(self) -> None:
+ await self._response.aclose()
+
+
+class MeshTransport(httpx.AsyncBaseTransport):
+ """Carries every request of an httpx client to the peer its URL names,
+ over /libp2p-http through the session. Runs under trio, as the session
+ does."""
+
+ def __init__(self, session: "MeshSession", *, agent: str = "", timeout: float = _REQUEST_TIMEOUT) -> None:
+ self._session = session
+ self._agent = agent
+ self._timeout = timeout
+
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ peer_text, target = split_mesh_url(request.url)
+ peer_id = await self._session.connect(peer_text)
+ body = await request.aread()
+ headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in request.headers.raw}
+ response = await open_http_request(
+ self._session.host,
+ peer_id,
+ self._session.mesh.credential.biscuit,
+ request.method,
+ target,
+ headers=headers,
+ body=body,
+ agent=self._agent,
+ timeout=self._timeout,
+ )
+ return httpx.Response(response.status, headers=list(response.headers.items()), stream=_BodyStream(response), request=request)
+
+
+__all__ = ("MESH_PATH_PREFIX", "MeshTransport", "split_mesh_url")
diff --git a/sdk/python/src/agent_mesh/serve.py b/sdk/python/src/agent_mesh/libp2p_http.py
similarity index 51%
rename from sdk/python/src/agent_mesh/serve.py
rename to sdk/python/src/agent_mesh/libp2p_http.py
index 691d2f41..58d31512 100644
--- a/sdk/python/src/agent_mesh/serve.py
+++ b/sdk/python/src/agent_mesh/libp2p_http.py
@@ -12,9 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""The provider side: /sam/mcp/1.0.0 for MCP services and /libp2p-http for
-inference and A2A services, both gated by the authorizer the way sam-node
-gates them (WithBiscuitAuth and StartIngressServer in internal/node)."""
+"""The /libp2p-http protocol (go-libp2p-http): the client that calls inference
+and A2A services on the mesh, and the ingress that accepts A2A requests for
+this member's own agent, gated by the authorizer the way sam-node gates its
+ingress (StartIngressServer in internal/node)."""
from __future__ import annotations
@@ -22,27 +23,19 @@ import base64
import json
import logging
from dataclasses import dataclass, field
-from typing import Awaitable, Callable, Literal, Mapping, Optional, Sequence, Union
+from typing import AsyncIterator, Awaitable, Callable, Mapping, Optional, Sequence, Union
-import anyio
import h11
import httpx
-import mcp_types
import trio
from libp2p.abc import IHost, INetStream
from libp2p.custom_types import TProtocol
from libp2p.peer.id import ID
-from libp2p.utils.varint import encode_varint_prefixed, read_varint_prefixed_bytes
-from mcp.server.mcpserver import MCPServer
-from mcp.shared.message import SessionMessage
-from ._proto import sam_pb2 as pb
-from .auth import AUTH_HANDSHAKE_TIMEOUT, MAX_AUTH_FRAME_BYTES
+from .auth import AUTH_HANDSHAKE_TIMEOUT
from .authorizer import AuthorizationError, AuthorizeRequest, ProviderAuthorizerOptions, authorize_caller
from .biscuit import VerifiedBiscuit
-from .discovery import ServiceType
from .host import open_stream
-from .mcp_client import MAX_MCP_MESSAGE_BYTES
logger = logging.getLogger("agent_mesh")
@@ -55,6 +48,9 @@ HEADER_SAM_AGENT = "x-sam-agent"
HEADER_PEER_ID = "x-peer-id"
HEADER_SAM_NO_TRAILING_SLASH = "x-sam-no-trailing-slash"
+# The service name an agent answers under unless it picks another.
+DEFAULT_A2A_NAME = "agent"
+
_MAX_INGRESS_BODY_BYTES = 8 * 1024 * 1024
_READ_CHUNK = 64 * 1024
_REQUEST_TIMEOUT = 60.0
@@ -63,7 +59,7 @@ _REQUEST_TIMEOUT = 60.0
@dataclass(frozen=True)
class HTTPRequest:
"""What an in-process HTTP handler receives: the request as it reached
- the service, path relative to /<type>/<name>."""
+ the agent, path relative to /a2a/<name>."""
method: str
path: str
@@ -93,181 +89,28 @@ HTTPHandler = Callable[[HTTPRequest, VerifiedBiscuit], Awaitable[HTTPResponse]]
@dataclass(frozen=True)
-class MCPService:
- """An MCP service: one server per session, since an MCP server run holds one transport."""
-
- name: str
- create_server: Callable[[], MCPServer]
- description: str = ""
- type: Literal["mcp"] = "mcp"
-
+class A2AEndpoint:
+ """This member's agent as other members reach it: `a2a://<name>`, answered
+ by target, the base URL of an A2A server beside this process or a handler
+ in it. Authorized requests are forwarded with the biscuit and agent headers
+ stripped and X-Peer-Id naming the verified caller, as sam-node does. The
+ endpoint is not announced anywhere; a caller reaches it by peer ID."""
-@dataclass(frozen=True)
-class HTTPService:
- """An inference or A2A service: authorized requests are forwarded to
- target, a base URL of a local backend or a handler in this process. The
- biscuit and agent headers are stripped and X-Peer-Id names the verified
- caller, as sam-node does."""
-
- type: Literal["inference", "a2a"]
- name: str
target: Union[str, HTTPHandler]
- description: str = ""
-
+ name: str = DEFAULT_A2A_NAME
-ServiceSpec = Union[MCPService, HTTPService]
+ @property
+ def service(self) -> str:
+ return f"a2a://{self.name}"
@dataclass(frozen=True)
class ProviderOptions:
authorizer: ProviderAuthorizerOptions
- # This provider's current biscuit, for the mutual AuthResponse.
- own_biscuit: Callable[[], bytes]
- # Called after a caller is authorized for a service, e.g. for the session's admitted set.
- on_authorized: Optional[Callable[[str, VerifiedBiscuit, str], None]] = None
# Peers the control plane has banned; refused before their token is looked at.
is_banned: Optional[Callable[[str], bool]] = None
-
-
-class ServiceRegistry:
- """Services registered on a member, keyed by type and name."""
-
- def __init__(self) -> None:
- self._services: dict[str, ServiceSpec] = {}
-
- @staticmethod
- def key(service_type: str, name: str) -> str:
- return f"{service_type}://{name}"
-
- def add(self, spec: ServiceSpec) -> None:
- key = self.key(spec.type, spec.name)
- if key in self._services:
- raise ValueError(f"service {key} is already registered")
- self._services[key] = spec
-
- def remove(self, service_type: ServiceType, name: str) -> bool:
- return self._services.pop(self.key(service_type, name), None) is not None
-
- def get(self, service_type: str, name: str) -> Optional[ServiceSpec]:
- return self._services.get(self.key(service_type, name))
-
- def list(self) -> list[tuple[str, str, str]]:
- """(type, name, description) of every registered service."""
- return [(s.type, s.name, s.description) for s in self._services.values()]
-
-
-def _catalog_server(registry: ServiceRegistry) -> MCPServer:
- """The member's own catalog over MCP, as sam-node's list_local_services."""
- server = MCPServer("agent-mesh-sdk")
-
- @server.tool(description="List the services this member publishes on the mesh")
- def list_local_services() -> str:
- return json.dumps([{"type": t, "name": n, "description": d} for t, n, d in registry.list()])
-
- return server
-
-
-async def _refuse(stream: INetStream, peer_id: str, reason: str) -> None:
- logger.info("refusing %s: %s", peer_id, reason)
- try:
- with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
- await stream.write(encode_varint_prefixed(pb.AuthResponse(success=False, error=reason).SerializeToString()))
- except Exception: # noqa: BLE001 - the caller may already be gone
- pass
-
-
-def mcp_stream_handler(registry: ServiceRegistry, options: ProviderOptions, protocol: str): # type: ignore[no-untyped-def]
- """Server side of /sam/mcp/1.0.0, as sam-node's WithBiscuitAuth(HandleMCPStream):
- read the AuthFrame, authorize the caller for the named service, answer with
- our own credential, then hand the stream to that service's MCP server. A
- denied caller gets AuthResponse{success: false}; an unknown service closes
- the stream after a successful answer, which is what sam-node does."""
-
- async def handle(stream: INetStream) -> None:
- peer_id = str(stream.muxed_conn.peer_id)
- try:
- with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
- data = await read_varint_prefixed_bytes(stream)
- if len(data) > MAX_AUTH_FRAME_BYTES:
- await stream.close()
- return
- frame = pb.AuthFrame.FromString(data)
- if options.is_banned is not None and options.is_banned(peer_id):
- await _refuse(stream, peer_id, "peer is revoked")
- await stream.close()
- return
- try:
- verified = await trio.to_thread.run_sync(
- authorize_caller,
- AuthorizeRequest(biscuit=frame.biscuit, peer_id=peer_id, target_service=frame.target_service, protocol=protocol, agent=frame.agent),
- options.authorizer,
- )
- except AuthorizationError as err:
- await _refuse(stream, peer_id, str(err))
- await stream.close()
- return
- if options.on_authorized:
- options.on_authorized(peer_id, verified, frame.target_service)
- with trio.fail_after(AUTH_HANDSHAKE_TIMEOUT):
- await stream.write(encode_varint_prefixed(pb.AuthResponse(success=True, biscuit=options.own_biscuit()).SerializeToString()))
-
- if frame.target_service == "":
- server = _catalog_server(registry)
- else:
- spec = registry.get("mcp", frame.target_service.removeprefix("mcp://")) if frame.target_service.startswith("mcp://") else None
- if not isinstance(spec, MCPService):
- logger.info("no MCP service %s for %s", frame.target_service, peer_id)
- await stream.close()
- return
- server = spec.create_server()
- await _serve_mcp(stream, server)
- except Exception as err: # noqa: BLE001 - one caller's failure must not take the handler down
- logger.debug("mcp stream from %s ended: %s", peer_id, err)
- await stream.close()
-
- return handle
-
-
-async def _serve_mcp(stream: INetStream, server: MCPServer) -> None:
- """Runs one MCP server over the stream until the caller goes away."""
- low = server._lowlevel_server # noqa: SLF001 - the only way to run it over custom streams
- read_writer, read_stream = anyio.create_memory_object_stream[SessionMessage | Exception](0)
- write_stream, write_reader = anyio.create_memory_object_stream[SessionMessage](0)
-
- async def pump_in() -> None:
- try:
- async with read_writer:
- while True:
- data = await read_varint_prefixed_bytes(stream)
- if len(data) > MAX_MCP_MESSAGE_BYTES:
- raise ValueError("oversized MCP frame")
- try:
- message = mcp_types.jsonrpc_message_adapter.validate_json(data, by_name=False)
- except ValueError as exc:
- await read_writer.send(exc)
- continue
- await read_writer.send(SessionMessage(message))
- except Exception: # noqa: BLE001 - the caller went away
- pass
-
- async def pump_out() -> None:
- try:
- async with write_reader:
- async for message in write_reader:
- await stream.write(encode_varint_prefixed(message.message.model_dump_json(by_alias=True, exclude_unset=True).encode()))
- except Exception: # noqa: BLE001
- pass
-
- async with trio.open_nursery() as nursery:
- nursery.start_soon(pump_in)
- nursery.start_soon(pump_out)
- try:
- await low.run(read_stream, write_stream, low.create_initialization_options())
- except Exception: # noqa: BLE001 - the session ended with the stream
- pass
- finally:
- await stream.close()
- nursery.cancel_scope.cancel()
+ # Called after a caller is authorized, e.g. for the session's admitted set.
+ on_authorized: Optional[Callable[[str, VerifiedBiscuit, str], None]] = None
def _has_dot_segment(path: str) -> bool:
@@ -310,10 +153,12 @@ async def _write_http_response(stream: INetStream, conn: h11.Connection, status:
await stream.write(data)
-def http_ingress_handler(registry: ServiceRegistry, options: ProviderOptions): # type: ignore[no-untyped-def]
+def http_ingress_handler(endpoint: A2AEndpoint, options: ProviderOptions): # type: ignore[no-untyped-def]
"""Server side of /libp2p-http, as sam-node's StartIngressServer: the path
is /<type>/<name>[/<upstream>], the caller's biscuit is X-Sam-Biscuit, and
- the request is authorized for <type>://<name> before anything is forwarded."""
+ the request is authorized for <type>://<name> before anything is forwarded.
+ Only the agent's own endpoint is answered; anything else is 404 after
+ authorization, so an unauthorized caller learns nothing about it."""
async def handle(stream: INetStream) -> None:
peer_id = str(stream.muxed_conn.peer_id)
@@ -329,7 +174,7 @@ def http_ingress_handler(registry: ServiceRegistry, options: ProviderOptions):
except (ValueError, h11.RemoteProtocolError, trio.TooSlowError) as err:
logger.debug("http ingress from %s: %s", peer_id, err)
return
- status, headers, out = await _handle_ingress(request, body, peer_id, registry, options)
+ status, headers, out = await _handle_ingress(request, body, peer_id, endpoint, options)
await _write_http_response(stream, conn, status, headers, out)
except Exception as err: # noqa: BLE001 - one caller's failure must not take the handler down
logger.debug("http ingress from %s failed: %s", peer_id, err)
@@ -344,7 +189,7 @@ def http_ingress_handler(registry: ServiceRegistry, options: ProviderOptions):
async def _handle_ingress(
- request: h11.Request, body: bytes, peer_id: str, registry: ServiceRegistry, options: ProviderOptions
+ request: h11.Request, body: bytes, peer_id: str, endpoint: A2AEndpoint, options: ProviderOptions
) -> tuple[int, dict[str, str], bytes]:
def plain(status: int, text: str) -> tuple[int, dict[str, str], bytes]:
return status, {"content-type": "text/plain; charset=utf-8"}, (text + "\n").encode()
@@ -352,7 +197,7 @@ async def _handle_ingress(
target = request.target.decode("latin-1")
raw_path, _, query = target.partition("?")
# Policy is decided on the /<type>/<name> prefix; a dot segment in what
- # follows could resolve to a sibling service on a shared backend.
+ # follows could resolve to a sibling path on the backend.
if _has_dot_segment(raw_path):
return plain(400, "Invalid path")
parts = raw_path.lstrip("/").split("/")
@@ -396,8 +241,7 @@ async def _handle_ingress(
options.on_authorized(peer_id, verified, target_service)
# Under the type the policy was evaluated on.
- spec = registry.get(service_type, service_name)
- if not isinstance(spec, HTTPService):
+ if target_service != endpoint.service:
return plain(404, "Service not found")
# The biscuit and the agent are for policy, not for the backend; X-Peer-Id
@@ -413,55 +257,96 @@ async def _handle_ingress(
method = request.method.decode()
path = "/" + upstream_path + (f"?{query}" if query else "")
- if callable(spec.target):
- response = await spec.target(HTTPRequest(method=method, path=path, headers=forwarded, body=body), verified)
+ if callable(endpoint.target):
+ response = await endpoint.target(HTTPRequest(method=method, path=path, headers=forwarded, body=body), verified)
return response.status, dict(response.headers), response.body
async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT, follow_redirects=False) as client:
- upstream = await client.request(method, spec.target.rstrip("/") + path, headers=forwarded, content=body or None)
+ upstream = await client.request(method, endpoint.target.rstrip("/") + path, headers=forwarded, content=body or None)
out_headers = {k: v for k, v in upstream.headers.items() if k.lower() not in ("content-length", "transfer-encoding", "connection")}
return upstream.status_code, out_headers, upstream.content
-async def http_request_over_stream(
+def mesh_http_target(target_service: str, path: str = "") -> str:
+ """The request target for a service on a peer: /<type>/<name>/<path>."""
+ scheme, sep, name = target_service.partition("://")
+ if not sep or scheme not in ("inference", "a2a", "mcp") or not name:
+ raise ValueError(f"service target must look like inference://<name>, got {target_service!r}")
+ if not path:
+ return f"/{scheme}/{name}"
+ return f"/{scheme}/{name}" + (path if path.startswith("/") else "/" + path)
+
+
+class StreamedResponse:
+ """A response whose body is still arriving on the stream: status and
+ headers are in; `iter_body` yields the body as the peer sends it, which is
+ what an SSE stream (A2A `message/stream`) needs. Close it when done."""
+
+ def __init__(self, stream: INetStream, conn: h11.Connection, status: int, headers: dict[str, str], peer_id: ID) -> None:
+ self._stream = stream
+ self._conn = conn
+ self._peer_id = peer_id
+ self.status = status
+ self.headers = headers
+
+ async def iter_body(self) -> AsyncIterator[bytes]:
+ while True:
+ event = self._conn.next_event()
+ if event is h11.NEED_DATA:
+ try:
+ chunk = await self._stream.read(_READ_CHUNK)
+ except Exception: # noqa: BLE001 - EOF ends the response
+ chunk = b""
+ self._conn.receive_data(chunk)
+ continue
+ if isinstance(event, h11.Data):
+ yield bytes(event.data)
+ elif isinstance(event, (h11.EndOfMessage, h11.ConnectionClosed, h11.PAUSED)):
+ return
+
+ async def read(self, limit: int = _MAX_INGRESS_BODY_BYTES) -> bytes:
+ body = bytearray()
+ async for chunk in self.iter_body():
+ body.extend(chunk)
+ if len(body) > limit:
+ raise ValueError("response body too large")
+ return bytes(body)
+
+ async def aclose(self) -> None:
+ await self._stream.close()
+
+
+async def open_http_request(
host: IHost,
peer_id: ID,
biscuit: bytes,
- target_service: str,
- path: str,
+ method: str,
+ target: str,
*,
- method: str = "GET",
headers: Optional[Mapping[str, str]] = None,
- body: Union[bytes, str, None] = None,
+ body: bytes = b"",
agent: str = "",
timeout: float = _REQUEST_TIMEOUT,
-) -> HTTPResponse:
+) -> StreamedResponse:
"""Client side of /libp2p-http, as go-libp2p-http's RoundTripper: one
- stream per request, plain HTTP/1.1 with Host set to the peer ID, the
- biscuit in X-Sam-Biscuit and the path /<type>/<name>/<path>."""
- scheme, sep, name = target_service.partition("://")
- if not sep or scheme not in ("inference", "a2a", "mcp") or not name:
- raise ValueError(f"service target must look like inference://<name>, got {target_service!r}")
- payload = body.encode() if isinstance(body, str) else (body or b"")
- out = [(k.lower(), v) for k, v in (headers or {}).items() if k.lower() not in ("host", "content-length")]
+ stream per request, plain HTTP/1.1 with Host set to the peer ID and the
+ biscuit in X-Sam-Biscuit. Returns once the response headers are in; the
+ body streams after. The timeout bounds the headers, not the body."""
+ out = [(k.lower(), v) for k, v in (headers or {}).items() if k.lower() not in ("host", "content-length", HEADER_SAM_BISCUIT, HEADER_PEER_ID)]
out.append(("host", str(peer_id)))
out.append((HEADER_SAM_BISCUIT, base64.b64encode(biscuit).decode()))
if agent:
out.append((HEADER_SAM_AGENT, agent))
- out.append(("content-length", str(len(payload))))
+ out.append(("content-length", str(len(body))))
conn = h11.Connection(h11.CLIENT)
stream = await open_stream(host, peer_id, HTTP_PROTOCOL, timeout)
try:
with trio.fail_after(timeout):
- data = conn.send(h11.Request(method=method, target=f"/{scheme}/{name}" + (path if path.startswith("/") else "/" + path), headers=out)) or b""
- data += conn.send(h11.Data(data=payload)) or b""
+ data = conn.send(h11.Request(method=method, target=target, headers=out)) or b""
+ data += conn.send(h11.Data(data=body)) or b""
data += conn.send(h11.EndOfMessage()) or b""
await stream.write(data)
-
- status = 0
- resp_headers: dict[str, str] = {}
- resp_body = bytearray()
while True:
event = conn.next_event()
if event is h11.NEED_DATA:
@@ -471,34 +356,51 @@ async def http_request_over_stream(
chunk = b""
conn.receive_data(chunk)
continue
- if isinstance(event, (h11.Response, h11.InformationalResponse)):
- if isinstance(event, h11.Response):
- status = event.status_code
- resp_headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in event.headers}
- elif isinstance(event, h11.Data):
- resp_body.extend(event.data)
- if len(resp_body) > _MAX_INGRESS_BODY_BYTES:
- raise ValueError("response body too large")
- elif isinstance(event, h11.EndOfMessage):
- return HTTPResponse(status=status, headers=resp_headers, body=bytes(resp_body))
- elif isinstance(event, (h11.ConnectionClosed, h11.PAUSED)):
- if status:
- return HTTPResponse(status=status, headers=resp_headers, body=bytes(resp_body))
- raise ConnectionError(f"peer {peer_id} closed the stream before answering")
- finally:
+ if isinstance(event, h11.Response):
+ resp_headers = {k.decode("latin-1"): v.decode("latin-1") for k, v in event.headers}
+ return StreamedResponse(stream, conn, event.status_code, resp_headers, peer_id)
+ if isinstance(event, h11.InformationalResponse):
+ continue
+ raise ConnectionError(f"peer {peer_id} closed the stream before answering")
+ except BaseException:
await stream.close()
+ raise
+
+
+async def http_request_over_stream(
+ host: IHost,
+ peer_id: ID,
+ biscuit: bytes,
+ target_service: str,
+ path: str,
+ *,
+ method: str = "GET",
+ headers: Optional[Mapping[str, str]] = None,
+ body: Union[bytes, str, None] = None,
+ agent: str = "",
+ timeout: float = _REQUEST_TIMEOUT,
+) -> HTTPResponse:
+ """One request to /<type>/<name>/<path> on a peer, body read whole."""
+ payload = body.encode() if isinstance(body, str) else (body or b"")
+ with trio.fail_after(timeout):
+ response = await open_http_request(host, peer_id, biscuit, method, mesh_http_target(target_service, path), headers=headers, body=payload, agent=agent, timeout=timeout)
+ try:
+ return HTTPResponse(status=response.status, headers=response.headers, body=await response.read())
+ finally:
+ await response.aclose()
__all__: Sequence[str] = (
+ "A2AEndpoint",
+ "DEFAULT_A2A_NAME",
"HTTP_PROTOCOL",
"HTTPHandler",
"HTTPRequest",
"HTTPResponse",
- "HTTPService",
- "MCPService",
"ProviderOptions",
- "ServiceRegistry",
+ "StreamedResponse",
"http_ingress_handler",
"http_request_over_stream",
- "mcp_stream_handler",
+ "mesh_http_target",
+ "open_http_request",
)
diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.py
index 6c96ed6f..3b36736b 100644
--- a/sdk/python/src/agent_mesh/session.py
+++ b/sdk/python/src/agent_mesh/session.py
@@ -25,7 +25,6 @@ from typing import TYPE_CHECKING, Any, AsyncIterator, Mapping, Optional, Sequenc
import multiaddr
import trio
from libp2p.abc import IHost
-from libp2p.custom_types import TProtocol
from libp2p.peer.id import ID
from libp2p.peer.peerinfo import PeerInfo, info_from_p2p_addr
from libp2p.pubsub.gossipsub import PROTOCOL_ID as GOSSIPSUB_V10
@@ -38,24 +37,26 @@ from mcp import ClientSession
from ._proto import circuit_pb2 as circuit
from ._proto import sam_pb2 as pb
-from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, auth_stream_handler, authenticate_with_peer
+from .auth import AUTH_PROTOCOL, auth_stream_handler, authenticate_with_peer
from .authorizer import ProviderAuthorizerOptions
from .biscuit import ROLE_ROUTER, VerifiedBiscuit, require_role
-from .discovery import DiscoveredProvider, ServiceType, find_providers, parse_service_target, provide, service_key
+from .discovery import DiscoveredProvider, find_providers, parse_service_target, service_key
from .host import create_mesh_host, dial_addrs, peer_info
+from .httpx_transport import MESH_PATH_PREFIX
from .identity import canonical_peer_id
-from .mcp_client import ToolCallResult, ToolInfo, open_mcp_session, tool_call_result
-from .relay import STOP_PROTOCOL, dial_through_relay, reserve_relay, split_circuit_address, stop_stream_handler
-from .serve import (
+from .libp2p_http import (
+ DEFAULT_A2A_NAME,
HTTP_PROTOCOL,
+ A2AEndpoint,
+ HTTPHandler,
HTTPResponse,
ProviderOptions,
- ServiceRegistry,
- ServiceSpec,
http_ingress_handler,
http_request_over_stream,
- mcp_stream_handler,
+ mesh_http_target,
)
+from .mcp_client import ToolCallResult, ToolInfo, open_mcp_session, tool_call_result
+from .relay import STOP_PROTOCOL, dial_through_relay, reserve_relay, split_circuit_address, stop_stream_handler
from .sync import GOSSIP_EVENTS_TOPIC, BanSet, verify_mesh_event
if TYPE_CHECKING:
@@ -71,8 +72,6 @@ MIN_REFRESH_DELAY = 2.0
RESERVATION_RENEW_LEAD = 2 * 60.0
# sam-node's --control-plane-sync-interval default.
DEFAULT_POLICY_SYNC = 15 * 60.0
-# How often provider records are refreshed; go-libp2p-kad-dht expires them after 48h.
-DEFAULT_PROVIDE_INTERVAL = 10 * 60.0
# sam-node's --control-plane-sync-interval default, and its 2s first pull.
DEFAULT_CONTROL_PLANE_SYNC = 15 * 60.0
FIRST_CONTROL_PLANE_SYNC = 2.0
@@ -151,17 +150,15 @@ class MeshSession:
authenticated_peers: dict[str, datetime] = field(default_factory=dict)
# Peers the control plane has banned; connections to and from them are refused.
banned: BanSet = field(default_factory=BanSet)
- # The services this member publishes.
- services: ServiceRegistry = field(default_factory=ServiceRegistry)
+ # This member's agent, once accept_a2a was called.
+ endpoint: Optional[A2AEndpoint] = None
policy_sync_interval: float = DEFAULT_POLICY_SYNC
- provide_interval: float = DEFAULT_PROVIDE_INTERVAL
control_plane_sync_interval: float = DEFAULT_CONTROL_PLANE_SYNC
control_plane_sync_jitter: float = DEFAULT_CONTROL_PLANE_SYNC_JITTER
reservation_lead: float = RESERVATION_RENEW_LEAD
reservation_retry: float = DEFAULT_REFRESH_RETRY
_nursery: Optional[trio.Nursery] = field(default=None, repr=False)
_policy_rules: Optional[list[str]] = field(default=None, repr=False)
- _serving: bool = field(default=False, repr=False)
_sync_lock: trio.Lock = field(default_factory=trio.Lock, repr=False)
_sync_trigger: trio.Event = field(default_factory=trio.Event, repr=False)
@@ -169,6 +166,18 @@ class MeshSession:
def peer_id(self) -> str:
return str(self.host.get_id())
+ @staticmethod
+ def mesh_url(peer_id: str, target_service: str, path: str = "") -> str:
+ """The URL an httpx client on `MeshTransport` uses for a service on a
+ peer: http://mesh/sam/<peer-id>/<type>/<name>/<path>, the shape of
+ sam-node's egress proxy and of an agent card it rewrote."""
+ return "http://mesh" + MESH_PATH_PREFIX + canonical_peer_id(peer_id) + mesh_http_target(target_service, path)
+
+ @property
+ def agent_url(self) -> Optional[str]:
+ """The mesh URL of this member's own agent, once accept_a2a was called."""
+ return self.mesh_url(self.peer_id, self.endpoint.service) if self.endpoint is not None else None
+
@property
def relay_addresses(self) -> list[str]:
"""The `.../p2p-circuit/p2p/<self>` addresses reserved on routers."""
@@ -302,7 +311,7 @@ class MeshSession:
def policy_rules(self) -> list[str]:
"""The mesh policy rules this member evaluates for callers, as the
control plane rendered them (PolicyConfigGetResponse.datalog_rules).
- Empty until the first serve() or sync_policy()."""
+ Empty until accept_a2a() or sync_policy()."""
return list(self._policy_rules or [])
async def sync_policy(self) -> None:
@@ -311,16 +320,17 @@ class MeshSession:
async def sync(self) -> "ControlPlaneSync":
"""Pulls keys, bans and router addresses from the control plane now, and
- the mesh policy when serving, then applies them: a newly banned peer is
- disconnected and dropped from the admitted set. Concurrent calls run
- one after the other. Errors of individual parts are in the result."""
+ the mesh policy when accepting callers, then applies them: a newly
+ banned peer is disconnected and dropped from the admitted set.
+ Concurrent calls run one after the other. Errors of individual parts
+ are in the result."""
async with self._sync_lock:
result = await trio.to_thread.run_sync(self.mesh.sync_control_plane)
if result.banned_peer_ids is not None:
newly_banned, _ = self.banned.reconcile(canonical_peer_ids(result.banned_peer_ids), result.fetched_at)
for peer in newly_banned:
await self._evict(peer)
- if self._serving:
+ if self.endpoint is not None:
try:
await self.sync_policy()
except Exception as err: # noqa: BLE001 - the last good policy stays in force
@@ -432,53 +442,35 @@ class MeshSession:
self.host, peer_id, self.mesh.credential.biscuit, target_service, path, method=method, headers=headers, body=body, agent=agent
)
- async def serve(self, spec: ServiceSpec) -> None:
- """Publishes a service on the mesh: registers it, announces it in the
- DHT and reports it to the control plane's catalog. The first call
- fetches the mesh policy and starts answering /sam/mcp/1.0.0 and
- /libp2p-http; a policy that cannot be read fails the call, since a
- provider without it could only authorize what callers carry in their
- own tokens."""
- if not self._serving:
- await self.sync_policy()
- options = ProviderOptions(
- authorizer=ProviderAuthorizerOptions(
- trusted_keys=lambda: self.mesh.credential.control_plane_keys,
- own_biscuit=lambda: self.mesh.credential.biscuit,
- policy_rules=lambda: self._policy_rules or [],
- ),
+ async def accept_a2a(self, target: Union[str, HTTPHandler], *, name: str = DEFAULT_A2A_NAME) -> str:
+ """Makes this member's agent reachable: other members call it as
+ `a2a://<name>` by peer ID, through a router, and the SDK answers
+ /libp2p-http with target, the base URL of an A2A server beside this
+ process or a handler in it. Nothing is announced: no DHT record, no
+ catalog entry. A tool, a model or a service others should find by
+ name is published by a sam-node. Fetches the mesh policy first and
+ keeps it current; a policy that cannot be read fails the call, since
+ an agent without it could only authorize what callers carry in their
+ own tokens. Returns the service target callers use. One agent per
+ session."""
+ if self.endpoint is not None:
+ raise RuntimeError(f"this session already accepts {self.endpoint.service}")
+ endpoint = A2AEndpoint(target=target, name=name)
+ await self.sync_policy()
+ options = ProviderOptions(
+ authorizer=ProviderAuthorizerOptions(
+ trusted_keys=lambda: self.mesh.credential.control_plane_keys,
own_biscuit=lambda: self.mesh.credential.biscuit,
- on_authorized=lambda peer, verified, _target: self.authenticated_peers.__setitem__(peer, verified.expiration),
- is_banned=lambda peer: peer in self.banned,
- )
- self.host.set_stream_handler(MCP_PROTOCOL, mcp_stream_handler(self.services, options, str(MCP_PROTOCOL)))
- self.host.set_stream_handler(HTTP_PROTOCOL, http_ingress_handler(self.services, options))
- if self._nursery is not None:
- self._nursery.start_soon(self._policy_loop)
- self._nursery.start_soon(self._provide_loop)
- self._serving = True
- self.services.add(spec)
- await self._provide(spec.type, spec.name)
- try:
- await self.report_catalog()
- except Exception as err: # noqa: BLE001 - the catalog is display only
- logger.warning("catalog report failed: %s", err)
-
- async def provide_all(self) -> None:
- """Announces every registered service in the DHT again."""
- for service_type, name, _ in self.services.list():
- await self._provide(service_type, name) # type: ignore[arg-type]
-
- async def _provide(self, service_type: ServiceType, name: str) -> None:
- # Once for the type and once for the name, as sam-node announces.
- seeds = [ID.from_base58(r.peer_id) for r in self.routers]
- addrs = [multiaddr.Multiaddr(a) for a in self.relay_addresses] + list(self.host.get_addrs())
- for key in (service_key(service_type), service_key(service_type, name)):
- await provide(self.host, key, seeds, addrs)
-
- async def report_catalog(self) -> None:
- """Reports the published services to the control plane's catalog (display only)."""
- await trio.to_thread.run_sync(self.mesh.control_plane.report_catalog, self.mesh.credential.biscuit, self.services.list())
+ policy_rules=lambda: self._policy_rules or [],
+ ),
+ on_authorized=lambda peer, verified, _target: self.authenticated_peers.__setitem__(peer, verified.expiration),
+ is_banned=lambda peer: peer in self.banned,
+ )
+ self.host.set_stream_handler(HTTP_PROTOCOL, http_ingress_handler(endpoint, options))
+ if self._nursery is not None:
+ self._nursery.start_soon(self._policy_loop)
+ self.endpoint = endpoint
+ return endpoint.service
async def _policy_loop(self) -> None:
while True:
@@ -488,14 +480,6 @@ class MeshSession:
except Exception as err: # noqa: BLE001 - the last good policy stays in force
logger.warning("mesh policy sync failed: %s", err)
- async def _provide_loop(self) -> None:
- while True:
- await trio.sleep(self.provide_interval)
- try:
- await self.provide_all()
- except Exception as err: # noqa: BLE001
- logger.warning("dht reprovide failed: %s", err)
-
async def _refresh_loop(mesh: "AgentMesh", lead: float, retry: float) -> None:
while True:
@@ -527,7 +511,6 @@ async def join_mesh(
refresh_retry: float = DEFAULT_REFRESH_RETRY,
reservation_lead: float = RESERVATION_RENEW_LEAD,
policy_sync_interval: float = DEFAULT_POLICY_SYNC,
- provide_interval: float = DEFAULT_PROVIDE_INTERVAL,
control_plane_sync_interval: float = DEFAULT_CONTROL_PLANE_SYNC,
control_plane_sync_jitter: float = DEFAULT_CONTROL_PLANE_SYNC_JITTER,
) -> AsyncIterator[MeshSession]:
@@ -568,7 +551,6 @@ async def join_mesh(
authenticated_peers=authenticated,
banned=banned,
policy_sync_interval=policy_sync_interval,
- provide_interval=provide_interval,
control_plane_sync_interval=control_plane_sync_interval,
control_plane_sync_jitter=control_plane_sync_jitter,
reservation_lead=reservation_lead,
diff --git a/sdk/python/tests/test_libp2p_http.py b/sdk/python/tests/test_libp2p_http.py
new file mode 100644
index 00000000..36d7e9c5
--- /dev/null
+++ b/sdk/python/tests/test_libp2p_http.py
@@ -0,0 +1,255 @@
+# Copyright 2026 Google LLC
+#
+# 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.
+
+"""The A2A ingress in one process: this SDK's /libp2p-http handler for one
+agent behind a py-libp2p host, called with this SDK's client, the streaming
+client and an httpx client on MeshTransport. The real sam-node as a caller is
+exercised by tests/integration."""
+
+import json
+import threading
+from dataclasses import dataclass
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import biscuit_auth as ba
+import httpx
+import multiaddr
+import pytest
+import trio
+from libp2p.peer.id import ID
+from libp2p.peer.peerinfo import info_from_p2p_addr
+
+from agent_mesh.authorizer import ProviderAuthorizerOptions
+from agent_mesh.controlplane import ROLE_NODE
+from agent_mesh.httpx_transport import MeshTransport, split_mesh_url
+from agent_mesh.identity import Identity
+from agent_mesh.libp2p_http import (
+ HTTP_PROTOCOL,
+ A2AEndpoint,
+ HTTPRequest,
+ HTTPResponse,
+ ProviderOptions,
+ http_ingress_handler,
+ http_request_over_stream,
+ mesh_http_target,
+ open_http_request,
+)
+from agent_mesh.session import MeshSession
+
+from .test_session import CP, CP_KEY, libp2p_host
+
+# What the control plane renders for a policy granting the node role every
+# A2A service on any target, and nothing else.
+POLICY_RULES = [
+ 'granted_service_all("a2a") <- role("sam:role:node")',
+ 'granted_service_all("sam:system") <- role("sam:role:node")',
+ 'target_unrestricted(true) <- role("sam:role:node")',
+]
+
+
+def mint(peer_id: str, role: str) -> bytes:
+ return ba.BiscuitBuilder(
+ "node({p}); client_peer_id({p}); expiration(2035-01-01T00:00:00Z); role({r});", {"p": peer_id, "r": role}
+ ).build(CP.private_key).to_bytes()
+
+
+class FakeA2AServer(BaseHTTPRequestHandler):
+ """Stands in for an A2A server beside the agent: echoes the request and,
+ on /stream, answers with three SSE events as message/stream would."""
+
+ seen: list[dict] = []
+
+ def _answer(self) -> None:
+ length = int(self.headers.get("content-length") or 0)
+ body = self.rfile.read(length) if length else b""
+ FakeA2AServer.seen.append({"method": self.command, "path": self.path, "peer": self.headers.get("x-peer-id"), "body": body.decode(), "biscuit": self.headers.get("x-sam-biscuit")})
+ if self.path == "/stream":
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.end_headers()
+ for i in range(3):
+ self.wfile.write(f"data: {json.dumps({'event': i})}\n\n".encode())
+ self.wfile.flush()
+ return
+ payload = json.dumps({"path": self.path, "echo": body.decode()}).encode()
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("x-backend", "fake")
+ self.send_header("content-length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ do_GET = _answer
+ do_POST = _answer
+
+ def log_message(self, *_args) -> None: # noqa: D102 - quiet
+ pass
+
+
[email protected](scope="module")
+def backend_url():
+ server = ThreadingHTTPServer(("127.0.0.1", 0), FakeA2AServer)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ yield f"http://127.0.0.1:{server.server_port}"
+ server.shutdown()
+
+
+async def start_agent(nursery, target, authorized: list[str]):
+ identity = Identity.generate()
+ host = libp2p_host(identity)
+ biscuit = mint(identity.peer_id, ROLE_NODE)
+ options = ProviderOptions(
+ authorizer=ProviderAuthorizerOptions(trusted_keys=lambda: [CP_KEY], own_biscuit=lambda: biscuit, policy_rules=lambda: POLICY_RULES),
+ on_authorized=lambda peer, _v, service: authorized.append(f"{peer} {service}"),
+ )
+ host.set_stream_handler(HTTP_PROTOCOL, http_ingress_handler(A2AEndpoint(target=target), options))
+ started = trio.Event()
+ addr_box = []
+
+ async def run():
+ async with host.run(listen_addrs=[multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")]):
+ addr_box.append(multiaddr.Multiaddr(f"{host.get_addrs()[0]}"))
+ started.set()
+ await trio.sleep_forever()
+
+ nursery.start_soon(run)
+ await started.wait()
+ return host, addr_box[0]
+
+
+@dataclass
+class _Credential:
+ biscuit: bytes
+
+
+@dataclass
+class _Mesh:
+ credential: _Credential
+
+
+class FakeSession:
+ """What MeshTransport needs of a session: the host, the credential and
+ connect(); the peer is already connected here."""
+
+ def __init__(self, host, biscuit: bytes) -> None:
+ self.host = host
+ self.mesh = _Mesh(_Credential(biscuit))
+
+ async def connect(self, peer) -> ID:
+ return ID.from_base58(str(peer))
+
+
+def test_the_agent_is_reachable_by_authorized_callers(backend_url):
+ authorized: list[str] = []
+
+ async def main():
+ async with trio.open_nursery() as nursery:
+ agent, addr = await start_agent(nursery, backend_url, authorized)
+ caller_identity = Identity.generate()
+ caller = libp2p_host(caller_identity)
+ caller_biscuit = mint(caller_identity.peer_id, ROLE_NODE)
+ guest_biscuit = mint(caller_identity.peer_id, "sam:role:guest")
+ async with caller.run(listen_addrs=[]):
+ await caller.connect(info_from_p2p_addr(addr))
+ pid = agent.get_id()
+
+ # The agent is forwarded the request with the caller's identity and without its biscuit.
+ res = await http_request_over_stream(caller, pid, caller_biscuit, "a2a://agent", "/card?x=1", headers={"x-sam-biscuit": "spoof"})
+ assert res.status == 200
+ assert res.headers.get("x-backend") == "fake"
+ assert res.json() == {"path": "/card?x=1", "echo": ""}
+ assert FakeA2AServer.seen[-1]["peer"] == caller_identity.peer_id
+ assert FakeA2AServer.seen[-1]["biscuit"] is None
+ assert f"{caller_identity.peer_id} a2a://agent" in authorized
+ post = await http_request_over_stream(
+ caller, pid, caller_biscuit, "a2a://agent", "/", method="POST", headers={"content-type": "application/json"}, body='{"jsonrpc": "2.0"}'
+ )
+ assert post.status == 200 and post.json()["echo"] == '{"jsonrpc": "2.0"}'
+
+ # A streamed body arrives event by event.
+ streamed = await open_http_request(caller, pid, caller_biscuit, "GET", mesh_http_target("a2a://agent", "/stream"))
+ assert streamed.status == 200 and streamed.headers["content-type"] == "text/event-stream"
+ events = []
+ async for chunk in streamed.iter_body():
+ events.extend(line for line in chunk.decode().split("\n") if line.startswith("data:"))
+ await streamed.aclose()
+ assert events == ['data: {"event": 0}', 'data: {"event": 1}', 'data: {"event": 2}']
+
+ # An httpx client on the mesh transport, as the A2A SDK's client is.
+ session = FakeSession(caller, caller_biscuit)
+ url = MeshSession.mesh_url(str(pid), "a2a://agent")
+ assert url == f"http://mesh/sam/{pid}/a2a/agent"
+ async with httpx.AsyncClient(transport=MeshTransport(session)) as client: # type: ignore[arg-type]
+ answer = await client.post(url, json={"method": "message/send"}, headers={"x-sam-biscuit": "spoof"})
+ assert answer.status_code == 200 and answer.json()["echo"] == '{"method":"message/send"}'
+ assert FakeA2AServer.seen[-1]["peer"] == caller_identity.peer_id
+ assert FakeA2AServer.seen[-1]["biscuit"] is None
+ async with client.stream("GET", url + "/stream") as answer:
+ lines = [line async for line in answer.aiter_lines() if line.startswith("data:")]
+ assert lines == ['data: {"event": 0}', 'data: {"event": 1}', 'data: {"event": 2}']
+ with pytest.raises(httpx.UnsupportedProtocol):
+ await client.get("http://mesh/not/the/mesh")
+
+ # What the policy does not grant is refused before the agent is reached.
+ before = len(FakeA2AServer.seen)
+ assert (await http_request_over_stream(caller, pid, guest_biscuit, "a2a://agent", "/card")).status == 403
+ assert (await http_request_over_stream(caller, pid, caller_biscuit, "inference://agent", "/")).status == 403
+ assert len(FakeA2AServer.seen) == before
+ # Granted, but not this agent: 404 after authorization.
+ assert (await http_request_over_stream(caller, pid, caller_biscuit, "a2a://other", "/card")).status == 404
+ assert (await http_request_over_stream(caller, pid, b"", "a2a://agent", "/card")).status == 401
+ assert (await http_request_over_stream(caller, pid, caller_biscuit, "a2a://agent", "/../other/x")).status == 400
+ nursery.cancel_scope.cancel()
+
+ async def with_timeout():
+ with trio.fail_after(30):
+ await main()
+
+ trio.run(with_timeout)
+
+
+def test_an_in_process_handler_sees_the_verified_caller():
+ async def hello(request: HTTPRequest, caller) -> HTTPResponse:
+ return HTTPResponse(status=201, body=f"hello {caller.peer_id} {request.method} {request.path}".encode())
+
+ async def main():
+ async with trio.open_nursery() as nursery:
+ agent, addr = await start_agent(nursery, hello, [])
+ caller_identity = Identity.generate()
+ caller = libp2p_host(caller_identity)
+ async with caller.run(listen_addrs=[]):
+ await caller.connect(info_from_p2p_addr(addr))
+ res = await http_request_over_stream(caller, agent.get_id(), mint(caller_identity.peer_id, ROLE_NODE), "a2a://agent", "/agent/card")
+ assert res.status == 201 and res.text == f"hello {caller_identity.peer_id} GET /agent/card"
+ nursery.cancel_scope.cancel()
+
+ async def with_timeout():
+ with trio.fail_after(30):
+ await main()
+
+ trio.run(with_timeout)
+
+
+def test_mesh_urls_name_a_peer_and_a_service():
+ peer = "12D3KooWJ2Yhy3CKwVPDw7AnkxN5HbZbb65xDoRif54hdXXUzh1U"
+ assert split_mesh_url(httpx.URL(f"http://mesh/sam/{peer}/a2a/agent")) == (peer, "/a2a/agent")
+ assert split_mesh_url(httpx.URL(f"http://anything:1/sam/{peer}/inference/llm/v1/models?x=1")) == (peer, "/inference/llm/v1/models?x=1")
+ for bad in ("http://mesh/a2a/agent", f"http://mesh/sam/{peer}", f"http://mesh/sam/{peer}/a2a", f"http://mesh/sam//a2a/agent"):
+ with pytest.raises(httpx.UnsupportedProtocol):
+ split_mesh_url(httpx.URL(bad))
+ assert mesh_http_target("a2a://agent") == "/a2a/agent"
+ assert mesh_http_target("a2a://agent", "card") == "/a2a/agent/card"
+ with pytest.raises(ValueError):
+ mesh_http_target("ftp://agent", "/")
diff --git a/sdk/python/tests/test_serve.py b/sdk/python/tests/test_serve.py
deleted file mode 100644
index ddbbadce..00000000
--- a/sdk/python/tests/test_serve.py
+++ /dev/null
@@ -1,212 +0,0 @@
-# Copyright 2026 Google LLC
-#
-# 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.
-
-"""The provider side in one process: this SDK's handlers for /sam/mcp/1.0.0
-and /libp2p-http behind a py-libp2p host, called with this SDK's clients.
-The real sam-node as a caller is exercised by tests/integration."""
-
-import json
-import threading
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-
-import biscuit_auth as ba
-import multiaddr
-import pytest
-import trio
-from libp2p.peer.peerinfo import info_from_p2p_addr
-from mcp.server.mcpserver import MCPServer
-
-from agent_mesh._proto import sam_pb2 as pb
-from agent_mesh.auth import MCP_PROTOCOL, AuthRejectedError
-from agent_mesh.authorizer import ProviderAuthorizerOptions
-from agent_mesh.controlplane import ROLE_NODE
-from agent_mesh.identity import Identity
-from agent_mesh.mcp_client import open_mcp_session, tool_call_result
-from agent_mesh.serve import (
- HTTP_PROTOCOL,
- HTTPRequest,
- HTTPResponse,
- HTTPService,
- MCPService,
- ProviderOptions,
- ServiceRegistry,
- http_ingress_handler,
- http_request_over_stream,
- mcp_stream_handler,
-)
-
-from .test_session import CP, CP_KEY, libp2p_host
-
-# What the control plane renders for a policy granting the node role calc,
-# echo and every inference service on any target.
-POLICY_RULES = [
- 'granted_service_set("mcp", ["calc", "echo"]) <- role("sam:role:node")',
- 'granted_service_all("inference") <- role("sam:role:node")',
- 'granted_service_all("sam:system") <- role("sam:role:node")',
- 'target_unrestricted(true) <- role("sam:role:node")',
-]
-
-
-def mint(peer_id: str, role: str) -> bytes:
- return ba.BiscuitBuilder(
- "node({p}); client_peer_id({p}); expiration(2035-01-01T00:00:00Z); role({r});", {"p": peer_id, "r": role}
- ).build(CP.private_key).to_bytes()
-
-
-def calc_server() -> MCPServer:
- server = MCPServer("calc")
-
- @server.tool()
- def add(a: int, b: int) -> str:
- return str(a + b)
-
- return server
-
-
-class FakeBackend(BaseHTTPRequestHandler):
- seen: list[dict] = []
-
- def _answer(self) -> None:
- length = int(self.headers.get("content-length") or 0)
- body = self.rfile.read(length) if length else b""
- FakeBackend.seen.append({"method": self.command, "path": self.path, "peer": self.headers.get("x-peer-id"), "body": body.decode(), "biscuit": self.headers.get("x-sam-biscuit")})
- payload = json.dumps({"path": self.path, "echo": body.decode()}).encode()
- self.send_response(200)
- self.send_header("content-type", "application/json")
- self.send_header("x-backend", "fake")
- self.send_header("content-length", str(len(payload)))
- self.end_headers()
- self.wfile.write(payload)
-
- do_GET = _answer
- do_POST = _answer
-
- def log_message(self, *_args) -> None: # noqa: D102 - quiet
- pass
-
-
[email protected](scope="module")
-def backend_url():
- server = ThreadingHTTPServer(("127.0.0.1", 0), FakeBackend)
- thread = threading.Thread(target=server.serve_forever, daemon=True)
- thread.start()
- yield f"http://127.0.0.1:{server.server_port}"
- server.shutdown()
-
-
-async def start_provider(nursery, backend_url: str, authorized: list[str]):
- identity = Identity.generate()
- host = libp2p_host(identity)
- biscuit = mint(identity.peer_id, ROLE_NODE)
- registry = ServiceRegistry()
- registry.add(MCPService(name="calc", create_server=calc_server))
- registry.add(HTTPService(type="inference", name="llm", target=backend_url))
-
- async def inproc(request: HTTPRequest, caller) -> HTTPResponse:
- return HTTPResponse(status=201, body=f"hello {caller.peer_id} {request.method} {request.path}".encode())
-
- registry.add(HTTPService(type="inference", name="inproc", target=inproc))
- options = ProviderOptions(
- authorizer=ProviderAuthorizerOptions(trusted_keys=lambda: [CP_KEY], own_biscuit=lambda: biscuit, policy_rules=lambda: POLICY_RULES),
- own_biscuit=lambda: biscuit,
- on_authorized=lambda peer, _v, target: authorized.append(f"{peer} {target}"),
- )
- host.set_stream_handler(MCP_PROTOCOL, mcp_stream_handler(registry, options, str(MCP_PROTOCOL)))
- host.set_stream_handler(HTTP_PROTOCOL, http_ingress_handler(registry, options))
- started = trio.Event()
- addr_box = []
-
- async def run():
- async with host.run(listen_addrs=[multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")]):
- addr_box.append(multiaddr.Multiaddr(f"{host.get_addrs()[0]}"))
- started.set()
- await trio.sleep_forever()
-
- nursery.start_soon(run)
- await started.wait()
- return host, addr_box[0]
-
-
-def frame(biscuit: bytes, target: str) -> bytes:
- return pb.AuthFrame(biscuit=biscuit, target_service=target).SerializeToString()
-
-
-def test_services_are_served_to_authorized_callers(backend_url):
- authorized: list[str] = []
-
- async def main():
- async with trio.open_nursery() as nursery:
- provider, addr = await start_provider(nursery, backend_url, authorized)
- caller_identity = Identity.generate()
- caller = libp2p_host(caller_identity)
- caller_biscuit = mint(caller_identity.peer_id, ROLE_NODE)
- guest_biscuit = mint(caller_identity.peer_id, "sam:role:guest")
- async with caller.run(listen_addrs=[]):
- await caller.connect(info_from_p2p_addr(addr))
- pid = provider.get_id()
-
- # An MCP service, then the member's own catalog.
- async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://calc"), [CP_KEY]) as (mcp, verified):
- assert verified.peer_id == str(pid)
- assert [t.name for t in (await mcp.list_tools()).tools] == ["add"]
- assert tool_call_result(await mcp.call_tool("add", {"a": 2, "b": 3})).text == ["5"]
- assert f"{caller_identity.peer_id} mcp://calc" in authorized
- async with open_mcp_session(caller, pid, frame(caller_biscuit, ""), [CP_KEY]) as (mcp, _):
- listed = json.loads(tool_call_result(await mcp.call_tool("list_local_services", {})).text[0])
- assert sorted(f"{s['type']}://{s['name']}" for s in listed) == ["inference://inproc", "inference://llm", "mcp://calc"]
-
- # A role that grants nothing is refused at the AuthResponse.
- with pytest.raises(AuthRejectedError, match="not authorized"):
- async with open_mcp_session(caller, pid, frame(guest_biscuit, "mcp://calc"), [CP_KEY]):
- pass
- # A service the role was not granted, likewise.
- with pytest.raises(AuthRejectedError):
- async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://secret"), [CP_KEY]):
- pass
- # Granted but not registered: success, then the stream closes.
- with pytest.raises(Exception): # noqa: B017 - the MCP initialize fails on the closed stream
- async with open_mcp_session(caller, pid, frame(caller_biscuit, "mcp://echo"), [CP_KEY]):
- pass
-
- # An inference service is proxied with the caller's identity and without its biscuit.
- res = await http_request_over_stream(caller, pid, caller_biscuit, "inference://llm", "/v1/models?x=1", headers={"x-sam-biscuit": "spoof"})
- assert res.status == 200
- assert res.headers.get("x-backend") == "fake"
- assert res.json() == {"path": "/v1/models?x=1", "echo": ""}
- assert FakeBackend.seen[-1]["peer"] == caller_identity.peer_id
- assert FakeBackend.seen[-1]["biscuit"] is None
- post = await http_request_over_stream(
- caller, pid, caller_biscuit, "inference://llm", "/v1/chat/completions", method="POST", headers={"content-type": "application/json"}, body='{"model": "m"}'
- )
- assert post.status == 200 and post.json()["echo"] == '{"model": "m"}'
-
- # An in-process handler sees the verified caller.
- res = await http_request_over_stream(caller, pid, caller_biscuit, "inference://inproc", "/agent/card")
- assert res.status == 201 and res.text == f"hello {caller_identity.peer_id} GET /agent/card"
-
- # What the policy does not grant is refused before the backend is reached.
- before = len(FakeBackend.seen)
- assert (await http_request_over_stream(caller, pid, guest_biscuit, "inference://llm", "/v1/models")).status == 403
- assert (await http_request_over_stream(caller, pid, caller_biscuit, "a2a://llm", "/")).status == 403
- assert len(FakeBackend.seen) == before
- assert (await http_request_over_stream(caller, pid, caller_biscuit, "inference://nope", "/")).status == 404
- assert (await http_request_over_stream(caller, pid, b"", "inference://llm", "/v1/models")).status == 401
- assert (await http_request_over_stream(caller, pid, caller_biscuit, "inference://llm", "/../other/x")).status == 400
- nursery.cancel_scope.cancel()
-
- async def with_timeout():
- with trio.fail_after(30):
- await main()
-
- trio.run(with_timeout)