Skip to content

Agent Mesh

sdk/python: resolve DNS multiaddrs and bound a dial; examples try every provider

Antonio Ojea3088dd8dab0c
diff --git a/sdk/js/README.md b/sdk/js/README.md
index 135390d5..857f1197 100644
--- a/sdk/js/README.md
+++ b/sdk/js/README.md
@@ -44,7 +44,7 @@ Find a service and call it:
// Kubernetes projected service account token), and keeps the identity and
// credential in SAM_STATE_DIR; later runs resume from there without it.
import { homedir } from "node:os";
-import { AgentMesh } from "@sam-mesh/sdk";
+import { AgentMesh, type DiscoveredProvider } from "@sam-mesh/sdk";
const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
@@ -59,10 +59,24 @@ const mesh = await AgentMesh.enroll({
const session = await mesh.join();
console.log(`on the mesh as ${session.peerId}`);
-const [provider] = await session.discover(service);
-if (provider === undefined) {
+const providers = await session.discover(service);
+if (providers.length === 0) {
throw new Error(`no member of the mesh serves ${service}`);
}
+// A provider record can outlive its member; the first that answers is used.
+let provider: DiscoveredProvider | undefined;
+for (const candidate of providers) {
+ try {
+ await session.connect(candidate);
+ provider = candidate;
+ break;
+ } catch (err) {
+ console.error(`${candidate.peerId}: ${(err as Error).message}`);
+ }
+}
+if (provider === undefined) {
+ throw new Error(`no provider of ${service} is reachable`);
+}
console.log(`${service} is served by ${provider.peerId}`);
if (service.startsWith("mcp://")) {
diff --git a/sdk/js/examples/call.ts b/sdk/js/examples/call.ts
index 124003c4..392ccb32 100644
--- a/sdk/js/examples/call.ts
+++ b/sdk/js/examples/call.ts
@@ -11,7 +11,7 @@
// Kubernetes projected service account token), and keeps the identity and
// credential in SAM_STATE_DIR; later runs resume from there without it.
import { homedir } from "node:os";
-import { AgentMesh } from "@sam-mesh/sdk";
+import { AgentMesh, type DiscoveredProvider } from "@sam-mesh/sdk";
const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
@@ -26,10 +26,24 @@ const mesh = await AgentMesh.enroll({
const session = await mesh.join();
console.log(`on the mesh as ${session.peerId}`);
-const [provider] = await session.discover(service);
-if (provider === undefined) {
+const providers = await session.discover(service);
+if (providers.length === 0) {
throw new Error(`no member of the mesh serves ${service}`);
}
+// A provider record can outlive its member; the first that answers is used.
+let provider: DiscoveredProvider | undefined;
+for (const candidate of providers) {
+ try {
+ await session.connect(candidate);
+ provider = candidate;
+ break;
+ } catch (err) {
+ console.error(`${candidate.peerId}: ${(err as Error).message}`);
+ }
+}
+if (provider === undefined) {
+ throw new Error(`no provider of ${service} is reachable`);
+}
console.log(`${service} is served by ${provider.peerId}`);
if (service.startsWith("mcp://")) {
diff --git a/sdk/python/README.md b/sdk/python/README.md
index b5f800f9..6d72c3ac 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -77,7 +77,15 @@ async def main() -> None:
providers = await session.discover(service)
if not providers:
raise SystemExit(f"no member of the mesh serves {service}")
- provider = providers[0]
+ # 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 {provider.peer_id}")
if service.startswith("mcp://"):
diff --git a/sdk/python/examples/call.py b/sdk/python/examples/call.py
index f37c1985..8a1ca068 100644
--- a/sdk/python/examples/call.py
+++ b/sdk/python/examples/call.py
@@ -41,7 +41,15 @@ async def main() -> None:
providers = await session.discover(service)
if not providers:
raise SystemExit(f"no member of the mesh serves {service}")
- provider = providers[0]
+ # 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 {provider.peer_id}")
if service.startswith("mcp://"):
diff --git a/sdk/python/src/agent_mesh/host.py b/sdk/python/src/agent_mesh/host.py
index d03d5ec3..69cdd3aa 100644
--- a/sdk/python/src/agent_mesh/host.py
+++ b/sdk/python/src/agent_mesh/host.py
@@ -23,16 +23,19 @@ from datetime import datetime, timedelta, timezone
from typing import Sequence
import multiaddr
+import trio
from cryptography import x509
from cryptography.x509.oid import NameOID
from libp2p import new_host
from libp2p.abc import IHost
from libp2p.crypto.ed25519 import create_new_key_pair
from libp2p.custom_types import TProtocol
+from libp2p.peer.peerinfo import PeerInfo, info_from_p2p_addr
from libp2p.security.tls.transport import PROTOCOL_ID as TLS_PROTOCOL_ID
from libp2p.security.tls.transport import IdentityConfig, TLSTransport
from libp2p.stream_muxer.yamux.yamux import PROTOCOL_ID as YAMUX_PROTOCOL_ID
from libp2p.stream_muxer.yamux.yamux import Yamux
+from multiaddr.resolvers import DNSResolver
from .identity import Identity
@@ -71,3 +74,41 @@ def create_mesh_host(identity: Identity, listen_addrs: Sequence[str] = ()) -> tu
if str(host.get_id()) != identity.peer_id:
raise RuntimeError(f"libp2p derived peer {host.get_id()} for identity {identity.peer_id}")
return host, [multiaddr.Multiaddr(a) for a in listen_addrs]
+
+
+_DNS_PROTOCOLS = frozenset({"dnsaddr", "dns", "dns4", "dns6"})
+# py-libp2p dials TCP only; a resolved address on another transport is noise.
+_UNDIALABLE_PROTOCOLS = frozenset({"quic", "quic-v1", "ws", "wss", "webtransport", "webrtc", "webrtc-direct"})
+_DNS_TIMEOUT = 10.0
+
+
+async def dial_addrs(addr: multiaddr.Multiaddr) -> list[multiaddr.Multiaddr]:
+ """The concrete addresses this host can dial for addr. A control plane
+ hands out router addresses as `/dnsaddr/<host>/p2p/<id>`, resolved here
+ through the host's `_dnsaddr` TXT records (and `/dns4`, `/dns6`, `/dns`
+ through A and AAAA records) the way go-libp2p and js-libp2p do before
+ dialing; py-libp2p does not, and would report no transport for them.
+ Addresses on transports this host lacks are left out."""
+ protocols = [p.name for p in addr.protocols()]
+ if protocols and protocols[0] in _DNS_PROTOCOLS:
+ resolved: list[multiaddr.Multiaddr] = []
+ with trio.move_on_after(_DNS_TIMEOUT):
+ resolved = list(await DNSResolver().resolve(addr))
+ if not resolved:
+ raise RuntimeError(f"{addr} resolved to no address")
+ else:
+ resolved = [addr]
+ dialable: list[multiaddr.Multiaddr] = []
+ for m in resolved:
+ names = {p.name for p in m.protocols()}
+ if "tcp" in names and not names & _UNDIALABLE_PROTOCOLS:
+ dialable.append(m)
+ if not dialable:
+ raise RuntimeError(f"{addr} offers no TCP address; this host dials TCP only")
+ return dialable
+
+
+async def peer_info(addr: multiaddr.Multiaddr) -> PeerInfo:
+ """The peer an address names and the concrete addresses to reach it on."""
+ addrs = await dial_addrs(addr)
+ return PeerInfo(info_from_p2p_addr(addrs[0]).peer_id, addrs)
diff --git a/sdk/python/src/agent_mesh/session.py b/sdk/python/src/agent_mesh/session.py
index fd3066f4..cfd51264 100644
--- a/sdk/python/src/agent_mesh/session.py
+++ b/sdk/python/src/agent_mesh/session.py
@@ -42,7 +42,7 @@ from .auth import AUTH_PROTOCOL, MCP_PROTOCOL, auth_stream_handler, authenticate
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 .host import create_mesh_host
+from .host import create_mesh_host, dial_addrs, peer_info
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
@@ -75,6 +75,11 @@ DEFAULT_CONTROL_PLANE_SYNC = 15 * 60.0
FIRST_CONTROL_PLANE_SYNC = 2.0
DEFAULT_CONTROL_PLANE_SYNC_JITTER = 2.0
+# sam-node's swarm dial timeout. py-libp2p has none of its own: a SYN to an
+# address nobody answers waits on the kernel, about two minutes, and is then
+# retried, and a provider record can name a pod a rollout just replaced.
+DIAL_TIMEOUT = 15.0
+
# How a caller names the peer it wants to reach: a provider `discover` returned,
# a peer id, or a multiaddr. For a provider or a peer id the SDK dials the
# addresses the peer advertised and then the relayed path through every router
@@ -88,6 +93,15 @@ def parse_peer_id(text: str) -> ID:
return ID.from_base58(canonical_peer_id(text))
+async def dial(host: IHost, info: PeerInfo) -> None:
+ """host.connect, bounded by DIAL_TIMEOUT."""
+ try:
+ with trio.fail_after(DIAL_TIMEOUT):
+ await host.connect(info)
+ except trio.TooSlowError:
+ raise ConnectionError(f"no connection to {info.peer_id} within {DIAL_TIMEOUT:g}s") from None
+
+
def canonical_peer_ids(ids: Sequence[str]) -> list[str]:
"""Canonicalizes a list from the control plane, dropping entries that are
not peer IDs: they can match nothing, so they ban nothing."""
@@ -182,10 +196,17 @@ class MeshSession:
return target
failures: list[str] = []
suffix = f"/p2p/{target}"
- direct = [multiaddr.Multiaddr(str(a).removesuffix(suffix)) for a in advertised if "/p2p-circuit" not in str(a)]
+ direct: list[multiaddr.Multiaddr] = []
+ for a in advertised:
+ if "/p2p-circuit" in str(a):
+ continue
+ try:
+ direct.extend(multiaddr.Multiaddr(str(m).removesuffix(suffix)) for m in await dial_addrs(a))
+ except Exception as err: # noqa: BLE001 - an address this host cannot use; the others are tried
+ failures.append(f"{a}: {err}")
if direct:
try:
- await self.host.connect(PeerInfo(target, direct))
+ await dial(self.host, PeerInfo(target, direct))
return target
except Exception as err: # noqa: BLE001 - the relayed path is tried next
failures.append(f"direct {[str(a) for a in direct]}: {err}")
@@ -204,13 +225,13 @@ class MeshSession:
self._refuse_banned(target)
relay = info_from_p2p_addr(relay_addr)
if relay.peer_id not in self.host.get_connected_peers():
- await self.host.connect(relay)
+ await dial(self.host, await peer_info(relay_addr))
if target not in self.host.get_connected_peers():
await dial_through_relay(self.host, relay.peer_id, target)
return target
- info = info_from_p2p_addr(ma)
+ info = await peer_info(ma)
self._refuse_banned(info.peer_id)
- await self.host.connect(info)
+ await dial(self.host, info)
return info.peer_id
def _refuse_banned(self, peer_id: ID) -> None:
@@ -539,8 +560,8 @@ async def _admit(host: IHost, mesh: "AgentMesh", router_addrs: list[multiaddr.Mu
failures: list[str] = []
for addr in router_addrs:
try:
- info = info_from_p2p_addr(addr)
- await host.connect(info)
+ info = await peer_info(addr)
+ await dial(host, info)
credential = await authenticate_with_peer(host, info.peer_id, mesh.auth_frame(), mesh.credential.control_plane_keys)
# Enforced under the key that verified the token; a relay that
# is not a router must not become our way onto the mesh.
diff --git a/sdk/python/tests/test_host.py b/sdk/python/tests/test_host.py
new file mode 100644
index 00000000..9e6996cd
--- /dev/null
+++ b/sdk/python/tests/test_host.py
@@ -0,0 +1,116 @@
+# 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.
+
+"""What a dial must do that py-libp2p does not: resolve a /dnsaddr router
+address through its TXT records and keep the transports this host has
+(dial_addrs), and give up on an address nobody answers (dial)."""
+
+import multiaddr
+import pytest
+import trio
+import trio.testing
+from libp2p.peer.id import ID
+from libp2p.peer.peerinfo import PeerInfo
+from multiaddr.resolvers import DNSResolver
+
+from agent_mesh.host import dial_addrs, peer_info
+from agent_mesh.session import DIAL_TIMEOUT, dial
+
+ROUTER = "12D3KooWG1pA6goegCncqwbZLSr8pnjUZ6JMAAe6SmnHTgUNCk88"
+OTHER = "12D3KooWGvdRCJLYATauVWfsieF2j3a2wXZoEQJUS2MsvRdDtgLM"
+
+
+class FakeTXT:
+ """A dnspython answer: one TXT record per string."""
+
+ def __init__(self, strings):
+ self._strings = strings
+
+ def __iter__(self):
+ for s in self._strings:
+ yield type("TXT", (), {"strings": [s.encode()]})()
+
+ def __len__(self):
+ return len(self._strings)
+
+
+def testnet_dns(monkeypatch):
+ """The _dnsaddr records a testnet publishes: two routers, TCP and QUIC each."""
+ records = {
+ "_dnsaddr.bootstrap.example": [
+ f"dnsaddr=/ip4/203.0.113.1/udp/4501/quic-v1/p2p/{ROUTER}",
+ f"dnsaddr=/ip4/203.0.113.1/tcp/4501/p2p/{ROUTER}",
+ f"dnsaddr=/ip4/203.0.113.2/tcp/4501/p2p/{OTHER}",
+ f"dnsaddr=/ip4/203.0.113.2/udp/4501/quic-v1/p2p/{OTHER}",
+ ],
+ "_dnsaddr.quic-only.example": [f"dnsaddr=/ip4/203.0.113.3/udp/4501/quic-v1/p2p/{ROUTER}"],
+ }
+
+ class FakeDNS:
+ async def resolve(self, name, rdtype):
+ assert rdtype == "TXT"
+ return FakeTXT(records.get(str(name).rstrip("."), []))
+
+ def init(self):
+ self._resolver = FakeDNS()
+
+ monkeypatch.setattr(DNSResolver, "__init__", init)
+
+
+def test_dnsaddr_router_address_resolves_to_its_tcp_address(testnet_dns):
+ async def main():
+ addrs = await dial_addrs(multiaddr.Multiaddr(f"/dnsaddr/bootstrap.example/p2p/{ROUTER}"))
+ assert [str(a) for a in addrs] == [f"/ip4/203.0.113.1/tcp/4501/p2p/{ROUTER}"]
+ info = await peer_info(multiaddr.Multiaddr(f"/dnsaddr/bootstrap.example/p2p/{ROUTER}"))
+ assert str(info.peer_id) == ROUTER and len(info.addrs) == 1
+
+ trio.run(main)
+
+
+def test_addresses_without_a_transport_this_host_has_are_an_error(testnet_dns):
+ async def main():
+ with pytest.raises(RuntimeError, match="TCP"):
+ await dial_addrs(multiaddr.Multiaddr(f"/dnsaddr/quic-only.example/p2p/{ROUTER}"))
+ with pytest.raises(RuntimeError, match="TCP"):
+ await dial_addrs(multiaddr.Multiaddr(f"/ip4/203.0.113.9/udp/4501/quic-v1/p2p/{ROUTER}"))
+ with pytest.raises(RuntimeError, match="no address"):
+ await dial_addrs(multiaddr.Multiaddr(f"/dnsaddr/nowhere.example/p2p/{ROUTER}"))
+
+ trio.run(main)
+
+
+def test_a_concrete_address_passes_through():
+ async def main():
+ ma = multiaddr.Multiaddr(f"/ip4/127.0.0.1/tcp/4001/p2p/{ROUTER}")
+ assert await dial_addrs(ma) == [ma]
+
+ trio.run(main)
+
+
+def test_a_dial_nobody_answers_ends_at_the_timeout():
+ """A provider record can name a pod a rollout replaced; its SYNs go
+ unanswered. The dial ends at DIAL_TIMEOUT, not at the kernel's."""
+
+ class Host:
+ async def connect(self, info):
+ await trio.sleep_forever()
+
+ async def main():
+ started = trio.current_time()
+ with pytest.raises(ConnectionError, match=f"within {DIAL_TIMEOUT:g}s"):
+ await dial(Host(), PeerInfo(ID.from_base58(ROUTER), []))
+ assert trio.current_time() - started == pytest.approx(DIAL_TIMEOUT)
+
+ trio.run(main, clock=trio.testing.MockClock(autojump_threshold=0))
diff --git a/site/content/docs/guides/native-sdks.md b/site/content/docs/guides/native-sdks.md
index 85e81e52..eedb11d9 100644
--- a/site/content/docs/guides/native-sdks.md
+++ b/site/content/docs/guides/native-sdks.md
@@ -289,7 +289,7 @@ JavaScript, `call.js`:
// Kubernetes projected service account token), and keeps the identity and
// credential in SAM_STATE_DIR; later runs resume from there without it.
import { homedir } from "node:os";
-import { AgentMesh } from "@sam-mesh/sdk";
+import { AgentMesh, type DiscoveredProvider } from "@sam-mesh/sdk";
const [service = "mcp://greeter", toolOrPath = "greet", args = '{"name": "world"}'] = process.argv.slice(2);
@@ -304,10 +304,24 @@ const mesh = await AgentMesh.enroll({
const session = await mesh.join();
console.log(`on the mesh as ${session.peerId}`);
-const [provider] = await session.discover(service);
-if (provider === undefined) {
+const providers = await session.discover(service);
+if (providers.length === 0) {
throw new Error(`no member of the mesh serves ${service}`);
}
+// A provider record can outlive its member; the first that answers is used.
+let provider: DiscoveredProvider | undefined;
+for (const candidate of providers) {
+ try {
+ await session.connect(candidate);
+ provider = candidate;
+ break;
+ } catch (err) {
+ console.error(`${candidate.peerId}: ${(err as Error).message}`);
+ }
+}
+if (provider === undefined) {
+ throw new Error(`no provider of ${service} is reachable`);
+}
console.log(`${service} is served by ${provider.peerId}`);
if (service.startsWith("mcp://")) {
@@ -371,7 +385,15 @@ async def main() -> None:
providers = await session.discover(service)
if not providers:
raise SystemExit(f"no member of the mesh serves {service}")
- provider = providers[0]
+ # 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 {provider.peer_id}")
if service.startswith("mcp://"):