"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(mcp): include remote server identity in specs cache key
Lanre Shittu5c7f591a040b
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 78ea20acc..6b43a1c68 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -35,6 +35,7 @@ from pydantic_core import PydanticSerializationError, to_jsonable_pythonfrom src.agent.tools import BaseToolfrom src.config.schema import (ROBINHOOD_AGENT_CONFIG_PATH,+ MCPOAuthConfig,MCPServerConfig,live_broker_key_for_entry,robinhood_readonly_enabled_tools,@@ -63,14 +64,56 @@ _MCP_SPECS_CACHE: dict[tuple[str, ...], list["MCPRemoteToolSpec"]] = {}_MCP_SPECS_LOCK = threading.Lock()+def _fingerprint(text: str) -> str:+ """One-way fingerprint for a cache-key component that may carry secrets."""+ return hashlib.sha256(text.encode("utf-8")).hexdigest()+++def _fingerprint_auth(auth: MCPOAuthConfig | None) -> str:+ """Fingerprint an MCP server's OAuth config, never storing it raw.++ ``MCPOAuthConfig.client_secret`` is a real credential, so the whole+ config is hashed as one unit rather than spread across raw tuple+ elements.+ """+ if auth is None:+ return _fingerprint("")+ canonical = "|".join(+ [+ auth.type,+ str(sorted(auth.scopes)),+ auth.client_name,+ auth.cache_dir,+ str(auth.callback_port),+ auth.client_id or "",+ auth.client_secret or "",+ auth.client_metadata_url or "",+ ]+ )+ return _fingerprint(canonical)++def _make_cache_key(server_name: str, server_config: "MCPServerConfig") -> tuple[str, ...]:- """Build a content-based cache key for MCP tool discovery results."""+ """Build a content-based cache key for MCP tool discovery results.++ Every field that can change the tool specs a server returns must+ participate in cache identity (mirrors the enabled_tools fix this cache+ key already went through once). ``url``, ``headers``, and ``auth`` are+ fingerprinted rather than stored raw: a URL can carry a credential in+ its query string, a header can carry a static bearer token, and+ ``auth`` can carry an OAuth client secret. None of those should sit as+ plaintext in a process-wide in-memory cache key.+ """return (server_name,+ str(server_config.type),server_config.command,str(server_config.args or []),str(sorted((server_config.env or {}).items())),str(sorted(server_config.enabled_tools or [])),+ _fingerprint(server_config.url or ""),+ _fingerprint(str(sorted((server_config.headers or {}).items()))),+ _fingerprint_auth(server_config.auth),)diff --git a/agent/tests/test_mcp_specs_cache.py b/agent/tests/test_mcp_specs_cache.pyindex e285c3466..14fb0ec9e 100644--- a/agent/tests/test_mcp_specs_cache.py+++ b/agent/tests/test_mcp_specs_cache.py@@ -30,21 +30,53 @@ def _clear_cache():invalidate_mcp_specs_cache()-def _make_server_config(command="mcp-server", args=None, env=None, enabled_tools=None):+def _make_server_config(+ command="mcp-server",+ args=None,+ env=None,+ enabled_tools=None,+ type_=None,+ url=None,+ headers=None,+ auth=None,+):"""Create a minimal MCPServerConfig-like object for testing."""config = MagicMock()config.command = commandconfig.args = args or ["--port", "8080"]config.env = env or {}config.enabled_tools = enabled_tools or ["*"]- config.url = None+ config.type = type_+ config.url = urlconfig.tool_timeout = 30.0config.init_timeout = None- config.headers = {}- config.auth = None+ config.headers = headers or {}+ config.auth = authreturn config+def _make_oauth_config(+ client_name="Vibe-Trading",+ scopes=None,+ cache_dir="~/.vibe-trading/oauth",+ callback_port=None,+ client_id=None,+ client_secret=None,+ client_metadata_url=None,+):+ """Create a minimal MCPOAuthConfig-like object for testing."""+ auth = MagicMock()+ auth.type = "oauth"+ auth.scopes = scopes or []+ auth.client_name = client_name+ auth.cache_dir = cache_dir+ auth.callback_port = callback_port+ auth.client_id = client_id+ auth.client_secret = client_secret+ auth.client_metadata_url = client_metadata_url+ return auth++def _make_specs(server_name: str, tool_names: list[str]) -> list[MCPRemoteToolSpec]:"""Build a list of fake MCPRemoteToolSpec for testing."""return [@@ -101,6 +133,114 @@ class TestMakeCacheKey:key2 = _make_cache_key("srv", config2)assert key1 != key2+ def test_different_url_produces_different_key(self):+ """Two HTTP configs differing only in url must not share a cache entry."""+ config1 = _make_server_config(+ type_="sse", url="https://staging.example.com/mcp"+ )+ config2 = _make_server_config(type_="sse", url="https://prod.example.com/mcp")+ key1 = _make_cache_key("srv", config1)+ key2 = _make_cache_key("srv", config2)+ assert key1 != key2++ def test_different_headers_produces_different_key(self):+ """Two HTTP configs differing only in a header value must not share a cache entry."""+ config1 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"Authorization": "Bearer token-a"},+ )+ config2 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"Authorization": "Bearer token-b"},+ )+ key1 = _make_cache_key("srv", config1)+ key2 = _make_cache_key("srv", config2)+ assert key1 != key2++ def test_raw_header_secret_not_present_in_key(self):+ """A secret header value must never appear as plaintext in the cache key."""+ secret = "super-secret-bearer-token"+ config = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"Authorization": f"Bearer {secret}"},+ )+ key = _make_cache_key("srv", config)+ assert all(secret not in str(part) for part in key)++ def test_headers_in_different_insertion_order_produce_same_key(self):+ """Header fingerprinting must canonicalize order, not hash insertion order."""+ config1 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"Authorization": "x", "X-Tenant": "a"},+ )+ config2 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"X-Tenant": "a", "Authorization": "x"},+ )+ key1 = _make_cache_key("srv", config1)+ key2 = _make_cache_key("srv", config2)+ assert key1 == key2++ def test_different_oauth_config_produces_different_key(self):+ """Two configs differing only in OAuth client secret must not share a cache entry."""+ config1 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ auth=_make_oauth_config(client_secret="secret-a"),+ )+ config2 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ auth=_make_oauth_config(client_secret="secret-b"),+ )+ key1 = _make_cache_key("srv", config1)+ key2 = _make_cache_key("srv", config2)+ assert key1 != key2++ def test_raw_oauth_client_secret_not_present_in_key(self):+ """An OAuth client secret must never appear as plaintext in the cache key."""+ secret = "super-secret-oauth-client-secret"+ config = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ auth=_make_oauth_config(client_secret=secret),+ )+ key = _make_cache_key("srv", config)+ assert all(secret not in str(part) for part in key)++ def test_different_transport_type_produces_different_key(self):+ """Same url on a different transport type must not share a cache entry."""+ config1 = _make_server_config(type_="sse", url="https://example.com/mcp")+ config2 = _make_server_config(+ type_="streamableHttp", url="https://example.com/mcp"+ )+ key1 = _make_cache_key("srv", config1)+ key2 = _make_cache_key("srv", config2)+ assert key1 != key2++ def test_identical_http_config_produces_identical_key(self):+ """Two separately-built but equal HTTP configs must produce the same key."""+ config1 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"X-Tenant": "a"},+ auth=_make_oauth_config(client_id="abc"),+ )+ config2 = _make_server_config(+ type_="sse",+ url="https://example.com/mcp",+ headers={"X-Tenant": "a"},+ auth=_make_oauth_config(client_id="abc"),+ )+ key1 = _make_cache_key("srv", config1)+ key2 = _make_cache_key("srv", config2)+ assert key1 == key2+class TestMCPSpecsCache:"""Tests for the MCP tool discovery specs cache."""