Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

feat(mcp)!: port MCP servers to SDK 2.x (#4603)

Kenneth Wongee2252a3155c
diff --git a/headroom/ccr/mcp_server.py b/headroom/ccr/mcp_server.py
index 37589df19..13c44d347 100644
--- a/headroom/ccr/mcp_server.py
+++ b/headroom/ccr/mcp_server.py
@@ -25,6 +25,7 @@ from __future__ import annotations
import argparse
import asyncio
import contextlib
+import contextvars
import errno
import json
import logging
@@ -56,11 +57,12 @@ try:
except ImportError:
_HAS_FCNTL = False
-# Try to import MCP SDK
+# Try to import MCP SDK (2.x: handlers are constructor callbacks, results are
+# typed ``*Result`` models rather than bare lists).
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
- from mcp.types import TextContent, Tool
+ from mcp.types import CallToolResult, ListToolsResult, TextContent, Tool
MCP_AVAILABLE = True
except ImportError:
@@ -97,6 +99,14 @@ _READ_ENABLED = os.environ.get("HEADROOM_MCP_READ", "off").lower().strip() in (
DEFAULT_PROXY_URL = os.environ.get("HEADROOM_PROXY_URL", "http://127.0.0.1:8787")
+# MCP 2.x removed ``Server.request_context``; the per-request context is now only
+# handed to the handler as an argument. ``_current_client()`` needs it three frames
+# below the handler, so we stash it here instead of threading it through every
+# ``_handle_*`` signature. A ContextVar rather than an instance attribute because
+# concurrent tool calls on one server would race on ``self`` — this is the same
+# mechanism 1.x used internally to back ``request_context``.
+_request_ctx: contextvars.ContextVar[Any] = contextvars.ContextVar("headroom_mcp_request_ctx")
+
# How often the parent-death watchdog polls os.getppid() (seconds). When the
# launching MCP client is SIGKILLed, stdin EOF may never arrive and the SDK's
# blocking stdin-reader thread wedges server.run() forever, orphaning this
@@ -479,8 +489,14 @@ class HeadroomMCPServer:
if not MCP_AVAILABLE or Server is None:
raise ImportError("MCP SDK not installed. Install with: pip install mcp")
- self.server: Server = Server("headroom")
- self._setup_handlers()
+ # MCP 2.x registers handlers as constructor callbacks. Bound methods are
+ # resolved at call time, so passing them here does not require the rest of
+ # ``__init__`` to have run.
+ self.server: Server = Server(
+ "headroom",
+ on_list_tools=self._on_list_tools,
+ on_call_tool=self._on_call_tool,
+ )
def _get_local_store(self) -> Any:
"""Get the shared compression store singleton (lazy init).
@@ -740,150 +756,159 @@ class HeadroomMCPServer:
)
return None
- def _setup_handlers(self) -> None:
- """Register all MCP tool handlers."""
+ async def _on_list_tools(self, ctx: Any, params: Any = None) -> ListToolsResult:
+ """MCP ``tools/list`` handler."""
+ tools = [
+ Tool(
+ name=COMPRESS_TOOL_NAME,
+ description=(
+ "Compress content to save context window space. "
+ "Use this on large tool outputs, file contents, search results, "
+ "or any content you want to shrink before reasoning over it. "
+ f"The original is stored and can be retrieved later via mcp__headroom__{CCR_TOOL_NAME}. "
+ "Returns compressed text + a hash for retrieval."
+ ),
+ input_schema={
+ "type": "object",
+ "properties": {
+ "content": {
+ "type": "string",
+ "description": (
+ "The content to compress. Can be any text: file contents, "
+ "JSON, search results, logs, code, etc."
+ ),
+ },
+ },
+ "required": ["content"],
+ },
+ ),
+ Tool(
+ name=CCR_TOOL_NAME,
+ description=(
+ "Retrieve original uncompressed content by hash. "
+ "Use this when you need full details from previously compressed content. "
+ "The hash comes from headroom_compress results or from compression "
+ "markers like [N items compressed... hash=abc123]."
+ ),
+ input_schema={
+ "type": "object",
+ "properties": {
+ "hash": {
+ "type": "string",
+ "description": "Hash key from compression (e.g., 'abc123' from hash=abc123)",
+ },
+ },
+ "required": ["hash"],
+ },
+ ),
+ Tool(
+ name=STATS_TOOL_NAME,
+ description=(
+ "Show compression statistics for this session: "
+ "total compressions, tokens saved, estimated cost savings, "
+ "and recent compression events."
+ ),
+ input_schema={
+ "type": "object",
+ "properties": {},
+ "required": [],
+ },
+ ),
+ ]
- @self.server.list_tools()
- async def list_tools() -> list[Tool]:
- tools = [
+ # Conditionally add headroom_read (behind feature flag)
+ if _READ_ENABLED:
+ tools.append(
Tool(
- name=COMPRESS_TOOL_NAME,
+ name=READ_TOOL_NAME,
description=(
- "Compress content to save context window space. "
- "Use this on large tool outputs, file contents, search results, "
- "or any content you want to shrink before reasoning over it. "
- f"The original is stored and can be retrieved later via mcp__headroom__{CCR_TOOL_NAME}. "
- "Returns compressed text + a hash for retrieval."
+ "Read a file with smart caching. First read returns full content "
+ "and caches it. Subsequent reads of the same unchanged file return "
+ "a lightweight cache marker (~20 tokens instead of thousands). "
+ f"Use mcp__headroom__{CCR_TOOL_NAME} with the hash to get full content if needed. "
+ "Use this INSTEAD of the built-in Read tool for significant token savings."
),
- inputSchema={
+ input_schema={
"type": "object",
"properties": {
- "content": {
+ "file_path": {
"type": "string",
"description": (
- "The content to compress. Can be any text: file contents, "
- "JSON, search results, logs, code, etc."
+ "Path to the file to read, inside the workspace "
+ "(the server's working directory or HEADROOM_MCP_READ_ROOTS)."
),
},
- },
- "required": ["content"],
- },
- ),
- Tool(
- name=CCR_TOOL_NAME,
- description=(
- "Retrieve original uncompressed content by hash. "
- "Use this when you need full details from previously compressed content. "
- "The hash comes from headroom_compress results or from compression "
- "markers like [N items compressed... hash=abc123]."
- ),
- inputSchema={
- "type": "object",
- "properties": {
- "hash": {
- "type": "string",
- "description": "Hash key from compression (e.g., 'abc123' from hash=abc123)",
+ "fresh": {
+ "type": "boolean",
+ "description": (
+ "Force a fresh read, bypassing cache. Use after context "
+ "compaction, in subagents, or when you need guaranteed "
+ "current content."
+ ),
},
},
- "required": ["hash"],
+ "required": ["file_path"],
},
- ),
- Tool(
- name=STATS_TOOL_NAME,
- description=(
- "Show compression statistics for this session: "
- "total compressions, tokens saved, estimated cost savings, "
- "and recent compression events."
- ),
- inputSchema={
- "type": "object",
- "properties": {},
- "required": [],
- },
- ),
- ]
-
- # Conditionally add headroom_read (behind feature flag)
- if _READ_ENABLED:
- tools.append(
- Tool(
- name=READ_TOOL_NAME,
- description=(
- "Read a file with smart caching. First read returns full content "
- "and caches it. Subsequent reads of the same unchanged file return "
- "a lightweight cache marker (~20 tokens instead of thousands). "
- f"Use mcp__headroom__{CCR_TOOL_NAME} with the hash to get full content if needed. "
- "Use this INSTEAD of the built-in Read tool for significant token savings."
- ),
- inputSchema={
- "type": "object",
- "properties": {
- "file_path": {
- "type": "string",
- "description": (
- "Path to the file to read, inside the workspace "
- "(the server's working directory or HEADROOM_MCP_READ_ROOTS)."
- ),
- },
- "fresh": {
- "type": "boolean",
- "description": (
- "Force a fresh read, bypassing cache. Use after context "
- "compaction, in subagents, or when you need guaranteed "
- "current content."
- ),
- },
- },
- "required": ["file_path"],
- },
- )
)
+ )
- return tools
+ return ListToolsResult(tools=tools)
- @self.server.call_tool()
- async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
- started = time.perf_counter()
+ async def _on_call_tool(self, ctx: Any, params: Any) -> CallToolResult:
+ """MCP ``tools/call`` handler."""
+ name = params.name
+ # 2.x types ``arguments`` as optional; the ``_handle_*`` helpers all call
+ # ``.get()`` on it, so normalise before dispatching.
+ arguments: dict[str, Any] = params.arguments or {}
+ started = time.perf_counter()
+ logger.info(
+ "event=mcp_tool_call_received tool=%s arguments=%s",
+ name,
+ json.dumps(arguments, ensure_ascii=False, default=str),
+ )
+ token = _request_ctx.set(ctx)
+ try:
+ if name == COMPRESS_TOOL_NAME:
+ result = await self._handle_compress(arguments)
+ elif name == CCR_TOOL_NAME:
+ result = await self._handle_retrieve(arguments)
+ elif name == STATS_TOOL_NAME:
+ result = await self._handle_stats()
+ elif name == READ_TOOL_NAME and _READ_ENABLED:
+ result = await self._handle_read(arguments)
+ else:
+ result = [
+ TextContent(
+ type="text",
+ text=json.dumps({"error": f"Unknown tool: {name}"}),
+ )
+ ]
logger.info(
- "event=mcp_tool_call_received tool=%s arguments=%s",
+ "event=mcp_tool_call_completed tool=%s duration_ms=%.2f output=%s",
name,
- json.dumps(arguments, ensure_ascii=False, default=str),
+ (time.perf_counter() - started) * 1000.0,
+ json.dumps(
+ [getattr(item, "text", str(item)) for item in result],
+ ensure_ascii=False,
+ default=str,
+ ),
)
- try:
- if name == COMPRESS_TOOL_NAME:
- result = await self._handle_compress(arguments)
- elif name == CCR_TOOL_NAME:
- result = await self._handle_retrieve(arguments)
- elif name == STATS_TOOL_NAME:
- result = await self._handle_stats()
- elif name == READ_TOOL_NAME and _READ_ENABLED:
- result = await self._handle_read(arguments)
- else:
- result = [
- TextContent(
- type="text",
- text=json.dumps({"error": f"Unknown tool: {name}"}),
- )
- ]
- logger.info(
- "event=mcp_tool_call_completed tool=%s duration_ms=%.2f output=%s",
- name,
- (time.perf_counter() - started) * 1000.0,
- json.dumps(
- [getattr(item, "text", str(item)) for item in result],
- ensure_ascii=False,
- default=str,
- ),
- )
- return result
- except Exception as e:
- logger.error(f"Tool {name} failed: {e}", exc_info=True)
- return [
+ # ponytail: is_error left unset, matching 1.x behaviour where the SDK
+ # wrapped a returned list as a success. Flagging error payloads as
+ # is_error=True is a behaviour change — separate PR, not this port.
+ return CallToolResult(content=list(result))
+ except Exception as e:
+ logger.error(f"Tool {name} failed: {e}", exc_info=True)
+ return CallToolResult(
+ content=[
TextContent(
type="text",
text=json.dumps({"error": str(e)}),
)
]
+ )
+ finally:
+ _request_ctx.reset(token)
async def _handle_compress(self, arguments: dict[str, Any]) -> list[TextContent]:
"""Handle headroom_compress tool call."""
@@ -949,8 +974,14 @@ class HeadroomMCPServer:
if override:
return override
try:
- params = self.server.request_context.session.client_params
- info = getattr(params, "clientInfo", None) if params else None
+ ctx = _request_ctx.get(None)
+ if ctx is None:
+ return "unknown"
+ params = ctx.session.client_params
+ # SDK 2 types are snake_case (`client_info`); SDK 1 exposed `clientInfo`.
+ # Both handshakes fill `client_params`: `initialize`, and the
+ # `_meta` client info that `server/discover` clients send per request.
+ info = getattr(params, "client_info", None) if params else None
name = getattr(info, "name", None)
if name:
return str(name)
diff --git a/headroom/memory/mcp_server.py b/headroom/memory/mcp_server.py
index 3720b3e4f..c863b87e2 100644
--- a/headroom/memory/mcp_server.py
+++ b/headroom/memory/mcp_server.py
@@ -36,7 +36,7 @@ from typing import Any
from mcp.server import Server
from mcp.server.stdio import stdio_server
-from mcp.types import TextContent, Tool
+from mcp.types import CallToolResult, ListToolsResult, TextContent, Tool
from headroom.memory.backends.local import LocalBackend, LocalBackendConfig
@@ -55,7 +55,7 @@ _TOOLS = [
"project context, user preferences, org info, codenames, debugging history, "
"or anything that might have been discussed before."
),
- inputSchema={
+ input_schema={
"type": "object",
"properties": {
"query": {
@@ -86,7 +86,7 @@ _TOOLS = [
"Good: facts: ['Repo owner is Tejas C.', 'User prefers dark mode']\n"
"Bad: facts: ['Repo owner is Tejas C. Prefers dark mode.']"
),
- inputSchema={
+ input_schema={
"type": "object",
"properties": {
"facts": {
@@ -159,7 +159,8 @@ async def _warm_up_backend(backend: LocalBackend, user_id: str) -> None:
def create_memory_server(db_path: str, user_id: str = "default") -> Server:
"""Create an MCP server backed by headroom's local memory."""
- server = Server("headroom-memory")
+ # MCP 2.x takes handlers as constructor callbacks, so the ``Server`` is built
+ # at the end of this factory once the handler closures below exist.
_backend: LocalBackend | None = None
_init_task: asyncio.Task[LocalBackend] | None = None
_close_lock = asyncio.Lock()
@@ -246,24 +247,33 @@ def create_memory_server(db_path: str, user_id: str = "default") -> Server:
except Exception as cleanup_error:
logger.warning("Memory MCP: failed backend cleanup: %s", cleanup_error)
- @server.list_tools()
- async def list_tools() -> list[Tool]:
+ async def on_list_tools(ctx: Any, params: Any = None) -> ListToolsResult:
# Kick off background init on first list_tools (called at MCP handshake)
if _backend is None:
_start_backend_init()
- return _TOOLS
+ return ListToolsResult(tools=list(_TOOLS))
- @server.call_tool()
- async def call_tool(name: str, arguments: dict) -> list[TextContent]:
+ async def on_call_tool(ctx: Any, params: Any) -> CallToolResult:
+ name = params.name
+ # 2.x types ``arguments`` as optional; the handlers below index into it.
+ arguments: dict[str, Any] = params.arguments or {}
backend = await _get_backend()
+ content: list[TextContent]
if name == "memory_search":
- return await _handle_search(backend, arguments, user_id)
+ content = await _handle_search(backend, arguments, user_id)
elif name == "memory_save":
- return await _handle_save(backend, arguments, user_id)
+ content = await _handle_save(backend, arguments, user_id)
+ else:
+ content = [TextContent(type="text", text=f"Unknown tool: {name}")]
- return [TextContent(type="text", text=f"Unknown tool: {name}")]
+ return CallToolResult(content=list(content))
+ server = Server(
+ "headroom-memory",
+ on_list_tools=on_list_tools,
+ on_call_tool=on_call_tool,
+ )
server._headroom_close = _close_backend # type: ignore[attr-defined]
return server
diff --git a/pyproject.toml b/pyproject.toml
index dcabe1655..3cf3ba4f1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -108,9 +108,9 @@ proxy = [
"orjson>=3.9.14; platform_python_implementation != 'PyPy'",
"httpx[http2]>=0.24.0",
"openai>=2.14.0", # OpenAI API format support
- # The server still uses the v1 low-level Server decorator API. Keep this
- # cap until the SDK 2.x port lands (GH #2658 / regression GH #2977).
- "mcp>=1.30.0,<2.0.0", # MCP server (headroom_compress, retrieve, stats)
+ # SDK 2 constructor-callback API (GH #2658). 2.2.0 fixes CVE-2026-59951
+ # and CVE-2026-116684/116685/116686, which affect 2.0.0-2.1.x.
+ "mcp>=2.2.0,<3.0.0", # MCP server (headroom_compress, retrieve, stats)
"magika>=0.6.0; python_version<'3.14' or sys_platform != 'darwin' or platform_machine != 'x86_64'", # ML detection needs ORT wheels
"zstandard>=0.20.0", # Decompress zstd request bodies (Codex, etc.)
"websockets>=13.0", # WebSocket proxy for /v1/responses (Codex gpt-5.4+)
@@ -277,7 +277,7 @@ autogen = [
]
# MCP server for Claude Code integration
mcp = [
- "mcp>=1.30.0,<2.0.0",
+ "mcp>=2.2.0,<3.0.0",
"httpx>=0.24.0",
"starlette>=0.27.0",
"uvicorn>=0.23.0,<1.0",
diff --git a/tests/_mcp_stub.py b/tests/_mcp_stub.py
index e788feefb..60ae8a2e7 100644
--- a/tests/_mcp_stub.py
+++ b/tests/_mcp_stub.py
@@ -19,14 +19,17 @@ def _build_mcp_sdk_stub() -> dict[str, ModuleType]:
mcp_types_module = type(sys)("mcp.types")
class DummyServer:
- def __init__(self, name: str) -> None:
- self.name = name
+ """Mirrors the MCP 2.x surface: handlers arrive as constructor callbacks.
- def list_tools(self):
- return lambda fn: fn
+ Deliberately does NOT expose ``list_tools()`` / ``call_tool()`` decorators.
+ Those were the 1.x API, and a stub that keeps accepting them lets a caller
+ still on decorators pass its tests while the real SDK rejects it — which is
+ how the 2.0.0 startup crash reached users with a green suite.
+ """
- def call_tool(self):
- return lambda fn: fn
+ def __init__(self, name: str, **handlers) -> None:
+ self.name = name
+ self.handlers = handlers
def create_initialization_options(self):
return {}
@@ -39,6 +42,16 @@ def _build_mcp_sdk_stub() -> dict[str, ModuleType]:
def __init__(self, **kwargs) -> None:
self.kwargs = kwargs
+ class DummyListToolsResult:
+ def __init__(self, tools=None, **kwargs) -> None:
+ self.tools = list(tools or [])
+ self.kwargs = kwargs
+
+ class DummyCallToolResult:
+ def __init__(self, content=None, **kwargs) -> None:
+ self.content = list(content or [])
+ self.kwargs = kwargs
+
async def dummy_stdio_server():
raise RuntimeError("stdio_server should not run in unit tests")
@@ -46,6 +59,8 @@ def _build_mcp_sdk_stub() -> dict[str, ModuleType]:
mcp_stdio_module.stdio_server = dummy_stdio_server
mcp_types_module.TextContent = DummyTextContent
mcp_types_module.Tool = DummyTool
+ mcp_types_module.ListToolsResult = DummyListToolsResult
+ mcp_types_module.CallToolResult = DummyCallToolResult
return {
"mcp": mcp_module,
diff --git a/tests/test_ccr_mcp_http.py b/tests/test_ccr_mcp_http.py
index d7b49fa5f..7d428213b 100644
--- a/tests/test_ccr_mcp_http.py
+++ b/tests/test_ccr_mcp_http.py
@@ -2,11 +2,12 @@
from __future__ import annotations
-import httpx
import pytest
pytest.importorskip("mcp")
+# MCP SDK 2 clients take an httpx2 client (a dependency of the SDK itself).
+import httpx2
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
@@ -28,24 +29,32 @@ async def test_streamable_http_initialize_and_list_tools() -> None:
server = create_ccr_mcp_server()
session_manager = create_streamable_http_session_manager(server)
app = create_streamable_http_app(session_manager, path="/mcp")
- transport = httpx.ASGITransport(app=app)
+ transport = httpx2.ASGITransport(app=app)
+ # SDK 2's client no longer yields a session-id getter; read the header instead.
+ session_ids: list[str] = []
+
+ async def record_session_id(response: httpx2.Response) -> None:
+ if session_id := response.headers.get("mcp-session-id"):
+ session_ids.append(session_id)
async with session_manager.run():
- async with httpx.AsyncClient(
- transport=transport, base_url="http://testserver"
+ async with httpx2.AsyncClient(
+ transport=transport,
+ base_url="http://testserver",
+ event_hooks={"response": [record_session_id]},
) as http_client:
async with streamable_http_client(
"http://testserver/mcp",
http_client=http_client,
terminate_on_close=False,
- ) as (read_stream, write_stream, get_session_id):
+ ) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
initialize_result = await session.initialize()
list_tools_result = await session.list_tools()
tool_names = [tool.name for tool in list_tools_result.tools]
- assert initialize_result.protocolVersion
- assert get_session_id() is not None
+ assert initialize_result.protocol_version
+ assert session_ids
assert "headroom_compress" in tool_names
assert "headroom_retrieve" in tool_names
assert "headroom_stats" in tool_names
diff --git a/tests/test_mcp_dependency_contract.py b/tests/test_mcp_dependency_contract.py
index 27ed0ce36..e28b6dc43 100644
--- a/tests/test_mcp_dependency_contract.py
+++ b/tests/test_mcp_dependency_contract.py
@@ -16,18 +16,23 @@ def _mcp_requirement(dependencies: list[str]) -> Requirement:
return matches[0]
-def test_all_shipping_mcp_extras_exclude_incompatible_sdk_v2() -> None:
- """SDK 2 removed Server.list_tools()/call_tool(); #2658 owns that port."""
+def test_all_shipping_mcp_extras_require_the_ported_sdk_v2() -> None:
+ """The shipped servers use SDK 2 constructor callbacks, not SDK 1 decorators."""
project = tomllib.loads((ROOT / "pyproject.toml").read_text())["project"]
optional = project["optional-dependencies"]
for extra in ("proxy", "mcp"):
requirement = _mcp_requirement(optional[extra])
- assert requirement.specifier.contains("1.30.0")
- # CVE-2026-59951: Streamable HTTP sessions never reclaimed before 1.30.0.
- assert not requirement.specifier.contains("1.29.1"), (
- f"the {extra!r} extra admits an MCP SDK affected by CVE-2026-59951"
+ assert requirement.specifier.contains("2.2.0"), (
+ f"the {extra!r} extra must admit the SDK used by the ported servers"
)
- assert not requirement.specifier.contains("2.0.0"), (
- f"the {extra!r} extra admits MCP SDK 2.x before the server port in #2658"
+ assert not requirement.specifier.contains("1.30.0"), (
+ f"the {extra!r} extra admits SDK 1 without the required constructor callbacks"
+ )
+ # CVE-2026-59951 and CVE-2026-116684/116685/116686 affect 2.0.0-2.1.x.
+ assert not requirement.specifier.contains("2.1.1"), (
+ f"the {extra!r} extra admits an MCP SDK 2.x release before the 2.2.0 security fixes"
+ )
+ assert not requirement.specifier.contains("3.0.0"), (
+ f"the {extra!r} extra admits an untested MCP SDK major version (see #2977)"
)
diff --git a/tests/test_mcp_sdk2_contract.py b/tests/test_mcp_sdk2_contract.py
new file mode 100644
index 000000000..6fcadcfdd
--- /dev/null
+++ b/tests/test_mcp_sdk2_contract.py
@@ -0,0 +1,112 @@
+"""Contract tests against the REAL MCP SDK (no stub).
+
+Every other MCP test in this suite goes through ``tests/_mcp_stub.py``, which
+replaces the SDK in ``sys.modules``. That is fast and dependency-free, but it
+means a breaking change in the real SDK is invisible: the ``mcp`` 2.0.0 release
+removed the ``Server.list_tools()``/``call_tool()`` decorators and every stubbed
+test stayed green while ``headroom mcp serve`` crashed on startup for anyone who
+installed it (#2642).
+
+These tests import the SDK for real so that class of breakage fails here first.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+# ``mcp`` is an optional extra; skip rather than fail where it isn't installed.
+mcp_types = pytest.importorskip("mcp.types", reason="mcp SDK not installed")
+mcp_server = pytest.importorskip("mcp.server", reason="mcp SDK not installed")
+
+from headroom.ccr.mcp_server import ( # noqa: E402 - must follow importorskip
+ CCR_TOOL_NAME,
+ COMPRESS_TOOL_NAME,
+ STATS_TOOL_NAME,
+ HeadroomMCPServer,
+ _request_ctx,
+)
+
+
+def _server() -> HeadroomMCPServer:
+ return HeadroomMCPServer(proxy_url="http://127.0.0.1:8787")
+
+
+def _client_ctx(name: str) -> SimpleNamespace:
+ """Stand-in for ``ServerRequestContext`` carrying the SDK's real client params.
+
+ ``client_params`` is the SDK's own ``InitializeRequestParams``, not a stand-in:
+ a hand-made object with SDK 1's ``clientInfo`` name kept this test green while
+ every SDK 2 client was recorded as "unknown".
+ """
+ params = mcp_types.InitializeRequestParams(
+ protocol_version="2025-06-18",
+ capabilities=mcp_types.ClientCapabilities(),
+ client_info=mcp_types.Implementation(name=name, version="1.0"),
+ )
+ return SimpleNamespace(session=SimpleNamespace(client_params=params))
+
+
+def test_sdk_registers_handlers_via_constructor_not_decorators() -> None:
+ """The canary: 2.x dropped the decorator surface headroom used to rely on.
+
+ If a future SDK reintroduces or re-removes either shape, this fails loudly
+ instead of surfacing as a startup crash in front of a user.
+ """
+ assert not hasattr(mcp_server.Server, "list_tools")
+ assert not hasattr(mcp_server.Server, "call_tool")
+ # ``request_context`` moved to a per-call handler argument.
+ assert not hasattr(mcp_server.Server, "request_context")
+
+
+def test_server_constructs_and_advertises_tools_capability() -> None:
+ srv = _server()
+ opts = srv.server.create_initialization_options()
+ assert opts.capabilities.tools is not None
+
+
+def test_list_tools_returns_typed_result() -> None:
+ result = asyncio.run(_server()._on_list_tools(None, None))
+ assert isinstance(result, mcp_types.ListToolsResult)
+ names = {t.name for t in result.tools}
+ assert {COMPRESS_TOOL_NAME, CCR_TOOL_NAME, STATS_TOOL_NAME} <= names
+
+
+def test_call_tool_returns_typed_result_and_dispatches_on_params_name() -> None:
+ params = mcp_types.CallToolRequestParams(name="nope", arguments={})
+ result = asyncio.run(_server()._on_call_tool(None, params))
+ assert isinstance(result, mcp_types.CallToolResult)
+ assert "Unknown tool: nope" in result.content[0].text
+
+
+def test_call_tool_tolerates_omitted_arguments() -> None:
+ """2.x types ``arguments`` as optional; the ``_handle_*`` helpers call ``.get()``."""
+ params = mcp_types.CallToolRequestParams(name="nope")
+ result = asyncio.run(_server()._on_call_tool(None, params))
+ assert isinstance(result, mcp_types.CallToolResult)
+
+
+def test_current_client_resolves_from_request_context() -> None:
+ """Replaces the removed ``Server.request_context`` lookup.
+
+ ``_current_client`` swallows all exceptions and returns "unknown", so a broken
+ port degrades silently into mis-attributed savings rather than crashing. Assert
+ the name actually resolves, not merely that the call survives.
+ """
+ srv = _server()
+ token = _request_ctx.set(_client_ctx("claude-code"))
+ try:
+ assert srv._current_client() == "claude-code"
+ finally:
+ _request_ctx.reset(token)
+ assert srv._current_client() == "unknown"
+
+
+def test_request_context_does_not_leak_between_calls() -> None:
+ """A ContextVar left set would mis-attribute the next call's client."""
+ srv = _server()
+ params = mcp_types.CallToolRequestParams(name="nope", arguments={})
+ asyncio.run(srv._on_call_tool(_client_ctx("claude-code"), params))
+ assert _request_ctx.get(None) is None
diff --git a/tests/test_mcp_stub.py b/tests/test_mcp_stub.py
index b3b1a72f4..d8f5e3a8c 100644
--- a/tests/test_mcp_stub.py
+++ b/tests/test_mcp_stub.py
@@ -12,19 +12,35 @@ from tests import _mcp_stub as mcp_stub
def test_build_mcp_sdk_stub_exposes_minimum_sdk_contract() -> None:
modules = mcp_stub._build_mcp_sdk_stub()
- server = modules["mcp.server"].Server("headroom")
- assert server.name == "headroom"
+ # MCP 2.x: handlers are constructor callbacks, not decorators.
+ async def on_list_tools(ctx, params=None): # pragma: no cover - identity only
+ return None
+
+ async def on_call_tool(ctx, params): # pragma: no cover - identity only
+ return None
- sentinel = object()
- assert server.list_tools()(sentinel) is sentinel
- assert server.call_tool()(sentinel) is sentinel
+ server = modules["mcp.server"].Server(
+ "headroom", on_list_tools=on_list_tools, on_call_tool=on_call_tool
+ )
+ assert server.name == "headroom"
+ assert server.handlers == {"on_list_tools": on_list_tools, "on_call_tool": on_call_tool}
assert server.create_initialization_options() == {}
+ # The 1.x decorator surface must be gone: keeping it would let a caller still
+ # on decorators pass its tests while the real 2.x SDK rejects it.
+ assert not hasattr(server, "list_tools")
+ assert not hasattr(server, "call_tool")
+
tool = modules["mcp.types"].Tool(name="search")
text = modules["mcp.types"].TextContent(text="payload")
assert tool.kwargs == {"name": "search"}
assert text.kwargs == {"text": "payload"}
+ tools_result = modules["mcp.types"].ListToolsResult(tools=[tool])
+ call_result = modules["mcp.types"].CallToolResult(content=[text])
+ assert tools_result.tools == [tool]
+ assert call_result.content == [text]
+
with pytest.raises(RuntimeError, match="should not run"):
asyncio.run(modules["mcp.server.stdio"].stdio_server())
diff --git a/tests/test_memory/test_mcp_server.py b/tests/test_memory/test_mcp_server.py
index b55f28218..d09eb6bd4 100644
--- a/tests/test_memory/test_mcp_server.py
+++ b/tests/test_memory/test_mcp_server.py
@@ -11,24 +11,20 @@ mcp_server_mod = import_module_with_mcp_stub("headroom.memory.mcp_server")
class _CapturingServer:
- def __init__(self, name: str) -> None:
- self.name = name
- self.list_tools_handler = None
- self.call_tool_handler = None
+ """MCP 2.x takes handlers as constructor callbacks rather than decorators."""
- def list_tools(self):
- def decorator(handler):
- self.list_tools_handler = handler
- return handler
+ def __init__(self, name: str, on_list_tools=None, on_call_tool=None, **_: object) -> None:
+ self.name = name
+ self.list_tools_handler = on_list_tools
+ self.call_tool_handler = on_call_tool
- return decorator
- def call_tool(self):
- def decorator(handler):
- self.call_tool_handler = handler
- return handler
+class _CallParams:
+ """Stand-in for ``mcp.types.CallToolRequestParams``."""
- return decorator
+ def __init__(self, name: str, arguments: dict | None = None) -> None:
+ self.name = name
+ self.arguments = arguments
def test_warm_up_backend_batches_embedding_and_indexing() -> None:
@@ -102,11 +98,11 @@ def test_tool_call_waits_for_handshake_warm_up(monkeypatch) -> None:
monkeypatch.setattr(mcp_server_mod, "_handle_search", handle_search)
server = mcp_server_mod.create_memory_server("memory.db", user_id="alice")
- await server.list_tools_handler()
+ await server.list_tools_handler(None, None)
await warm_up_started.wait()
tool_call = asyncio.create_task(
- server.call_tool_handler("memory_search", {"query": "preferences"})
+ server.call_tool_handler(None, _CallParams("memory_search", {"query": "preferences"}))
)
await asyncio.sleep(0)
@@ -114,7 +110,7 @@ def test_tool_call_waits_for_handshake_warm_up(monkeypatch) -> None:
assert not tool_call.done()
release_warm_up.set()
- assert await tool_call == ["search result"]
+ assert (await tool_call).content == ["search result"]
handle_search.assert_awaited_once_with(
backend,
{"query": "preferences"},
@@ -151,7 +147,7 @@ def test_failed_handshake_init_is_discarded_and_retried(monkeypatch) -> None:
monkeypatch.setattr(mcp_server_mod, "_handle_search", handle_search)
server = mcp_server_mod.create_memory_server("memory.db", user_id="alice")
- await server.list_tools_handler()
+ await server.list_tools_handler(None, None)
await first_warm_up_started.wait()
fail_first_warm_up.set()
@@ -161,9 +157,10 @@ def test_failed_handshake_init_is_discarded_and_retried(monkeypatch) -> None:
failed_backend.close.assert_awaited_once()
handle_search.assert_not_awaited()
- assert await server.call_tool_handler("memory_search", {"query": "preferences"}) == [
- "search result"
- ]
+ result = await server.call_tool_handler(
+ None, _CallParams("memory_search", {"query": "preferences"})
+ )
+ assert result.content == ["search result"]
handle_search.assert_awaited_once_with(
ready_backend,
{"query": "preferences"},
@@ -201,7 +198,9 @@ def test_concurrent_tool_calls_share_backend_initialization(monkeypatch) -> None
server = mcp_server_mod.create_memory_server("memory.db", user_id="alice")
calls = [
asyncio.create_task(
- server.call_tool_handler("memory_search", {"query": f"query-{index}"})
+ server.call_tool_handler(
+ None, _CallParams("memory_search", {"query": f"query-{index}"})
+ )
)
for index in range(2)
]
@@ -212,7 +211,10 @@ def test_concurrent_tool_calls_share_backend_initialization(monkeypatch) -> None
handle_search.assert_not_awaited()
release_warm_up.set()
- assert await asyncio.gather(*calls) == [["search result"], ["search result"]]
+ assert [r.content for r in await asyncio.gather(*calls)] == [
+ ["search result"],
+ ["search result"],
+ ]
assert handle_search.await_count == 2
assert all(call.args[0] is backend for call in handle_search.await_args_list)
@@ -227,7 +229,7 @@ def test_server_cleanup_closes_initialized_backend_once(monkeypatch) -> None:
monkeypatch.setattr(mcp_server_mod, "_warm_up_backend", AsyncMock())
server = mcp_server_mod.create_memory_server("memory.db", user_id="alice")
- await server.list_tools_handler()
+ await server.list_tools_handler(None, None)
await asyncio.sleep(0)
close_backend = server._headroom_close
@@ -253,7 +255,7 @@ def test_server_cleanup_cancels_pending_backend_initialization(monkeypatch) -> N
monkeypatch.setattr(mcp_server_mod, "_warm_up_backend", warm_up)
server = mcp_server_mod.create_memory_server("memory.db", user_id="alice")
- await server.list_tools_handler()
+ await server.list_tools_handler(None, None)
await init_started.wait()
await server._headroom_close()
diff --git a/uv.lock b/uv.lock
index 87ebcd148..9acdca548 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1749,8 +1749,8 @@ requires-dist = [
{ name = "litellm", specifier = ">=1.96.2,<2.0" },
{ name = "litellm", marker = "extra == 'dev'", specifier = ">=1.96.2,<2.0" },
{ name = "magika", marker = "(python_full_version < '3.14' and extra == 'proxy') or (platform_machine != 'x86_64' and extra == 'proxy') or (sys_platform != 'darwin' and extra == 'proxy')", specifier = ">=0.6.0" },
- { name = "mcp", marker = "extra == 'mcp'", specifier = ">=1.30.0,<2.0.0" },
- { name = "mcp", marker = "extra == 'proxy'", specifier = ">=1.30.0,<2.0.0" },
+ { name = "mcp", marker = "extra == 'mcp'", specifier = ">=2.2.0,<3.0.0" },
+ { name = "mcp", marker = "extra == 'proxy'", specifier = ">=2.2.0,<3.0.0" },
{ name = "mem0ai", marker = "extra == 'memory-stack'", specifier = ">=2.0.18,<3.0" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.0.0" },
{ name = "neo4j", marker = "extra == 'memory-stack'", specifier = ">=5.20.0,<7.0" },
@@ -1896,6 +1896,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
]
+[[package]]
+name = "httpcore2"
+version = "2.16.0"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "h11", marker = "sys_platform != 'emscripten'" },
+ { name = "truststore", marker = "sys_platform != 'emscripten'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" },
+]
+
[[package]]
name = "httpx"
version = "0.28.1"
@@ -1920,12 +1933,29 @@ socks = [
]
[[package]]
-name = "httpx-sse"
-version = "0.4.3"
+name = "httpx2"
+version = "2.16.0"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "anyio", marker = "sys_platform != 'emscripten'" },
+ { name = "httpcore2", marker = "sys_platform != 'emscripten'" },
+ { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" },
+ { name = "idna" },
+ { name = "truststore", marker = "sys_platform != 'emscripten'" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7b/3d/2e4bc4fd1ef9770871669adb348d612a6e4786b303a23f9935b81c48dd60/httpx2-2.16.0-py3-none-any.whl", hash = "sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a", size = 97880, upload-time = "2026-10-21T07:09:44.01Z" },
+]
+
+[[package]]
+name = "httpx2-jsfetch"
+version = "1.0"
source = { registry = "https://pypi.org/simple/" }
-sdist = { url = "https://files.pythonhosted.org/packages/0f/4c/751061ffa58615a32c31b2d82e8482be8dd4a89154f003147acee90f2be9/httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d", size = 15943, upload-time = "2025-10-10T21:48:22.271Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
]
[[package]]
@@ -1977,11 +2007,11 @@ wheels = [
[[package]]
name = "idna"
-version = "3.15"
+version = "3.20"
source = { registry = "https://pypi.org/simple/" }
-sdist = { url = "https://files.pythonhosted.org/packages/82/77/7b3966d0b9d1d31a36ddf1746926a11dface89a83409bf1483f0237aa758/idna-3.15.tar.gz", hash = "sha256:ca962446ea538f7092a95e057da437618e886f4d349216d2b1e294abfdb65fdc", size = 199245, upload-time = "2026-05-12T22:45:57.011Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/d2/23/408243171aa9aaba178d3e2559159c24c1171a641aa83b67bdd3394ead8e/idna-3.15-py3-none-any.whl", hash = "sha256:048adeaf8c2d788c40fee287673ccaa74c24ffd8dcf09ffa555a2fbb59f10ac8", size = 72340, upload-time = "2026-05-12T22:45:55.733Z" },
+ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" },
]
[[package]]
@@ -2725,15 +2755,15 @@ wheels = [
[[package]]
name = "mcp"
-version = "1.30.0"
+version = "2.3.0"
source = { registry = "https://pypi.org/simple/" }
dependencies = [
{ name = "anyio" },
- { name = "httpx" },
- { name = "httpx-sse" },
+ { name = "httpx2" },
{ name = "jsonschema" },
+ { name = "mcp-types" },
+ { name = "opentelemetry-api" },
{ name = "pydantic" },
- { name = "pydantic-settings" },
{ name = "pyjwt", extra = ["crypto"] },
{ name = "python-multipart" },
{ name = "pywin32", marker = "sys_platform == 'win32'" },
@@ -2743,9 +2773,22 @@ dependencies = [
{ name = "typing-inspection" },
{ name = "uvicorn", marker = "sys_platform != 'emscripten'" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/ba/93/0142dc84a666daf8ad51a34268f34c12fd6fda4f3810c4be2504eecc8212/mcp-1.30.0.tar.gz", hash = "sha256:445414625fce5c295faa505bb11bacece661ab6f4028d57c935db57820b7a3e4", size = 680511, upload-time = "2026-09-07T14:34:15.845Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/9d/8d/e0d339616f4810e9051d4aba6887afab289ab1f81875fe908b606cdfd0e3/mcp-2.3.0.tar.gz", hash = "sha256:8b147a50441cf059dc88c684e0aeed3687f0aa0f39c6cde7b90330effd2b34d8", size = 4171955, upload-time = "2026-10-02T22:06:56.091Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/d7/4a2878f128df729db3ca04e71bfce26405cc2e0c9ebe19c592feeb4c61b9/mcp-2.3.0-py3-none-any.whl", hash = "sha256:dd0c44c089d16453e8ae31a3877a0054d7a2314caaa81f5e0541b9b1734b2377", size = 368664, upload-time = "2026-10-02T22:06:52.119Z" },
+]
+
+[[package]]
+name = "mcp-types"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple/" }
+dependencies = [
+ { name = "pydantic" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9e/2d/7c251e34207f6c51000312fc8839111ac45cfe02023f90b44e7f1051dd8e/mcp_types-2.3.0.tar.gz", hash = "sha256:d1e46549edb35ee19a94940fcee6d1addd7e589ab7ea92dda83f5d84781fc362", size = 65898, upload-time = "2026-10-02T22:06:57.863Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/f5/f4/e58bc33317c92a0203664daaf00bf6f41166cc0149e5d6870a03f7cd004a/mcp-1.30.0-py3-none-any.whl", hash = "sha256:666edb5009503e1047c9d60346a756f94b261f05cc2625f23d41c728ffc484d0", size = 234581, upload-time = "2026-09-07T14:34:14.266Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/48/32583066b155bb5d4507e7887dc88ee23118cc4de8e2a12870c49719e2a8/mcp_types-2.3.0-py3-none-any.whl", hash = "sha256:968efdbdaedfab06adae40d378a34395f1090c5921d4be3c9cde283aaf76d91d", size = 69108, upload-time = "2026-10-02T22:06:54.099Z" },
]
[[package]]
@@ -5440,7 +5483,7 @@ wheels = [
[[package]]
name = "strands-agents"
-version = "1.62.0"
+version = "1.63.0"
source = { registry = "https://pypi.org/simple/" }
dependencies = [
{ name = "boto3" },
@@ -5457,9 +5500,9 @@ dependencies = [
{ name = "typing-extensions" },
{ name = "watchdog" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/27/4a/b129a14394b35a24ebecea48a68523ee41adc874d4ced07d47e4ccee580a/strands_agents-1.62.0.tar.gz", hash = "sha256:8732c87f9c1ceb6ef4c5c4bd6d96b4cdf1bbfde095f1537ec2ac6fddb8d5a066", size = 1831346, upload-time = "2026-10-21T18:47:51.666Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/a6/ab/74fc54111f3009fc52337afd84ee27c02df7c0b932ba471a84a8ba15a2a7/strands_agents-1.63.0.tar.gz", hash = "sha256:b6ac864ac3726b9d5566fecf09688ab12d00fd6f16379ad1c91465ae9d197bfb", size = 1929378, upload-time = "2026-10-30T19:53:37.774Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/2a/ea/47b842643804b59e32fac5116ed6aa8a07b3c1a089728f9e2be0a076fa02/strands_agents-1.62.0-py3-none-any.whl", hash = "sha256:331c94c61a5ddf2c4f06dfd877551bdd1d0bfee5ea89b76d6c546b65ea2104e1", size = 923503, upload-time = "2026-10-21T18:47:49.513Z" },
+ { url = "https://files.pythonhosted.org/packages/5f/85/37b156ba498cadd833c806c9fe0ef137433950219fe335f368438c65a3a2/strands_agents-1.63.0-py3-none-any.whl", hash = "sha256:fc0a140943855c0199a83fe5a78fc07f1e82ef7d60592538c2d52793121980f0", size = 972613, upload-time = "2026-10-30T19:53:35.714Z" },
]
[[package]]