Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(mcp): support mcp 2.x Python SDK, unpin mcp<2.0.0 (#2216)
chenshiyang6c60853f4237
diff --git a/pyproject.toml b/pyproject.tomlindex 3aa83dbcf..51704ace9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -26,8 +26,9 @@ dependencies = ["filetype","json5","json_repair[schema]>=0.63.4",- "mcp<2.0.0",+ "mcp>=2.0.0","httpx",+ "httpx2>=2.5.0","numpy","openai","python-datauri",diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.pyindex d8f48adf4..61158b69e 100644--- a/src/agentscope/mcp/_mcp_client.py+++ b/src/agentscope/mcp/_mcp_client.py@@ -10,7 +10,7 @@ from contextlib import (from typing import Any, AsyncGenerator, ClassVar, TYPE_CHECKINGfrom urllib.parse import urlsplit-import httpx+import httpx2import mcp.typesfrom mcp import ClientSession, stdio_client, StdioServerParametersfrom mcp.client.sse import sse_client@@ -78,7 +78,7 @@ class MCPClient(BaseModel):"""- # httpx derives these from the request URL and body with setdefault,+ # httpx2 derives these from the request URL and body with setdefault,# so a client-level value silently wins and breaks routing or framing.# The headers MCP itself sends are set per request and need no guard._RESERVED_HEADERS: ClassVar[frozenset[str]] = frozenset(@@ -128,8 +128,8 @@ class MCPClient(BaseModel):_stack: AsyncExitStack | None = PrivateAttr(default=None)_is_connected: bool = PrivateAttr(default=False)_cached_tools: list[mcp.types.Tool] | None = PrivateAttr(default=None)- _http_client: httpx.AsyncClient | None = PrivateAttr(default=None)- _static_headers: httpx.Headers | None = PrivateAttr(default=None)+ _http_client: httpx2.AsyncClient | None = PrivateAttr(default=None)+ _static_headers: httpx2.Headers | None = PrivateAttr(default=None)_runtime_headers: dict[str, str] = PrivateAttr(default_factory=dict)@property@@ -238,13 +238,13 @@ class MCPClient(BaseModel):client = create_mcp_http_client(headers=config.headers,timeout=(- httpx.Timeout(config.timeout)+ httpx2.Timeout(config.timeout)if config.timeout is not Noneelse None),)# Snapshot before overlaying: clearing runtime headers restores it.- self._static_headers = httpx.Headers(client.headers)+ self._static_headers = httpx2.Headers(client.headers)client.headers.update(self._runtime_headers)self._http_client = client@@ -276,7 +276,7 @@ class MCPClient(BaseModel):Streamable HTTP session, whose headers are fixed when the streamis established. Headers MCP sends itself (``mcp-session-id``,``content-type``, ...) are set per request and always win over- the ones set here; the few httpx derives from the URL and body+ the ones set here; the few httpx2 derives from the URL and bodyare rejected outright.Args:@@ -295,7 +295,7 @@ class MCPClient(BaseModel):if not isinstance(headers, dict):raise ValueError("Runtime headers must be a dict.")- # httpx accepts illegal names and CRLF in values, and only h11+ # httpx2 accepts illegal names and CRLF in values, and only h11# rejects them mid-request, so validate before storing.for name, value in headers.items():if (@@ -312,7 +312,7 @@ class MCPClient(BaseModel):self._runtime_headers = dict(headers)if self._http_client is not None:- merged = httpx.Headers(self._static_headers)+ merged = httpx2.Headers(self._static_headers)merged.update(self._runtime_headers)self._http_client.headers = mergeddiff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex d62aa6bd8..a199a81f0 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -4,7 +4,6 @@ import inspectimport jsonimport refrom contextlib import AbstractAsyncContextManager-from datetime import timedeltafrom typing import Callable, Any, AsyncGenerator, Generatorfrom mcp import ClientSession@@ -253,11 +252,11 @@ class MCPTool(ToolBase):self.description = tool.description or ""- # Preserve the full inputSchema (including $defs, anyOf, oneOf, etc.)- # rather than only copying "properties" and "required", which would- # silently drop any nested type definitions that the LLM needs to- # resolve $ref pointers.- _schema = dict(tool.inputSchema) if tool.inputSchema else {}+ # Preserve the full input_schema (including $defs, anyOf, oneOf,+ # etc.) rather than only copying "properties" and "required",+ # which would silently drop any nested type definitions that the+ # LLM needs to resolve $ref pointers.+ _schema = dict(tool.input_schema) if tool.input_schema else {}_schema.setdefault("type", "object")_schema.setdefault("properties", {})_schema.setdefault("required", [])@@ -269,8 +268,8 @@ class MCPTool(ToolBase):# Extract is_read_only from MCP tool annotationsself.is_read_only = False- if tool.annotations and hasattr(tool.annotations, "readOnlyHint"):- self.is_read_only = tool.annotations.readOnlyHint or False+ if tool.annotations:+ self.is_read_only = tool.annotations.read_only_hint or False# Store MCP tool and connection infoself._tool = tool@@ -278,7 +277,7 @@ class MCPTool(ToolBase):self._session = sessionif timeout:- self._timeout = timedelta(seconds=timeout)+ self._timeout = float(timeout)else:self._timeout = None@@ -350,7 +349,7 @@ class MCPTool(ToolBase):return ToolChunk(content=self._convert_mcp_content_to_blocks(result.content),state=ToolResultState.ERROR- if result.isError+ if result.is_errorelse ToolResultState.RUNNING,)@@ -380,7 +379,7 @@ class MCPTool(ToolBase):DataBlock(source=Base64Source(type="base64",- media_type=content.mimeType,+ media_type=content.mime_type,data=content.data,),),@@ -407,7 +406,7 @@ class MCPTool(ToolBase):as_content.append(DataBlock(source=URLSource(- media_type=content.mimeType,+ media_type=content.mime_type,url=content.uri,),),diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex 2cd949e9f..9d6ded572 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -340,7 +340,7 @@ class Toolkit:f"but got {type(res)}.",)- except mcp.shared.exceptions.McpError as e:+ except mcp.shared.exceptions.MCPError as e:chunk = ToolChunk(content=[TextBlock(diff --git a/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.py b/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.pyindex fb218425b..469ea4442 100644--- a/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.py+++ b/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.py@@ -502,7 +502,7 @@ class AppleContainerWorkspace(SandboxedWorkspaceBase):``--no-deps`` on agentscope is mandatory: the gateway onlyimports :class:`agentscope.mcp.MCPClient` whose transitive- needs (``mcp / pydantic / httpx``) are already installed via+ needs (``mcp / pydantic / httpx / httpx2``) are installed viathe gateway base requirements."""pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(self.extra_pip)diff --git a/src/agentscope/workspace/_e2b/_e2b_workspace.py b/src/agentscope/workspace/_e2b/_e2b_workspace.pyindex 40b21007b..d601f8237 100644--- a/src/agentscope/workspace/_e2b/_e2b_workspace.py+++ b/src/agentscope/workspace/_e2b/_e2b_workspace.py@@ -333,7 +333,7 @@ class E2BWorkspace(SandboxedWorkspaceBase):``--no-deps`` on agentscope is mandatory: the gateway onlyimports :class:`agentscope.mcp.MCPClient` whose transitive- needs (``mcp / pydantic / httpx``) are already installed via+ needs (``mcp / pydantic / httpx / httpx2``) are installed viathe gateway base requirements. Pulling the full dep treedrags in heavy / Rust-built packages the E2B image cannotcompile.diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.pyindex c9b4945df..f08980ff8 100644--- a/src/agentscope/workspace/_gateway_client.py+++ b/src/agentscope/workspace/_gateway_client.py@@ -85,8 +85,8 @@ class GatewayMCPTool(ToolBase):``mcp__{mcp}__{tool}`` name and the URL path.tool (`mcp.types.Tool`):Raw upstream tool descriptor as returned by the gateway.- ``inputSchema`` is forwarded verbatim;- ``annotations.readOnlyHint`` drives the permission+ ``input_schema`` is forwarded verbatim;+ ``annotations.read_only_hint`` drives the permissionpolicy.gateway (`GatewayClient`):Facade dispatching every call through@@ -102,7 +102,7 @@ class GatewayMCPTool(ToolBase):self.name = f"mcp__{mcp_name}__{tool.name}"self.description = tool.description or ""- schema = dict(tool.inputSchema) if tool.inputSchema else {}+ schema = dict(tool.input_schema) if tool.input_schema else {}schema.setdefault("type", "object")schema.setdefault("properties", {})schema.setdefault("required", [])@@ -112,8 +112,8 @@ class GatewayMCPTool(ToolBase):self.is_external_tool = Falseself.is_read_only = False- if tool.annotations and hasattr(tool.annotations, "readOnlyHint"):- self.is_read_only = tool.annotations.readOnlyHint or False+ if tool.annotations:+ self.is_read_only = tool.annotations.read_only_hint or Falseself._tool = toolself._gateway = gatewaydiff --git a/src/agentscope/workspace/_utils.py b/src/agentscope/workspace/_utils.pyindex 52de302dc..28a99054d 100644--- a/src/agentscope/workspace/_utils.py+++ b/src/agentscope/workspace/_utils.py@@ -100,15 +100,17 @@ DEFAULT_GLOB_HELPER_SCRIPT = "_glob_helper.py"#: same tuple into the gateway venv before adding ``agentscope`` itself.#:#: ``agentscope`` goes in with ``--no-deps``, so anything it imports has-#: to be named here — depending on another package to drag it along is-#: what broke when ``mcp`` 2.0 swapped ``httpx`` for ``httpx2``. The-#: bound on ``mcp`` mirrors ``pyproject.toml``, so the gateway speaks-#: the same protocol version as the process driving it.+#: to be named here. The current MCP client imports ``httpx2``, while+#: released versions installed by DockerWorkspace can still import+#: ``httpx``. Keep both explicit during the transition.+#: The version on ``mcp`` mirrors ``pyproject.toml``, so the gateway+#: speaks the same protocol version as the process driving it._GATEWAY_BASE_REQUIREMENTS: tuple[str, ...] = (- "mcp<2.0.0",+ "mcp>=2.0.0","uvicorn","fastapi","httpx",+ "httpx2>=2.5.0",)diff --git a/tests/docker/k8s_workspace_test.Dockerfile b/tests/docker/k8s_workspace_test.Dockerfileindex 2d283a775..86a1be4f9 100644--- a/tests/docker/k8s_workspace_test.Dockerfile+++ b/tests/docker/k8s_workspace_test.Dockerfile@@ -37,11 +37,11 @@ RUN curl -LsSf https://astral.sh/uv/install.sh \ENV GATEWAY_HOME=/root/.agentscope# Gateway venv + base runtime requirements-# (mirrors ``_GATEWAY_BASE_REQUIREMENTS`` in _sandboxed_base.py)+# (mirrors ``_GATEWAY_BASE_REQUIREMENTS`` in _utils.py)RUN mkdir -p "${GATEWAY_HOME}" \&& uv venv "${GATEWAY_HOME}/.venv" \&& uv pip install --python "${GATEWAY_HOME}/.venv/bin/python" \- 'mcp<2.0.0' uvicorn fastapi httpx+ 'mcp>=2.0.0' uvicorn fastapi httpx 'httpx2>=2.5.0'# Install agentscope itself from the local checkout.# Build context is repo root, so pyproject.toml + src/ are visible at /src.diff --git a/tests/mcp_runtime_headers_test.py b/tests/mcp_runtime_headers_test.pyindex 2bd2d61ad..b355208b3 100644--- a/tests/mcp_runtime_headers_test.py+++ b/tests/mcp_runtime_headers_test.py@@ -7,7 +7,6 @@ from typing import Any, AsyncGeneratorfrom unittest.async_case import IsolatedAsyncioTestCasefrom unittest.mock import AsyncMock, patch-import httpxfrom fastapi.testclient import TestClientfrom mcp.client.streamable_http import create_mcp_http_client@@ -32,7 +31,7 @@ class MCPRuntimeHeadersTest(IsolatedAsyncioTestCase):async def fake_transport(url: str,*,- http_client: httpx.AsyncClient,+ http_client: Any,) -> AsyncGenerator[tuple[object, object, object], None]:self.seen.update(url=url, http_client=http_client)yield object(), object(), object()diff --git a/tests/mcp_sse_client_test.py b/tests/mcp_sse_client_test.pyindex 326255279..cf82bca7c 100644--- a/tests/mcp_sse_client_test.py+++ b/tests/mcp_sse_client_test.py@@ -5,7 +5,8 @@ import jsonfrom multiprocessing import Processfrom unittest.async_case import IsolatedAsyncioTestCase-from mcp.server import FastMCP+from mcp.server import MCPServer+from mcp.types import ToolAnnotationsfrom pydantic import BaseModelfrom agentscope.mcp import MCPClient, HttpMCPConfig@@ -28,9 +29,12 @@ async def tool_1(arg1: str, arg2: list[int]) -> str:def setup_server() -> None:"""Set up the streamable HTTP MCP server."""- sse_server = FastMCP("SSE", port=8003)- sse_server.tool(description="A test tool function.")(tool_1)- sse_server.run(transport="sse")+ sse_server = MCPServer("SSE")+ sse_server.tool(+ description="A test tool function.",+ annotations=ToolAnnotations(read_only_hint=True),+ )(tool_1)+ sse_server.run(transport="sse", port=8003)# ---------------------------------------------------------------------------@@ -58,9 +62,9 @@ async def tool_with_model(name: str, config: _ItemConfig) -> str:def setup_defs_server() -> None:"""Set up an SSE MCP server that exposes a tool with Pydanticsub-models."""- server = FastMCP("DefsSSE", port=8005)+ server = MCPServer("DefsSSE")server.tool()(tool_with_model)- server.run(transport="sse")+ server.run(transport="sse", port=8005)class SseMCPClientTest(IsolatedAsyncioTestCase):@@ -123,6 +127,7 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):)mcp_tool_1 = await stateless_client.get_tool("tool_1")+ self.assertTrue(mcp_tool_1.is_read_only)# Repeat to ensure idempotencyres_1: ToolChunk = await mcp_tool_1(arg1="123", arg2=[1, 2, 3])res_2: ToolChunk = await mcp_tool_1(arg1="345", arg2=[4, 5, 6])@@ -313,8 +318,8 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):class SseSchemaDefsPreservationTest(IsolatedAsyncioTestCase):"""End-to-end tests for $defs preservation in MCP tool schemas.- These tests start a real FastMCP server that exposes a tool whose- parameter is a Pydantic sub-model. FastMCP generates an inputSchema with+ These tests start a real MCPServer that exposes a tool whose parameter is+ a Pydantic sub-model. MCPServer generates an inputSchema with``$defs`` for the sub-model. We verify that the schema returned by``await toolkit.get_tool_schemas()`` preserves those ``$defs`` and thatPydantic-generated ``title`` fields inside ``$defs`` are stripped.@@ -332,7 +337,7 @@ class SseSchemaDefsPreservationTest(IsolatedAsyncioTestCase):"type": "function","function": {"name": "mcp__test_defs_client__tool_with_model",- # FastMCP forwards the tool's ``__doc__`` verbatim;+ # MCPServer forwards the tool's ``__doc__`` verbatim;# deriving the expectation from it keeps the test# correct under Python 3.13+, where the compiler# strips common leading whitespace from docstrings.diff --git a/tests/mcp_streamable_http_client_test.py b/tests/mcp_streamable_http_client_test.pyindex 49a25a4fc..ef2bdd62f 100644--- a/tests/mcp_streamable_http_client_test.py+++ b/tests/mcp_streamable_http_client_test.py@@ -4,7 +4,7 @@ import asynciofrom multiprocessing import Processfrom unittest.async_case import IsolatedAsyncioTestCase-from mcp.server import FastMCP+from mcp.server import MCPServerfrom mcp.types import EmbeddedResource, TextResourceContentsfrom agentscope.mcp import MCPClient, HttpMCPConfig@@ -32,7 +32,7 @@ async def tool_2() -> list:type="resource",resource=TextResourceContents(uri="file://tmp.txt",- mimeType="text/plain",+ mime_type="text/plain",text="test content",),),@@ -41,12 +41,12 @@ async def tool_2() -> list:def setup_server() -> None:"""Set up the streamable HTTP MCP server."""- sse_server = FastMCP("StreamableHTTP", port=8002)- sse_server.tool(description="A test tool function.")(tool_1)- sse_server.tool(+ server = MCPServer("StreamableHTTP")+ server.tool(description="A test tool function.")(tool_1)+ server.tool(description="A test tool function with embedded resource.",)(tool_2)- sse_server.run(transport="streamable-http")+ server.run(transport="streamable-http", port=8002)class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):@@ -139,8 +139,8 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):self.assertEqual(res.content[0].text,"""{- "uri": "file://tmp.txt/",- "mimeType": "text/plain",+ "uri": "file://tmp.txt",+ "mime_type": "text/plain","meta": null,"text": "test content"}""",diff --git a/tests/workspace_applecontainer_test.py b/tests/workspace_applecontainer_test.pyindex 0ed716497..8749b2837 100644--- a/tests/workspace_applecontainer_test.py+++ b/tests/workspace_applecontainer_test.py@@ -299,9 +299,9 @@ _GATEWAY_PYTHON = f"{GATEWAY_HOME}/{DEFAULT_GATEWAY_VENV}/bin/python"_ECHO_MCP_SERVER_SCRIPT = '''\# -*- coding: utf-8 -*-"""Minimal echo MCP server for live-test verification."""-from mcp.server.fastmcp import FastMCP+from mcp.server import MCPServer-mcp = FastMCP("EchoServer")+mcp = MCPServer("EchoServer")@mcp.tool()diff --git a/tests/workspace_bubblewrap_test.py b/tests/workspace_bubblewrap_test.pyindex 71bf54703..b304f04c2 100644--- a/tests/workspace_bubblewrap_test.py+++ b/tests/workspace_bubblewrap_test.py@@ -18,10 +18,11 @@ import unittestimport uuidfrom typing import Anyfrom unittest.async_case import IsolatedAsyncioTestCase-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport aiofilesfrom fastapi.testclient import TestClient+from mcp.types import Tool, ToolAnnotationsfrom agentscope.app.workspace_manager import BubblewrapWorkspaceManagerfrom agentscope.mcp import MCPClient, StdioMCPConfig@@ -32,7 +33,7 @@ from agentscope.workspace._bubblewrap._constants import (BWRAP_SMOKE_PROBE_ARGV,SANDBOX_WORKDIR,)-from agentscope.workspace._gateway_client import GatewayClient+from agentscope.workspace._gateway_client import GatewayClient, GatewayMCPToolfrom agentscope.workspace._mcp_gateway._mcp_gateway_app import (_State,_build_app,@@ -707,6 +708,24 @@ class TestBubblewrapWorkspaceCache(IsolatedAsyncioTestCase):self.assertFalse(os.path.exists(workdir))+class TestGatewayMCPTool(unittest.TestCase):+ """Tests for gateway-backed MCP tools."""++ def test_preserves_read_only_hint(self) -> None:+ """Gateway tools preserve MCP 2.x read-only annotations."""+ tool = GatewayMCPTool(+ mcp_name="gateway",+ tool=Tool(+ name="read_data",+ input_schema={"type": "object"},+ annotations=ToolAnnotations(read_only_hint=True),+ ),+ gateway=MagicMock(spec=GatewayClient),+ )++ self.assertTrue(tool.is_read_only)++class TestGatewayAuth(unittest.TestCase):"""Pure FastAPI tests for optional gateway authentication."""@@ -1018,9 +1037,8 @@ class TestBubblewrapWorkspace(IsolatedAsyncioTestCase):is_stateful=True,mcp_config=StdioMCPConfig(command="uvx",- # Constrained because the client is pinned to mcp<2:- # unpinned, uvx now resolves an mcp 2.x server, whose- # handshake this client cannot complete.+ # mcp-server-time currently requires MCP 1.x and runs+ # in an isolated uvx environment.args=["--with", "mcp<2.0.0", "mcp-server-time"],),)diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.pyindex a080e1c4e..3970ce616 100644--- a/tests/workspace_daytona_test.py+++ b/tests/workspace_daytona_test.py@@ -1330,10 +1330,10 @@ class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):def _mcp_server_script() -> bytes:- """Minimal FastMCP stdio server used by live reattach tests."""- return b"""from mcp.server import FastMCP+ """Minimal MCPServer stdio server used by live reattach tests."""+ return b"""from mcp.server import MCPServer-mcp = FastMCP("Persist")+mcp = MCPServer("Persist")@mcp.tool()diff --git a/tests/workspace_k8s_test.py b/tests/workspace_k8s_test.pyindex fad5ade31..c4a08aa1a 100644--- a/tests/workspace_k8s_test.py+++ b/tests/workspace_k8s_test.py@@ -194,9 +194,8 @@ class TestK8sWorkspaceHappyPath(IsolatedAsyncioTestCase):is_stateful=True,mcp_config=StdioMCPConfig(command="uvx",- # Constrained because the client is pinned to mcp<2:- # unpinned, uvx now resolves an mcp 2.x server, whose- # handshake this client cannot complete.+ # mcp-server-time currently requires MCP 1.x and runs+ # in an isolated uvx environment.args=["--with", "mcp<2.0.0", "mcp-server-time"],),)