diff --git a/core/mcp/models.py b/core/mcp/models.py index a16f4d95..b6b51f44 100644 --- a/core/mcp/models.py +++ b/core/mcp/models.py @@ -537,6 +537,11 @@ class McpToolIdentity: server_name: str source: McpServerSource raw_name: str + # Short fingerprint of the normalised input schema. Names and descriptions + # are text a server chooses; the schema is the shape a call must match, so + # this is the field that lets two providers be compared on substance. + # Defaulted so every existing construction site keeps working. + schema_digest: str = "" @dataclass(frozen=True, slots=True) diff --git a/core/mcp/naming.py b/core/mcp/naming.py index 705ab9f5..5a028158 100644 --- a/core/mcp/naming.py +++ b/core/mcp/naming.py @@ -3,7 +3,11 @@ from __future__ import annotations import hashlib +import json import re +from collections.abc import Iterable +from dataclasses import dataclass +from typing import Any MAX_TOOL_NAME_LENGTH = 64 _INVALID = re.compile(r"[^A-Za-z0-9_-]+") @@ -40,4 +44,89 @@ def _segment(value: str) -> str: return cleaned or "unnamed" -__all__ = ["MAX_TOOL_NAME_LENGTH", "visible_tool_name"] +def schema_digest(schema: dict[str, Any] | None) -> str: + """Stable short fingerprint of an MCP tool's normalised input schema. + + Names and descriptions are advisory text a server chooses freely; the input + schema is the shape a call must actually match. Two tools that accept + exactly the same arguments are interchangeable to a model even when they are + advertised by different servers -- that is the amplifier measured in + arXiv:2611.21577 (schema compatibility lifts the violation rate from 0 to + ~0.78 in its C09/C10 contrast). This digest lets a client *see* that overlap + instead of trusting the name. + + Canonicalisation is deliberate: ``sort_keys`` removes dict ordering, compact + separators remove whitespace, and non-ASCII is preserved so a localized + schema does not digest differently across machines. An absent schema + digests to a fixed value rather than raising -- a no-parameter tool is a + legitimate, common shape. + """ + canonical = json.dumps( + schema or {}, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + ) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:12] + + +@dataclass(frozen=True, slots=True) +class IdentityCollision: + """Two or more providers advertised a tool a model cannot tell apart. + + ``kind`` is ``"name"`` when the raw tool name is shared, or ``"schema"`` + when the parameter shape is. Both are advisory signals, not verdicts: a + legitimate deployment can expose the same ``read_file`` on two servers. + """ + + kind: str + value: str + server_ids: tuple[str, ...] + + @property + def key(self) -> tuple[str, str, tuple[str, ...]]: + return (self.kind, self.value, self.server_ids) + + +def find_identity_collisions( + entries: Iterable[tuple[str, str, str]], +) -> list[IdentityCollision]: + """Find tools that two different providers advertise indistinguishably. + + ``entries`` are ``(server_id, raw_tool_name, schema_digest)`` triples. A + collision needs *at least two distinct server ids*: the same server listing + the same shape twice is its own bug, not a provider-binding problem. + + An empty digest never collides -- it means we could not fingerprint the + schema, and reporting every unfingerprintable tool as a collision would + drown the signal. + """ + by_name: dict[str, set[str]] = {} + by_digest: dict[str, set[str]] = {} + for server_id, raw_name, digest in entries: + if raw_name: + by_name.setdefault(raw_name, set()).add(server_id) + if digest: + by_digest.setdefault(digest, set()).add(server_id) + + collisions: list[IdentityCollision] = [] + for raw_name, servers in sorted(by_name.items()): + if len(servers) > 1: + collisions.append( + IdentityCollision("name", raw_name, tuple(sorted(servers))) + ) + for digest, servers in sorted(by_digest.items()): + if len(servers) > 1: + collisions.append( + IdentityCollision("schema", digest, tuple(sorted(servers))) + ) + return collisions + + +__all__ = [ + "MAX_TOOL_NAME_LENGTH", + "IdentityCollision", + "find_identity_collisions", + "schema_digest", + "visible_tool_name", +] diff --git a/core/mcp/runtime.py b/core/mcp/runtime.py index e7d5f280..b7deea8e 100644 --- a/core/mcp/runtime.py +++ b/core/mcp/runtime.py @@ -13,7 +13,11 @@ from core.agent_runtime.tools.registry import ToolRegistry from core.mcp.connection import CredentialResolver, McpConnection, OAuthProviderFactory from core.mcp.models import McpRuntimePlan, McpStartupError, ResolvedMcpServer -from core.mcp.naming import visible_tool_name +from core.mcp.naming import ( + IdentityCollision, + find_identity_collisions, + visible_tool_name, +) from core.mcp.tools import McpToolAdapter # Servers whose startup timed out in this process. Every new session would @@ -152,6 +156,14 @@ def __init__( self._lock = asyncio.Lock() self._started = False self._closed = False + # Provider-binding bookkeeping (arXiv:2611.21577). Two servers may + # advertise tools a model cannot tell apart; recording that here turns + # an invisible selection hazard into a warning. It never blocks a tool: + # the paper shows there is no client-side identity to compare, so the + # only honest first step is to make the overlap observable. + self._identity_entries: list[tuple[str, str, str]] = [] + self._identity_collisions: tuple[IdentityCollision, ...] = () + self._logged_collision_keys: set[tuple[str, str, tuple[str, ...]]] = set() @property def started(self) -> bool: @@ -428,6 +440,14 @@ def _register_server_tools( self.registry.register(adapter) server_tools.append(name) exposed_count += 1 + self._identity_entries.append( + ( + adapter.identity.server_id, + adapter.identity.raw_name, + adapter.identity.schema_digest, + ) + ) + self._publish_identity_collisions() self._warn_unmatched_filters(server, seen_raw) tools = tuple(server_tools) self._capabilities[server.server_id] = tools @@ -446,6 +466,37 @@ def _register_server_tools( ) return server_tools + def _publish_identity_collisions(self) -> None: + """Recompute provider-binding overlaps and warn once per new overlap. + + A collision means two different servers advertised a tool that a model + cannot distinguish by name or by input shape (arXiv:2611.21577: metadata + helps recognition but does not prove origin). This is deliberately a + warning only -- there is no client-side provider identity to reject on, + and refusing to register a legitimate duplicate tool would break + deployments that expose the same capability twice. Downstream readers + can inspect :attr:`identity_collisions` instead of parsing logs. + """ + collisions = tuple(find_identity_collisions(self._identity_entries)) + self._identity_collisions = collisions + for collision in collisions: + if collision.key in self._logged_collision_keys: + continue + self._logged_collision_keys.add(collision.key) + what = "tool name" if collision.kind == "name" else "input schema" + logger.warning( + "MCP provider-binding overlap: {} {!r} is advertised by {} — " + "the metadata does not prove which provider a call reaches.", + what, + collision.value, + ", ".join(collision.server_ids), + ) + + @property + def identity_collisions(self) -> tuple[IdentityCollision, ...]: + """Tools two providers advertise indistinguishably (advisory only).""" + return self._identity_collisions + async def aclose(self) -> None: async with self._lock: if self._closed: diff --git a/core/mcp/tools.py b/core/mcp/tools.py index 66a02f3b..ae2e2039 100644 --- a/core/mcp/tools.py +++ b/core/mcp/tools.py @@ -16,6 +16,7 @@ McpToolAnnotations, McpToolIdentity, ) +from core.mcp.naming import schema_digest from core.mcp.schema import normalize_schema_for_openai from core.observability import log_mcp_call @@ -32,13 +33,19 @@ def __init__( ) -> None: server = connection.server self.connection = connection + self._name = visible_name + # The schema is normalised before the identity is built: the digest is + # part of the identity, and an identity without it cannot answer "is + # this the same tool another provider is advertising?". + raw_schema = getattr(tool_definition, "inputSchema", None) + self._parameters = normalize_schema_for_openai(raw_schema) self.identity = McpToolIdentity( server_id=server.server_id, server_name=server.name, source=server.source, raw_name=str(tool_definition.name), + schema_digest=schema_digest(self._parameters), ) - self._name = visible_name # Remote descriptions are untrusted and quality-uncontrolled — bound # length (they count against the prompt budget, keeping the historical # 8,000-character allowance) and replace degenerate/empty ones so the @@ -48,8 +55,6 @@ def __init__( name=visible_name, max_chars=_MCP_DESCRIPTION_MAX_CHARS, ) - raw_schema = getattr(tool_definition, "inputSchema", None) - self._parameters = normalize_schema_for_openai(raw_schema) self.annotations = McpToolAnnotations.from_sdk( getattr(tool_definition, "annotations", None) ) diff --git a/tests/test_mcp_identity_binding.py b/tests/test_mcp_identity_binding.py new file mode 100644 index 00000000..4a920c3a --- /dev/null +++ b/tests/test_mcp_identity_binding.py @@ -0,0 +1,123 @@ +"""Provider-bound tool identity: schema fingerprints and cross-server overlap. + +Background: arXiv:2611.21577 ("When Tool Names Are Not Identities") shows that +MCP tool metadata is not bound to a provider -- a second server can advertise a +tool the model cannot tell from the real one. The client-side answer available +to us is *not* enforcement (there is no signed identity to check) but making the +overlap observable: a stable schema fingerprint plus a collision report. + +These tests pin three properties that are easy to regress: + +* the digest ignores dict ordering and whitespace, so two servers emitting the + same schema digest identically; +* a collision needs two *different* servers -- one server repeating itself is a + different bug and must not be reported as a provider-binding overlap; +* an empty digest never collides, because "we could not fingerprint this" is + not evidence of a duplicate. +""" + +from __future__ import annotations + +from core.mcp.models import McpToolIdentity +from core.mcp.naming import ( + IdentityCollision, + find_identity_collisions, + schema_digest, +) + + +class TestSchemaDigest: + def test_digest_ignores_key_order_and_whitespace(self) -> None: + first = { + "type": "object", + "properties": {"a": {"type": "string"}, "b": {"type": "number"}}, + } + second = { + "properties": {"b": {"type": "number"}, "a": {"type": "string"}}, + "type": "object", + } + assert schema_digest(first) == schema_digest(second) + + def test_digest_changes_when_the_shape_changes(self) -> None: + base = {"type": "object", "properties": {"path": {"type": "string"}}} + widened = { + "type": "object", + "properties": {"path": {"type": "string", "description": "x"}}, + } + assert schema_digest(base) != schema_digest(widened) + + def test_absent_schema_is_a_value_not_an_error(self) -> None: + assert schema_digest(None) == schema_digest({}) + assert len(schema_digest(None)) == 12 + + def test_digest_is_deterministic(self) -> None: + schema = {"type": "object", "properties": {}} + assert schema_digest(schema) == schema_digest(dict(schema)) + + +class TestIdentityCollisions: + def test_same_name_from_two_servers_is_a_collision(self) -> None: + collisions = find_identity_collisions( + [ + ("server-a", "read_file", "aaa111"), + ("server-b", "read_file", "bbb222"), + ] + ) + name_hits = [c for c in collisions if c.kind == "name"] + assert len(name_hits) == 1 + assert name_hits[0].value == "read_file" + assert name_hits[0].server_ids == ("server-a", "server-b") + + def test_same_schema_from_two_servers_is_a_collision(self) -> None: + collisions = find_identity_collisions( + [ + ("server-a", "read_text", "same123"), + ("server-b", "load_document", "same123"), + ] + ) + schema_hits = [c for c in collisions if c.kind == "schema"] + assert len(schema_hits) == 1 + assert schema_hits[0].value == "same123" + + def test_one_server_repeating_itself_is_not_a_collision(self) -> None: + collisions = find_identity_collisions( + [ + ("server-a", "read_file", "same123"), + ("server-a", "read_file", "same123"), + ] + ) + assert collisions == [] + + def test_empty_digest_never_collides(self) -> None: + collisions = find_identity_collisions( + [ + ("server-a", "alpha", ""), + ("server-b", "beta", ""), + ] + ) + assert collisions == [] + + def test_disjoint_servers_produce_nothing(self) -> None: + collisions = find_identity_collisions( + [ + ("server-a", "alpha", "aaa111"), + ("server-b", "beta", "bbb222"), + ] + ) + assert collisions == [] + + def test_collision_key_is_stable_for_dedup(self) -> None: + one = IdentityCollision("name", "read_file", ("a", "b")) + two = IdentityCollision("name", "read_file", ("a", "b")) + assert one.key == two.key + + +class TestIdentityCarriesTheDigest: + def test_digest_defaults_to_empty_for_old_construction_sites(self) -> None: + identity = McpToolIdentity( + server_id="server-a", + server_name="Server A", + source="user", + raw_name="read_file", + ) + assert identity.schema_digest == "" diff --git a/tests/test_mcp_runtime.py b/tests/test_mcp_runtime.py index a3e5f134..cb4e3e64 100644 --- a/tests/test_mcp_runtime.py +++ b/tests/test_mcp_runtime.py @@ -1,5 +1,6 @@ from __future__ import annotations +import dataclasses import json import sys from pathlib import Path @@ -466,3 +467,41 @@ async def cancelled(self): result = await probe.probe_mcp_server(_server(tmp_path)) assert result.ok is False assert result.error.startswith("CancelledError") + + +@pytest.mark.asyncio +async def test_two_servers_exposing_the_same_tools_report_a_binding_overlap( + tmp_path: Path, +) -> None: + """A provider-binding overlap is observable, and nothing is refused. + + Two servers running the same fixture advertise identical tool names *and* + identical input schemas -- exactly the shape arXiv:2611.21577 measures + (name collision plus a compatible schema is its strongest amplifier). + + The runtime must report the overlap and still register every tool: there is + no client-side provider identity to reject on, and a legitimate deployment + may expose the same capability twice. Observability, not enforcement. + """ + registry = ToolRegistry() + first = _server(tmp_path) + second = dataclasses.replace(first, server_id="fixture-b", name="fixture-b") + plan = McpRuntimePlan(tmp_path, (first, second), "test") + runtime = McpSessionRuntime(plan, registry) + await runtime.ensure_started() + try: + collisions = runtime.identity_collisions + by_name = {c.value: c for c in collisions if c.kind == "name"} + assert set(by_name) == {"read_value", "write_value", "slow"} + assert by_name["read_value"].server_ids == ("fixture", "fixture-b") + # Identical schemas on both servers surface as schema collisions too. + assert any(c.kind == "schema" for c in collisions) + + # Fail-safe: both servers stay ready and every tool stays callable. + assert [status.state for status in runtime.statuses] == ["ready", "ready"] + assert [status.tool_count for status in runtime.statuses] == [3, 3] + assert len(registry.tool_names) == 6 + finally: + await runtime.aclose() + await registry.aclose() + assert not registry.tool_names