From 8b1dfe01da0175f36d627df54f059d34b3cfc61e Mon Sep 17 00:00:00 2001 From: Rohan Date: Mon, 23 Nov 2026 17:56:49 +0530 Subject: [PATCH 1/3] mcp: insert server and tool names into generated handlers with repr() MCP tool names are chosen by the MCP server and can contain any character, including quotes, backslashes and newlines. Build the generated handler source with repr() literals, so every server and tool name is kept exactly as a string, in the docstring as well as in the values the handler uses. Action names and calls are unchanged. Adds tests with names containing quotes, newlines, triple quotes and a line continuation. Co-Authored-By: Claude Opus 5.5 --- agent_core/core/impl/mcp/adapter.py | 16 +++++---- tests/test_mcp_adapter_names.py | 50 +++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 tests/test_mcp_adapter_names.py diff --git a/agent_core/core/impl/mcp/adapter.py b/agent_core/core/impl/mcp/adapter.py index e34a32d1..42dcaca8 100644 --- a/agent_core/core/impl/mcp/adapter.py +++ b/agent_core/core/impl/mcp/adapter.py @@ -132,16 +132,20 @@ def create_mcp_handler_with_source( Returns: Tuple of (handler_function, source_code_string) """ - # Generate the source code as a string with values baked in + # Generate the source code as a string with values baked in. + # Server and tool names can contain any character (the server picks + # its tool names), so they are inserted with repr(), which always + # gives a valid string literal for them. # Note: We use double braces {{ }} for dict literals since this is an f-string - source_code = f'''def mcp_handler(input_data): - """MCP tool handler for {server_name}/{tool_name}.""" + docstring = f"MCP tool handler for {server_name}/{tool_name}." + source_code = f"""def mcp_handler(input_data): + {docstring!r} import asyncio from agent_core.core.impl.mcp.client import mcp_client from agent_core.utils.logger import logger - _server = "{server_name}" - _tool = "{tool_name}" + _server = {server_name!r} + _tool = {tool_name!r} # Remove any internal parameters (starting with _) tool_args = {{ @@ -166,7 +170,7 @@ async def async_call(): except Exception as e: logger.error(f"Error calling MCP tool {{_server}}/{{_tool}}: {{e}}") return {{"status": "error", "message": str(e)}} -''' +""" # Create the actual function by executing the source local_ns = {} diff --git a/tests/test_mcp_adapter_names.py b/tests/test_mcp_adapter_names.py new file mode 100644 index 00000000..0fe9e3bd --- /dev/null +++ b/tests/test_mcp_adapter_names.py @@ -0,0 +1,50 @@ +"""Generated MCP tool handlers keep server and tool names as plain strings. + +A tool's name comes from the MCP server and may contain quotes, newlines +or backslashes. The generated handler must hold it unchanged as a string, +both when the action is defined and when the agent calls it. +""" + +from __future__ import annotations + +from typing import Dict + +import pytest + +from agent_core.core.impl.mcp.adapter import MCPActionAdapter +from agent_core.core.impl.mcp.server import MCPTool + + +@pytest.mark.parametrize( + "tool_name", + [ + 'x"; open(MARKER, "w").close(); _ = "', + 'x"\nopen(MARKER, "w").close()\n_ = "', + 'y"""\nopen(MARKER, "w").close()\n"""', + "z\\\nopen(MARKER, 'w').close()", + ], +) +def test_names_with_quotes_and_newlines_stay_strings(tmp_path, tool_name): + marker = tmp_path / "marker" + name = tool_name.replace("MARKER", repr(str(marker))) + handler, source = MCPActionAdapter.create_mcp_handler_with_source( + f'srv"{name}', name + ) + compile(source, "", "exec") # still valid Python + namespace: Dict = {} + exec(source, namespace) # how the action system defines it + assert not marker.exists() + code = namespace["mcp_handler"].__code__ + assert name in code.co_consts and f'srv"{name}' in code.co_consts + # ...and how it runs it when the agent uses the tool. The call itself + # fails (no MCP client here); what matters is that the name did not run. + namespace["mcp_handler"]({}) + handler({}) + assert not marker.exists() + + +def test_a_registered_tool_with_quotes_in_its_name_round_trips(tmp_path): + tool = MCPTool(name='echo"; import os #', description="d", input_schema={}) + action = MCPActionAdapter.mcp_tool_to_registered_action("srv", tool, "mcp_srv") + assert action.metadata.name == 'mcp_srv_echo"; import os #' + assert 'echo"; import os #' in action.handler.__code__.co_consts From 5dd9d81e28e0c6f5bd28c062a129360b97644bb8 Mon Sep 17 00:00:00 2001 From: Rohan Date: Mon, 23 Nov 2026 17:56:50 +0530 Subject: [PATCH 2/3] #185: add Streamable HTTP transport and per-server headers for MCP Adds the MCP Streamable HTTP transport ("transport": "http", with the aliases streamable_http and streamable-http): JSON and SSE responses, Mcp-Session-Id and MCP-Protocol-Version handling, renewing an expired session once, resuming SSE streams, a size limit per message and DELETE on close. Redirects are not followed. Per-server "headers" and "timeout" are validated in mcp_config.json. ${NAME} references in header values resolve only from that server's own "env", never from the process environment. Header values are never listed or logged, and URLs are logged without credentials. Also: - reload reconnects changed or dead servers and keeps the last good settings of a server whose new entry is invalid; - invalid entries are kept on save and reported; - tool listing is paginated; - /mcp add --transport http and /mcp header; - profile bundles validate entries with the same rules and keep local credentials only for the same server; - AGENT.md documents the http transport. The settings payload for the existing editors is unchanged; header values and stdio arguments are not sent. Part of #185. Co-Authored-By: Claude Opus 5.5 --- agent_core/core/impl/mcp/__init__.py | 2 + agent_core/core/impl/mcp/adapter.py | 30 +- agent_core/core/impl/mcp/client.py | 311 ++++++-- agent_core/core/impl/mcp/config.py | 437 ++++++++++- agent_core/core/impl/mcp/server.py | 690 ++++++++++++++++- agent_file_system/AGENT.md | 27 +- app/data/agent_file_system_template/AGENT.md | 27 +- app/mcp/__init__.py | 2 + app/ui_layer/commands/builtin/mcp.py | 78 +- app/ui_layer/settings/__init__.py | 4 + app/ui_layer/settings/mcp_settings.py | 222 ++++-- app/ui_layer/settings/profile_bundle.py | 150 +++- tests/mcp_http_mock.py | 203 +++++ tests/test_mcp_client_lifecycle.py | 417 +++++++++++ tests/test_mcp_config.py | 388 ++++++++++ tests/test_mcp_settings.py | 354 +++++++++ tests/test_mcp_streamable_http.py | 739 +++++++++++++++++++ tests/test_mcp_streamable_http_interop.py | 179 +++++ 18 files changed, 4024 insertions(+), 236 deletions(-) create mode 100644 tests/mcp_http_mock.py create mode 100644 tests/test_mcp_client_lifecycle.py create mode 100644 tests/test_mcp_config.py create mode 100644 tests/test_mcp_settings.py create mode 100644 tests/test_mcp_streamable_http.py create mode 100644 tests/test_mcp_streamable_http_interop.py diff --git a/agent_core/core/impl/mcp/__init__.py b/agent_core/core/impl/mcp/__init__.py index 3566183c..f38bac36 100644 --- a/agent_core/core/impl/mcp/__init__.py +++ b/agent_core/core/impl/mcp/__init__.py @@ -16,6 +16,7 @@ StdioTransport, SSETransport, WebSocketTransport, + StreamableHTTPTransport, MCPServerConnection, set_client_info, get_client_info, @@ -39,6 +40,7 @@ "StdioTransport", "SSETransport", "WebSocketTransport", + "StreamableHTTPTransport", "MCPServerConnection", "set_client_info", "get_client_info", diff --git a/agent_core/core/impl/mcp/adapter.py b/agent_core/core/impl/mcp/adapter.py index 42dcaca8..a4efac06 100644 --- a/agent_core/core/impl/mcp/adapter.py +++ b/agent_core/core/impl/mcp/adapter.py @@ -141,6 +141,7 @@ def create_mcp_handler_with_source( source_code = f"""def mcp_handler(input_data): {docstring!r} import asyncio + import concurrent.futures from agent_core.core.impl.mcp.client import mcp_client from agent_core.utils.logger import logger @@ -166,7 +167,15 @@ async def async_call(): # Use run_coroutine_threadsafe to schedule on the MCP client's event loop # This works from any thread (including ThreadPoolExecutor workers) future = asyncio.run_coroutine_threadsafe(async_call(), loop) - return future.result(timeout=60) + wait = mcp_client.handler_timeout(_server) + try: + return future.result(timeout=wait) + except concurrent.futures.TimeoutError: + future.cancel() # do not leave the call running unseen + return {{ + "status": "error", + "message": f"MCP tool {{_server}}/{{_tool}} did not finish within {{wait:g}}s", + }} except Exception as e: logger.error(f"Error calling MCP tool {{_server}}/{{_tool}}: {{e}}") return {{"status": "error", "message": str(e)}} @@ -203,7 +212,7 @@ def mcp_tool_to_registered_action( RegisteredAction ready for registration """ # Generate unique action name - action_name = f"mcp_{server_name}_{tool.name}" + action_name = MCPActionAdapter.action_name(server_name, tool.name) # Build description with MCP context description_parts = [f"[MCP:{server_name}]"] @@ -325,3 +334,20 @@ def unregister_mcp_tools(server_name: str) -> int: logger.debug(f"Unregistered MCP action: {action_name}") return count + + @staticmethod + def action_name(server_name: str, tool_name: str) -> str: + """The action name an MCP tool is registered under.""" + return f"mcp_{server_name}_{tool_name}" + + @staticmethod + def unregister_actions(action_names) -> int: + """Unregister exactly these actions (unlike unregister_mcp_tools, + whose prefix match also hits a server whose name extends this one, + e.g. "foo" and "foo_bar").""" + count = 0 + for action_name in list(action_names): + if registry_instance._registry.pop(action_name, None) is not None: + count += 1 + logger.debug(f"Unregistered MCP action: {action_name}") + return count diff --git a/agent_core/core/impl/mcp/client.py b/agent_core/core/impl/mcp/client.py index bb63954f..b60230df 100644 --- a/agent_core/core/impl/mcp/client.py +++ b/agent_core/core/impl/mcp/client.py @@ -4,16 +4,24 @@ Singleton manager for all MCP server connections. Handles initialization, connection management, tool discovery, and action registration. + +Servers are independent: each has its own connection, headers and error, and +a reload only touches the servers whose configuration changed. """ import asyncio from pathlib import Path -from typing import Any, Dict, List, Optional +from typing import Any, Dict, Iterable, List, Optional, Set from agent_core.utils.logger import logger -from agent_core.core.impl.mcp.config import MCPConfig +from agent_core.core.impl.mcp.config import MCPConfig, MCPServerConfig from agent_core.core.impl.mcp.server import MCPServerConnection, MCPTool +# How long a tool handler waits for a call when the server sets no longer +# timeout; http servers get their own timeout plus HANDLER_MARGIN. +DEFAULT_HANDLER_TIMEOUT = 60.0 +HANDLER_MARGIN = 10.0 + def _default_config_path() -> Path: """The user-editable MCP config. @@ -63,6 +71,12 @@ def __init__(self): self._servers: Dict[str, MCPServerConnection] = {} self._config: Optional[MCPConfig] = None self._event_loop: Optional[asyncio.AbstractEventLoop] = None + # Why each enabled server that is not connected failed (safe text). + self._last_errors: Dict[str, str] = {} + # Exact action names registered for each server. + self._registered_actions: Dict[str, Set[str]] = {} + # Serialises initialize/reload so two config writes cannot interleave. + self._lifecycle_lock: Optional[asyncio.Lock] = None self._initialized = True @property @@ -80,6 +94,29 @@ def event_loop(self) -> Optional[asyncio.AbstractEventLoop]: """Get the event loop used by this client for MCP connections.""" return self._event_loop + @property + def last_errors(self) -> Dict[str, str]: + """Why each enabled server that is not connected failed.""" + return dict(self._last_errors) + + def _lock(self) -> asyncio.Lock: + if self._lifecycle_lock is None: + self._lifecycle_lock = asyncio.Lock() + return self._lifecycle_lock + + def handler_timeout(self, server_name: str) -> float: + """Seconds a tool handler waits for a call on this server: long + enough for the server's own request timeout to fire first.""" + connection = self._servers.get(server_name) + config = connection.config if connection else None + if config is None and self._config is not None: + config = self._config.get_server_by_name(server_name) + if config is not None and config.transport == "http": + return max( + DEFAULT_HANDLER_TIMEOUT, config.effective_timeout + HANDLER_MARGIN + ) + return DEFAULT_HANDLER_TIMEOUT + async def initialize(self, config_path: Optional[Path] = None) -> None: """ Initialize the MCP client with configuration. @@ -111,7 +148,8 @@ async def initialize(self, config_path: Optional[Path] = None) -> None: # Auto-connect to enabled servers if configured if self._config.auto_connect: - await self._connect_enabled_servers() + async with self._lock(): + await self._connect_enabled_servers() async def _connect_enabled_servers(self) -> None: """Connect to all enabled servers in parallel for faster startup.""" @@ -127,35 +165,40 @@ async def _connect_enabled_servers(self) -> None: logger.info( f"Connecting to {len(enabled_servers)} MCP server(s) in parallel..." ) + await self._connect_many([s.name for s in enabled_servers]) - async def connect_with_logging(server): - """Connect to a single server with logging.""" - try: + async def _connect_many(self, names: Iterable[str]) -> Dict[str, bool]: + """Connect several servers concurrently; one failing (or raising) + never stops the others.""" + + async def connect_with_logging(name: str) -> bool: + server = self._config.get_server_by_name(name) if self._config else None + if server is not None: logger.info( - f"[MCP] Connecting to '{server.name}' ({server.transport}): {server.command} {server.args}" + f"[MCP] Connecting to '{name}' ({server.transport}): {_describe(server)}" ) - result = await self.connect_server(server.name) - if result: - tools = self._servers[server.name].tools - logger.info( - f"[MCP] Successfully connected to '{server.name}' with {len(tools)} tools" - ) - else: - logger.warning( - f"[MCP] Failed to connect to '{server.name}' - check server configuration" - ) - return result - except Exception as e: - import traceback - + try: + result = await self.connect_server(name) + except Exception as e: # connect_server reports its own failures + self._last_errors[name] = f"connect failed: {type(e).__name__}" logger.error( - f"[MCP] Exception connecting to '{server.name}': {type(e).__name__}: {e}" + f"[MCP] Exception connecting to '{name}': {type(e).__name__}: {e}" ) - logger.debug(f"[MCP] Traceback: {traceback.format_exc()}") return False + if result: + tools = self._servers[name].tools + logger.info( + f"[MCP] Successfully connected to '{name}' with {len(tools)} tools" + ) + else: + logger.warning( + f"[MCP] Failed to connect to '{name}' - check server configuration" + ) + return result - # Connect to all servers in parallel - await asyncio.gather(*[connect_with_logging(s) for s in enabled_servers]) + names = list(names) + results = await asyncio.gather(*[connect_with_logging(n) for n in names]) + return dict(zip(names, results)) async def connect_server(self, server_name: str) -> bool: """ @@ -178,7 +221,7 @@ async def connect_server(self, server_name: str) -> bool: return True else: # Remove stale connection - del self._servers[server_name] + await self.disconnect_server(server_name) # Get server config server_config = self._config.get_server_by_name(server_name) @@ -190,26 +233,37 @@ async def connect_server(self, server_name: str) -> bool: connection = MCPServerConnection(server_config) if await connection.connect(): self._servers[server_name] = connection + self._last_errors.pop(server_name, None) return True - else: - return False + self._last_errors[server_name] = connection.last_error or "connection failed" + return False async def disconnect_server(self, server_name: str) -> None: """ - Disconnect from a specific MCP server. + Disconnect from a specific MCP server and remove its actions. Args: server_name: Name of the server to disconnect """ - if server_name in self._servers: - await self._servers[server_name].disconnect() - del self._servers[server_name] + connection = self._servers.pop(server_name, None) + self._unregister_server_actions(server_name) + if connection is not None: + await connection.disconnect() logger.info(f"Disconnected from server '{server_name}'") async def disconnect_all(self) -> None: - """Disconnect from all MCP servers.""" - for server_name in list(self._servers.keys()): - await self.disconnect_server(server_name) + """Disconnect from all MCP servers (concurrently, so one slow + server does not delay the others at shutdown).""" + names = list(self._servers.keys()) + results = await asyncio.gather( + *[self.disconnect_server(name) for name in names], + return_exceptions=True, + ) + for name, result in zip(names, results): + if isinstance(result, BaseException): + logger.warning( + f"[MCP] Error disconnecting '{name}': {type(result).__name__}" + ) logger.info("Disconnected from all MCP servers") def get_all_tools(self) -> Dict[str, List[MCPTool]]: @@ -296,10 +350,20 @@ async def refresh_tools(self, server_name: Optional[str] = None) -> None: if server.is_connected: await server.list_tools() + def _unregister_server_actions(self, server_name: str) -> int: + from agent_core.core.impl.mcp.adapter import MCPActionAdapter + + names = self._registered_actions.pop(server_name, set()) + return MCPActionAdapter.unregister_actions(names) + def register_tools_as_actions(self) -> int: """ Register all MCP tools as actions in the ActionRegistry. + Actions of servers that are gone, and tools a server no longer + offers, are unregistered by exact name (never by prefix: server + "foo" must not remove "foo_bar"'s actions). + Returns: Number of tools registered """ @@ -307,6 +371,11 @@ def register_tools_as_actions(self) -> int: total_registered = 0 + for server_name in list(self._registered_actions): + server = self._servers.get(server_name) + if server is None or not server.is_connected: + self._unregister_server_actions(server_name) + if not self._servers: logger.warning("[MCP] No servers connected, cannot register tools") return 0 @@ -318,8 +387,11 @@ def register_tools_as_actions(self) -> int: ) continue + previous = self._registered_actions.get(server_name, set()) if not server.tools: logger.warning(f"[MCP] Server '{server_name}' has no tools to register") + MCPActionAdapter.unregister_actions(previous) + self._registered_actions.pop(server_name, None) continue action_set_name = server.config.resolved_action_set_name @@ -330,6 +402,12 @@ def register_tools_as_actions(self) -> int: action_set_name=action_set_name, server_description=server.config.description, ) + current = { + MCPActionAdapter.action_name(server_name, tool.name) + for tool in server.tools + } + MCPActionAdapter.unregister_actions(previous - current) + self._registered_actions[server_name] = current total_registered += count logger.info( @@ -343,10 +421,13 @@ def get_status(self) -> Dict[str, Any]: """ Get current status of all MCP connections. + Servers that are enabled but failed to connect are included with + ``connected: False`` and a safe ``error``. + Returns: Status information for each server """ - status = { + status: Dict[str, Any] = { "initialized": self._config is not None, "servers": {}, } @@ -358,6 +439,20 @@ def get_status(self) -> Dict[str, Any]: "tool_count": len(server.tools), "tools": [t.name for t in server.tools], "action_set": server.config.resolved_action_set_name, + "error": None if server.is_connected else self._last_errors.get(name), + } + + for name, error in self._last_errors.items(): + if name in status["servers"]: + continue + config = self._config.get_server_by_name(name) if self._config else None + status["servers"][name] = { + "connected": False, + "transport": config.transport if config else None, + "tool_count": 0, + "tools": [], + "action_set": config.resolved_action_set_name if config else None, + "error": error, } return status @@ -368,9 +463,14 @@ async def reload(self, config_path: Optional[Path] = None) -> Dict[str, Any]: This method: 1. Reloads the config file from disk - 2. Disconnects servers that are no longer enabled or removed - 3. Connects new servers that are now enabled - 4. Re-registers all tools as actions + 2. Disconnects servers that were removed or disabled + 3. Reconnects only servers whose connection settings changed + 4. Keeps a running server on its last good settings when its entry + became invalid, and reports the error + 5. Connects servers that are new, or that failed before + 6. Re-registers all tools as actions + + Servers whose settings did not change are left connected. Args: config_path: Path to the configuration file. If None, uses the @@ -379,11 +479,14 @@ async def reload(self, config_path: Optional[Path] = None) -> Dict[str, Any]: Returns: Dictionary with reload results including connected/disconnected servers """ - result = { + result: Dict[str, Any] = { "success": True, "disconnected": [], + "reconnected": [], "connected": [], "failed": [], + "kept": [], + "invalid": [], "total_tools": 0, "message": "", } @@ -391,58 +494,97 @@ async def reload(self, config_path: Optional[Path] = None) -> Dict[str, Any]: # Use provided path, stored path, or default config_path = Path(config_path) if config_path else DEFAULT_CONFIG_PATH - # Reload configuration - try: - new_config = MCPConfig.load(config_path) - logger.info( - f"[MCP] Reloaded config with {len(new_config.mcp_servers)} server(s)" - ) - except Exception as e: - logger.error(f"[MCP] Failed to reload config: {e}") - result["success"] = False - result["message"] = f"Failed to reload config: {e}" - return result - - # Get list of currently enabled servers from new config - enabled_server_names = {s.name for s in new_config.get_enabled_servers()} - current_server_names = set(self._servers.keys()) - - # Disconnect servers that are no longer enabled or removed - servers_to_disconnect = current_server_names - enabled_server_names - for server_name in servers_to_disconnect: + async with self._lock(): + # Reload configuration try: - await self.disconnect_server(server_name) - result["disconnected"].append(server_name) + new_config = MCPConfig.load(config_path) logger.info( - f"[MCP] Disconnected server '{server_name}' (no longer enabled)" + f"[MCP] Reloaded config with {len(new_config.mcp_servers)} server(s)" ) except Exception as e: - logger.warning(f"[MCP] Error disconnecting '{server_name}': {e}") + logger.error(f"[MCP] Failed to reload config: {e}") + result["success"] = False + result["message"] = f"Failed to reload config: {e}" + return result + + enabled: Dict[str, MCPServerConfig] = { + s.name: s for s in new_config.get_enabled_servers() + } + invalid = {e.name: e.error for e in new_config.invalid_servers if e.name} + result["invalid"] = [ + {"name": name, "error": error} for name, error in invalid.items() + ] + + to_disconnect: List[str] = [] + to_reconnect: List[str] = [] + for name, connection in self._servers.items(): + new = enabled.get(name) + if new is not None: + if ( + new.connection_fingerprint() + != connection.config.connection_fingerprint() + # A connection that died (e.g. its session could not + # be renewed) is retried even if nothing changed. + or not connection.is_connected + ): + to_reconnect.append(name) + else: + # Same connection; pick up description/action set. + connection.config = new + elif name in invalid and new_config.get_server_by_name(name) is None: + # The edit broke the entry: keep serving the last good one. + result["kept"].append(name) + logger.warning( + f"[MCP] Keeping '{name}' connected on its previous settings: " + f"{invalid[name]}" + ) + else: + to_disconnect.append(name) - # Update config before connecting new servers - self._config = new_config + # Update config before connecting new servers + self._config = new_config + # Errors are kept only for servers that are still enabled. + self._last_errors = { + n: e for n, e in self._last_errors.items() if n in enabled + } - # Connect new servers that are now enabled - servers_to_connect = enabled_server_names - current_server_names - for server_name in servers_to_connect: - try: - success = await self.connect_server(server_name) - if success: - result["connected"].append(server_name) - logger.info(f"[MCP] Connected new server '{server_name}'") + for name in to_disconnect + to_reconnect: + try: + await self.disconnect_server(name) + if name in to_disconnect: + result["disconnected"].append(name) + logger.info( + f"[MCP] Disconnected server '{name}' (no longer enabled)" + ) + except Exception as e: + logger.warning( + f"[MCP] Error disconnecting '{name}': {type(e).__name__}" + ) + + to_connect = to_reconnect + [ + name + for name in enabled + if name not in self._servers and name not in to_reconnect + ] + outcomes = await self._connect_many(to_connect) + for name, ok in outcomes.items(): + if not ok: + result["failed"].append(name) + elif name in to_reconnect: + result["reconnected"].append(name) else: - result["failed"].append(server_name) - except Exception as e: - logger.error(f"[MCP] Failed to connect '{server_name}': {e}") - result["failed"].append(server_name) + result["connected"].append(name) + logger.info(f"[MCP] Connected new server '{name}'") - # Re-register all tools as actions - result["total_tools"] = self.register_tools_as_actions() + # Re-register all tools as actions + result["total_tools"] = self.register_tools_as_actions() result["message"] = ( f"Reload complete. Connected: {len(result['connected'])}, " + f"Reconnected: {len(result['reconnected'])}, " f"Disconnected: {len(result['disconnected'])}, " f"Failed: {len(result['failed'])}, " + f"Kept on previous settings: {len(result['kept'])}, " f"Total tools: {result['total_tools']}" ) @@ -450,5 +592,16 @@ async def reload(self, config_path: Optional[Path] = None) -> Dict[str, Any]: return result +def _describe(server: MCPServerConfig) -> str: + """How a server is reached, for logs. Never includes env or header + values; URLs lose their user info and query.""" + from agent_core.core.impl.mcp.config import redact_url + + if server.transport == "stdio": + return f"{server.command} {server.args}" + headers = f", headers: {sorted(server.headers)}" if server.headers else "" + return f"{redact_url(server.url)}{headers}" + + # Global singleton instance mcp_client = MCPClient() diff --git a/agent_core/core/impl/mcp/config.py b/agent_core/core/impl/mcp/config.py index a5960db4..dae96734 100644 --- a/agent_core/core/impl/mcp/config.py +++ b/agent_core/core/impl/mcp/config.py @@ -3,15 +3,204 @@ MCP Configuration Module Handles loading and validation of MCP server configurations. + +Validation happens in two places, on purpose: + +* Structure is checked when an entry is built (``MCPServerConfig``): the + transport, the URL shape, header names and values, the timeout. An entry + that fails is kept as an ``InvalidServerEntry`` and written back unchanged + on save, so a typo never deletes a server. +* Secrets are resolved when a server connects (``resolve_headers``). A header + value may reference ``${NAME}``, which is looked up in that server's own + ``env`` and nowhere else. A missing or empty value fails only that server, + and error messages name the variable, never a value. + +The ``env`` and header values are credentials: nothing in this module puts +them in a log line or an exception message. """ import json +import math +import re from dataclasses import dataclass, field from pathlib import Path -from typing import Dict, List, Optional, Any +from typing import Any, Dict, List, Optional +from urllib.parse import urlsplit, urlunsplit from agent_core.utils.logger import logger +# Streamable HTTP is configured as "http"; the aliases are accepted on input +# and normalised, so a saved file always says "http". +VALID_TRANSPORTS = ("stdio", "sse", "websocket", "http") +TRANSPORT_ALIASES = {"streamable_http": "http", "streamable-http": "http"} +URL_TRANSPORTS = ("sse", "websocket", "http") + +DEFAULT_HTTP_TIMEOUT = 30.0 +MAX_TIMEOUT = 300.0 + +# RFC 9110 token characters. +_HEADER_NAME_RE = re.compile(r"^[!#$%&'*+.^_`|~0-9A-Za-z-]+$") +# Any control character except horizontal tab (CR/LF would split headers). +_HEADER_VALUE_FORBIDDEN_RE = re.compile(r"[\x00-\x08\x0a-\x1f\x7f]") +_ENV_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}") +# Public: other modules (profile bundles) find ${NAME} references with it. +ENV_REF_RE = _ENV_REF_RE + +# Headers the transport owns. A configured value would break the protocol +# (Accept, Content-Type, session/version headers) or HTTP framing. +RESERVED_HEADERS = frozenset( + { + "accept", + "connection", + "content-length", + "content-type", + "expect", + "host", + "keep-alive", + "last-event-id", + "mcp-protocol-version", + "mcp-session-id", + "proxy-connection", + "te", + "trailer", + "transfer-encoding", + "upgrade", + } +) + +_KNOWN_SERVER_KEYS = frozenset( + { + "name", + "description", + "transport", + "command", + "args", + "cwd", + "url", + "env", + "headers", + "timeout", + "enabled", + "action_set_name", + } +) + + +class MCPConfigError(ValueError): + """An MCP server configuration is invalid. The message is safe to show: + it never contains an env or header value.""" + + +def redact_url(url: Optional[str]) -> str: + """The URL without user info, query string or fragment, for logs and + errors. Those parts are where credentials end up in URLs.""" + if not url: + return "" + try: + parts = urlsplit(str(url)) + except ValueError: + return "" + host = parts.hostname or "" + if ":" in host: # IPv6 literal + host = f"[{host}]" + try: + port = parts.port + except ValueError: + port = None + netloc = f"{host}:{port}" if port else host + redacted = urlunsplit((parts.scheme, netloc, parts.path, "", "")) + if parts.username or parts.password or parts.query or parts.fragment: + redacted += " (credentials/query hidden)" + return redacted + + +def _env_refs(value: str) -> List[str]: + return _ENV_REF_RE.findall(value) + + +def _validate_header_value(server: str, header: str, value: str) -> None: + if _HEADER_VALUE_FORBIDDEN_RE.search(value): + raise MCPConfigError( + f"Server '{server}': header '{header}' contains a control character " + "(line breaks are not allowed in header values)" + ) + leftover = _ENV_REF_RE.sub("", value) + if "${" in leftover: + raise MCPConfigError( + f"Server '{server}': header '{header}' has a malformed reference; " + "use ${NAME} with letters, digits and underscores" + ) + + +def _validate_headers(server: str, headers: Any) -> Dict[str, str]: + if headers is None: + return {} + if not isinstance(headers, dict): + raise MCPConfigError(f"Server '{server}': 'headers' must be an object") + seen: Dict[str, str] = {} + for name, value in headers.items(): + if not isinstance(name, str) or not _HEADER_NAME_RE.match(name): + raise MCPConfigError( + f"Server '{server}': invalid header name {name!r} " + "(letters, digits and !#$%&'*+.^_`|~- only)" + ) + lower = name.lower() + if lower in RESERVED_HEADERS: + raise MCPConfigError( + f"Server '{server}': header '{name}' is set by the transport " + "and cannot be configured" + ) + if lower in seen: + raise MCPConfigError( + f"Server '{server}': header '{name}' is given twice " + f"(also as '{seen[lower]}'); header names are case-insensitive" + ) + seen[lower] = name + if not isinstance(value, str): + raise MCPConfigError(f"Server '{server}': header '{name}' must be a string") + _validate_header_value(server, name, value) + return dict(headers) + + +def _validate_url(server: str, transport: str, url: Any) -> None: + if not url: + raise MCPConfigError( + f"Server '{server}' uses {transport} transport but 'url' is not specified" + ) + if transport != "http": + return # sse/websocket keep their historical (presence-only) check + if not isinstance(url, str) or url != url.strip() or any(c.isspace() for c in url): + raise MCPConfigError(f"Server '{server}': 'url' must be a URL without spaces") + try: + parts = urlsplit(url) + parts.port # noqa: B018 — raises ValueError for a bad port + except ValueError: + raise MCPConfigError(f"Server '{server}': 'url' is not a valid URL") from None + if parts.scheme not in ("http", "https"): + raise MCPConfigError( + f"Server '{server}': http transport needs an http:// or https:// url" + ) + if not parts.hostname: + raise MCPConfigError(f"Server '{server}': 'url' has no host") + if parts.username or parts.password: + raise MCPConfigError( + f"Server '{server}': put credentials in 'headers', not in the url" + ) + if parts.fragment: + raise MCPConfigError(f"Server '{server}': 'url' must not have a #fragment") + + +def _validate_timeout(server: str, timeout: Any) -> Optional[float]: + if timeout is None: + return None + if isinstance(timeout, bool) or not isinstance(timeout, (int, float)): + raise MCPConfigError(f"Server '{server}': 'timeout' must be a number") + if not math.isfinite(timeout) or not 0 < timeout <= MAX_TIMEOUT: + raise MCPConfigError( + f"Server '{server}': 'timeout' must be between 0 and {MAX_TIMEOUT:g} seconds" + ) + return float(timeout) + @dataclass class MCPServerConfig: @@ -19,45 +208,136 @@ class MCPServerConfig: name: str # Server identifier (e.g., "filesystem") description: str = "" # Human-readable description - transport: str = "stdio" # "stdio" | "sse" | "websocket" + transport: str = "stdio" # "stdio" | "sse" | "websocket" | "http" command: Optional[str] = None # For stdio: executable path args: List[str] = field(default_factory=list) # For stdio: command arguments cwd: Optional[str] = None # For stdio: working directory for the subprocess - url: Optional[str] = None # For sse/websocket: server URL + url: Optional[str] = None # For sse/websocket/http: server URL env: Dict[str, str] = field(default_factory=dict) # Environment variables enabled: bool = True # Enable/disable toggle action_set_name: Optional[str] = None # Custom set name (defaults to mcp_{name}) + # For http: extra request headers; values may reference ${NAME} in env. + headers: Dict[str, str] = field(default_factory=dict) + # For http: seconds allowed for connecting and for each request. + timeout: Optional[float] = None + # Keys this version does not know, written back unchanged on save. + extra: Dict[str, Any] = field(default_factory=dict) def __post_init__(self): - """Validate configuration after initialization.""" - # Validate transport type - valid_transports = {"stdio", "sse", "websocket"} - if self.transport not in valid_transports: - raise ValueError( + """Validate the entry's structure (secrets are resolved at connect).""" + if not isinstance(self.name, str) or not self.name.strip(): + raise MCPConfigError("MCP server 'name' must be a non-empty string") + + transport = self.transport + if isinstance(transport, str): + transport = transport.strip().lower() + transport = TRANSPORT_ALIASES.get(transport, transport) + if transport not in VALID_TRANSPORTS: + raise MCPConfigError( f"Invalid transport '{self.transport}' for server '{self.name}'. " - f"Must be one of: {valid_transports}" + f"Must be one of: {', '.join(VALID_TRANSPORTS)} " + "(streamable_http is accepted for http)" ) + self.transport = transport - # Validate required fields based on transport - if self.transport == "stdio": + if transport == "stdio": if not self.command: - raise ValueError( + raise MCPConfigError( f"Server '{self.name}' uses stdio transport but 'command' is not specified" ) - elif self.transport in ("sse", "websocket"): - if not self.url: - raise ValueError( - f"Server '{self.name}' uses {self.transport} transport but 'url' is not specified" - ) + else: + _validate_url(self.name, transport, self.url) + + if self.env is None: + self.env = {} + if not isinstance(self.env, dict): + raise MCPConfigError(f"Server '{self.name}': 'env' must be an object") + + self.headers = _validate_headers(self.name, self.headers) + if self.headers and transport != "http": + raise MCPConfigError( + f"Server '{self.name}': 'headers' are only supported by the http transport" + ) + self.timeout = _validate_timeout(self.name, self.timeout) @property def resolved_action_set_name(self) -> str: """Get the action set name, defaulting to mcp_{name} if not specified.""" return self.action_set_name or f"mcp_{self.name}" + @property + def effective_timeout(self) -> float: + """Seconds the http transport allows per request.""" + return self.timeout if self.timeout is not None else DEFAULT_HTTP_TIMEOUT + + def header_env_refs(self) -> List[str]: + """Names of the env entries the headers reference, in order.""" + refs: List[str] = [] + for value in self.headers.values(): + for ref in _env_refs(value): + if ref not in refs: + refs.append(ref) + return refs + + def resolve_headers(self) -> Dict[str, str]: + """The headers to send, with ``${NAME}`` filled from this server's + ``env``. Raises MCPConfigError naming every missing or empty + variable; never substitutes an empty value.""" + missing: List[str] = [] + resolved: Dict[str, str] = {} + for header, value in self.headers.items(): + + def substitute(match: "re.Match[str]") -> str: + ref = match.group(1) + env_value = self.env.get(ref) + if not isinstance(env_value, str) or env_value == "": + if ref not in missing: + missing.append(ref) + return "" + return env_value + + final = _ENV_REF_RE.sub(substitute, value) + if not missing and final.strip() == "": + raise MCPConfigError( + f"Server '{self.name}': header '{header}' resolves to an empty value" + ) + if _HEADER_VALUE_FORBIDDEN_RE.search(final): + raise MCPConfigError( + f"Server '{self.name}': the value for header '{header}' " + "contains a line break or control character" + ) + resolved[header] = final + if missing: + names = ", ".join(missing) + raise MCPConfigError( + f"Server '{self.name}': set {names} in this server's env " + "(referenced by its headers)" + ) + return resolved + + def connection_fingerprint(self) -> str: + """Everything that changes how the server is reached. Two configs + with the same fingerprint can share one live connection.""" + return json.dumps( + { + "transport": self.transport, + "command": self.command, + "args": self.args, + "cwd": self.cwd, + "url": self.url, + "env": self.env, + "headers": self.headers, + "timeout": self.timeout, + }, + sort_keys=True, + default=str, + ) + @classmethod def from_dict(cls, data: Dict[str, Any]) -> "MCPServerConfig": """Create MCPServerConfig from a dictionary.""" + if not isinstance(data, dict): + raise MCPConfigError("MCP server entry must be an object") return cls( name=data["name"], description=data.get("description", ""), @@ -69,11 +349,14 @@ def from_dict(cls, data: Dict[str, Any]) -> "MCPServerConfig": env=data.get("env", {}), enabled=data.get("enabled", True), action_set_name=data.get("action_set_name"), + headers=data.get("headers") or {}, + timeout=data.get("timeout"), + extra={k: v for k, v in data.items() if k not in _KNOWN_SERVER_KEYS}, ) def to_dict(self) -> Dict[str, Any]: """Convert to dictionary for serialization.""" - result = { + result: Dict[str, Any] = { "name": self.name, "description": self.description, "transport": self.transport, @@ -89,15 +372,39 @@ def to_dict(self) -> Dict[str, Any]: result["url"] = self.url if self.action_set_name: result["action_set_name"] = self.action_set_name + if self.headers: + result["headers"] = dict(self.headers) + if self.timeout is not None: + result["timeout"] = self.timeout + for key, value in self.extra.items(): + result.setdefault(key, value) return result +@dataclass +class InvalidServerEntry: + """An entry that failed validation. It is not connected, but it is kept + and saved back verbatim so the user can fix it.""" + + raw: Any + error: str + index: int # position in the file's mcp_servers list + + @property + def name(self) -> Optional[str]: + if isinstance(self.raw, dict) and isinstance(self.raw.get("name"), str): + return self.raw["name"] + return None + + @dataclass class MCPConfig: """Main MCP configuration containing all server configurations.""" mcp_servers: List[MCPServerConfig] = field(default_factory=list) auto_connect: bool = True # Automatically connect to enabled servers on init + invalid_servers: List[InvalidServerEntry] = field(default_factory=list) + extra: Dict[str, Any] = field(default_factory=dict) @classmethod def load(cls, config_path: Path) -> "MCPConfig": @@ -133,26 +440,58 @@ def load(cls, config_path: Path) -> "MCPConfig": @classmethod def from_dict(cls, data: Dict[str, Any]) -> "MCPConfig": """Create MCPConfig from a dictionary.""" - servers = [] - for server_data in data.get("mcp_servers", []): + if not isinstance(data, dict): + raise MCPConfigError("MCP config must be a JSON object") + servers: List[MCPServerConfig] = [] + invalid: List[InvalidServerEntry] = [] + seen: set = set() + entries = data.get("mcp_servers", []) + if not isinstance(entries, list): + raise MCPConfigError("'mcp_servers' must be a list") + for index, server_data in enumerate(entries): try: server = MCPServerConfig.from_dict(server_data) - servers.append(server) - except (KeyError, ValueError) as e: - logger.warning(f"Skipping invalid server config: {e}") - continue + except KeyError: + error = "missing 'name'" + except (MCPConfigError, ValueError, TypeError) as e: + error = str(e) + else: + if server.name in seen: + error = ( + f"duplicate server name '{server.name}'; " + "the first entry with this name is used" + ) + else: + seen.add(server.name) + servers.append(server) + continue + invalid.append(InvalidServerEntry(server_data, error, index)) + logger.warning(f"[MCP] Skipping invalid server config: {error}") return cls( mcp_servers=servers, auto_connect=data.get("auto_connect", True), + invalid_servers=invalid, + extra={ + k: v + for k, v in data.items() + if k not in ("mcp_servers", "auto_connect") + }, ) def to_dict(self) -> Dict[str, Any]: - """Convert to dictionary for serialization.""" - return { - "mcp_servers": [s.to_dict() for s in self.mcp_servers], + """Convert to dictionary for serialization. Invalid entries are put + back at their original positions, unchanged.""" + entries: List[Any] = [s.to_dict() for s in self.mcp_servers] + for entry in sorted(self.invalid_servers, key=lambda e: e.index): + entries.insert(min(entry.index, len(entries)), entry.raw) + result: Dict[str, Any] = { + "mcp_servers": entries, "auto_connect": self.auto_connect, } + for key, value in self.extra.items(): + result.setdefault(key, value) + return result def save(self, config_path: Path) -> None: """Save configuration to a JSON file.""" @@ -173,6 +512,10 @@ def get_server_by_name(self, name: str) -> Optional[MCPServerConfig]: return server return None + def get_invalid_entries(self, name: str) -> List[InvalidServerEntry]: + """Invalid entries that carry this name.""" + return [e for e in self.invalid_servers if e.name == name] + def add_server(self, server: MCPServerConfig) -> bool: """ Add a new server configuration. @@ -183,30 +526,60 @@ def add_server(self, server: MCPServerConfig) -> bool: Returns: True if added, False if server with same name already exists """ - if self.get_server_by_name(server.name): + if self.get_server_by_name(server.name) or self.get_invalid_entries( + server.name + ): logger.warning(f"Server '{server.name}' already exists") return False self.mcp_servers.append(server) logger.info(f"Added MCP server: {server.name}") return True + def replace_server(self, server: MCPServerConfig) -> bool: + """Replace the entry with this name in place (valid or invalid), + keeping its position. Returns False if there is none.""" + for i, existing in enumerate(self.mcp_servers): + if existing.name == server.name: + self.mcp_servers[i] = server + return True + invalid = self.get_invalid_entries(server.name) + if invalid: + target = invalid[0] + self.invalid_servers = [e for e in self.invalid_servers if e is not target] + position = sum(1 for e in self.invalid_servers if e.index < target.index) + self.mcp_servers.insert( + max(0, min(target.index - position, len(self.mcp_servers))), server + ) + return True + return False + def remove_server(self, name: str) -> bool: """ Remove a server configuration by name. + Also removes invalid entries with that name, so a broken entry can be + deleted from the UI. + Args: name: Name of the server to remove Returns: True if removed, False if not found """ + removed = False for i, server in enumerate(self.mcp_servers): if server.name == name: del self.mcp_servers[i] - logger.info(f"Removed MCP server: {name}") - return True - logger.warning(f"Server '{name}' not found") - return False + removed = True + break + before = len(self.invalid_servers) + self.invalid_servers = [e for e in self.invalid_servers if e.name != name] + removed = removed or len(self.invalid_servers) != before + if removed: + logger.info(f"Removed MCP server: {name}") + else: + logger.warning(f"Server '{name}' not found") + return removed def enable_server(self, name: str) -> bool: """Enable a server by name.""" diff --git a/agent_core/core/impl/mcp/server.py b/agent_core/core/impl/mcp/server.py index 2b3cabf1..552e2da7 100644 --- a/agent_core/core/impl/mcp/server.py +++ b/agent_core/core/impl/mcp/server.py @@ -6,9 +6,11 @@ - stdio: Subprocess-based communication - sse: HTTP Server-Sent Events - websocket: WebSocket bidirectional communication +- http: Streamable HTTP (one endpoint, POST + JSON or SSE responses) """ import asyncio +import json import os import shutil import sys @@ -19,7 +21,7 @@ from agent_core.utils.logger import logger from agent_core.utils.windows_process import hidden_console_kwargs -from agent_core.core.impl.mcp.config import MCPServerConfig +from agent_core.core.impl.mcp.config import MCPConfigError, MCPServerConfig, redact_url # Default client info - can be overridden DEFAULT_CLIENT_NAME = "Agent" @@ -114,6 +116,10 @@ def from_dict(cls, data: Dict[str, Any]) -> "MCPTool": class MCPTransport(ABC): """Abstract base class for MCP transports.""" + # Why the last connect() failed, when the transport can say so safely + # (no header or env values). None means "see the log". + last_error: Optional[str] = None + @abstractmethod async def connect(self) -> bool: """Establish connection. Returns True if successful.""" @@ -828,6 +834,613 @@ async def _send_notification( logger.warning(f"Failed to send WebSocket notification: {e}") +class _HTTPTransportError(Exception): + """A Streamable HTTP failure whose message is safe to log and show: it + never contains header values, and URLs in it are redacted.""" + + +class _SessionExpired(_HTTPTransportError): + """HTTP 404 on a request that carried a session id: the session ended.""" + + +def _clean_server_text(text: Any, limit: int = 300) -> str: + """Server-supplied text for a log line or error: printable, bounded.""" + text = "".join(c if c.isprintable() else " " for c in str(text)) + return text if len(text) <= limit else text[: limit - 3] + "..." + + +class StreamableHTTPTransport(MCPTransport): + """Streamable HTTP transport (MCP 2025-03-26 and later). + + Every client message is a POST to one endpoint. A request is answered + either with one JSON body or with an SSE stream that may carry server + requests and notifications before the response; notifications and + responses are accepted with 202. The server may issue an + ``Mcp-Session-Id`` on the initialize response; it is sent back on every + later request, together with ``MCP-Protocol-Version``. + + Each instance owns one ``httpx.AsyncClient`` with this server's headers + only. Redirects are never followed, so configured credentials cannot be + sent to another URL. Requests run concurrently (no transport lock); + each is bounded by ``timeout`` from start to response. + + Not implemented (optional in the spec): the standalone GET stream for + unsolicited server messages, and sampling/elicitation/roots, which this + client does not advertise. A server request on a response stream is + answered (``ping``) or refused with "method not found". + """ + + # Requested in initialize; the server may answer with any version below. + PROTOCOL_VERSION = "2025-11-25" + SUPPORTED_PROTOCOL_VERSIONS = ("2025-03-26", "2025-06-18", "2025-11-25") + MAX_MESSAGE_BYTES = 16 * 1024 * 1024 + MAX_ERROR_BODY_BYTES = 64 * 1024 + # Streams a 2025-11-25 server closes before answering are resumed with + # GET + Last-Event-ID this many times, within the request deadline. + MAX_RESUME_ATTEMPTS = 2 + DEFAULT_RETRY_MS = 1000 + MAX_RETRY_MS = 5000 + DELETE_TIMEOUT = 5.0 + # How long to keep reading a stream after its response (see _drain). + DRAIN_TIMEOUT = 1.0 + + def __init__( + self, + url: str, + headers: Optional[Dict[str, str]] = None, + timeout: float = 30.0, + server_name: str = "", + *, + _http_transport: Any = None, + ): + self.url = url + self.timeout = float(timeout) + self.server_name = server_name or redact_url(url) + # Copied: this transport never shares a header dict with another. + self._headers: Dict[str, str] = dict(headers or {}) + self._http_transport = _http_transport # test seam (httpx.MockTransport) + self._client: Any = None # httpx.AsyncClient while connected + self._connected = False + self._session_id: Optional[str] = None + self._protocol_version: Optional[str] = None + self._renew_lock = asyncio.Lock() + self._request_id = 0 + self.server_info: Dict[str, Any] = {} + self.last_error: Optional[str] = None + + @property + def is_connected(self) -> bool: + return self._connected and self._client is not None + + @property + def session_id(self) -> Optional[str]: + return self._session_id + + @property + def protocol_version(self) -> Optional[str]: + return self._protocol_version + + def _log_prefix(self) -> str: + return f"[MCP:{self.server_name}]" + + # ─────────────────────── Lifecycle ────────────────────────────────────── + + async def connect(self) -> bool: + """Run the initialize handshake. False (with ``last_error`` set) when + the server cannot be reached, rejects the client, or negotiates a + protocol version this client does not speak.""" + import httpx + + self.last_error = None + self._client = httpx.AsyncClient( + timeout=httpx.Timeout(self.timeout), + follow_redirects=False, + transport=self._http_transport, + ) + try: + await asyncio.wait_for(self._initialize(), timeout=self.timeout) + except asyncio.CancelledError: + await self._close(send_delete=False) + raise + except asyncio.TimeoutError: + self.last_error = f"initialize timed out after {self.timeout:g}s" + except _HTTPTransportError as e: + self.last_error = str(e) + except Exception as e: # noqa: BLE001 — reported, never swallowed + self.last_error = f"initialize failed: {type(e).__name__}" + else: + self._connected = True + logger.info( + f"{self._log_prefix()} Connected to {redact_url(self.url)} " + f"(protocol {self._protocol_version}" + f"{', session' if self._session_id else ''})" + ) + return True + logger.error(f"{self._log_prefix()} {self.last_error}") + await self._close(send_delete=True) + return False + + async def _initialize(self) -> None: + response = await self._exchange( + "initialize", + { + "protocolVersion": self.PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": get_client_info(), + }, + initializing=True, + ) + if "error" in response: + raise _HTTPTransportError( + f"initialize rejected: {self._error_text(response['error'])}" + ) + result = response.get("result") + if not isinstance(result, dict): + raise _HTTPTransportError("initialize returned no result") + version = result.get("protocolVersion") + if version not in self.SUPPORTED_PROTOCOL_VERSIONS: + raise _HTTPTransportError( + f"server negotiated protocol version {_clean_server_text(version, 40)!r}, " + f"supported: {', '.join(self.SUPPORTED_PROTOCOL_VERSIONS)}" + ) + self._protocol_version = version + info = result.get("serverInfo") + self.server_info = info if isinstance(info, dict) else {} + await self._post({"jsonrpc": "2.0", "method": "notifications/initialized"}) + + async def disconnect(self) -> None: + """End the session (DELETE, best effort) and close the client.""" + await self._close(send_delete=True) + + async def _close(self, *, send_delete: bool) -> None: + self._connected = False + client, self._client = self._client, None + session_id, self._session_id = self._session_id, None + if client is None: + return + try: + if send_delete and session_id: + headers = {**self._headers, "Mcp-Session-Id": session_id} + if self._protocol_version: + headers["MCP-Protocol-Version"] = self._protocol_version + try: + response = await asyncio.wait_for( + client.delete(self.url, headers=headers), + timeout=min(self.DELETE_TIMEOUT, self.timeout), + ) + if response.status_code not in (200, 202, 204, 404, 405): + logger.debug( + f"{self._log_prefix()} Session DELETE returned " + f"HTTP {response.status_code}" + ) + except Exception as e: # noqa: BLE001 — best effort + logger.debug( + f"{self._log_prefix()} Session DELETE failed: {type(e).__name__}" + ) + finally: + await client.aclose() + + # ─────────────────────── Requests ─────────────────────────────────────── + + async def send_request( + self, method: str, params: Optional[Dict] = None + ) -> Dict[str, Any]: + """Send a JSON-RPC request; returns the response, or an error dict.""" + if not self.is_connected: + return {"error": {"code": -1, "message": "Not connected"}} + try: + return await asyncio.wait_for( + self._exchange_renewing(method, params), timeout=self.timeout + ) + except asyncio.TimeoutError: + message = f"'{method}' timed out after {self.timeout:g}s" + except _HTTPTransportError as e: + message = str(e) + except Exception as e: # noqa: BLE001 — reported to the caller + message = f"'{method}' failed: {type(e).__name__}" + logger.warning(f"{self._log_prefix()} {message}") + return {"error": {"code": -1, "message": message}} + + async def _exchange_renewing( + self, method: str, params: Optional[Dict] + ) -> Dict[str, Any]: + """``_exchange``, and if the server says the session ended (404 with + a session id) start a new session and retry once, as the spec + requires. The server rejected the original request without running + it, so the retry cannot run it twice.""" + expired = self._session_id + try: + return await self._exchange(method, params) + except _SessionExpired: + pass + try: + await self._renew_session(expired) + except _HTTPTransportError as e: + self._connected = False + raise _HTTPTransportError( + f"the server ended the MCP session and a new one could not be started: {e}" + ) from None + return await self._exchange(method, params) + + async def _renew_session(self, expired: Optional[str]) -> None: + """Run a fresh initialize, once for all requests that saw ``expired`` + end (concurrent requests share one renewal).""" + async with self._renew_lock: + if self._session_id != expired: + return # another request already renewed it + logger.info(f"{self._log_prefix()} Session ended; starting a new one") + # The old id stays in place until the new initialize replaces it: + # requests running meanwhile keep a session header, get their own + # 404, and then wait here for this renewal. + await self._initialize() + + async def _exchange( + self, method: str, params: Optional[Dict], *, initializing: bool = False + ) -> Dict[str, Any]: + self._request_id += 1 + request: Dict[str, Any] = { + "jsonrpc": "2.0", + "id": self._request_id, + "method": method, + } + if params is not None: + request["params"] = params + response = await self._post(request, initializing=initializing) + if response is None: + raise _HTTPTransportError(f"server answered '{method}' with no response") + return response + + def _request_headers( + self, *, accept: str, with_session: bool = True + ) -> Dict[str, str]: + headers = dict(self._headers) + headers["Accept"] = accept + # initialize never carries a session or version: it starts a session. + if with_session and self._session_id: + headers["Mcp-Session-Id"] = self._session_id + if with_session and self._protocol_version: + headers["MCP-Protocol-Version"] = self._protocol_version + return headers + + async def _post( + self, message: Dict[str, Any], *, initializing: bool = False + ) -> Optional[Dict[str, Any]]: + """POST one message. For a request, returns its response; for a + notification or response, returns None once the server accepted it.""" + import httpx + + if self._client is None: + raise _HTTPTransportError("not connected") + is_request = "method" in message and "id" in message + # The session this very request carries: a 404 means *that* session + # ended, whatever another request has done to the shared state since. + sent_session = None if initializing else self._session_id + headers = self._request_headers( + accept="application/json, text/event-stream", + with_session=not initializing, + ) + headers["Content-Type"] = "application/json" + body = json.dumps(message).encode("utf-8") + try: + async with self._client.stream( + "POST", self.url, content=body, headers=headers + ) as response: + if initializing: + self._capture_session_id(response) + return await self._handle_post_response( + response, message, is_request, sent_session + ) + except _HTTPTransportError: + raise + except httpx.TimeoutException: + raise _HTTPTransportError( + f"timed out after {self.timeout:g}s waiting for {redact_url(self.url)}" + ) from None + except httpx.ConnectError: + raise _HTTPTransportError( + f"could not connect to {redact_url(self.url)}" + ) from None + except (httpx.RemoteProtocolError, httpx.ReadError, httpx.WriteError): + raise _HTTPTransportError( + f"connection to {redact_url(self.url)} was interrupted" + ) from None + except httpx.HTTPError as e: + raise _HTTPTransportError( + f"HTTP error talking to {redact_url(self.url)}: {type(e).__name__}" + ) from None + + def _capture_session_id(self, response) -> None: + session_id = response.headers.get("mcp-session-id") + if session_id is None: + return + if not session_id or any(not 0x21 <= ord(c) <= 0x7E for c in session_id): + raise _HTTPTransportError( + "server sent an invalid Mcp-Session-Id (visible ASCII only)" + ) + self._session_id = session_id + + async def _handle_post_response( + self, + response, + message: Dict[str, Any], + is_request: bool, + sent_session: Optional[str] = None, + ) -> Optional[Dict[str, Any]]: + status = response.status_code + method = message.get("method", "response") + if 300 <= status < 400: + location = response.headers.get("location", "") + raise _HTTPTransportError( + f"server redirected to {redact_url(location) or 'another URL'} " + f"(HTTP {status}); redirects are not followed so headers are not " + "sent elsewhere; configure the final URL if you trust it" + ) + if status >= 400: + await self._raise_for_status(response, message, is_request, sent_session) + if not is_request: + return None # 202 (or any 2xx) for a notification/response + if status == 202: + raise _HTTPTransportError( + f"server accepted '{method}' but sent no response" + ) + content_type = response.headers.get("content-type", "").lower() + if content_type.startswith("application/json"): + return self._match_response(await self._read_json(response), message) + if content_type.startswith("text/event-stream"): + return await self._read_event_stream(response, message) + raise _HTTPTransportError( + f"unexpected Content-Type {_clean_server_text(content_type, 60)!r} " + f"for '{method}'" + ) + + async def _raise_for_status( + self, + response, + message: Dict[str, Any], + is_request: bool, + sent_session: Optional[str] = None, + ) -> None: + status = response.status_code + method = message.get("method", "response") + detail = "" + body = await self._read_limited(response, self.MAX_ERROR_BODY_BYTES) + if body and "json" in response.headers.get("content-type", "").lower(): + try: + parsed = json.loads(body) + except ValueError: + parsed = None + # A JSON-RPC error carried by an HTTP error status. + if ( + is_request + and isinstance(parsed, dict) + and isinstance(parsed.get("error"), dict) + ): + detail = self._error_text(parsed["error"]) + if status in (401, 403): + raise _HTTPTransportError( + f"'{method}' was refused with HTTP {status} (authentication " + "failed or not permitted); check this server's headers" + + (f": {detail}" if detail else "") + ) + if status == 404 and sent_session: + # The session ended on the server; send_request starts a new one. + raise _SessionExpired("the server ended the MCP session (HTTP 404)") + raise _HTTPTransportError( + f"'{method}' failed with HTTP {status}" + (f": {detail}" if detail else "") + ) + + async def _read_limited(self, response, limit: int) -> Optional[bytes]: + """The body, or None if it is longer than ``limit`` (reading stops + there, so an oversized body is never held in memory).""" + chunks: List[bytes] = [] + size = 0 + body = response.aiter_bytes() + async for chunk in body: + size += len(chunk) + if size > limit: + await self._drain(body) + return None + chunks.append(chunk) + return b"".join(chunks) + + async def _drain(self, iterator) -> None: + """Read an httpx stream iterator to its end, discarding the data, + for at most DRAIN_TIMEOUT seconds. + + Stopping half way leaves httpx's chain of async generators (lines → + text → bytes → httpcore's connection stream) suspended; the garbage + collector then finalises httpcore's generator in another task, which + it rejects ("exit cancel scope in a different task"). Reading to the + end — or being cancelled at a socket read by the timeout — unwinds the + whole chain here instead. Servers close a response stream after the + response, so this normally returns at once.""" + + async def exhaust() -> None: + async for _ in iterator: + pass + + try: + await asyncio.wait_for(exhaust(), timeout=self.DRAIN_TIMEOUT) + except asyncio.TimeoutError: + logger.debug( + f"{self._log_prefix()} Server kept a response stream open; closing it" + ) + except Exception: # noqa: BLE001 — the stream is being discarded + pass + + async def _read_json(self, response) -> Any: + body = await self._read_limited(response, self.MAX_MESSAGE_BYTES) + if body is None: + raise _HTTPTransportError("response exceeds the 16 MB message limit") + try: + return json.loads(body) + except ValueError: + raise _HTTPTransportError("server sent malformed JSON") from None + + def _match_response(self, payload: Any, request: Dict[str, Any]) -> Dict[str, Any]: + if not isinstance(payload, dict) or ( + "result" not in payload and "error" not in payload + ): + raise _HTTPTransportError( + f"server sent a non-response body for '{request['method']}'" + ) + if payload.get("id") != request["id"]: + if "error" in payload and payload.get("id") is None: + return {**payload, "id": request["id"]} + raise _HTTPTransportError( + f"server answered '{request['method']}' with the wrong id" + ) + return payload + + @staticmethod + def _error_text(error: Any) -> str: + if isinstance(error, dict): + message = error.get("message", "") + code = error.get("code") + text = _clean_server_text(message) or "error" + return f"{text} (code {code})" if code is not None else text + return _clean_server_text(error) + + # ─────────────────────── SSE response streams ─────────────────────────── + + async def _read_event_stream( + self, response, request: Dict[str, Any] + ) -> Dict[str, Any]: + """Read SSE events until this request's response. A stream that ends + early after carrying an event id is resumed with GET + Last-Event-ID + (2025-11-25 servers may close it on purpose), up to + MAX_RESUME_ATTEMPTS times.""" + outcome = await self._consume_events(response, request) + attempts = 0 + while outcome.response is None: + if outcome.last_event_id is None or attempts >= self.MAX_RESUME_ATTEMPTS: + raise _HTTPTransportError( + f"the response stream for '{request['method']}' ended " + "before the response arrived" + ) + attempts += 1 + retry_ms = outcome.retry_ms or self.DEFAULT_RETRY_MS + await asyncio.sleep(min(retry_ms, self.MAX_RETRY_MS) / 1000) + stream = await self._resume(outcome.last_event_id) + try: + content_type = stream.headers.get("content-type", "").lower() + if stream.status_code >= 400 or not content_type.startswith( + "text/event-stream" + ): + raise _HTTPTransportError( + f"could not resume the stream for '{request['method']}' " + f"(HTTP {stream.status_code})" + ) + resumed = await self._consume_events(stream, request) + finally: + await stream.aclose() + resumed.last_event_id = resumed.last_event_id or outcome.last_event_id + if resumed.retry_ms is None: + resumed.retry_ms = outcome.retry_ms + outcome = resumed + return outcome.response + + async def _resume(self, last_event_id: str): + headers = self._request_headers(accept="text/event-stream") + headers["Last-Event-ID"] = last_event_id + request = self._client.build_request("GET", self.url, headers=headers) + return await self._client.send(request, stream=True) + + async def _consume_events( + self, stream, request: Dict[str, Any] + ) -> "_StreamOutcome": + outcome = _StreamOutcome() + lines = stream.aiter_lines() + messages = self._sse_messages(lines, outcome) + cancelled = False + try: + async for message in messages: + if "method" in message: + if "id" in message: + await self._answer_server_request(message) + continue # notification + if message.get("id") == request["id"] and ( + "result" in message or "error" in message + ): + outcome.response = message + break + except asyncio.CancelledError: + cancelled = True + raise + finally: + await messages.aclose() # our parser: no I/O, closes at its yield + # Whatever ended the loop (the response, an oversized event), + # read on to the end of this same stream instead of abandoning + # httpx's generators mid-iteration (see _drain). A finished + # stream makes this a no-op; a cancellation already unwound it. + if not cancelled: + await self._drain(lines) + return outcome + + async def _sse_messages(self, lines, outcome: "_StreamOutcome"): + """JSON-RPC objects from an SSE line stream; records event ids and + retry hints on ``outcome`` for resumption.""" + event = "message" + data: List[str] = [] + size = 0 + async for line in lines: + if line: + if line.startswith(":"): + continue + field_name, _, value = line.partition(":") + value = value[1:] if value.startswith(" ") else value + if field_name == "event": + event = value or "message" + elif field_name == "data": + size += len(value) + if size > self.MAX_MESSAGE_BYTES: + raise _HTTPTransportError( + "stream event exceeds the 16 MB message limit" + ) + data.append(value) + elif field_name == "id": + if "\x00" not in value: + outcome.last_event_id = value + elif field_name == "retry" and value.isdigit(): + outcome.retry_ms = int(value) + continue + payload, kind, data, size, event = "\n".join(data), event, [], 0, "message" + if kind != "message" or not payload.strip(): + continue + try: + message = json.loads(payload) + except ValueError: + logger.debug(f"{self._log_prefix()} Ignoring malformed stream event") + continue + if isinstance(message, dict): + yield message + + async def _answer_server_request(self, message: Dict[str, Any]) -> None: + if message.get("method") == "ping": + reply: Dict[str, Any] = { + "jsonrpc": "2.0", + "id": message["id"], + "result": {}, + } + else: + reply = { + "jsonrpc": "2.0", + "id": message["id"], + "error": {"code": -32601, "message": "Method not found"}, + } + try: + await self._post(reply) + except _HTTPTransportError as e: + logger.debug(f"{self._log_prefix()} Could not answer server request: {e}") + + +@dataclass +class _StreamOutcome: + response: Optional[Dict[str, Any]] = None + last_event_id: Optional[str] = None + retry_ms: Optional[int] = None + + class MCPServerConnection: """ Manages connection to a single MCP server. @@ -835,10 +1448,15 @@ class MCPServerConnection: Handles transport selection, connection lifecycle, tool discovery, and tool execution. """ + # tools/list pages followed via nextCursor before giving up. + MAX_TOOL_PAGES = 50 + def __init__(self, config: MCPServerConfig): self.config = config self._transport: Optional[MCPTransport] = None self._tools: List[MCPTool] = [] + # Why the last connect() failed; safe to show (no credentials). + self.last_error: Optional[str] = None @property def is_connected(self) -> bool: @@ -869,6 +1487,15 @@ def _create_transport(self) -> MCPTransport: url=self.config.url, env=self.config.env, ) + elif self.config.transport == "http": + # Resolved per connect from this server's env; raises + # MCPConfigError naming any missing variable. + return StreamableHTTPTransport( + url=self.config.url or "", + headers=self.config.resolve_headers(), + timeout=self.config.effective_timeout, + server_name=self.config.name, + ) else: raise ValueError(f"Unknown transport: {self.config.transport}") @@ -883,15 +1510,22 @@ async def connect(self) -> bool: logger.warning(f"Server '{self.config.name}' is already connected") return True + self.last_error = None try: # Create and connect transport logger.debug( f"[MCPServer:{self.config.name}] Creating {self.config.transport} transport..." ) - self._transport = self._create_transport() + try: + self._transport = self._create_transport() + except MCPConfigError as e: + self.last_error = str(e) + logger.error(f"[MCPServer:{self.config.name}] {self.last_error}") + return False logger.debug(f"[MCPServer:{self.config.name}] Connecting transport...") if not await self._transport.connect(): + self.last_error = self._transport.last_error or "connection failed" logger.error( f"[MCPServer:{self.config.name}] Transport connection failed" ) @@ -915,10 +1549,15 @@ async def connect(self) -> bool: return True + except asyncio.CancelledError: + # Never leave a half-open transport (or a spawned process) behind. + await self.disconnect() + raise except Exception as e: logger.error( f"[MCPServer:{self.config.name}] Failed to connect: {type(e).__name__}: {e}" ) + self.last_error = f"connect failed: {type(e).__name__}" await self.disconnect() return False @@ -943,25 +1582,46 @@ async def _discover_tools(self) -> None: ) return - response = await self._transport.send_request("tools/list", {}) + tools_data: List[Dict[str, Any]] = [] + cursor: Optional[str] = None + for _ in range(self.MAX_TOOL_PAGES): + params: Dict[str, Any] = {"cursor": cursor} if cursor else {} + response = await self._transport.send_request("tools/list", params) - if "error" in response: - error_info = response.get("error", {}) - if isinstance(error_info, dict): - error_msg = error_info.get("message", str(error_info)) - else: - error_msg = str(error_info) + if "error" in response: + error_info = response.get("error", {}) + if isinstance(error_info, dict): + error_msg = error_info.get("message", str(error_info)) + else: + error_msg = str(error_info) + logger.warning( + f"[MCPServer:{self.config.name}] Failed to list tools: {error_msg}" + ) + if not tools_data: + return + break + + result = response.get("result", {}) or {} + page = result.get("tools", []) + if isinstance(page, list): + tools_data.extend(t for t in page if isinstance(t, dict)) + next_cursor = result.get("nextCursor") + if ( + not isinstance(next_cursor, str) + or not next_cursor + or next_cursor == cursor + ): + break + cursor = next_cursor + else: logger.warning( - f"[MCPServer:{self.config.name}] Failed to list tools: {error_msg}" + f"[MCPServer:{self.config.name}] Stopped listing tools after " + f"{self.MAX_TOOL_PAGES} pages" ) - return - - result = response.get("result", {}) - tools_data = result.get("tools", []) if not tools_data: logger.debug( - f"[MCPServer:{self.config.name}] Server returned empty tools list. Response: {response}" + f"[MCPServer:{self.config.name}] Server returned empty tools list." ) self._tools = [MCPTool.from_dict(t) for t in tools_data] diff --git a/agent_file_system/AGENT.md b/agent_file_system/AGENT.md index 06027191..9d12e9f5 100644 --- a/agent_file_system/AGENT.md +++ b/agent_file_system/AGENT.md @@ -1692,14 +1692,16 @@ Run `/help` for the live list. If you need to verify a specific command, read it ``` /mcp list list configured MCP servers + enabled state /mcp add --transport stdio -- [args] register a new MCP server (stdio) +/mcp add --transport http [--timeout N] register a remote Streamable HTTP server /mcp add-json '' register from a full JSON entry /mcp remove remove a server /mcp enable enable a server (next reload picks it up) /mcp disable disable a server /mcp env set an env variable on a server entry +/mcp header
set an HTTP header on an http server (--remove deletes it) ``` -Edits go to [app/config/mcp_config.json](app/config/mcp_config.json) and are hot-reloaded. See `## MCP` and `## Configs`. `--transport http` is refused: only stdio, sse and websocket are valid. +Edits go to [app/config/mcp_config.json](app/config/mcp_config.json) and are hot-reloaded. See `## MCP` and `## Configs`. Valid transports: stdio, http (Streamable HTTP; `streamable_http` is accepted and saved as `http`), sse (legacy HTTP+SSE) and websocket. ### Skill management @@ -2007,11 +2009,15 @@ mcp_servers: [ { name: string required, unique within file description: string human-readable, shown to the LLM - transport: "stdio" | "sse" | "websocket" default "stdio" + transport: "stdio" | "http" | "sse" | "websocket" default "stdio"; "http" = Streamable HTTP command: string required for stdio (e.g. "npx", "uv", "python") args: [string] stdio command arguments - url: string required for sse / websocket + url: string required for http / sse / websocket (http: http:// or https://, + no user:password@ and no #fragment) env: { KEY: VALUE } environment variables passed to the server process + headers: { Name: VALUE } (http only) extra request headers; a VALUE may reference + ${KEY} from this server's env, and only from it + timeout: number (http only) seconds per request, 1-300, default 30 cwd: string (stdio only) working directory for the subprocess; default = the agent workspace (see ## MCP) enabled: bool controls whether the server connects on load/reload @@ -2023,6 +2029,7 @@ Patterns by transport: NPX (Node): transport="stdio" command="npx" args=["-y", "@org/server-name", ...optional-args] Python (uv): transport="stdio" command="uv" args=["run", "--directory", "", "main.py"] Python (pip): transport="stdio" command="python" args=["-m", "", ...args] + Remote HTTP: transport="http" url="https:///mcp" headers={"Authorization": "Bearer ${TOKEN}"} env={"TOKEN": ""} Remote SSE: transport="sse" url="http://localhost:3000/mcp" Remote WS: transport="websocket" url="ws://..." @@ -2269,6 +2276,20 @@ stdio (subprocess, most common) Python pip: command="python", args=["-m", ""] Node: command="node", args=[""] +http (Streamable HTTP, remote; the current MCP standard for remote servers) + transport: "http" + url: "https:///mcp" + headers: { "Authorization": "Bearer ${TOKEN}" } sent only to this server + env: { "TOKEN": "" } ${TOKEN} is read from here, never from the process environment + timeout: 30 seconds per request (raise it for slow tools, max 300) + command: (omit) + + A header that references a missing or empty env value fails that server with + "set TOKEN in this server's env" instead of sending an empty credential. + Redirects are not followed (credentials stay with the configured URL). + Headers Accept, Content-Type, Host, Mcp-Session-Id, MCP-Protocol-Version are + set by the transport and cannot be configured. + sse (server-sent events, remote) transport: "sse" url: "http://localhost:3000/mcp" or "https:///mcp" diff --git a/app/data/agent_file_system_template/AGENT.md b/app/data/agent_file_system_template/AGENT.md index 2a8d37cf..9605ab89 100644 --- a/app/data/agent_file_system_template/AGENT.md +++ b/app/data/agent_file_system_template/AGENT.md @@ -1523,14 +1523,16 @@ Run `/help` for the live list. If you need to verify a specific command, read it ``` /mcp list list configured MCP servers + enabled state /mcp add --transport stdio -- [args] register a new MCP server (stdio) +/mcp add --transport http [--timeout N] register a remote Streamable HTTP server /mcp add-json '' register from a full JSON entry /mcp remove remove a server /mcp enable enable a server (next reload picks it up) /mcp disable disable a server /mcp env set an env variable on a server entry +/mcp header
set an HTTP header on an http server (--remove deletes it) ``` -Edits go to [app/config/mcp_config.json](app/config/mcp_config.json) and are hot-reloaded. See `## MCP` and `## Configs`. `--transport http` is refused: only stdio, sse and websocket are valid. +Edits go to [app/config/mcp_config.json](app/config/mcp_config.json) and are hot-reloaded. See `## MCP` and `## Configs`. Valid transports: stdio, http (Streamable HTTP; `streamable_http` is accepted and saved as `http`), sse (legacy HTTP+SSE) and websocket. ### Skill management @@ -1838,11 +1840,15 @@ mcp_servers: [ { name: string required, unique within file description: string human-readable, shown to the LLM - transport: "stdio" | "sse" | "websocket" default "stdio" + transport: "stdio" | "http" | "sse" | "websocket" default "stdio"; "http" = Streamable HTTP command: string required for stdio (e.g. "npx", "uv", "python") args: [string] stdio command arguments - url: string required for sse / websocket + url: string required for http / sse / websocket (http: http:// or https://, + no user:password@ and no #fragment) env: { KEY: VALUE } environment variables passed to the server process + headers: { Name: VALUE } (http only) extra request headers; a VALUE may reference + ${KEY} from this server's env, and only from it + timeout: number (http only) seconds per request, 1-300, default 30 cwd: string (stdio only) working directory for the subprocess; default = the agent workspace (see ## MCP) enabled: bool controls whether the server connects on load/reload @@ -1854,6 +1860,7 @@ Patterns by transport: NPX (Node): transport="stdio" command="npx" args=["-y", "@org/server-name", ...optional-args] Python (uv): transport="stdio" command="uv" args=["run", "--directory", "", "main.py"] Python (pip): transport="stdio" command="python" args=["-m", "", ...args] + Remote HTTP: transport="http" url="https:///mcp" headers={"Authorization": "Bearer ${TOKEN}"} env={"TOKEN": ""} Remote SSE: transport="sse" url="http://localhost:3000/mcp" Remote WS: transport="websocket" url="ws://..." @@ -2100,6 +2107,20 @@ stdio (subprocess, most common) Python pip: command="python", args=["-m", ""] Node: command="node", args=[""] +http (Streamable HTTP, remote; the current MCP standard for remote servers) + transport: "http" + url: "https:///mcp" + headers: { "Authorization": "Bearer ${TOKEN}" } sent only to this server + env: { "TOKEN": "" } ${TOKEN} is read from here, never from the process environment + timeout: 30 seconds per request (raise it for slow tools, max 300) + command: (omit) + + A header that references a missing or empty env value fails that server with + "set TOKEN in this server's env" instead of sending an empty credential. + Redirects are not followed (credentials stay with the configured URL). + Headers Accept, Content-Type, Host, Mcp-Session-Id, MCP-Protocol-Version are + set by the transport and cannot be configured. + sse (server-sent events, remote) transport: "sse" url: "http://localhost:3000/mcp" or "https:///mcp" diff --git a/app/mcp/__init__.py b/app/mcp/__init__.py index 9dbad41c..b0d10a29 100644 --- a/app/mcp/__init__.py +++ b/app/mcp/__init__.py @@ -21,6 +21,7 @@ StdioTransport, SSETransport, WebSocketTransport, + StreamableHTTPTransport, get_client_info, set_default_stdio_cwd, get_default_stdio_cwd, @@ -37,6 +38,7 @@ "StdioTransport", "SSETransport", "WebSocketTransport", + "StreamableHTTPTransport", "MCPServerConnection", "set_mcp_client_info", "get_client_info", diff --git a/app/ui_layer/commands/builtin/mcp.py b/app/ui_layer/commands/builtin/mcp.py index 98d220ed..af1285d2 100644 --- a/app/ui_layer/commands/builtin/mcp.py +++ b/app/ui_layer/commands/builtin/mcp.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List +from typing import List, Optional from app.ui_layer.commands.base import Command, CommandResult from app.ui_layer.settings import ( @@ -13,8 +13,11 @@ enable_mcp_server, disable_mcp_server, update_mcp_server_env, + set_mcp_server_header, ) +HTTP_TRANSPORTS = ("http", "streamable_http", "streamable-http") + class MCPCommand(Command): """Manage MCP servers.""" @@ -36,14 +39,23 @@ def help_text(self) -> str: return """Manage Model Context Protocol (MCP) servers. Subcommands: - list - List configured servers - add --transport stdio -- - Add stdio server - add --transport http - Add HTTP server + list [--all] - List configured servers + add --transport stdio -- [args] - Add stdio server + add --transport http [--timeout N] - Add Streamable HTTP server add-json '' - Add from JSON config remove - Remove server enable - Enable server disable - Disable server env - Set environment variable + header
- Set an HTTP header (http servers) + header
--remove - Remove an HTTP header + +Header values can reference the server's env as ${NAME}, so the secret +itself lives in env and is never sent anywhere but that server: + + /mcp add stitch --transport http https://example.com/mcp + /mcp header stitch X-Api-Key ${STITCH_API_KEY} + /mcp env stitch STITCH_API_KEY Examples: /mcp list @@ -73,6 +85,7 @@ async def execute( "enable": lambda: self._enable_server(sub_args), "disable": lambda: self._disable_server(sub_args), "env": lambda: self._set_env(sub_args), + "header": lambda: self._set_header(sub_args), } handler = handlers.get(subcommand) @@ -109,9 +122,16 @@ async def _list_servers(self, args: List[str] = None) -> CommandResult: name = server.get("name", "unknown") if show_all: status = "enabled" if server.get("enabled", True) else "disabled" - lines.append(f" {name} [{status}]") + line = f" {name} [{status}]" else: - lines.append(f" {name}") + line = f" {name}" + if server.get("transport") and server["transport"] != "stdio": + line += f" ({server['transport']})" + if server.get("invalid"): + line += f" - invalid: {server.get('error')}" + elif server.get("missing_env"): + line += f" - needs env: {', '.join(server['missing_env'])}" + lines.append(line) if not show_all: lines.append("") @@ -136,6 +156,7 @@ async def _add_server(self, args: List[str]) -> CommandResult: name = args[0] transport_idx = args.index("--transport") transport = args[transport_idx + 1] if len(args) > transport_idx + 1 else "" + transport = transport.lower() if transport == "stdio": # Find command after -- @@ -146,18 +167,36 @@ async def _add_server(self, args: List[str]) -> CommandResult: success, message = add_mcp_server( name=name, transport="stdio", - command=cmd, + command=cmd[0], + args=cmd[1:], ) return CommandResult(success=success, message=message) - elif transport == "http": - url = args[transport_idx + 2] if len(args) > transport_idx + 2 else "" - if url: + elif transport in HTTP_TRANSPORTS: + rest = args[transport_idx + 2 :] + timeout: Optional[float] = None + if "--timeout" in rest: + t_idx = rest.index("--timeout") + try: + timeout = float(rest[t_idx + 1]) + except (IndexError, ValueError): + return CommandResult( + success=False, message="--timeout needs a number of seconds" + ) + rest = rest[:t_idx] + rest[t_idx + 2 :] + if len(rest) == 1: success, message = add_mcp_server( name=name, transport="http", - url=url, + url=rest[0], + timeout=timeout, ) + if success: + message += ( + "\nAdd headers with /mcp header " + f"{name}
; reference secrets as ${{NAME}} " + f"and set them with /mcp env {name} NAME ." + ) return CommandResult(success=success, message=message) return CommandResult( @@ -226,3 +265,20 @@ async def _set_env(self, args: List[str]) -> CommandResult: name, key, value = args[0], args[1], " ".join(args[2:]) success, message = update_mcp_server_env(name, key, value) return CommandResult(success=success, message=message) + + async def _set_header(self, args: List[str]) -> CommandResult: + """Set or remove one HTTP header of an http server.""" + if len(args) < 3: + return CommandResult( + success=False, + message=( + "Usage: /mcp header \n" + " /mcp header --remove" + ), + ) + name, header = args[0], args[1] + if args[2:] == ["--remove"]: + success, message = set_mcp_server_header(name, header, None) + else: + success, message = set_mcp_server_header(name, header, " ".join(args[2:])) + return CommandResult(success=success, message=message) diff --git a/app/ui_layer/settings/__init__.py b/app/ui_layer/settings/__init__.py index e4f9a540..cd07353f 100644 --- a/app/ui_layer/settings/__init__.py +++ b/app/ui_layer/settings/__init__.py @@ -13,6 +13,8 @@ disable_mcp_server, get_server_env_vars, update_mcp_server_env, + set_mcp_server_header, + describe_server, ) from app.ui_layer.settings.skill_settings import ( @@ -153,6 +155,8 @@ "disable_mcp_server", "get_server_env_vars", "update_mcp_server_env", + "set_mcp_server_header", + "describe_server", # Skill settings "list_skills", "get_skill_info", diff --git a/app/ui_layer/settings/mcp_settings.py b/app/ui_layer/settings/mcp_settings.py index 9666b8c8..9ccee97c 100644 --- a/app/ui_layer/settings/mcp_settings.py +++ b/app/ui_layer/settings/mcp_settings.py @@ -1,14 +1,23 @@ -"""MCP settings management.""" +"""MCP settings management. + +The one path by which the UI and the ``/mcp`` command change +``mcp_config.json``. Every write builds an ``MCPServerConfig`` first, so they +share the runtime's validation, and a rejected change is never saved. + +Header values are never listed: a server's headers are reported by name +(and the env keys they reference) only. +""" from __future__ import annotations import json import sys -from typing import Dict, List, Optional, Any +from typing import Any, Dict, List, Optional, Tuple from app.config import APP_CONFIG_PATH from app.logger import logger from app.mcp import MCPConfig, MCPServerConfig +from agent_core.core.impl.mcp.config import MCPConfigError, redact_url # Default MCP config path MCP_CONFIG_PATH = APP_CONFIG_PATH / "mcp_config.json" @@ -51,46 +60,104 @@ def save_mcp_config(config: MCPConfig) -> bool: return False +def _missing_config(server: MCPServerConfig) -> List[str]: + """Env keys the server needs but has no value for: empty env entries, + and variables its headers reference.""" + missing = [k for k, v in (server.env or {}).items() if not v] + for ref in server.header_env_refs(): + if not server.env.get(ref) and ref not in missing: + missing.append(ref) + return missing + + +def describe_server(server: MCPServerConfig) -> Dict[str, Any]: + """A server as the UI and /mcp see it: no env or header values.""" + platform_blocked = not _path_usable_on_current_platform( + server.command or "", getattr(server, "args", []) or [] + ) + if platform_blocked: + logger.debug( + "MCP server %s has platform-specific paths — skipping on %s", + server.name, + sys.platform, + ) + missing = _missing_config(server) + return { + "name": server.name, + "description": server.description, + "enabled": server.enabled, + "transport": server.transport, + "command": server.command, + "url": redact_url(server.url) if server.url else None, + "timeout": server.timeout, + "action_set": server.resolved_action_set_name, + # Unchanged shape for the existing editors (see mcp_get_env). + "env": dict(server.env or {}), + # Header names and the env keys each references; no values. + "headers": [ + { + "name": name, + "uses": [r for r in server.header_env_refs() if f"${{{r}}}" in value], + } + for name, value in server.headers.items() + ], + "missing_env": missing, + "needs_config": bool(missing), + "platform_blocked": platform_blocked, + "invalid": False, + "error": None, + } + + def list_mcp_servers() -> List[Dict[str, Any]]: """Get list of configured MCP servers with their status. Servers with platform-incompatible paths (e.g. Windows paths on macOS) are annotated with a ``platform_blocked`` flag so the UI can explain why - they cannot be started. + they cannot be started. Entries that fail validation are listed with + ``invalid: True`` and the (credential-free) reason, so they can be fixed + or removed instead of silently disappearing. """ try: config = load_mcp_config() except Exception as exc: logger.error(f"Failed to load MCP config: {exc}") return [] - servers = [] - for server in config.mcp_servers: - platform_blocked = not _path_usable_on_current_platform( - server.command or "", getattr(server, "args", []) or [] - ) - if platform_blocked: - logger.debug( - "MCP server %s has platform-specific paths — skipping on %s", - server.name, - sys.platform, - ) + servers = [describe_server(server) for server in config.mcp_servers] + for entry in config.invalid_servers: + raw = entry.raw if isinstance(entry.raw, dict) else {} servers.append( { - "name": server.name, - "description": server.description, - "enabled": server.enabled, - "transport": server.transport, - "command": server.command, - "action_set": server.resolved_action_set_name, - "env": server.env, - "platform_blocked": platform_blocked, + "name": entry.name or f"", + "description": raw.get("description", "") + if isinstance(raw.get("description"), str) + else "", + "enabled": bool(raw.get("enabled", True)), + "transport": raw.get("transport", "stdio") + if isinstance(raw.get("transport"), str) + else None, + "command": None, + "url": None, + "timeout": None, + "action_set": None, + "env": {}, + "headers": [], + "missing_env": [], + "needs_config": False, + "platform_blocked": False, + "invalid": True, + "error": entry.error, } ) return servers def get_server_env_vars(server_name: str) -> Dict[str, str]: - """Get the environment variables for an existing server.""" + """Get the environment variables for an existing server. + + Returns raw values: for server-side use only. Anything sent to a client + should use ``get_server_env_status``. + """ config = load_mcp_config() server = config.get_server_by_name(server_name) if server: @@ -98,6 +165,15 @@ def get_server_env_vars(server_name: str) -> Dict[str, str]: return {} +def _build_server(data: Dict[str, Any]) -> Tuple[Optional[MCPServerConfig], str]: + try: + return MCPServerConfig.from_dict(data), "" + except KeyError: + return None, "Server 'name' is required" + except (MCPConfigError, ValueError, TypeError) as e: + return None, str(e) + + def add_mcp_server( name: str, description: str = "", @@ -107,6 +183,8 @@ def add_mcp_server( url: Optional[str] = None, env: Optional[Dict[str, str]] = None, enabled: bool = True, + headers: Optional[Dict[str, str]] = None, + timeout: Optional[float] = None, ) -> tuple[bool, str]: """ Add a new MCP server configuration. @@ -114,28 +192,37 @@ def add_mcp_server( Returns: Tuple of (success, message) """ + data: Dict[str, Any] = { + "name": name, + "description": description, + "transport": transport, + "command": command, + "args": args or [], + "url": url, + "env": env or {}, + "enabled": enabled, + } + if headers: + data["headers"] = headers + if timeout is not None: + data["timeout"] = timeout + return _add_entry(data) + + +def _add_entry(data: Dict[str, Any]) -> Tuple[bool, str]: config = load_mcp_config() - - # Check if server already exists - if config.get_server_by_name(name): + name = data.get("name") + if isinstance(name, str) and ( + config.get_server_by_name(name) or config.get_invalid_entries(name) + ): return False, f"Server '{name}' already exists" - - try: - server = MCPServerConfig( - name=name, - description=description, - transport=transport, - command=command, - args=args or [], - url=url, - env=env or {}, - enabled=enabled, - ) - config.add_server(server) - save_mcp_config(config) - return True, f"Added MCP server: {name}" - except ValueError as e: - return False, str(e) + server, error = _build_server(data) + if server is None: + return False, error + config.add_server(server) + if not save_mcp_config(config): + return False, f"Could not save the MCP config for '{server.name}'" + return True, f"Added MCP server: {server.name}" def add_mcp_server_from_json(name: str, json_config: str) -> tuple[bool, str]: @@ -145,41 +232,36 @@ def add_mcp_server_from_json(name: str, json_config: str) -> tuple[bool, str]: Args: name: Server name json_config: JSON string with server configuration - Expected fields: transport, command, args, url, env, description, enabled + Fields: transport, command, args, url, env, headers, timeout, + description, enabled; unknown fields are kept as-is. Returns: Tuple of (success, message) Example: add_mcp_server_from_json("my-server", '{"transport":"stdio","command":"python","args":["-m","my_server"]}') + add_mcp_server_from_json("remote", '{"transport":"http","url":"https://host/mcp","headers":{"Authorization":"Bearer ${TOKEN}"},"env":{"TOKEN":""}}') """ try: config_dict = json.loads(json_config) except json.JSONDecodeError as e: - return False, f"Invalid JSON: {e}" - - return add_mcp_server( - name=name, - description=config_dict.get("description", ""), - transport=config_dict.get("transport", "stdio"), - command=config_dict.get("command"), - args=config_dict.get("args", []), - url=config_dict.get("url"), - env=config_dict.get("env", {}), - enabled=config_dict.get("enabled", True), - ) + return False, f"Invalid JSON: {e.msg} (line {e.lineno}, column {e.colno})" + if not isinstance(config_dict, dict): + return False, "The server configuration must be a JSON object" + + return _add_entry({**config_dict, "name": name}) def remove_mcp_server(name: str) -> tuple[bool, str]: """ - Remove an MCP server configuration. + Remove an MCP server configuration (valid or invalid entry). Returns: Tuple of (success, message) """ config = load_mcp_config() - if not config.get_server_by_name(name): + if not config.get_server_by_name(name) and not config.get_invalid_entries(name): return False, f"Server '{name}' not found" config.remove_server(name) @@ -237,3 +319,27 @@ def update_mcp_server_env(name: str, env_key: str, env_value: str) -> tuple[bool server.env[env_key] = env_value save_mcp_config(config) return True, f"Updated {env_key} for server '{name}'" + + +def set_mcp_server_header( + name: str, header: str, value: Optional[str] +) -> Tuple[bool, str]: + """Set (or, with ``value=None``, remove) one header of an http server. + Validated exactly like the JSON file; nothing is saved on error.""" + config = load_mcp_config() + server = config.get_server_by_name(name) + if not server: + return False, f"Server '{name}' not found" + headers = {k: v for k, v in server.headers.items() if k.lower() != header.lower()} + if value is not None: + headers[header] = value + elif len(headers) == len(server.headers): + return False, f"Server '{name}' has no header '{header}'" + updated, error = _build_server({**server.to_dict(), "headers": headers}) + if updated is None: + return False, error + config.replace_server(updated) + if not save_mcp_config(config): + return False, f"Could not save the MCP config for '{name}'" + action = "Set" if value is not None else "Removed" + return True, f"{action} header '{header}' for server '{name}'" diff --git a/app/ui_layer/settings/profile_bundle.py b/app/ui_layer/settings/profile_bundle.py index 1e84f232..5d80549a 100644 --- a/app/ui_layer/settings/profile_bundle.py +++ b/app/ui_layer/settings/profile_bundle.py @@ -32,6 +32,11 @@ get_app_version, ) from app.logger import logger +from agent_core.core.impl.mcp.config import ( + ENV_REF_RE as _ENV_REF_RE, + MCPConfigError, + MCPServerConfig, +) BUNDLE_FORMAT_VERSION = "1.0" @@ -115,27 +120,77 @@ def _validate_skill_md(skill_md: Path) -> Optional[str]: def _validate_mcp_entry(server: Dict[str, Any]) -> Optional[str]: - """Mirror agent_core.core.impl.mcp.config.MCPConfig.from_dict validation. + """The runtime's own validation (MCPServerConfig), not a copy of it. Returns None if the entry would be accepted by the runtime, else a short reason. This is the same shape check applied by the bundler — the importer enforces it again so corrupt bundles (or polluted upstream catalogs) can never silently bloat the recipient's mcp_config.json. """ - if not server.get("name"): + if not isinstance(server, dict) or not server.get("name"): return "missing name" - transport = server.get("transport", "stdio") - if transport == "stdio": - if not server.get("command"): - return "transport=stdio without command" - elif transport in ("sse", "http", "streamable_http"): - if not server.get("url"): - return f"transport={transport} without url" - else: - return f"unknown transport {transport!r}" + try: + MCPServerConfig.from_dict(server) + except (MCPConfigError, ValueError, TypeError, KeyError) as exc: + return str(exc) return None +# Header value prefixes that are not secrets themselves ("Bearer ${TOKEN}"). +_AUTH_SCHEMES = ("", "Bearer", "Basic", "Token", "Bot") + + +def _header_is_template(value: Any) -> bool: + """True when a header value holds no literal secret: only ${NAME} + references, optionally after an auth scheme word.""" + if not isinstance(value, str) or "${" not in value: + return False + leftover = _ENV_REF_RE.sub("", value).strip() + return leftover in _AUTH_SCHEMES + + +def _mcp_needs_config(server: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """What the recipient must fill in before a bundled server can connect: + empty env values (including ones its headers reference) and headers + whose value was blanked on export.""" + env = server.get("env") or {} + if not isinstance(env, dict): + env = {} + missing = [k for k in env if not env.get(k)] + headers = server.get("headers") or {} + if not isinstance(headers, dict): + headers = {} + for value in headers.values(): + for ref in _ENV_REF_RE.findall(value) if isinstance(value, str) else []: + if not env.get(ref) and ref not in missing: + missing.append(ref) + blank_headers = [k for k, v in headers.items() if v == ""] + if not missing and not blank_headers: + return None + result: Dict[str, Any] = {"name": server.get("name", ""), "env_keys": missing} + if blank_headers: + result["header_names"] = blank_headers + return result + + +def _same_mcp_target(a: Dict[str, Any], b: Dict[str, Any]) -> bool: + """Whether two entries reach the same server: same transport and the + same command+args or URL. Local credentials are only ever carried over + to an imported entry that passes this, so a bundle cannot reuse a local + server's name to point its secrets somewhere else.""" + + def key(entry: Dict[str, Any]) -> Tuple[Any, ...]: + transport = str(entry.get("transport") or "stdio").strip().lower() + transport = {"streamable_http": "http", "streamable-http": "http"}.get( + transport, transport + ) + if transport == "stdio": + return (transport, entry.get("command"), list(entry.get("args") or [])) + return (transport, entry.get("url")) + + return key(a) == key(b) + + def _copy_dir_filtered(src: Path, dst: Path) -> None: """Recursive copy honoring SKIP_DIR_NAMES / SKIP_FILE_SUFFIXES.""" if not src.exists(): @@ -177,7 +232,10 @@ def _looks_like_secret(env_key: str) -> bool: def _strip_mcp_secrets( servers: List[Dict[str, Any]], ) -> Tuple[List[Dict[str, Any]], List[str]]: - """Strip env-var values that look like secrets. Returns (cleaned, stripped_names).""" + """Strip env-var values that look like secrets. Returns (cleaned, stripped_names). + + HTTP header values are blanked too, unless they are pure ``${NAME}`` + templates (whose secret lives in env, which is always blanked).""" stripped: List[str] = [] cleaned: List[Dict[str, Any]] = [] for server in servers: @@ -192,6 +250,16 @@ def _strip_mcp_secrets( stripped.append(f"{s.get('name', '?')}::{key}") env[key] = "" s["env"] = env + headers = s.get("headers") + if isinstance(headers, dict) and headers: + kept: Dict[str, Any] = {} + for header, value in headers.items(): + if _header_is_template(value) or value == "": + kept[header] = value + else: + stripped.append(f"{s.get('name', '?')}::header:{header}") + kept[header] = "" + s["headers"] = kept cleaned.append(s) return cleaned, stripped @@ -430,12 +498,9 @@ def inspect_bundle(bundle_path: str) -> Dict[str, Any]: mcp_servers_in_bundle = [] mcp_needs_env: List[Dict[str, Any]] = [] for server in mcp_servers_in_bundle: - env = server.get("env") or {} - missing = [k for k in env if not env.get(k)] - if missing: - mcp_needs_env.append( - {"name": server.get("name", ""), "env_keys": missing} - ) + needs = _mcp_needs_config(server) if isinstance(server, dict) else None + if needs: + mcp_needs_env.append(needs) contents = manifest.get("contents", {}) return { @@ -747,9 +812,9 @@ def _filter_valid(servers: List[Dict[str, Any]]) -> List[Dict[str, Any]]: cleaned: List[Dict[str, Any]] = [] for server in _filter_valid(bundle_servers): name = server["name"] - missing_env = [k for k, v in (server.get("env") or {}).items() if not v] - if missing_env: - needs_env.append({"name": name, "env_keys": missing_env}) + needs = _mcp_needs_config(server) + if needs: + needs_env.append(needs) cleaned.append(server) added.append(name) MCP_CONFIG_PATH.write_text( @@ -765,25 +830,44 @@ def _filter_valid(servers: List[Dict[str, Any]]) -> List[Dict[str, Any]]: for server in _filter_valid(bundle_servers): name = server["name"] - missing_env = [k for k, v in (server.get("env") or {}).items() if not v] - if missing_env: - needs_env.append({"name": name, "env_keys": missing_env}) if name in by_name: - # Keep ANY env values the user had set locally — don't blow - # them away, since the user's filled-in tokens are more - # valuable than the (empty) tokens from the bundle. - preserved_env = by_name[name].get("env", {}) - merged_env = dict(server.get("env", {})) - for k, v in preserved_env.items(): - if v and k in merged_env and not merged_env[k]: - merged_env[k] = v - server["env"] = merged_env + # Keep env values (and blanked header values) the user had set + # locally — their filled-in tokens are more valuable than the + # bundle's empty ones — but ONLY when the imported entry still + # reaches the same server. Otherwise a bundle could reuse a + # local name with a new url/command and receive the user's keys. + local = by_name[name] + if _same_mcp_target(local, server): + preserved_env = local.get("env", {}) or {} + merged_env = dict(server.get("env", {}) or {}) + for k, v in preserved_env.items(): + if v and k in merged_env and not merged_env[k]: + merged_env[k] = v + server["env"] = merged_env + local_headers = local.get("headers") or {} + if isinstance(server.get("headers"), dict) and isinstance( + local_headers, dict + ): + merged_headers = dict(server["headers"]) + for k, v in local_headers.items(): + if v and merged_headers.get(k) == "": + merged_headers[k] = v + server["headers"] = merged_headers + else: + logger.warning( + f"[PROFILE_BUNDLE] MCP '{name}' points somewhere new; " + "local credentials are not carried over" + ) by_name[name] = server added.append(name) else: by_name[name] = server added.append(name) + # After any merge, so values the user already has are not reported. + needs = _mcp_needs_config(server) + if needs: + needs_env.append(needs) current["mcp_servers"] = list(by_name.values()) MCP_CONFIG_PATH.write_text( diff --git a/tests/mcp_http_mock.py b/tests/mcp_http_mock.py new file mode 100644 index 00000000..3df0e507 --- /dev/null +++ b/tests/mcp_http_mock.py @@ -0,0 +1,203 @@ +"""In-process Streamable HTTP MCP server for tests (#185). + +Follows the MCP spec (2025-03-26 .. 2025-11-25): one endpoint, POST for every +client message, JSON or SSE responses, 202 for notifications, Mcp-Session-Id +issued on initialize, DELETE to end a session, and GET + Last-Event-ID to +resume a stream the server closed early. Behaviour switches let tests make it +misbehave in specific ways. +""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any, Dict, List, Optional + +from aiohttp import web + +TOOLS = [ + { + "name": "echo", + "description": "Echo text", + "inputSchema": { + "type": "object", + "properties": {"text": {"type": "string"}}, + "required": ["text"], + }, + } +] + + +class MockStreamableServer: + """A spec-shaped Streamable HTTP MCP server with switchable misbehaviour.""" + + def __init__(self, *, mode: str = "json", tools=None, name: str = "mock"): + self.mode = mode # "json" | "sse" + self.tools = TOOLS if tools is None else tools + self.name = name + self.version = "2025-11-25" + self.session_id: Optional[str] = "session-1" + self.required_headers: Dict[str, str] = {} + self.status_for: Dict[str, int] = {} # method -> HTTP status + self.hang_on: set = set() # methods that never answer + self.received = asyncio.Event() # set when a hung method arrives + self.pre_messages: List[Dict[str, Any]] = [] # SSE before response + self.close_early = False # SSE: end the stream without a response + self.resumable = False # SSE: close after an event id, resume via GET + self.expired: set = set() # session ids that now get HTTP 404 + self._sessions_issued = 1 + self.redirect_to: Optional[str] = None + self.page_size: Optional[int] = None + self.requests: List[Dict[str, Any]] = [] + self._pending: Dict[str, Dict[str, Any]] = {} + + def expire(self) -> None: + """End the current session: requests carrying it get HTTP 404, and + the next initialize issues a new session id.""" + if self.session_id: + self.expired.add(self.session_id) + + # ── recording ── + def calls(self, method: str) -> List[Dict[str, Any]]: + return [r for r in self.requests if r["method"] == method] + + def _record(self, request: web.Request, body: Optional[dict]) -> None: + self.requests.append( + { + "http": request.method, + "method": (body or {}).get("method") + or ("" if body and "id" in body else request.method), + "headers": {k.lower(): v for k, v in request.headers.items()}, + "body": body, + } + ) + + # ── routes ── + async def _post(self, request: web.Request) -> web.StreamResponse: + body = await request.json() + self._record(request, body) + if self.redirect_to: + return web.Response(status=307, headers={"Location": self.redirect_to}) + for header, value in self.required_headers.items(): + if request.headers.get(header) != value: + return web.json_response( + { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32001, "message": "unauthorized"}, + }, + status=401, + ) + if "method" not in body: # a response to our ping + return web.Response(status=202) + method = body["method"] + if method == "initialize" and self.session_id in self.expired: + self._sessions_issued += 1 + self.session_id = f"session-{self._sessions_issued}" + if method != "initialize" and self.session_id: + sent = request.headers.get("Mcp-Session-Id") + if sent in self.expired: + return web.Response(status=404) + if sent != self.session_id: + return web.Response(status=400, text="missing session") + if "id" not in body: # notification + return web.Response(status=202) + if method in self.status_for: + return web.json_response( + { + "jsonrpc": "2.0", + "id": body["id"], + "error": {"code": -32000, "message": "boom {x}"}, + }, + status=self.status_for[method], + ) + if method in self.hang_on: + self.received.set() + await asyncio.Event().wait() + response = {"jsonrpc": "2.0", "id": body["id"], "result": self._result(body)} + headers = {} + if method == "initialize" and self.session_id: + headers["Mcp-Session-Id"] = self.session_id + if self.mode == "json": + return web.json_response(response, headers=headers) + return await self._sse(request, response, headers) + + def _result(self, body: dict) -> Dict[str, Any]: + method, params = body["method"], body.get("params") or {} + if method == "initialize": + return { + "protocolVersion": self.version, + "capabilities": {"tools": {}}, + "serverInfo": {"name": self.name, "version": "0"}, + } + if method == "tools/list": + if not self.page_size: + return {"tools": self.tools} + start = int(params.get("cursor") or 0) + page = self.tools[start : start + self.page_size] + result: Dict[str, Any] = {"tools": page} + if start + self.page_size < len(self.tools): + result["nextCursor"] = str(start + self.page_size) + return result + if method == "tools/call": + text = params.get("arguments", {}).get("text", "") + return {"content": [{"type": "text", "text": f"{self.name}:{text}"}]} + return {} + + async def _sse(self, request, response, headers) -> web.StreamResponse: + stream = web.StreamResponse( + headers={"Content-Type": "text/event-stream", **headers} + ) + await stream.prepare(request) + for message in self.pre_messages: + await stream.write(f"data: {json.dumps(message)}\n\n".encode()) + if self.close_early: + return stream + if self.resumable: + event_id = f"evt-{response['id']}" + self._pending[event_id] = response + await stream.write(f"id: {event_id}\nretry: 10\ndata:\n\n".encode()) + return stream + await stream.write( + f"event: message\nid: 1\ndata: {json.dumps(response)}\n\n".encode() + ) + return stream + + async def _get(self, request: web.Request) -> web.StreamResponse: + self._record(request, None) + response = self._pending.pop(request.headers.get("Last-Event-ID", ""), None) + if response is None: + return web.Response(status=405) + stream = web.StreamResponse(headers={"Content-Type": "text/event-stream"}) + await stream.prepare(request) + await stream.write(f"data: {json.dumps(response)}\n\n".encode()) + return stream + + async def _delete(self, request: web.Request) -> web.Response: + self._record(request, None) + return web.Response(status=200) + + async def start(self) -> str: + app = web.Application() + app.add_routes( + [ + web.post("/mcp", self._post), + web.get("/mcp", self._get), + web.delete("/mcp", self._delete), + ] + ) + self._runner = web.AppRunner(app, shutdown_timeout=0.1) + await self._runner.setup() + site = web.TCPSite(self._runner, "127.0.0.1", 0) + await site.start() + self.port = self._runner.addresses[0][1] + return f"http://127.0.0.1:{self.port}/mcp" + + async def stop(self) -> None: + await self._runner.cleanup() + + +async def serve(**kwargs) -> tuple: + server = MockStreamableServer(**kwargs) + url = await server.start() + return server, url diff --git a/tests/test_mcp_client_lifecycle.py b/tests/test_mcp_client_lifecycle.py new file mode 100644 index 00000000..5b09cbbf --- /dev/null +++ b/tests/test_mcp_client_lifecycle.py @@ -0,0 +1,417 @@ +"""MCPClient with several Streamable HTTP servers: isolation and reloads (#185). + +Each server has its own connection, headers, credentials and error. A reload +touches only the servers whose connection settings changed; a removed server +takes exactly its own actions with it. Also covers the generated tool handler +treating server-supplied names as data. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from typing import Dict, List + +import pytest + +from agent_core.core.action_framework import registry_instance +from agent_core.core.impl.mcp.adapter import MCPActionAdapter +from agent_core.core.impl.mcp.client import MCPClient +from tests.mcp_http_mock import serve + +KEY_A = "key-A-SENTINEL-1111" +KEY_B = "key-B-SENTINEL-2222" + + +@pytest.fixture +def client(): + """A fresh MCPClient (the module-level one is a singleton).""" + instance = object.__new__(MCPClient) + instance._initialized = False + instance.__init__() + yield instance + for names in instance._registered_actions.values(): + MCPActionAdapter.unregister_actions(names) + + +def entry(name: str, url: str, key: str, **extra) -> Dict: + data = { + "name": name, + "transport": "http", + "url": url, + "timeout": 10, + "headers": {"Authorization": "Bearer ${TOKEN}"}, + "env": {"TOKEN": key}, + "enabled": True, + } + data.update(extra) + return data + + +def write(path: Path, servers: List[Dict]) -> Path: + path.write_text(json.dumps({"mcp_servers": servers}), encoding="utf-8") + return path + + +def inits(server) -> int: + return len(server.calls("initialize")) + + +def deletes(server) -> int: + return len([r for r in server.requests if r["http"] == "DELETE"]) + + +async def two_servers(): + a, url_a = await serve(name="a") + b, url_b = await serve(name="b") + a.required_headers = {"Authorization": f"Bearer {KEY_A}"} + b.required_headers = {"Authorization": f"Bearer {KEY_B}"} + return a, url_a, b, url_b + + +# ───────────────────────── Several servers at once ────────────────────────── + + +def test_two_servers_connect_with_their_own_credentials_and_tools(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write( + tmp_path / "mcp.json", + [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, KEY_B)], + ) + await client.initialize(path) + client.register_tools_as_actions() + registered = set(registry_instance._registry) + ra = await client.call_tool("srv_a", "echo", {"text": "hi"}) + rb = await client.call_tool("srv_b", "echo", {"text": "hi"}) + status = client.get_status() + await client.disconnect_all() + after = set(registry_instance._registry) + return a, b, ra, rb, status, registered, after + finally: + await a.stop() + await b.stop() + + a, b, ra, rb, status, registered, after = asyncio.run(scenario()) + assert ra["result"] == "a:hi" + assert rb["result"] == "b:hi" + assert status["servers"]["srv_a"]["connected"] is True + assert status["servers"]["srv_b"]["connected"] is True + # No cross-server leakage: each server only ever saw its own key and session. + for server, own, other in ((a, KEY_A, KEY_B), (b, KEY_B, KEY_A)): + for request in server.requests: + assert request["headers"].get("authorization") == f"Bearer {own}" + assert other not in json.dumps(request["headers"]) + assert {"mcp_srv_a_echo", "mcp_srv_b_echo"} <= registered + assert deletes(a) == 1 and deletes(b) == 1 # disconnect_all ended both + # ...and took their actions with them. + assert not {"mcp_srv_a_echo", "mcp_srv_b_echo"} & after + + +def test_one_failing_server_does_not_affect_the_other(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write( + tmp_path / "mcp.json", + # srv_b gets srv_a's key: its server refuses it. + [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, KEY_A)], + ) + await client.initialize(path) + ra = await client.call_tool("srv_a", "echo", {"text": "ok"}) + rb = await client.call_tool("srv_b", "echo", {"text": "ok"}) + status = client.get_status() + await client.disconnect_all() + return ra, rb, status + finally: + await a.stop() + await b.stop() + + ra, rb, status = asyncio.run(scenario()) + assert ra["status"] == "success" + assert rb == {"status": "error", "message": "MCP server 'srv_b' is not connected"} + failed = status["servers"]["srv_b"] + assert failed["connected"] is False + assert "HTTP 401" in failed["error"] + assert KEY_A not in json.dumps(status) + + +def test_a_missing_credential_is_reported_per_server(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + broken = entry("srv_b", url_b, KEY_B) + broken["env"] = {} + path = write(tmp_path / "mcp.json", [entry("srv_a", url_a, KEY_A), broken]) + await client.initialize(path) + status = client.get_status() + await client.disconnect_all() + return status, b + finally: + await a.stop() + await b.stop() + + status, b = asyncio.run(scenario()) + assert status["servers"]["srv_a"]["connected"] is True + assert status["servers"]["srv_b"]["error"] == ( + "Server 'srv_b': set TOKEN in this server's env (referenced by its headers)" + ) + assert b.requests == [] # never contacted without its credential + + +# ───────────────────────── Reloads ────────────────────────────────────────── + + +def test_editing_one_server_reconnects_only_that_server(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write( + tmp_path / "mcp.json", + [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, "old-key")], + ) + await client.initialize(path) + transport_a = client.servers["srv_a"]._transport + assert "srv_b" not in client.servers # old key refused + # Fix srv_b's key and change only srv_a's description. + write( + path, + [ + entry("srv_a", url_a, KEY_A, description="renamed"), + entry("srv_b", url_b, KEY_B), + ], + ) + result = await client.reload(path) + same_a = client.servers["srv_a"]._transport is transport_a + description = client.servers["srv_a"].config.description + rb = await client.call_tool("srv_b", "echo", {"text": "x"}) + await client.disconnect_all() + return result, same_a, description, rb, a + finally: + await a.stop() + await b.stop() + + result, same_a, description, rb, a = asyncio.run(scenario()) + assert result["connected"] == ["srv_b"] + assert result["reconnected"] == [] and result["disconnected"] == [] + assert same_a and description == "renamed" + assert inits(a) == 1 # srv_a was never re-initialised + assert rb["result"] == "b:x" + + +def test_changing_a_header_reconnects_with_the_new_value(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + b.required_headers = {} + try: + path = write( + tmp_path / "mcp.json", + [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, "first")], + ) + await client.initialize(path) + write(path, [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, "second")]) + result = await client.reload(path) + await client.call_tool("srv_b", "echo", {"text": "x"}) + await client.disconnect_all() + return result, a, b + finally: + await a.stop() + await b.stop() + + result, a, b = asyncio.run(scenario()) + assert result["reconnected"] == ["srv_b"] + assert inits(a) == 1 and inits(b) == 2 + assert deletes(b) == 2 # the old session was ended, then the new one + assert b.calls("tools/call")[0]["headers"]["authorization"] == "Bearer second" + + +def test_removing_a_server_disconnects_it_and_removes_only_its_actions( + client, tmp_path +): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + # "foo" is a prefix of "foo_bar": removing foo must keep foo_bar's. + path = write( + tmp_path / "mcp.json", + [entry("foo", url_a, KEY_A), entry("foo_bar", url_b, KEY_B)], + ) + await client.initialize(path) + client.register_tools_as_actions() + before = set(registry_instance._registry) + write(path, [entry("foo_bar", url_b, KEY_B)]) + result = await client.reload(path) + after = set(registry_instance._registry) + still = await client.call_tool("foo_bar", "echo", {"text": "y"}) + await client.disconnect_all() + return before, after, result, still, a + finally: + await a.stop() + await b.stop() + + before, after, result, still, a = asyncio.run(scenario()) + assert {"mcp_foo_echo", "mcp_foo_bar_echo"} <= before + assert "mcp_foo_echo" not in after + assert "mcp_foo_bar_echo" in after + assert result["disconnected"] == ["foo"] + assert deletes(a) == 1 + assert still["result"] == "b:y" + + +def test_a_broken_edit_keeps_the_running_server_on_its_last_good_settings( + client, tmp_path +): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write(tmp_path / "mcp.json", [entry("srv_a", url_a, KEY_A)]) + await client.initialize(path) + write(path, [entry("srv_a", "ftp://not-http/mcp", KEY_A)]) + result = await client.reload(path) + still = await client.call_tool("srv_a", "echo", {"text": "z"}) + saved = json.loads(path.read_text(encoding="utf-8")) + await client.disconnect_all() + return result, still, saved + finally: + await a.stop() + await b.stop() + + result, still, saved = asyncio.run(scenario()) + assert result["kept"] == ["srv_a"] + assert result["invalid"][0]["name"] == "srv_a" + assert "http:// or https://" in result["invalid"][0]["error"] + assert still["result"] == "a:z" + assert saved["mcp_servers"][0]["url"] == "ftp://not-http/mcp" # untouched + + +def test_disabling_a_server_disconnects_it_and_clears_its_error(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write( + tmp_path / "mcp.json", + [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, "wrong")], + ) + await client.initialize(path) + had_error = "srv_b" in client.last_errors + write( + path, + [ + entry("srv_a", url_a, KEY_A, enabled=False), + entry("srv_b", url_b, "wrong", enabled=False), + ], + ) + result = await client.reload(path) + status = client.get_status() + return had_error, result, status + finally: + await a.stop() + await b.stop() + + had_error, result, status = asyncio.run(scenario()) + assert had_error + assert result["disconnected"] == ["srv_a"] + assert status["servers"] == {} + + +def test_concurrent_reloads_are_serialised(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write(tmp_path / "mcp.json", [entry("srv_a", url_a, KEY_A)]) + await client.initialize(path) + write(path, [entry("srv_a", url_a, KEY_A), entry("srv_b", url_b, KEY_B)]) + results = await asyncio.gather(client.reload(path), client.reload(path)) + await client.disconnect_all() + return results, b + finally: + await a.stop() + await b.stop() + + results, b = asyncio.run(scenario()) + assert inits(b) == 1 # connected once, not by both reloads + assert sorted(r["connected"] for r in results) == [[], ["srv_b"]] + + +def test_an_unreadable_config_leaves_connections_alone(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write(tmp_path / "mcp.json", [entry("srv_a", url_a, KEY_A)]) + await client.initialize(path) + path.write_text("{ not json", encoding="utf-8") + result = await client.reload(path) + connected = client.servers["srv_a"].is_connected + await client.disconnect_all() + return result, connected + finally: + await a.stop() + await b.stop() + + result, connected = asyncio.run(scenario()) + assert result["success"] is False + assert connected + + +# ───────────────────────── Tool handler ───────────────────────────────────── + + +def test_handler_timeout_follows_the_http_servers_timeout(client, tmp_path): + async def scenario(): + path = write( + tmp_path / "mcp.json", + [ + { + "name": "slow", + "transport": "http", + "url": "https://h/mcp", + "timeout": 120, + "enabled": False, + }, + { + "name": "fast", + "transport": "http", + "url": "https://h/mcp", + "timeout": 5, + "enabled": False, + }, + {"name": "local", "command": "x", "enabled": False}, + ], + ) + await client.initialize(path) + + asyncio.run(scenario()) + assert client.handler_timeout("slow") == 130.0 + assert client.handler_timeout("fast") == 60.0 + assert client.handler_timeout("local") == 60.0 + assert client.handler_timeout("unknown") == 60.0 + + +def test_a_reload_reconnects_a_server_whose_connection_died(client, tmp_path): + async def scenario(): + a, url_a, b, url_b = await two_servers() + try: + path = write(tmp_path / "mcp.json", [entry("srv_a", url_a, KEY_A)]) + await client.initialize(path) + # The session ends and cannot be renewed: the transport gives up. + a.expire() + a.status_for = {"initialize": 503} + failed = await client.call_tool("srv_a", "echo", {"text": "1"}) + dead = not client.servers["srv_a"].is_connected + # The server recovers; settings are unchanged. + a.status_for = {} + result = await client.reload(path) + again = await client.call_tool("srv_a", "echo", {"text": "2"}) + await client.disconnect_all() + return failed, dead, result, again + finally: + await a.stop() + await b.stop() + + failed, dead, result, again = asyncio.run(scenario()) + assert failed["status"] == "error" + assert dead + assert result["reconnected"] == ["srv_a"] + assert again["result"] == "a:2" diff --git a/tests/test_mcp_config.py b/tests/test_mcp_config.py new file mode 100644 index 00000000..85c9e8b2 --- /dev/null +++ b/tests/test_mcp_config.py @@ -0,0 +1,388 @@ +"""MCP server configuration: the http transport, headers and safe saving (#185). + +Structure is validated when an entry is built; ``${NAME}`` references in +headers are resolved at connect time from that server's own ``env`` only. +Nothing here may put an env or header value into an error message. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from agent_core.core.impl.mcp.config import ( + DEFAULT_HTTP_TIMEOUT, + MCPConfig, + MCPConfigError, + MCPServerConfig, + redact_url, +) + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +SECRET = "sk-config-SENTINEL-4242" + + +def http(**overrides) -> dict: + entry = { + "name": "remote", + "transport": "http", + "url": "https://mcp.example.com/mcp", + } + entry.update(overrides) + return entry + + +def build(**overrides) -> MCPServerConfig: + return MCPServerConfig.from_dict(http(**overrides)) + + +# ───────────────────────── Backward compatibility ─────────────────────────── + + +def test_every_shipped_server_entry_still_loads_unchanged(): + path = PROJECT_ROOT / "app" / "config" / "mcp_config.default.json" + raw = json.loads(path.read_text(encoding="utf-8")) + config = MCPConfig.from_dict(raw) + assert config.invalid_servers == [] + assert len(config.mcp_servers) == len(raw["mcp_servers"]) + # A load/save round trip does not change any shipped entry. + assert config.to_dict()["mcp_servers"] == [ + MCPServerConfig.from_dict(e).to_dict() for e in raw["mcp_servers"] + ] + for before, after in zip(raw["mcp_servers"], config.to_dict()["mcp_servers"]): + for key, value in before.items(): + assert after[key] == value + + +@pytest.mark.parametrize("transport", ["sse", "websocket"]) +def test_existing_url_transports_keep_their_lenient_url_check(transport): + # Unchanged: sse/websocket only require a url to be present. + server = MCPServerConfig.from_dict( + {"name": "x", "transport": transport, "url": "localhost:9000/sse"} + ) + assert server.url == "localhost:9000/sse" + with pytest.raises(MCPConfigError, match="'url' is not specified"): + MCPServerConfig.from_dict({"name": "x", "transport": transport}) + + +def test_mcp_config_error_is_a_value_error_for_existing_callers(): + assert issubclass(MCPConfigError, ValueError) + + +# ───────────────────────── Transport ──────────────────────────────────────── + + +@pytest.mark.parametrize( + "spelling", ["http", "HTTP", " http ", "streamable_http", "streamable-http"] +) +def test_http_transport_spellings_normalise_to_http(spelling): + server = build(transport=spelling) + assert server.transport == "http" + assert server.to_dict()["transport"] == "http" + + +def test_unknown_transport_is_rejected_with_the_valid_choices(): + with pytest.raises(MCPConfigError) as excinfo: + build(transport="grpc") + assert "stdio, sse, websocket, http" in str(excinfo.value) + + +@pytest.mark.parametrize( + "url, message", + [ + (None, "not specified"), + ("", "not specified"), + ("ftp://mcp.example.com/mcp", "http:// or https://"), + ("ws://mcp.example.com/mcp", "http:// or https://"), + ("mcp.example.com/mcp", "http:// or https://"), + ("https:///mcp", "no host"), + ("https://mcp.example.com:99999/mcp", "not a valid URL"), + ("https://user:pw@mcp.example.com/mcp", "not in the url"), + ("https://mcp.example.com/mcp#frag", "fragment"), + ("https://mcp.example.com/m cp", "without spaces"), + (" https://mcp.example.com/mcp", "without spaces"), + ], +) +def test_http_url_validation(url, message): + with pytest.raises(MCPConfigError, match=message): + build(url=url) + + +def test_http_url_errors_never_echo_the_url(): + # A query string may carry a key; the message names the server only. + with pytest.raises(MCPConfigError) as excinfo: + build(url=f"ftp://mcp.example.com/mcp?key={SECRET}") + assert SECRET not in str(excinfo.value) + + +def test_http_urls_with_ports_ipv6_and_query_are_accepted(): + for url in ( + "http://127.0.0.1:8123/mcp", + "https://[::1]:8443/mcp", + "https://mcp.example.com/mcp?region=eu", + ): + assert build(url=url).url == url + + +# ───────────────────────── Headers ────────────────────────────────────────── + + +def test_headers_are_kept_per_server_and_saved(): + server = build(headers={"Authorization": "Bearer ${TOKEN}", "X-Team": "a"}) + assert server.headers == {"Authorization": "Bearer ${TOKEN}", "X-Team": "a"} + assert server.to_dict()["headers"] == server.headers + # Not shared with another instance (no mutable default leakage). + other = build(name="other") + assert other.headers == {} + assert server.headers is not other.headers + + +@pytest.mark.parametrize( + "headers, message", + [ + ("Bearer x", "must be an object"), + ({"Bad Header": "x"}, "invalid header name"), + ({"X-Ok:": "x"}, "invalid header name"), + ({"": "x"}, "invalid header name"), + ({"X-Num": 5}, "must be a string"), + ({"X-Split": "a\r\nInjected: 1"}, "control character"), + ({"X-Null": "a\x00b"}, "control character"), + ({"X-Ref": "${UNCLOSED"}, "malformed reference"), + ({"X-Ref": "${1BAD}"}, "malformed reference"), + ({"Authorization": "a", "authorization": "b"}, "given twice"), + ], +) +def test_invalid_headers_are_rejected(headers, message): + with pytest.raises(MCPConfigError, match=message): + build(headers=headers) + + +@pytest.mark.parametrize( + "name", + [ + "Accept", + "content-type", + "Content-Length", + "Host", + "Mcp-Session-Id", + "MCP-Protocol-Version", + "Last-Event-ID", + "Transfer-Encoding", + ], +) +def test_transport_owned_headers_cannot_be_configured(name): + with pytest.raises(MCPConfigError, match="set by the transport"): + build(headers={name: "x"}) + + +def test_header_errors_never_echo_the_value(): + with pytest.raises(MCPConfigError) as excinfo: + build(headers={"Authorization": f"Bearer {SECRET}\r\nX: y"}) + assert SECRET not in str(excinfo.value) + + +def test_headers_are_only_accepted_on_the_http_transport(): + with pytest.raises(MCPConfigError, match="only supported by the http"): + MCPServerConfig.from_dict( + { + "name": "s", + "transport": "sse", + "url": "http://h/sse", + "headers": {"A": "b"}, + } + ) + + +def test_a_tab_is_allowed_in_a_header_value(): + assert build(headers={"X": "a\tb"}).headers == {"X": "a\tb"} + + +# ───────────────────────── Resolving ${NAME} ──────────────────────────────── + + +def test_references_resolve_from_the_servers_own_env(): + server = build( + headers={"Authorization": "Bearer ${TOKEN}", "X-Pair": "${A}-${B}"}, + env={"TOKEN": SECRET, "A": "1", "B": "2"}, + ) + assert server.resolve_headers() == { + "Authorization": f"Bearer {SECRET}", + "X-Pair": "1-2", + } + assert server.header_env_refs() == ["TOKEN", "A", "B"] + + +def test_references_never_fall_back_to_the_process_environment(monkeypatch): + # An imported or agent-written config must not be able to send a key + # from the app's own environment to a remote host. + monkeypatch.setenv("TOKEN", SECRET) + server = build(headers={"Authorization": "Bearer ${TOKEN}"}) + with pytest.raises(MCPConfigError) as excinfo: + server.resolve_headers() + assert "TOKEN" in str(excinfo.value) + assert SECRET not in str(excinfo.value) + + +@pytest.mark.parametrize("env", [{}, {"TOKEN": ""}, {"TOKEN": None}]) +def test_missing_or_empty_references_fail_instead_of_sending_empty(env): + server = build(headers={"Authorization": "Bearer ${TOKEN}"}, env=env) + with pytest.raises(MCPConfigError, match="set TOKEN in this server's env"): + server.resolve_headers() + + +def test_every_missing_reference_is_named_once(): + server = build(headers={"A": "${ONE}${TWO}", "B": "${ONE}"}) + with pytest.raises(MCPConfigError) as excinfo: + server.resolve_headers() + assert "set ONE, TWO in" in str(excinfo.value) + + +def test_a_literal_empty_header_value_fails_at_connect(): + server = build(headers={"X-Key": ""}) + with pytest.raises(MCPConfigError, match="resolves to an empty value"): + server.resolve_headers() + + +def test_a_resolved_value_with_a_line_break_is_rejected_without_echo(): + server = build( + headers={"Authorization": "${TOKEN}"}, env={"TOKEN": f"{SECRET}\nX: y"} + ) + with pytest.raises(MCPConfigError) as excinfo: + server.resolve_headers() + assert "line break" in str(excinfo.value) + assert SECRET not in str(excinfo.value) + + +# ───────────────────────── Timeout ────────────────────────────────────────── + + +def test_timeout_defaults_and_bounds(): + assert build().timeout is None + assert build().effective_timeout == DEFAULT_HTTP_TIMEOUT + assert build(timeout=5).effective_timeout == 5.0 + for bad in (0, -1, 301, float("inf"), float("nan"), True, "10"): + with pytest.raises(MCPConfigError, match="timeout"): + build(timeout=bad) + + +# ───────────────────────── Saving never loses entries ─────────────────────── + + +def test_unknown_fields_survive_a_round_trip(): + raw = { + "mcp_servers": [http(future_option={"a": 1}, note="keep me")], + "auto_connect": False, + "schema_version": 2, + } + saved = MCPConfig.from_dict(raw).to_dict() + assert saved["mcp_servers"][0]["future_option"] == {"a": 1} + assert saved["mcp_servers"][0]["note"] == "keep me" + assert saved["schema_version"] == 2 + assert saved["auto_connect"] is False + + +def test_invalid_entries_are_kept_in_place_and_reported(tmp_path): + raw = { + "mcp_servers": [ + {"name": "a", "command": "a"}, + http(name="broken", url="ftp://x/mcp"), + {"transport": "stdio", "command": "noname"}, + {"name": "b", "command": "b"}, + ] + } + config = MCPConfig.from_dict(raw) + assert [s.name for s in config.mcp_servers] == ["a", "b"] + assert [(e.name, e.index) for e in config.invalid_servers] == [ + ("broken", 1), + (None, 2), + ] + assert "missing 'name'" in config.invalid_servers[1].error + + path = tmp_path / "mcp_config.json" + config.save(path) + assert json.loads(path.read_text(encoding="utf-8"))["mcp_servers"] == [ + MCPServerConfig.from_dict(raw["mcp_servers"][0]).to_dict(), + raw["mcp_servers"][1], + raw["mcp_servers"][2], + MCPServerConfig.from_dict(raw["mcp_servers"][3]).to_dict(), + ] + + +def test_a_duplicate_name_is_kept_as_invalid_and_the_first_wins(): + config = MCPConfig.from_dict( + {"mcp_servers": [http(), http(url="https://other.example.com/mcp")]} + ) + assert len(config.mcp_servers) == 1 + assert config.mcp_servers[0].url == "https://mcp.example.com/mcp" + assert "duplicate server name 'remote'" in config.invalid_servers[0].error + assert len(config.to_dict()["mcp_servers"]) == 2 + + +def test_an_invalid_entry_blocks_adding_the_same_name_and_can_be_replaced(): + config = MCPConfig.from_dict( + {"mcp_servers": [{"name": "a", "command": "a"}, http(url="ftp://x")]} + ) + assert config.add_server(build()) is False + assert config.replace_server(build()) is True + assert config.invalid_servers == [] + assert [s.name for s in config.mcp_servers] == ["a", "remote"] + + +def test_remove_also_deletes_invalid_entries_with_that_name(): + config = MCPConfig.from_dict({"mcp_servers": [http(url="ftp://x")]}) + assert config.remove_server("remote") is True + assert config.to_dict()["mcp_servers"] == [] + + +def test_non_object_entries_and_files_are_handled(): + config = MCPConfig.from_dict({"mcp_servers": ["oops", 3]}) + assert len(config.invalid_servers) == 2 + with pytest.raises(MCPConfigError): + MCPConfig.from_dict({"mcp_servers": {"not": "a list"}}) + with pytest.raises(MCPConfigError): + MCPConfig.from_dict(["not", "an", "object"]) + + +# ───────────────────────── Fingerprint ────────────────────────────────────── + + +def test_connection_fingerprint_tracks_only_what_changes_the_connection(): + base = build(headers={"A": "1"}) + assert ( + base.connection_fingerprint() + == build( + headers={"A": "1"}, description="new text", enabled=False + ).connection_fingerprint() + ) + for change in ( + {"url": "https://other.example.com/mcp"}, + {"headers": {"A": "2"}}, + {"env": {"K": "v"}}, + {"timeout": 9}, + ): + assert build(**{"headers": {"A": "1"}, **change}).connection_fingerprint() != ( + base.connection_fingerprint() + ) + + +# ───────────────────────── redact_url ─────────────────────────────────────── + + +@pytest.mark.parametrize( + "url, expected", + [ + ("https://mcp.example.com/mcp", "https://mcp.example.com/mcp"), + ("https://mcp.example.com:8443/mcp", "https://mcp.example.com:8443/mcp"), + ( + f"https://u:{SECRET}@mcp.example.com/mcp?key={SECRET}#x", + "https://mcp.example.com/mcp (credentials/query hidden)", + ), + ("https://[::1]:9000/mcp", "https://[::1]:9000/mcp"), + ("", ""), + (None, ""), + ], +) +def test_redact_url(url, expected): + assert redact_url(url) == expected diff --git a/tests/test_mcp_settings.py b/tests/test_mcp_settings.py new file mode 100644 index 00000000..26903bf3 --- /dev/null +++ b/tests/test_mcp_settings.py @@ -0,0 +1,354 @@ +"""MCP settings, the /mcp command, profile bundles and the browser handlers +with http servers and headers (#185). + +They all write through ``mcp_settings`` and the runtime's validation, and +none of them may hand an env or header value to the browser, the chat, or an +exported bundle. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from typing import Any, Dict, List + +import pytest + +import app.ui_layer.settings.mcp_settings as mcp_settings +import app.ui_layer.settings.profile_bundle as profile_bundle +from app.ui_layer.commands.builtin.mcp import MCPCommand + +SECRET = "sk-settings-SENTINEL-7777" +OTHER_SECRET = "sk-other-SENTINEL-8888" + + +@pytest.fixture +def config_path(tmp_path, monkeypatch) -> Path: + path = tmp_path / "mcp_config.json" + monkeypatch.setattr(mcp_settings, "MCP_CONFIG_PATH", path) + monkeypatch.setattr(profile_bundle, "MCP_CONFIG_PATH", path) + return path + + +def write(path: Path, servers: List[Dict[str, Any]], **top) -> None: + path.write_text(json.dumps({"mcp_servers": servers, **top}), encoding="utf-8") + + +def read(path: Path) -> Dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) + + +def stitch(**overrides) -> Dict[str, Any]: + entry = { + "name": "stitch", + "transport": "http", + "url": "https://mcp.example.com/mcp", + "headers": {"X-Api-Key": "${STITCH_KEY}", "X-Literal": SECRET}, + "env": {"STITCH_KEY": SECRET}, + "enabled": True, + } + entry.update(overrides) + return entry + + +def test_list_flags_a_header_reference_with_no_env_value(config_path): + write(config_path, [stitch(env={})]) + (server,) = mcp_settings.list_mcp_servers() + assert server["missing_env"] == ["STITCH_KEY"] + assert server["needs_config"] is True + + +def test_list_redacts_url_credentials_and_query(config_path): + write(config_path, [stitch(url=f"https://mcp.example.com/mcp?key={SECRET}")]) + (server,) = mcp_settings.list_mcp_servers() + assert server["url"] == "https://mcp.example.com/mcp (credentials/query hidden)" + + +def test_list_includes_invalid_entries_with_their_reason(config_path): + write(config_path, [stitch(url="ftp://x/mcp", headers={"X": SECRET})]) + (server,) = mcp_settings.list_mcp_servers() + assert server["invalid"] is True + assert "http:// or https://" in server["error"] + assert SECRET not in json.dumps(server) + + +# ───────────────────────── Adding ─────────────────────────────────────────── + + +def test_add_json_http_server_keeps_headers_and_unknown_fields(config_path): + write(config_path, []) + ok, message = mcp_settings.add_mcp_server_from_json( + "remote", + json.dumps( + { + "transport": "streamable_http", + "url": "https://h.example.com/mcp", + "headers": {"Authorization": "Bearer ${TOKEN}"}, + "env": {"TOKEN": ""}, + "timeout": 45, + "custom": [1, 2], + } + ), + ) + assert ok, message + (saved,) = read(config_path)["mcp_servers"] + assert saved["transport"] == "http" + assert saved["headers"] == {"Authorization": "Bearer ${TOKEN}"} + assert saved["timeout"] == 45 + assert saved["custom"] == [1, 2] + + +@pytest.mark.parametrize( + "config, message", + [ + ("{not json", "Invalid JSON"), + ("[]", "must be a JSON object"), + ('{"transport": "http", "url": "ftp://x"}', "http:// or https://"), + ( + '{"transport": "http", "url": "https://h/mcp", "headers": {"Host": "x"}}', + "set by the transport", + ), + ], +) +def test_add_json_rejects_bad_input_without_saving(config_path, config, message): + write(config_path, []) + before = config_path.read_bytes() + ok, text = mcp_settings.add_mcp_server_from_json("bad", config) + assert ok is False and message in text + assert config_path.read_bytes() == before + + +def test_add_refuses_a_name_held_by_an_invalid_entry(config_path): + write(config_path, [stitch(url="ftp://x")]) + ok, message = mcp_settings.add_mcp_server_from_json( + "stitch", '{"transport": "http", "url": "https://h/mcp"}' + ) + assert ok is False and "already exists" in message + + +def test_toggling_a_server_no_longer_drops_headers_or_unknown_fields(config_path): + write(config_path, [stitch(custom={"x": 1}), {"bad": "entry"}], schema=3) + assert mcp_settings.disable_mcp_server("stitch")[0] + data = read(config_path) + assert data["mcp_servers"][0]["headers"] == stitch()["headers"] + assert data["mcp_servers"][0]["custom"] == {"x": 1} + assert data["mcp_servers"][1] == {"bad": "entry"} # invalid entry kept + assert data["schema"] == 3 + + +def test_header_set_and_remove(config_path): + write(config_path, [stitch(), {"name": "local", "command": "x"}]) + assert mcp_settings.set_mcp_server_header("stitch", "X-Team", "a")[0] + assert mcp_settings.set_mcp_server_header("stitch", "x-team", None)[0] + assert ( + "has no header" + in mcp_settings.set_mcp_server_header("stitch", "X-Team", None)[1] + ) + ok, message = mcp_settings.set_mcp_server_header("local", "X", "y") + assert ok is False and "only supported by the http" in message + ok, message = mcp_settings.set_mcp_server_header("stitch", "Bad Name", "y") + assert ok is False and "invalid header name" in message + assert "X-Team" not in read(config_path)["mcp_servers"][0]["headers"] + + +def test_remove_deletes_an_invalid_entry(config_path): + write(config_path, [stitch(url="ftp://x")]) + assert mcp_settings.remove_mcp_server("stitch")[0] + assert read(config_path)["mcp_servers"] == [] + + +# ───────────────────────── /mcp ───────────────────────────────────────────── + + +def run_command(*args: str): + # /mcp never uses the UI controller. + return asyncio.run(MCPCommand(controller=None).execute(list(args))) + + +def test_command_adds_an_http_server_with_a_timeout(config_path): + write(config_path, []) + result = run_command( + "add", + "remote", + "--transport", + "http", + "https://h.example.com/mcp", + "--timeout", + "45", + ) + assert result.success, result.message + assert "/mcp header remote" in result.message + (saved,) = read(config_path)["mcp_servers"] + assert (saved["transport"], saved["url"], saved["timeout"]) == ( + "http", + "https://h.example.com/mcp", + 45.0, + ) + + +def test_command_accepts_the_streamable_http_spelling(config_path): + write(config_path, []) + assert run_command( + "add", "r", "--transport", "streamable_http", "https://h/mcp" + ).success + assert read(config_path)["mcp_servers"][0]["transport"] == "http" + + +def test_command_reports_validation_errors(config_path): + write(config_path, []) + result = run_command("add", "r", "--transport", "http", "ftp://h/mcp") + assert result.success is False and "http:// or https://" in result.message + assert run_command( + "add", "r", "--transport", "http", "https://h", "--timeout", "x" + ).message == ("--timeout needs a number of seconds") + + +def test_command_stdio_add_splits_command_and_args(config_path): + # Regression: the whole token list used to become the command. + write(config_path, []) + assert run_command( + "add", "py", "--transport", "stdio", "--", "python", "-m", "srv" + ).success + (saved,) = read(config_path)["mcp_servers"] + assert saved["command"] == "python" and saved["args"] == ["-m", "srv"] + + +def test_command_header_value_keeps_spaces_and_can_be_removed(config_path): + write(config_path, [stitch()]) + assert run_command( + "header", "stitch", "Authorization", "Bearer", "${STITCH_KEY}" + ).success + assert ( + read(config_path)["mcp_servers"][0]["headers"]["Authorization"] + == "Bearer ${STITCH_KEY}" + ) + assert run_command("header", "stitch", "Authorization", "--remove").success + assert "Authorization" not in read(config_path)["mcp_servers"][0]["headers"] + + +def test_command_list_shows_transport_and_needs_but_never_secrets(config_path): + write(config_path, [stitch(env={}), stitch(name="broken", url="ftp://x")]) + message = run_command("list", "--all").message + assert "stitch [enabled] (http) - needs env: STITCH_KEY" in message + assert "broken [enabled] (http) - invalid:" in message + assert SECRET not in message + + +# ───────────────────────── Profile bundles ────────────────────────────────── + + +def test_export_blanks_literal_header_values_but_keeps_templates(): + cleaned, stripped = profile_bundle._strip_mcp_secrets([stitch()]) + (server,) = cleaned + assert server["headers"] == {"X-Api-Key": "${STITCH_KEY}", "X-Literal": ""} + assert server["env"] == {"STITCH_KEY": ""} + assert "stitch::header:X-Literal" in stripped + assert SECRET not in json.dumps(cleaned) + + +@pytest.mark.parametrize( + "value, template", + [ + ("${T}", True), + ("Bearer ${T}", True), + ("Basic ${USER}${PASS}", True), + ("Bearer abc${T}", False), + ("plain-secret", False), + ("", False), + ], +) +def test_header_template_detection(value, template): + assert profile_bundle._header_is_template(value) is template + + +def test_bundle_validation_is_the_runtime_validation(): + assert ( + profile_bundle._validate_mcp_entry( + {"name": "w", "transport": "websocket", "url": "ws://h"} + ) + is None + ) + assert "http:// or https://" in profile_bundle._validate_mcp_entry( + {"name": "h", "transport": "http", "url": "ftp://h"} + ) + assert profile_bundle._validate_mcp_entry({"transport": "http"}) == "missing name" + + +def write_bundle(tmp_path: Path, servers: List[Dict[str, Any]]) -> Path: + bundle = tmp_path / "bundle_mcp" + bundle.mkdir() + (bundle / "servers.json").write_text( + json.dumps({"mcp_servers": servers}), encoding="utf-8" + ) + return bundle + + +def test_import_keeps_local_credentials_for_the_same_server(config_path, tmp_path): + write(config_path, [stitch()]) + exported, _ = profile_bundle._strip_mcp_secrets([stitch()]) + added, _, needs, invalid = profile_bundle._apply_mcp( + write_bundle(tmp_path, exported), "replace" + ) + assert added == ["stitch"] and invalid == [] + (saved,) = read(config_path)["mcp_servers"] + assert saved["env"] == {"STITCH_KEY": SECRET} + assert saved["headers"]["X-Literal"] == SECRET + assert needs == [] + + +def test_import_never_hands_local_credentials_to_a_new_target(config_path, tmp_path): + # A bundle reuses a local name but points it at another host and + # references the local key from a header: the key must not follow. + write(config_path, [stitch()]) + hostile = stitch(url="https://attacker.example.net/mcp", env={"STITCH_KEY": ""}) + hostile["headers"] = {"Authorization": "${STITCH_KEY}"} + added, _, needs, _ = profile_bundle._apply_mcp( + write_bundle(tmp_path, [hostile]), "replace" + ) + (saved,) = read(config_path)["mcp_servers"] + assert saved["url"] == "https://attacker.example.net/mcp" + assert saved["env"] == {"STITCH_KEY": ""} + assert SECRET not in json.dumps(read(config_path)) + assert needs == [{"name": "stitch", "env_keys": ["STITCH_KEY"]}] + + +def test_import_reports_header_needs_and_rejects_invalid_entries(config_path, tmp_path): + write(config_path, []) + servers = [ + stitch(env={}, headers={"X-Api-Key": "${STITCH_KEY}", "X-Literal": ""}), + stitch(name="bad", url="ftp://x"), + ] + added, _, needs, invalid = profile_bundle._apply_mcp( + write_bundle(tmp_path, servers), "replace" + ) + assert added == ["stitch"] + assert needs == [ + {"name": "stitch", "env_keys": ["STITCH_KEY"], "header_names": ["X-Literal"]} + ] + assert invalid[0]["name"] == "bad" + + +def test_list_reports_header_names_and_never_header_values(config_path): + write( + config_path, + [stitch(headers={"X-Api-Key": "${STITCH_KEY}", "X-Literal": OTHER_SECRET})], + ) + (server,) = mcp_settings.list_mcp_servers() + assert server["transport"] == "http" + assert server["headers"] == [ + {"name": "X-Api-Key", "uses": ["STITCH_KEY"]}, + {"name": "X-Literal", "uses": []}, + ] + assert server["needs_config"] is False + assert OTHER_SECRET not in json.dumps(server) + assert "args" not in server or server["args"] is None + + +def test_list_never_sends_stdio_arguments(config_path): + write( + config_path, + [{"name": "local", "command": "srv", "args": ["--api-key", OTHER_SECRET]}], + ) + (server,) = mcp_settings.list_mcp_servers() + assert OTHER_SECRET not in json.dumps(server) diff --git a/tests/test_mcp_streamable_http.py b/tests/test_mcp_streamable_http.py new file mode 100644 index 00000000..cdc72505 --- /dev/null +++ b/tests/test_mcp_streamable_http.py @@ -0,0 +1,739 @@ +"""StreamableHTTPTransport against an in-process Streamable HTTP server (#185). + +The mock server follows the MCP spec (2025-03-26 .. 2025-11-25): one +endpoint, POST for every client message, JSON or SSE responses, 202 for +notifications, Mcp-Session-Id issued on initialize, DELETE to end a session, +and GET + Last-Event-ID to resume a stream the server closed early. + +No test sleeps for timing: waits use events, and the timeouts asserted on are +the transport's own (a server that never answers). +""" + +from __future__ import annotations + +import asyncio +import json +import socket +from typing import List, Optional + +import httpx +import pytest +from loguru import logger + +from agent_core.core.impl.mcp.config import MCPServerConfig +from agent_core.core.impl.mcp.server import ( + MCPServerConnection, + StreamableHTTPTransport, +) +from tests.mcp_http_mock import serve + +SECRET = "sk-http-SENTINEL-9001" + + +@pytest.fixture +def log_lines(): + lines: List[str] = [] + sink = logger.add( + lambda m: lines.append(str(m)), + level="DEBUG", + format="{level}|{message}\n{exception}", + backtrace=True, + diagnose=True, + ) + try: + yield lines + finally: + logger.remove(sink) + + +def run(coro): + return asyncio.run(coro) + + +# ───────────────────────── Happy path ─────────────────────────────────────── + + +@pytest.mark.parametrize("mode", ["json", "sse"]) +def test_handshake_discovery_and_call_follow_the_spec(mode): + async def scenario(): + server, url = await serve(mode=mode) + try: + transport = StreamableHTTPTransport( + url, headers={"X-Api-Key": SECRET}, timeout=10, server_name="t" + ) + assert await transport.connect() is True + listed = await transport.send_request("tools/list", {}) + called = await transport.send_request( + "tools/call", {"name": "echo", "arguments": {"text": "hi"}} + ) + state = (transport.session_id, transport.protocol_version) + await transport.disconnect() + return server, listed, called, state, transport + finally: + await server.stop() + + server, listed, called, state, transport = run(scenario()) + assert state == ("session-1", "2025-11-25") + assert listed["result"]["tools"][0]["name"] == "echo" + assert called["result"]["content"][0]["text"] == "mock:hi" + assert not transport.is_connected + + init, initialized = server.requests[0], server.requests[1] + assert init["method"] == "initialize" + assert init["body"]["params"]["protocolVersion"] == "2025-11-25" + assert init["headers"]["accept"] == "application/json, text/event-stream" + assert init["headers"]["content-type"] == "application/json" + assert "mcp-session-id" not in init["headers"] + assert "mcp-protocol-version" not in init["headers"] + assert initialized["method"] == "notifications/initialized" + # Every request after initialize carries the session and version. + for request in server.requests[1:]: + assert request["headers"]["mcp-session-id"] == "session-1" + assert request["headers"]["mcp-protocol-version"] == "2025-11-25" + assert request["headers"]["x-api-key"] == SECRET + assert server.requests[-1]["http"] == "DELETE" + + +def test_a_server_without_sessions_works_and_gets_no_delete(): + async def scenario(): + server, url = await serve() + server.session_id = None + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + assert "result" in await transport.send_request("tools/list", {}) + await transport.disconnect() + return server + finally: + await server.stop() + + server = run(scenario()) + assert all("mcp-session-id" not in r["headers"] for r in server.requests) + assert not [r for r in server.requests if r["http"] == "DELETE"] + + +@pytest.mark.parametrize("version", ["2025-03-26", "2025-06-18", "2025-11-25"]) +def test_supported_negotiated_versions_are_used_in_later_headers(version): + async def scenario(): + server, url = await serve() + server.version = version + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + await transport.send_request("tools/list", {}) + await transport.disconnect() + return server + finally: + await server.stop() + + server = run(scenario()) + assert server.calls("tools/list")[0]["headers"]["mcp-protocol-version"] == version + + +def test_concurrent_requests_each_get_their_own_response(): + async def scenario(): + server, url = await serve(mode="sse") + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + results = await asyncio.gather( + *[ + transport.send_request( + "tools/call", {"name": "echo", "arguments": {"text": str(i)}} + ) + for i in range(8) + ] + ) + await transport.disconnect() + return results + finally: + await server.stop() + + results = run(scenario()) + assert [r["result"]["content"][0]["text"] for r in results] == [ + f"mock:{i}" for i in range(8) + ] + + +# ───────────────────────── SSE stream handling ────────────────────────────── + + +def test_server_requests_and_notifications_before_the_response_are_handled(): + async def scenario(): + server, url = await serve(mode="sse") + server.pre_messages = [ + {"jsonrpc": "2.0", "method": "notifications/progress", "params": {}}, + {"jsonrpc": "2.0", "id": "srv-1", "method": "ping"}, + {"jsonrpc": "2.0", "id": "srv-2", "method": "sampling/createMessage"}, + {"not": "json-rpc"}, + ] + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + await transport.disconnect() + return server + finally: + await server.stop() + + server = run(scenario()) + replies = [r["body"] for r in server.requests if r["method"] == ""] + assert {"jsonrpc": "2.0", "id": "srv-1", "result": {}} in replies + refused = [r for r in replies if r["id"] == "srv-2"][0] + assert refused["error"]["code"] == -32601 + # The session id arrives in the initialize response's headers, before its + # SSE body, so replies sent while reading that stream already carry it. + reply_headers = [ + r["headers"] for r in server.requests if r["method"] == "" + ] + assert len(reply_headers) == 2 + assert all(h.get("mcp-session-id") == "session-1" for h in reply_headers) + + +def test_a_stream_closed_with_an_event_id_is_resumed_with_last_event_id(): + async def scenario(): + server, url = await serve(mode="sse") + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + server.resumable = True + listed = await transport.send_request("tools/list", {}) + await transport.disconnect() + return server, listed + finally: + await server.stop() + + server, listed = run(scenario()) + assert listed["result"]["tools"][0]["name"] == "echo" + resume = [r for r in server.requests if r["http"] == "GET"][0] + assert resume["headers"]["last-event-id"].startswith("evt-") + assert resume["headers"]["accept"] == "text/event-stream" + assert resume["headers"]["mcp-session-id"] == "session-1" + + +def test_a_stream_that_ends_without_a_response_is_an_error(): + async def scenario(): + server, url = await serve(mode="sse") + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + server.close_early = True + result = await transport.send_request("tools/list", {}) + still_connected = transport.is_connected + await transport.disconnect() + return result, still_connected + finally: + await server.stop() + + result, still_connected = run(scenario()) + assert "ended before the response" in result["error"]["message"] + assert still_connected # one failed request does not drop the session + + +# ───────────────────────── Failures ───────────────────────────────────────── + + +@pytest.mark.parametrize("status", [401, 403]) +def test_authentication_failures_are_reported_without_the_credential(status, log_lines): + async def scenario(): + server, url = await serve() + server.status_for = {"initialize": status} + try: + transport = StreamableHTTPTransport( + url, headers={"Authorization": f"Bearer {SECRET}"}, timeout=10 + ) + ok = await transport.connect() + return ok, transport + finally: + await server.stop() + + ok, transport = run(scenario()) + assert ok is False + assert f"HTTP {status}" in transport.last_error + assert "check this server's headers" in transport.last_error + assert "boom {x}" in transport.last_error # server's JSON-RPC error text + assert transport._client is None + assert SECRET not in transport.last_error + assert SECRET not in "\n".join(log_lines) + + +@pytest.mark.parametrize("status", [400, 404, 500, 503]) +def test_http_errors_on_a_request_become_error_responses(status): + async def scenario(): + server, url = await serve() + server.session_id = None # a 404 without a session is "not found" + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + server.status_for = {"tools/list": status} + result = await transport.send_request("tools/list", {}) + connected = transport.is_connected + await transport.disconnect() + return result, connected + finally: + await server.stop() + + result, connected = run(scenario()) + assert f"HTTP {status}" in result["error"]["message"] + assert "boom {x} (code -32000)" in result["error"]["message"] + assert connected + + +def test_a_404_on_a_session_starts_a_new_session_and_retries_once(): + # Spec: on 404 for a request with a session id the client MUST start a + # new session (fresh initialize, no session id). + async def scenario(): + server, url = await serve() + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + server.expire() + result = await transport.send_request("tools/list", {}) + state = (transport.is_connected, transport.session_id) + await transport.disconnect() + return server, result, state + finally: + await server.stop() + + server, result, (connected, session_id) = run(scenario()) + assert result["result"]["tools"][0]["name"] == "echo" + assert connected and session_id == "session-2" + inits = server.calls("initialize") + assert len(inits) == 2 + assert "mcp-session-id" not in inits[1]["headers"] + lists = server.calls("tools/list") + assert [r["headers"]["mcp-session-id"] for r in lists] == ["session-1", "session-2"] + + +def test_concurrent_requests_share_one_session_renewal(): + async def scenario(): + server, url = await serve() + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + server.expire() + results = await asyncio.gather( + *[transport.send_request("tools/list", {}) for _ in range(5)] + ) + await transport.disconnect() + return server, results + finally: + await server.stop() + + server, results = run(scenario()) + assert all("result" in r for r in results) + assert len(server.calls("initialize")) == 2 # one renewal, not five + + +def test_a_failed_session_renewal_disconnects_with_the_reason(): + async def scenario(): + server, url = await serve() + try: + transport = StreamableHTTPTransport(url, timeout=10) + assert await transport.connect() + server.expire() + server.status_for = {"initialize": 503} + result = await transport.send_request("tools/list", {}) + connected = transport.is_connected + await transport.disconnect() + return result, connected + finally: + await server.stop() + + result, connected = run(scenario()) + message = result["error"]["message"] + assert "ended the MCP session and a new one could not be started" in message + assert "HTTP 503" in message + assert connected is False + + +def test_redirects_are_not_followed_so_headers_stay_with_the_configured_url(log_lines): + async def scenario(): + target, target_url = await serve(name="elsewhere") + server, url = await serve() + server.redirect_to = target_url + f"?token={SECRET}" + try: + transport = StreamableHTTPTransport( + url, headers={"Authorization": SECRET}, timeout=10 + ) + ok = await transport.connect() + return ok, transport, target + finally: + await server.stop() + await target.stop() + + ok, transport, target = run(scenario()) + assert ok is False + assert "redirected" in transport.last_error + assert "redirects are not followed" in transport.last_error + assert target.requests == [] # the credential never reached the target + assert SECRET not in transport.last_error + assert SECRET not in "\n".join(log_lines) + + +def test_an_unreachable_endpoint_fails_cleanly(): + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() # nothing listens here now + + async def scenario(): + transport = StreamableHTTPTransport( + f"http://127.0.0.1:{port}/mcp?key={SECRET}", timeout=5 + ) + ok = await transport.connect() + return ok, transport + + ok, transport = run(scenario()) + assert ok is False + assert "could not connect to http://127.0.0.1" in transport.last_error + assert SECRET not in transport.last_error + assert transport._client is None + + +def test_initialize_that_never_answers_times_out_and_cleans_up(): + async def scenario(): + server, url = await serve() + server.hang_on = {"initialize"} + try: + transport = StreamableHTTPTransport(url, timeout=0.5) + ok = await transport.connect() + return ok, transport + finally: + await server.stop() + + ok, transport = run(scenario()) + assert ok is False + assert "timed out after 0.5s" in transport.last_error + assert transport._client is None + + +def test_a_request_that_never_answers_times_out_without_dropping_the_session(): + async def scenario(): + server, url = await serve() + try: + transport = StreamableHTTPTransport(url, timeout=0.5) + assert await transport.connect() + server.hang_on = {"tools/call"} + result = await transport.send_request("tools/call", {"name": "echo"}) + connected = transport.is_connected + server.hang_on = set() + after = await transport.send_request("tools/list", {}) + await transport.disconnect() + return result, connected, after + finally: + await server.stop() + + result, connected, after = run(scenario()) + assert "timed out after 0.5s" in result["error"]["message"] + assert connected + assert "result" in after + + +def test_cancelling_connect_closes_the_client_and_propagates(): + async def scenario(): + server, url = await serve() + server.hang_on = {"initialize"} + try: + transport = StreamableHTTPTransport(url, timeout=30) + task = asyncio.create_task(transport.connect()) + await asyncio.wait_for(server.received.wait(), 10) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + return transport + finally: + await server.stop() + + transport = run(scenario()) + assert transport._client is None + assert not transport.is_connected + + +def test_an_unsupported_protocol_version_is_rejected(): + async def scenario(): + server, url = await serve() + server.version = "2024-11-05" + try: + transport = StreamableHTTPTransport(url, timeout=10) + ok = await transport.connect() + return ok, transport, server + finally: + await server.stop() + + ok, transport, server = run(scenario()) + assert ok is False + assert "protocol version '2024-11-05'" in transport.last_error + # It asked to end the session it was given. + assert server.requests[-1]["http"] == "DELETE" + + +# ── Malformed responses (httpx.MockTransport: precise wire control) ── + + +def mock_transport(handler) -> StreamableHTTPTransport: + return StreamableHTTPTransport( + "https://mcp.example.com/mcp", + timeout=5, + _http_transport=httpx.MockTransport(handler), + ) + + +def init_ok(request: httpx.Request) -> Optional[httpx.Response]: + body = json.loads(request.content) if request.content else {} + if body.get("method") == "initialize": + return httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": body["id"], + "result": {"protocolVersion": "2025-06-18", "capabilities": {}}, + }, + ) + if "id" not in body: + return httpx.Response(202) + return None + + +@pytest.mark.parametrize( + "response, message", + [ + ( + httpx.Response( + 200, content=b"{not json", headers={"content-type": "application/json"} + ), + "malformed JSON", + ), + ( + httpx.Response(200, content=b"hi", headers={"content-type": "text/plain"}), + "unexpected Content-Type", + ), + (httpx.Response(202), "sent no response"), + ( + httpx.Response(200, json={"jsonrpc": "2.0", "id": 999, "result": {}}), + "wrong id", + ), + ( + httpx.Response(200, json=[{"jsonrpc": "2.0", "id": 2, "result": {}}]), + "non-response body", + ), + ], +) +def test_malformed_responses_become_errors(response, message): + def handler(request): + return init_ok(request) or response + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + result = await transport.send_request("tools/list", {}) + await transport.disconnect() + return result + + assert message in run(scenario())["error"]["message"] + + +def test_a_json_rpc_error_with_a_null_id_is_matched_to_the_request(): + def handler(request): + return init_ok(request) or httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32600, "message": "bad"}, + }, + ) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + return await transport.send_request("tools/list", {}) + + result = run(scenario()) + assert result["error"]["message"] == "bad" + + +def test_an_oversized_response_is_refused(monkeypatch): + monkeypatch.setattr(StreamableHTTPTransport, "MAX_MESSAGE_BYTES", 1024) + + def handler(request): + return init_ok(request) or httpx.Response( + 200, json={"jsonrpc": "2.0", "id": 2, "result": {"x": "a" * 4096}} + ) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + return await transport.send_request("tools/list", {}) + + assert "16 MB message limit" in run(scenario())["error"]["message"] + + +@pytest.mark.parametrize("session_id", ["", "has space", "tab\tin", "ünicode"]) +def test_an_invalid_session_id_fails_the_handshake(session_id): + def handler(request): + body = json.loads(request.content) + return httpx.Response( + 200, + # Raw bytes: httpx will not build a non-ASCII str header itself. + headers=[(b"Mcp-Session-Id", session_id.encode("latin-1"))], + json={ + "jsonrpc": "2.0", + "id": body["id"], + "result": {"protocolVersion": "2025-06-18"}, + }, + ) + + async def scenario(): + transport = mock_transport(handler) + return await transport.connect(), transport + + ok, transport = run(scenario()) + assert ok is False + assert "invalid Mcp-Session-Id" in transport.last_error + + +def test_initialize_rejected_with_a_json_rpc_error(): + def handler(request): + body = json.loads(request.content) + return httpx.Response( + 200, + json={ + "jsonrpc": "2.0", + "id": body["id"], + "error": {"code": -32602, "message": "Unsupported protocol version"}, + }, + ) + + async def scenario(): + transport = mock_transport(handler) + return await transport.connect(), transport + + ok, transport = run(scenario()) + assert ok is False + assert transport.last_error == ( + "initialize rejected: Unsupported protocol version (code -32602)" + ) + + +def test_an_interrupted_connection_is_reported(): + def handler(request): + if init_ok(request): + return init_ok(request) + raise httpx.RemoteProtocolError("peer closed", request=request) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + return await transport.send_request("tools/list", {}) + + assert "was interrupted" in run(scenario())["error"]["message"] + + +def test_disconnect_survives_a_failing_delete_and_always_closes(): + def handler(request): + if request.method == "DELETE": + raise httpx.ConnectError("gone", request=request) + body = json.loads(request.content) + if body.get("method") == "initialize": + return httpx.Response( + 200, + headers={"Mcp-Session-Id": "s"}, + json={ + "jsonrpc": "2.0", + "id": body["id"], + "result": {"protocolVersion": "2025-06-18"}, + }, + ) + return httpx.Response(202) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + await transport.disconnect() + return transport + + transport = run(scenario()) + assert transport._client is None + assert transport.session_id is None + + +# ───────────────────────── Through MCPServerConnection ────────────────────── + + +def http_config(url: str, **overrides) -> MCPServerConfig: + entry = {"name": "remote", "transport": "http", "url": url, "timeout": 10} + entry.update(overrides) + return MCPServerConfig.from_dict(entry) + + +def test_connection_resolves_header_references_and_discovers_paginated_tools(): + tools = [{"name": f"tool{i}", "inputSchema": {"type": "object"}} for i in range(5)] + + async def scenario(): + server, url = await serve(tools=tools) + server.page_size = 2 + server.required_headers = {"Authorization": f"Bearer {SECRET}"} + try: + connection = MCPServerConnection( + http_config( + url, + headers={"Authorization": "Bearer ${TOKEN}"}, + env={"TOKEN": SECRET}, + ) + ) + assert await connection.connect() + names = [t.name for t in connection.tools] + called = await connection.call_tool("tool1", {}) + await connection.disconnect() + return server, names, called + finally: + await server.stop() + + server, names, called = run(scenario()) + assert names == [f"tool{i}" for i in range(5)] + cursors = [ + (r["body"].get("params") or {}).get("cursor") + for r in server.calls("tools/list") + ] + assert cursors == [None, "2", "4"] + assert called["status"] == "success" + + +def test_a_missing_header_variable_fails_that_server_before_any_request(log_lines): + async def scenario(): + server, url = await serve() + try: + connection = MCPServerConnection( + http_config(url, headers={"Authorization": "Bearer ${TOKEN}"}) + ) + ok = await connection.connect() + return ok, connection, server + finally: + await server.stop() + + ok, connection, server = run(scenario()) + assert ok is False + assert connection.last_error == ( + "Server 'remote': set TOKEN in this server's env (referenced by its headers)" + ) + assert server.requests == [] # nothing was sent without the credential + + +def test_connection_reports_the_transport_failure_reason(): + async def scenario(): + server, url = await serve() + server.status_for = {"initialize": 401} + try: + connection = MCPServerConnection( + http_config(url, headers={"Authorization": SECRET}) + ) + ok = await connection.connect() + return ok, connection + finally: + await server.stop() + + ok, connection = run(scenario()) + assert ok is False + assert "HTTP 401" in connection.last_error + assert SECRET not in connection.last_error + assert not connection.is_connected diff --git a/tests/test_mcp_streamable_http_interop.py b/tests/test_mcp_streamable_http_interop.py new file mode 100644 index 00000000..7bda2c7c --- /dev/null +++ b/tests/test_mcp_streamable_http_interop.py @@ -0,0 +1,179 @@ +"""Interoperability: CraftBot's Streamable HTTP client against the official +MCP Python SDK server (#185). + +Opt-in, because the SDK is not a CraftBot dependency. Point +CRAFTBOT_MCP_INTEROP_PYTHON at any interpreter that has ``mcp`` (2.x) and +``uvicorn`` installed; the SDK server runs in that interpreter, in a +subprocess, so nothing is added to the test environment itself: + + CRAFTBOT_MCP_INTEROP_PYTHON=/path/to/venv-with-mcp/python pytest \\ + tests/test_mcp_streamable_http_interop.py + +The server sits behind a small ASGI guard that requires an X-Api-Key header, +so the header path is exercised against the real protocol stack too. +""" + +from __future__ import annotations + +import asyncio +import os +import queue +import subprocess +import sys +import threading +import textwrap + +import pytest + +from agent_core.core.impl.mcp.config import MCPServerConfig +from agent_core.core.impl.mcp.server import MCPServerConnection + +INTEROP_PYTHON = os.environ.get("CRAFTBOT_MCP_INTEROP_PYTHON") +pytestmark = pytest.mark.skipif( + not INTEROP_PYTHON, + reason="set CRAFTBOT_MCP_INTEROP_PYTHON to an interpreter with mcp installed", +) + +API_KEY = "interop-test-key" # a test value for a local, throwaway server + +SERVER_SCRIPT = textwrap.dedent( + """ + import socket + import sys + + import uvicorn + from mcp.server.mcpserver import MCPServer + + mode, sessions, key = sys.argv[1], sys.argv[2], sys.argv[3] + server = MCPServer("interop") + + @server.tool() + def add(a: int, b: int) -> int: + \"\"\"Add two integers.\"\"\" + return a + b + + app = server.streamable_http_app( + json_response=(mode == "json"), + stateless_http=(sessions == "stateless"), + host="127.0.0.1", + ) + + async def guarded(scope, receive, send): + if scope["type"] == "http": + headers = dict(scope["headers"]) + if headers.get(b"x-api-key") != key.encode(): + await send({"type": "http.response.start", "status": 401, + "headers": [(b"content-type", b"application/json")]}) + await send({"type": "http.response.body", + "body": b'{"error": "unauthorized"}'}) + return + await app(scope, receive, send) + + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + sock.listen(16) + print(sock.getsockname()[1], flush=True) + uvicorn.Server(uvicorn.Config(guarded, log_level="warning")).run(sockets=[sock]) + """ +) + + +@pytest.fixture +def sdk_server(tmp_path, request): + mode, sessions = request.param + script = tmp_path / "sdk_server.py" + script.write_text(SERVER_SCRIPT, encoding="utf-8") + proc = subprocess.Popen( + [INTEROP_PYTHON, str(script), mode, sessions, API_KEY], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + lines: "queue.Queue[str]" = queue.Queue() + threading.Thread( + target=lambda: lines.put(proc.stdout.readline()), daemon=True + ).start() + try: + port = int(lines.get(timeout=60).strip()) + except (queue.Empty, ValueError): + proc.kill() + raise RuntimeError(f"SDK server did not start: {proc.stderr.read()[-2000:]}") + try: + yield f"http://127.0.0.1:{port}/mcp", sessions + finally: + proc.kill() + proc.wait(timeout=10) + + +def connection(url: str, key: str | None) -> MCPServerConnection: + entry = { + "name": "sdk", + "transport": "http", + "url": url, + "timeout": 20, + "headers": {"X-Api-Key": "${KEY}"}, + "env": {"KEY": key} if key else {"KEY": "wrong-key"}, + } + return MCPServerConnection(MCPServerConfig.from_dict(entry)) + + +MODES = [ + ("json", "stateful"), + ("sse", "stateful"), + ("json", "stateless"), + ("sse", "stateless"), +] + + +@pytest.mark.parametrize("sdk_server", MODES, indirect=True, ids=lambda m: "-".join(m)) +def test_connect_discover_and_call_against_the_sdk_server(sdk_server): + url, sessions = sdk_server + + async def scenario(): + conn = connection(url, API_KEY) + assert await conn.connect(), conn.last_error + transport = conn._transport + state = (transport.protocol_version, transport.session_id) + tools = [t.name for t in conn.tools] + result = await conn.call_tool("add", {"a": 2, "b": 3}) + await conn.disconnect() + return state, tools, result + + (version, session_id), tools, result = asyncio.run(scenario()) + assert version in ("2025-03-26", "2025-06-18", "2025-11-25") + if sessions == "stateful": + assert session_id + assert tools == ["add"] + assert result["status"] == "success" + assert result["result"] == "5" + + +@pytest.mark.parametrize( + "sdk_server", [("json", "stateful")], indirect=True, ids=["json"] +) +def test_a_wrong_key_is_refused_by_the_sdk_server(sdk_server): + url, _ = sdk_server + + async def scenario(): + conn = connection(url, None) + return await conn.connect(), conn + + ok, conn = asyncio.run(scenario()) + assert ok is False + assert "HTTP 401" in conn.last_error + assert "wrong-key" not in conn.last_error + + +def test_the_interop_python_really_has_the_sdk(): + out = subprocess.run( + [ + INTEROP_PYTHON, + "-c", + "import mcp, importlib.metadata as m; print(m.version('mcp'))", + ], + capture_output=True, + text=True, + timeout=60, + ) + assert out.returncode == 0, out.stderr + print(f"mcp SDK {out.stdout.strip()} on {sys.version.split()[0]} client") From 61709e2149a837ea519293a9181acecfc53dd160 Mon Sep 17 00:00:00 2001 From: Rohan Date: Wed, 25 Nov 2026 09:36:57 +0530 Subject: [PATCH 3/3] #185: address review: SSE framing, old configs, bundle credentials - Split SSE streams on CR, LF and CRLF only. httpx's aiter_lines also splits on U+2028, U+0085 and the other str.splitlines separators, which servers send unescaped inside JSON data. Both the Streamable HTTP transport and the legacy SSE transport use the new splitter. - Enforce the 16 MB limit while a line is being read, so an unterminated line is never held in memory in full. - Accept "headers" and "timeout" on stdio, sse and websocket entries again, as earlier versions did. They are ignored with a one-time warning and kept unchanged in the file. - Profile bundle import keeps a local entry that has saved credentials when the bundle's entry with the same name reaches a different server, and reports the name as skipped. - Clear the old Mcp-Session-Id when a renewed session comes back without one. - Never save over an MCP config file that exists but cannot be read when adding a server; report the error instead. Part of #185. --- agent_core/core/impl/mcp/config.py | 34 +++++- agent_core/core/impl/mcp/server.py | 64 ++++++++-- app/ui_layer/settings/mcp_settings.py | 31 ++++- app/ui_layer/settings/profile_bundle.py | 31 ++++- tests/test_mcp_config.py | 85 ++++++++++++-- tests/test_mcp_settings.py | 71 ++++++++++- tests/test_mcp_sse_transport.py | 35 +++++- tests/test_mcp_streamable_http.py | 149 ++++++++++++++++++++++++ 8 files changed, 466 insertions(+), 34 deletions(-) diff --git a/agent_core/core/impl/mcp/config.py b/agent_core/core/impl/mcp/config.py index dae96734..b2f172a7 100644 --- a/agent_core/core/impl/mcp/config.py +++ b/agent_core/core/impl/mcp/config.py @@ -190,6 +190,11 @@ def _validate_url(server: str, transport: str, url: Any) -> None: raise MCPConfigError(f"Server '{server}': 'url' must not have a #fragment") +# (server, transport, keys) already warned about: the config is re-read on +# every reload and settings refresh, and one warning per entry is enough. +_WARNED_IGNORED_KEYS: set = set() + + def _validate_timeout(server: str, timeout: Any) -> Optional[float]: if timeout is None: return None @@ -253,13 +258,34 @@ def __post_init__(self): if not isinstance(self.env, dict): raise MCPConfigError(f"Server '{self.name}': 'env' must be an object") + if transport != "http": + self._set_aside_http_only_fields(transport) self.headers = _validate_headers(self.name, self.headers) - if self.headers and transport != "http": - raise MCPConfigError( - f"Server '{self.name}': 'headers' are only supported by the http transport" - ) self.timeout = _validate_timeout(self.name, self.timeout) + def _set_aside_http_only_fields(self, transport: str) -> None: + """``headers`` and ``timeout`` only apply to http. Earlier versions + ignored them on the other transports, so an entry that has them + still loads: they are not applied, but kept unchanged (written back + on save, and used again if the entry is switched to http).""" + ignored: Dict[str, Any] = {} + if self.headers: + ignored["headers"] = self.headers + if self.timeout is not None: + ignored["timeout"] = self.timeout + self.headers = {} + self.timeout = None + if not ignored: + return + self.extra = {**self.extra, **ignored} + warned = (self.name, transport, tuple(ignored)) + if warned not in _WARNED_IGNORED_KEYS: + _WARNED_IGNORED_KEYS.add(warned) + logger.warning( + f"MCP server '{self.name}': {' and '.join(ignored)} only apply " + f"to the http transport; ignored for {transport}" + ) + @property def resolved_action_set_name(self) -> str: """Get the action set name, defaulting to mcp_{name} if not specified.""" diff --git a/agent_core/core/impl/mcp/server.py b/agent_core/core/impl/mcp/server.py index 552e2da7..170fa3d5 100644 --- a/agent_core/core/impl/mcp/server.py +++ b/agent_core/core/impl/mcp/server.py @@ -12,6 +12,7 @@ import asyncio import json import os +import re import shutil import sys from abc import ABC, abstractmethod @@ -587,7 +588,7 @@ async def _listen_sse(self) -> None: data_lines: List[str] = [] try: async with self._client.stream("GET", self.url) as response: - async for line in response.aiter_lines(): + async for line in _sse_lines(response.aiter_bytes()): if line: field_name, _, value = line.partition(":") value = value[1:] if value.startswith(" ") else value @@ -849,6 +850,45 @@ def _clean_server_text(text: Any, limit: int = 300) -> str: return text if len(text) <= limit else text[: limit - 3] + "..." +_SSE_LINE_END_RE = re.compile(rb"\r\n|\r|\n") +_MAX_SSE_LINE_BYTES = 16 * 1024 * 1024 + + +async def _sse_lines(chunks, max_line_bytes: int = _MAX_SSE_LINE_BYTES): + """The lines of an SSE byte stream, split on CR, LF or CRLF only, as SSE + requires. (httpx's ``aiter_lines`` also splits on U+2028, U+0085 and the + other ``str.splitlines`` separators, which servers send unescaped inside + JSON data.) A line longer than ``max_line_bytes`` raises as soon as it + passes the limit, so it is never held in memory in full.""" + buffer = bytearray() + skip_lf = False # the previous chunk ended in CR: a leading LF ends nothing + async for chunk in chunks: + if not chunk: + continue + start = 0 + if skip_lf: + skip_lf = False + if chunk[:1] == b"\n": + start = 1 + for match in _SSE_LINE_END_RE.finditer(chunk, start): + buffer += chunk[start : match.start()] + if len(buffer) > max_line_bytes: + raise _HTTPTransportError( + "stream event exceeds the 16 MB message limit" + ) + if match.group() == b"\r" and match.end() == len(chunk): + skip_lf = True + # Splitting bytes on CR/LF never cuts a UTF-8 sequence. + yield buffer.decode("utf-8", errors="replace") + buffer = bytearray() + start = match.end() + buffer += chunk[start:] + if len(buffer) > max_line_bytes: + raise _HTTPTransportError("stream event exceeds the 16 MB message limit") + if buffer: + yield buffer.decode("utf-8", errors="replace") + + class StreamableHTTPTransport(MCPTransport): """Streamable HTTP transport (MCP 2025-03-26 and later). @@ -1152,6 +1192,10 @@ async def _post( def _capture_session_id(self, response) -> None: session_id = response.headers.get("mcp-session-id") if session_id is None: + # A successful initialize without an id starts a session without + # one (e.g. the server restarted stateless): stop sending the old. + if 200 <= response.status_code < 300: + self._session_id = None return if not session_id or any(not 0x21 <= ord(c) <= 0x7E for c in session_id): raise _HTTPTransportError( @@ -1350,7 +1394,8 @@ async def _consume_events( self, stream, request: Dict[str, Any] ) -> "_StreamOutcome": outcome = _StreamOutcome() - lines = stream.aiter_lines() + chunks = stream.aiter_bytes() + lines = _sse_lines(chunks, self.MAX_MESSAGE_BYTES) messages = self._sse_messages(lines, outcome) cancelled = False try: @@ -1368,13 +1413,16 @@ async def _consume_events( cancelled = True raise finally: - await messages.aclose() # our parser: no I/O, closes at its yield - # Whatever ended the loop (the response, an oversized event), - # read on to the end of this same stream instead of abandoning - # httpx's generators mid-iteration (see _drain). A finished - # stream makes this a no-op; a cancellation already unwound it. + # Our parser and line splitter: no I/O, they close at their yield. + await messages.aclose() + await lines.aclose() + # Whatever ended the loop (the response, an oversized line or + # event), read on to the end of this same stream instead of + # abandoning httpx's generator mid-iteration (see _drain). A + # finished stream makes this a no-op; a cancellation already + # unwound it. if not cancelled: - await self._drain(lines) + await self._drain(chunks) return outcome async def _sse_messages(self, lines, outcome: "_StreamOutcome"): diff --git a/app/ui_layer/settings/mcp_settings.py b/app/ui_layer/settings/mcp_settings.py index 9ccee97c..c0b46682 100644 --- a/app/ui_layer/settings/mcp_settings.py +++ b/app/ui_layer/settings/mcp_settings.py @@ -49,6 +49,27 @@ def load_mcp_config() -> MCPConfig: return MCPConfig() +def _load_for_update() -> Tuple[Optional[MCPConfig], str]: + """The config to change and save back, or why it cannot be changed. + + ``load_mcp_config`` falls back to an empty config when the file cannot + be read; saving that would replace every server in the file (and its + credentials) with just the change. So a file that exists but cannot be + read is never written: the user is told to fix it first.""" + try: + return MCPConfig.load(MCP_CONFIG_PATH), "" + except Exception as e: # noqa: BLE001 - reported; nothing is saved + logger.error(f"Failed to load MCP config: {e}") + if isinstance(e, json.JSONDecodeError): + reason = f"invalid JSON at line {e.lineno}, column {e.colno}" + else: + reason = type(e).__name__ + return None, ( + f"Could not read {MCP_CONFIG_PATH.name} ({reason}). Fix the file " + "first; nothing was saved." + ) + + def save_mcp_config(config: MCPConfig) -> bool: """Save MCP configuration to file.""" try: @@ -210,7 +231,9 @@ def add_mcp_server( def _add_entry(data: Dict[str, Any]) -> Tuple[bool, str]: - config = load_mcp_config() + config, error = _load_for_update() + if config is None: + return False, error name = data.get("name") if isinstance(name, str) and ( config.get_server_by_name(name) or config.get_invalid_entries(name) @@ -330,6 +353,12 @@ def set_mcp_server_header( server = config.get_server_by_name(name) if not server: return False, f"Server '{name}' not found" + if server.transport != "http": + return ( + False, + f"Server '{name}' uses {server.transport}: headers are only " + "supported by the http transport", + ) headers = {k: v for k, v in server.headers.items() if k.lower() != header.lower()} if value is not None: headers[header] = value diff --git a/app/ui_layer/settings/profile_bundle.py b/app/ui_layer/settings/profile_bundle.py index 5d80549a..d43d71b4 100644 --- a/app/ui_layer/settings/profile_bundle.py +++ b/app/ui_layer/settings/profile_bundle.py @@ -173,6 +173,18 @@ def _mcp_needs_config(server: Dict[str, Any]) -> Optional[Dict[str, Any]]: return result +def _has_local_credentials(server: Dict[str, Any]) -> bool: + """Whether an entry holds values the user filled in: a non-empty env + value or a literal (non-template) header value.""" + env = server.get("env") or {} + if isinstance(env, dict) and any(v for v in env.values()): + return True + headers = server.get("headers") or {} + return isinstance(headers, dict) and any( + v and not _header_is_template(v) for v in headers.values() + ) + + def _same_mcp_target(a: Dict[str, Any], b: Dict[str, Any]) -> bool: """Whether two entries reach the same server: same transport and the same command+args or URL. Local credentials are only ever carried over @@ -771,7 +783,10 @@ def _apply_mcp( """Install MCP server configs from the bundle. ``replace`` — bundle overwrites local on name collision (preserving any - env tokens the user already filled in); new servers added. + env tokens the user already filled in); new servers added. If the + bundle's entry reaches a different server and the local one has saved + credentials, the local entry is kept and the name reported in + ``skipped``. ``overwrite`` — local mcp_config.json is wiped and replaced entirely with the bundle's servers; no env values are preserved (the recipient's MCP state ends up exactly = bundle's). @@ -854,11 +869,19 @@ def _filter_valid(servers: List[Dict[str, Any]]) -> List[Dict[str, Any]]: if v and merged_headers.get(k) == "": merged_headers[k] = v server["headers"] = merged_headers - else: + elif _has_local_credentials(local): + # The bundle's entry reaches a different server (another + # url, command or args): carrying the local credentials over + # could send them there, and replacing the entry would lose + # them. Keep the local entry and report the bundle's as + # skipped. logger.warning( - f"[PROFILE_BUNDLE] MCP '{name}' points somewhere new; " - "local credentials are not carried over" + f"[PROFILE_BUNDLE] MCP '{name}' in the bundle points to a " + "different server than the local entry, which has saved " + "credentials; keeping the local entry" ) + skipped.append(name) + continue by_name[name] = server added.append(name) else: diff --git a/tests/test_mcp_config.py b/tests/test_mcp_config.py index 85c9e8b2..9cfef0d4 100644 --- a/tests/test_mcp_config.py +++ b/tests/test_mcp_config.py @@ -183,16 +183,85 @@ def test_header_errors_never_echo_the_value(): assert SECRET not in str(excinfo.value) -def test_headers_are_only_accepted_on_the_http_transport(): - with pytest.raises(MCPConfigError, match="only supported by the http"): - MCPServerConfig.from_dict( +@pytest.mark.parametrize( + "entry, kept", + [ + ( + { + "name": "a", + "transport": "stdio", + "command": "npx", + "args": ["x"], + "timeout": 60000, + }, + {"timeout": 60000}, + ), + ( { - "name": "s", + "name": "b", "transport": "sse", - "url": "http://h/sse", - "headers": {"A": "b"}, - } - ) + "url": "https://h/sse", + "headers": {"Authorization": "Bearer t"}, + }, + {"headers": {"Authorization": "Bearer t"}}, + ), + ( + { + "name": "c", + "transport": "websocket", + "url": "wss://h/ws", + "headers": {"bad name": "x"}, + "timeout": "soon", + }, + {"headers": {"bad name": "x"}, "timeout": "soon"}, + ), + ], +) +def test_http_only_keys_on_other_transports_still_load_and_are_ignored(entry, kept): + # Earlier versions ignored these keys outside http, so such entries must + # keep loading after an upgrade: not applied, not validated, kept as-is. + config = MCPConfig.from_dict({"mcp_servers": [entry]}) + assert config.invalid_servers == [] + (server,) = config.mcp_servers + assert server.headers == {} and server.timeout is None + saved = server.to_dict() + for key, value in kept.items(): + assert saved[key] == value + + +def test_http_only_keys_kept_on_sse_apply_again_after_switching_to_http(): + entry = { + "name": "b", + "transport": "sse", + "url": "https://h/mcp", + "headers": {"Authorization": "Bearer t"}, + "timeout": 45, + } + saved = MCPServerConfig.from_dict(entry).to_dict() + switched = MCPServerConfig.from_dict({**saved, "transport": "http"}) + assert switched.headers == {"Authorization": "Bearer t"} + assert switched.timeout == 45 + + +def test_ignoring_http_only_keys_warns_once_without_header_values(): + from loguru import logger + + entry = { + "name": "warned-once", + "transport": "sse", + "url": "https://h/sse", + "headers": {"Authorization": f"Bearer {SECRET}"}, + } + lines = [] + sink = logger.add(lambda m: lines.append(str(m)), level="WARNING") + try: + MCPServerConfig.from_dict(entry) + MCPServerConfig.from_dict(entry) # a reload: no second warning + finally: + logger.remove(sink) + warnings = [line for line in lines if "only apply to the http transport" in line] + assert len(warnings) == 1 + assert SECRET not in "".join(lines) def test_a_tab_is_allowed_in_a_header_value(): diff --git a/tests/test_mcp_settings.py b/tests/test_mcp_settings.py index 26903bf3..e51ab6d5 100644 --- a/tests/test_mcp_settings.py +++ b/tests/test_mcp_settings.py @@ -147,6 +147,7 @@ def test_header_set_and_remove(config_path): ) ok, message = mcp_settings.set_mcp_server_header("local", "X", "y") assert ok is False and "only supported by the http" in message + assert "headers" not in read(config_path)["mcp_servers"][1] ok, message = mcp_settings.set_mcp_server_header("stitch", "Bad Name", "y") assert ok is False and "invalid header name" in message assert "X-Team" not in read(config_path)["mcp_servers"][0]["headers"] @@ -299,17 +300,60 @@ def test_import_keeps_local_credentials_for_the_same_server(config_path, tmp_pat def test_import_never_hands_local_credentials_to_a_new_target(config_path, tmp_path): # A bundle reuses a local name but points it at another host and - # references the local key from a header: the key must not follow. + # references the local key from a header: the key must not follow, and + # the local entry (with the user's saved key) must not be lost either. write(config_path, [stitch()]) hostile = stitch(url="https://attacker.example.net/mcp", env={"STITCH_KEY": ""}) hostile["headers"] = {"Authorization": "${STITCH_KEY}"} - added, _, needs, _ = profile_bundle._apply_mcp( + added, skipped, needs, _ = profile_bundle._apply_mcp( write_bundle(tmp_path, [hostile]), "replace" ) + assert added == [] and skipped == ["stitch"] and needs == [] (saved,) = read(config_path)["mcp_servers"] - assert saved["url"] == "https://attacker.example.net/mcp" - assert saved["env"] == {"STITCH_KEY": ""} - assert SECRET not in json.dumps(read(config_path)) + assert saved == stitch() # the local entry, unchanged + + +def test_import_keeps_a_local_stdio_entry_whose_bundle_version_differs( + config_path, tmp_path +): + # Same name, slightly different command (a version pin): not the same + # target, so the local token must neither move nor be lost. + local = { + "name": "gh", + "command": "npx", + "args": ["-y", "gh-mcp@1"], + "env": {"TOKEN": SECRET}, + } + write(config_path, [local]) + bundled = { + "name": "gh", + "command": "npx", + "args": ["-y", "gh-mcp@2"], + "env": {"TOKEN": ""}, + } + added, skipped, _, _ = profile_bundle._apply_mcp( + write_bundle(tmp_path, [bundled]), "replace" + ) + assert added == [] and skipped == ["gh"] + assert read(config_path)["mcp_servers"] == [local] + + +def test_import_replaces_a_moved_entry_that_has_no_local_credentials( + config_path, tmp_path +): + empty = {"STITCH_KEY": ""} + write(config_path, [stitch(env=empty, headers={"X-Api-Key": "${STITCH_KEY}"})]) + moved = stitch( + url="https://new.example.com/mcp", + env=empty, + headers={"X-Api-Key": "${STITCH_KEY}"}, + ) + added, skipped, needs, _ = profile_bundle._apply_mcp( + write_bundle(tmp_path, [moved]), "replace" + ) + assert added == ["stitch"] and skipped == [] + (saved,) = read(config_path)["mcp_servers"] + assert saved["url"] == "https://new.example.com/mcp" assert needs == [{"name": "stitch", "env_keys": ["STITCH_KEY"]}] @@ -352,3 +396,20 @@ def test_list_never_sends_stdio_arguments(config_path): ) (server,) = mcp_settings.list_mcp_servers() assert OTHER_SECRET not in json.dumps(server) + + +def test_adding_a_server_never_replaces_an_unreadable_config(config_path): + # A hand-edit left a trailing comma: saving the empty fallback config + # would delete every server in the file and its credentials. + broken = ( + '{"mcp_servers": [{"name": "local", "command": "x", "env": {"K": "%s"}},]}' + % SECRET + ) + config_path.write_text(broken, encoding="utf-8") + ok, message = mcp_settings.add_mcp_server( + "new", transport="http", url="https://mcp.example.com/mcp" + ) + assert ok is False + assert "invalid JSON at line 1" in message and "nothing was saved" in message + assert SECRET not in message + assert config_path.read_text(encoding="utf-8") == broken diff --git a/tests/test_mcp_sse_transport.py b/tests/test_mcp_sse_transport.py index 694b3401..6912260f 100644 --- a/tests/test_mcp_sse_transport.py +++ b/tests/test_mcp_sse_transport.py @@ -22,6 +22,7 @@ def __init__(self, post_path, announce=None): self.announce = announce # data of the `endpoint` event; None = send none self.data_first = False # emit `data:` before `event:` in the announcement self.posts = [] # (path, method name) + self.result_text = None # tools/call answers with this text self._queue: asyncio.Queue = asyncio.Queue() async def _sse(self, request): @@ -36,9 +37,9 @@ async def _sse(self, request): msg = await self._queue.get() if msg is None: # stop() sentinel: end the stream break - await resp.write( - f"event: message\ndata: {json.dumps(msg)}\n\n".encode() - ) + # Unescaped non-ASCII, as the official SDKs write it. + data = json.dumps(msg, ensure_ascii=False) + await resp.write(f"event: message\ndata: {data}\n\n".encode()) except (asyncio.CancelledError, ConnectionResetError): pass return resp @@ -47,8 +48,11 @@ async def _post(self, request): body = await request.json() self.posts.append((request.path, body.get("method"))) if "id" in body: + result = INIT_RESULT + if body.get("method") == "tools/call" and self.result_text is not None: + result = {"content": [{"type": "text", "text": self.result_text}]} await self._queue.put( - {"jsonrpc": "2.0", "id": body["id"], "result": INIT_RESULT} + {"jsonrpc": "2.0", "id": body["id"], "result": result} ) return web.Response(status=202) @@ -148,3 +152,26 @@ def test_origin_ignores_default_port_and_hostname_case(): assert origin("http://example.com/sse") == origin("http://example.com:80/m/") assert origin("https://example.com/sse") != origin("https://example.com:8443/m/") assert origin("https://example.com/sse") != origin("http://example.com/m/") + + +def test_a_result_with_unicode_line_separators_is_received_whole(): + # Only CR and LF end an SSE line; servers write U+2028 and U+0085 + # unescaped inside a data: line. + text = "scraped\u2028web\u2029text\u0085end" + server = _MockSSEServer("/messages/", announce="/messages/?session_id=abc") + server.result_text = text + + async def run(): + url = await server.start() + transport = SSETransport(url, {}) + try: + assert await transport.connect() + return await asyncio.wait_for( + transport.send_request("tools/call", {"name": "x"}), timeout=10 + ) + finally: + await transport.disconnect() + await server.stop() + + result = asyncio.run(run()) + assert result["result"]["content"][0]["text"] == text diff --git a/tests/test_mcp_streamable_http.py b/tests/test_mcp_streamable_http.py index cdc72505..54cc3629 100644 --- a/tests/test_mcp_streamable_http.py +++ b/tests/test_mcp_streamable_http.py @@ -24,6 +24,8 @@ from agent_core.core.impl.mcp.server import ( MCPServerConnection, StreamableHTTPTransport, + _HTTPTransportError, + _sse_lines, ) from tests.mcp_http_mock import serve @@ -737,3 +739,150 @@ async def scenario(): assert "HTTP 401" in connection.last_error assert SECRET not in connection.last_error assert not connection.is_connected + + +# ── SSE framing: CR/LF/CRLF only, bounded lines ── + + +async def _chunks(*parts: bytes): + for part in parts: + yield part + + +def _lines(chunks, limit: int = 1024) -> List[str]: + async def collect(): + return [line async for line in _sse_lines(chunks, limit)] + + return run(collect()) + + +def test_sse_lines_split_only_on_cr_lf_and_crlf(): + # str.splitlines() would also split on every one of these. + text = "a\u2028b\u2029c\u0085d\x0be\x0cf\x1cg\x1dh\x1ei" + lines = _lines(_chunks(f"data: {text}\r\n".encode(), b"x\ry\n", b"\n")) + assert lines == [f"data: {text}", "x", "y", ""] + + +def test_sse_lines_handle_line_ends_and_characters_split_across_chunks(): + lines = _lines( + _chunks(b"one\r", b"\ntwo\r", b"three\n", b"\xe2\x80", b"\xa8four\n", b"tail") + ) + assert lines == ["one", "two", "three", "\u2028four", "tail"] + + +def test_sse_lines_refuse_an_endless_line_without_buffering_it(): + pulled = 0 + + async def endless(): + nonlocal pulled + while True: + pulled += 1 + yield b"x" * 1000 + + with pytest.raises(_HTTPTransportError, match="16 MB message limit"): + _lines(endless(), limit=10_000) + assert pulled <= 11 # stopped just past the limit, not at the end + + +def test_a_result_with_unicode_line_separators_survives_an_sse_response(): + text = "scraped\u2028web\u2029text\u0085end" + + def handler(request): + body = json.loads(request.content) if request.content else {} + response = { + "jsonrpc": "2.0", + "id": body.get("id"), + "result": {"content": [{"type": "text", "text": text}]}, + } + event = ( + "event: message\ndata: " + json.dumps(response, ensure_ascii=False) + "\n\n" + ) + return init_ok(request) or httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=event.encode() + ) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + result = await transport.send_request("tools/call", {"name": "x"}) + await transport.disconnect() + return result + + assert run(scenario())["result"]["content"][0]["text"] == text + + +def test_an_sse_line_that_never_ends_is_refused_at_the_message_limit(monkeypatch): + monkeypatch.setattr(StreamableHTTPTransport, "MAX_MESSAGE_BYTES", 4096) + + async def body(): + yield b"event: message\ndata: " + for _ in range(64): + yield b"a" * 1024 + + def handler(request): + return init_ok(request) or httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=body() + ) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + result = await transport.send_request("tools/list", {}) + await transport.disconnect() + return result + + assert "16 MB message limit" in run(scenario())["error"]["message"] + + +# ── Session renewal: a new session without an id ── + + +def test_a_renewed_session_without_an_id_stops_sending_the_old_one(): + # The server restarts stateless: the old session gets 404, the new + # initialize returns no Mcp-Session-Id, so nothing may carry the old id. + seen = [] + state = {"inits": 0, "restarted": False} + + def handler(request): + body = json.loads(request.content) if request.content else {} + method = body.get("method", request.method) + sid = request.headers.get("mcp-session-id") + seen.append((method, sid)) + if request.method == "DELETE": + return httpx.Response(405) + if method == "initialize": + state["inits"] += 1 + headers = {"mcp-session-id": "s1"} if state["inits"] == 1 else {} + return httpx.Response( + 200, + headers=headers, + json={ + "jsonrpc": "2.0", + "id": body["id"], + "result": {"protocolVersion": "2025-06-18", "capabilities": {}}, + }, + ) + if state["restarted"] and sid == "s1": + return httpx.Response(404) + if "id" not in body: + return httpx.Response(202) + return httpx.Response( + 200, json={"jsonrpc": "2.0", "id": body["id"], "result": {"tools": []}} + ) + + async def scenario(): + transport = mock_transport(handler) + assert await transport.connect() + assert transport.session_id == "s1" + state["restarted"] = True + first = await transport.send_request("tools/list", {}) + second = await transport.send_request("tools/list", {}) + status = (transport.session_id, transport.is_connected) + await transport.disconnect() + return first, second, status + + first, second, (session_id, connected) = run(scenario()) + assert "result" in first and "result" in second + assert session_id is None and connected + renewal = seen.index(("initialize", None), 1) + assert all(sid is None for _, sid in seen[renewal:])