Skip to content

Build and run agents you can see, understand and trust.

fix(mcp): support mcp 2.x Python SDK, unpin mcp<2.0.0 (#2216)

chenshiyang6c60853f4237
diff --git a/pyproject.toml b/pyproject.toml
index 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.py
index 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_CHECKING
from urllib.parse import urlsplit
-import httpx
+import httpx2
import mcp.types
from mcp import ClientSession, stdio_client, StdioServerParameters
from 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 None
else 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 stream
is 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 body
are 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 = merged
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.py
index d62aa6bd8..a199a81f0 100644
--- a/src/agentscope/tool/_adapters.py
+++ b/src/agentscope/tool/_adapters.py
@@ -4,7 +4,6 @@ import inspect
import json
import re
from contextlib import AbstractAsyncContextManager
-from datetime import timedelta
from typing import Callable, Any, AsyncGenerator, Generator
from 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 annotations
self.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 info
self._tool = tool
@@ -278,7 +277,7 @@ class MCPTool(ToolBase):
self._session = session
if 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_error
else 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.py
index 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.py
index 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 only
imports :class:`agentscope.mcp.MCPClient` whose transitive
- needs (``mcp / pydantic / httpx``) are already installed via
+ needs (``mcp / pydantic / httpx / httpx2``) are installed via
the 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.py
index 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 only
imports :class:`agentscope.mcp.MCPClient` whose transitive
- needs (``mcp / pydantic / httpx``) are already installed via
+ needs (``mcp / pydantic / httpx / httpx2``) are installed via
the gateway base requirements. Pulling the full dep tree
drags in heavy / Rust-built packages the E2B image cannot
compile.
diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.py
index 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 permission
policy.
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 = False
self.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
self._tool = tool
self._gateway = gateway
diff --git a/src/agentscope/workspace/_utils.py b/src/agentscope/workspace/_utils.py
index 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.Dockerfile
index 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.py
index 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, AsyncGenerator
from unittest.async_case import IsolatedAsyncioTestCase
from unittest.mock import AsyncMock, patch
-import httpx
from fastapi.testclient import TestClient
from 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.py
index 326255279..cf82bca7c 100644
--- a/tests/mcp_sse_client_test.py
+++ b/tests/mcp_sse_client_test.py
@@ -5,7 +5,8 @@ import json
from multiprocessing import Process
from unittest.async_case import IsolatedAsyncioTestCase
-from mcp.server import FastMCP
+from mcp.server import MCPServer
+from mcp.types import ToolAnnotations
from pydantic import BaseModel
from 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 Pydantic
sub-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 idempotency
res_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 that
Pydantic-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.py
index 49a25a4fc..ef2bdd62f 100644
--- a/tests/mcp_streamable_http_client_test.py
+++ b/tests/mcp_streamable_http_client_test.py
@@ -4,7 +4,7 @@ import asyncio
from multiprocessing import Process
from unittest.async_case import IsolatedAsyncioTestCase
-from mcp.server import FastMCP
+from mcp.server import MCPServer
from mcp.types import EmbeddedResource, TextResourceContents
from 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.py
index 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.py
index 71bf54703..b304f04c2 100644
--- a/tests/workspace_bubblewrap_test.py
+++ b/tests/workspace_bubblewrap_test.py
@@ -18,10 +18,11 @@ import unittest
import uuid
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import aiofiles
from fastapi.testclient import TestClient
+from mcp.types import Tool, ToolAnnotations
from agentscope.app.workspace_manager import BubblewrapWorkspaceManager
from 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, GatewayMCPTool
from 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.py
index 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.py
index 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"],
),
)