Skip to content

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

refactor(mcp): unify the MCP implementation into a `MCPClient` class (#1572)

DavdGaodc768cbce697
diff --git a/pyproject.toml b/pyproject.toml
index 21f12d17f..6a684413a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -28,6 +28,7 @@ dependencies = [
"json5",
"json_repair",
"mcp",
+ "httpx",
"numpy",
"openai",
"python-datauri",
diff --git a/src/agentscope/mcp/__init__.py b/src/agentscope/mcp/__init__.py
index 813bd9df1..7e0f555fa 100644
--- a/src/agentscope/mcp/__init__.py
+++ b/src/agentscope/mcp/__init__.py
@@ -2,17 +2,12 @@
"""The MCP module in AgentScope, that provides fine-grained control over
the MCP servers."""
-from ._client_base import MCPClientBase
-from ._stateful_client_base import StatefulClientBase
-from ._stdio_stateful_client import StdIOStatefulClient
-from ._http_stateless_client import HttpStatelessClient
-from ._http_stateful_client import HttpStatefulClient
+from ._config import StdioMCPConfig, HttpMCPConfig
+from ._mcp_client import MCPClient
__all__ = [
- "MCPClientBase",
- "StatefulClientBase",
- "StdIOStatefulClient",
- "HttpStatelessClient",
- "HttpStatefulClient",
+ "MCPClient",
+ "StdioMCPConfig",
+ "HttpMCPConfig",
]
diff --git a/src/agentscope/mcp/_client_base.py b/src/agentscope/mcp/_client_base.py
deleted file mode 100644
index 3005699cf..000000000
--- a/src/agentscope/mcp/_client_base.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The base class for MCP clients in AgentScope."""
-from abc import abstractmethod
-from typing import Any, TYPE_CHECKING, List
-
-import mcp
-
-if TYPE_CHECKING:
- from ..tool import MCPTool
-else:
- MCPTool = Any
-
-
-class MCPClientBase:
- """Base class for MCP clients."""
-
- def __init__(self, name: str) -> None:
- """Initialize the MCP client with a name.
-
- Args:
- name (`str`):
- The name to identify the MCP server, which should be unique
- across the MCP servers.
- """
- self.name = name
-
- @abstractmethod
- async def get_tool(
- self,
- name: str,
- ) -> MCPTool:
- """Get a tool object by its name.
-
- Args:
- name (`str`):
- The name of the tool to get.
-
- Returns:
- `MCPTool`:
- A tool object that implements ToolProtocol.
- """
-
- @abstractmethod
- async def list_tools(self) -> List[mcp.types.Tool]:
- """List the MCP tools."""
diff --git a/src/agentscope/mcp/_config.py b/src/agentscope/mcp/_config.py
new file mode 100644
index 000000000..a076d9ee0
--- /dev/null
+++ b/src/agentscope/mcp/_config.py
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 -*-
+"""The MCP configurations."""
+from pathlib import Path
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+
+class StdioMCPConfig(BaseModel):
+ """The STDIO MCP server configuration."""
+
+ type: Literal["stdio_mcp"] = "stdio_mcp"
+
+ command: str = Field(
+ title="Command",
+ description="The command to start the MCP server.",
+ )
+
+ args: list[str] | None = Field(
+ title="Args",
+ description="The command line arguments to pass to the MCP server.",
+ default=None,
+ )
+
+ env: dict[str, str] | None = Field(
+ title="Environment Variables",
+ default=None,
+ description="The environment variables to pass to the MCP server.",
+ )
+
+ cwd: str | Path | None = Field(
+ default=None,
+ title="CWD",
+ description="The working directory to use when spawning the process.",
+ )
+
+ encoding_error_handler: Literal["strict", "ignore", "replace"] = Field(
+ default="strict",
+ title="Encoding Error Handler",
+ description="The text encoding error handler.",
+ )
+
+
+class HttpMCPConfig(BaseModel):
+ """The HTTP MCP server configuration."""
+
+ type: Literal["http_mcp"] = "http_mcp"
+
+ url: str = Field(
+ title="URL",
+ description="The URL of the MCP server.",
+ )
+
+ headers: dict[str, str] | None = Field(
+ title="Headers",
+ description="The additional headers to include in the HTTP request.",
+ default=None,
+ )
+
+ timeout: float | None = Field(
+ title="Timeout",
+ description="The HTTP request timeout in seconds.",
+ default=30.0,
+ )
diff --git a/src/agentscope/mcp/_http_stateful_client.py b/src/agentscope/mcp/_http_stateful_client.py
deleted file mode 100644
index e9b6caec7..000000000
--- a/src/agentscope/mcp/_http_stateful_client.py
+++ /dev/null
@@ -1,85 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The MCP stateful HTTP client module in AgentScope."""
-from typing import Any, Literal
-
-import httpx
-from mcp.client.sse import sse_client
-from mcp.client.streamable_http import streamable_http_client
-
-from ._stateful_client_base import StatefulClientBase
-
-
-class HttpStatefulClient(StatefulClientBase):
- """The stateful sse/streamable HTTP MCP client implementation in
- AgentScope.
-
- .. tip:: The stateful client is recommended for MCP servers that need to
- maintain session states, e.g. web browsers or other interactive
- MCP servers.
-
- .. note:: The stateful client will maintain one session across multiple
- tool calls, until the client is closed by explicitly calling the
- `close()` method.
-
- .. note:: When multiple HttpStatefulClient instances are connected,
- they should be closed following the Last In First Out (LIFO) principle
- to avoid potential errors. Always close the most recently registered
- client first, then work backwards to the first one.
- For more details, please refer to this `issue
- <https://github.com/modelcontextprotocol/python-sdk/issues/577>`_.
- """
-
- def __init__(
- self,
- name: str,
- transport: Literal["streamable_http", "sse"],
- url: str,
- headers: dict[str, str] | None = None,
- timeout: float | None = None,
- **client_kwargs: Any,
- ) -> None:
- """Initialize the streamable HTTP MCP client.
-
- Args:
- name (`str`):
- The name to identify the MCP server, which should be unique
- across the MCP servers.
- transport (`Literal["streamable_http", "sse"]`):
- The transport type of MCP server. Generally, the URL of sse
- transport should end with `/sse`, while the streamable HTTP
- URL ends with `/mcp`.
- url (`str`):
- The URL to the MCP server.
- headers (`dict[str, str] | None`, optional):
- Additional headers to include in the HTTP request.
- timeout (`float`, optional):
- The timeout for the HTTP request in seconds.
- **client_kwargs (`Any`):
- The additional keyword arguments to pass to the streamable
- HTTP client.
- """
- super().__init__(name=name)
-
- assert transport in ["streamable_http", "sse"]
- self.transport = transport
-
- if self.transport == "streamable_http":
- if headers or timeout:
- client = httpx.AsyncClient(
- headers=headers,
- timeout=timeout,
- )
- else:
- client = None
- self.client = streamable_http_client(
- url=url,
- http_client=client,
- **client_kwargs,
- )
- else:
- self.client = sse_client(
- url=url,
- headers=headers,
- timeout=timeout,
- **client_kwargs,
- )
diff --git a/src/agentscope/mcp/_http_stateless_client.py b/src/agentscope/mcp/_http_stateless_client.py
deleted file mode 100644
index 6942f2771..000000000
--- a/src/agentscope/mcp/_http_stateless_client.py
+++ /dev/null
@@ -1,163 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The MCP streamable HTTP server."""
-from contextlib import _AsyncGeneratorContextManager
-from typing import Any, Literal, List, TYPE_CHECKING
-
-import httpx
-import mcp.types
-from mcp import ClientSession
-from mcp.client.sse import sse_client
-from mcp.client.streamable_http import streamable_http_client
-
-from ._client_base import MCPClientBase
-
-if TYPE_CHECKING:
- from ..tool import MCPTool
-else:
- MCPTool = Any
-
-
-class HttpStatelessClient(MCPClientBase):
- """The sse/streamable HTTP MCP client implementation in AgentScope.
-
- .. note:: Note this client is stateless, meaning it won't maintain the
- session state across multiple tool calls. Each tool call will start a
- new session and close it after the call is done.
-
- """
-
- stateful: bool = False
- """Whether the MCP server is stateful, meaning it will maintain the
- session state across multiple tool calls, or stateless, meaning it
- will start a new session for each tool call."""
-
- def __init__(
- self,
- name: str,
- transport: Literal["streamable_http", "sse"],
- url: str,
- headers: dict[str, str] | None = None,
- timeout: float = 30,
- **client_kwargs: Any,
- ) -> None:
- """Initialize the streamable HTTP MCP server.
-
- Args:
- name (`str`):
- The name to identify the MCP server, which should be unique
- across the MCP servers.
- transport (`Literal["streamable_http", "sse"]`):
- The transport type of MCP server. Generally, the URL of sse
- transport should end with `/sse`, while the streamable HTTP
- URL ends with `/mcp`.
- url (`str`):
- The URL of the MCP server.
- headers (`dict[str, str] | None`, optional):
- Additional headers to include in the HTTP request.
- timeout (`float`, optional):
- The timeout for the HTTP request in seconds. Defaults to 30.
- **client_kwargs (`Any`):
- The additional keyword arguments to pass to the streamable
- HTTP client.
- """
- super().__init__(name=name)
-
- assert transport in ["streamable_http", "sse"]
-
- self.transport = transport
-
- self.client_config = {
- "url": url,
- "headers": headers or None,
- "timeout": timeout,
- **client_kwargs,
- }
-
- self._tools = None
-
- def get_client(self) -> _AsyncGeneratorContextManager[Any]:
- """The disposable MCP client object, which is a context manager."""
- if self.transport == "sse":
- return sse_client(**self.client_config)
-
- if self.transport == "streamable_http":
- # For the newest version of mcp client, headers is not supported,
- # we should create an async client here
- if self.client_config.get("headers") or self.client_config.get(
- "timeout",
- ):
- client = httpx.AsyncClient(
- headers=self.client_config.get("headers", None),
- timeout=self.client_config.get("timeout"),
- )
- else:
- client = None
- return streamable_http_client(
- url=self.client_config["url"],
- http_client=client,
- )
-
- raise ValueError(
- f"Unsupported transport type: {self.transport}. "
- "Supported types are 'sse' and 'streamable_http'.",
- )
-
- async def get_tool(
- self,
- name: str,
- execution_timeout: float | None = None,
- ) -> MCPTool:
- """Get a tool object by its name.
-
- The returned MCPTool object implements ToolProtocol and can be:
- - Called directly: `await tool(arg1=val1)`
- - Registered to toolkit: `toolkit.register_tool(tool)`
-
- Args:
- name (`str`):
- The name of the tool function.
- execution_timeout (`float | None`, optional):
- The preset timeout in seconds for calling the tool function.
-
- Returns:
- `MCPTool`:
- A tool object that implements ToolProtocol.
- """
-
- if self._tools is None:
- await self.list_tools()
-
- target_tool = None
- for tool in self._tools:
- if tool.name == name:
- target_tool = tool
- break
-
- if target_tool is None:
- raise ValueError(
- f"Tool '{name}' not found in the MCP server ",
- )
-
- from ..tool import MCPTool
-
- return MCPTool(
- mcp_name=self.name,
- tool=target_tool,
- client_gen=self.get_client,
- timeout=execution_timeout,
- )
-
- async def list_tools(self) -> List[mcp.types.Tool]:
- """List all tools available on the MCP server.
-
- Returns:
- `mcp.types.ListToolsResult`:
- The result containing the list of tools.
- """
- async with self.get_client() as cli:
- read_stream, write_stream = cli[0], cli[1]
- async with ClientSession(read_stream, write_stream) as session:
- await session.initialize()
- res = await session.list_tools()
- self._tools = res.tools
- return res.tools
diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.py
new file mode 100644
index 000000000..d8bb0f963
--- /dev/null
+++ b/src/agentscope/mcp/_mcp_client.py
@@ -0,0 +1,347 @@
+# -*- coding: utf-8 -*-
+"""Unified MCP client implementation for AgentScope."""
+from contextlib import AsyncExitStack, _AsyncGeneratorContextManager
+from typing import Any, TYPE_CHECKING
+
+import httpx
+import mcp.types
+from mcp import ClientSession, stdio_client, StdioServerParameters
+from mcp.client.sse import sse_client
+from mcp.client.streamable_http import streamable_http_client
+from pydantic import Field, BaseModel, PrivateAttr
+
+from ._config import StdioMCPConfig, HttpMCPConfig
+from .._logging import logger
+
+if TYPE_CHECKING:
+ from ..tool import MCPTool
+else:
+ MCPTool = Any
+
+
+class MCPClient(BaseModel):
+ """The unified MCP client in AgentScope.
+
+ This class provides a unified interface for MCP connections, handling both
+ stateful (persistent) and stateless (ephemeral) connections.
+
+ - Stateful: Requires explicit connect() and close(), maintains session
+ - Stateless: No connect() needed, creates temporary session per call
+
+ Private attributes:
+ - _client: The underlying MCP client context manager
+ - _session: The MCP ClientSession (for stateful connections only)
+ - _stack: AsyncExitStack for managing connection lifecycle
+ - _is_connected: Connection state flag
+ - _cached_tools: Cached list of tools
+
+ Example:
+
+ .. code-block:: python
+
+ # Stateful connection (STDIO or HTTP)
+ client = MCPClient(
+ name="file_system",
+ is_stateful=True,
+ mcp_config=StdioMCPConfig(
+ command="mcp-server-filesystem"
+ )
+ )
+ await client.connect()
+ tools = await client.list_tools()
+ await client.close()
+
+ # Stateless connection (HTTP only)
+ client = MCPClient(
+ name="weather_search",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(
+ url="https://api.weather.com/mcp"
+ )
+ )
+ # No connect() needed
+ tools = await client.list_tools()
+
+ """
+
+ name: str = Field(
+ title="MCP Name",
+ description="The MCP name.",
+ )
+
+ is_stateful: bool = Field(
+ title="Stateful",
+ description=(
+ "Whether this is a stateful connection that requires explicit "
+ "connect() and close(). STDIO MCP must be stateful. HTTP MCP "
+ "can be either stateful or stateless."
+ ),
+ )
+
+ mcp_config: StdioMCPConfig | HttpMCPConfig = Field(
+ discriminator="type",
+ title="MCP Config",
+ description="The MCP server configuration.",
+ )
+
+ # Private attributes
+ _client: Any = PrivateAttr(default=None)
+ _session: ClientSession | None = PrivateAttr(default=None)
+ _stack: AsyncExitStack | None = PrivateAttr(default=None)
+ _is_connected: bool = PrivateAttr(default=False)
+ _cached_tools: list[mcp.types.Tool] | None = PrivateAttr(default=None)
+
+ @property
+ def is_connected(self) -> bool:
+ """Whether the client is currently connected.
+
+ Returns:
+ True if connected, False otherwise.
+ """
+ return self._is_connected
+
+ def model_post_init(self, __context: Any) -> None:
+ """Validate configuration and initialize client."""
+ # STDIO MCP must be stateful
+ if self.mcp_config.type == "stdio_mcp" and not self.is_stateful:
+ raise ValueError(
+ "STDIO MCP must be stateful (is_stateful=True).",
+ )
+
+ # Initialize the underlying client
+ self._initialize_client()
+
+ def _initialize_client(self) -> None:
+ """Initialize the underlying MCP client based on config type."""
+ if self.mcp_config.type == "stdio_mcp":
+ config = self.mcp_config
+ self._client = stdio_client(
+ StdioServerParameters(
+ command=config.command,
+ args=config.args or [],
+ env=config.env,
+ cwd=str(config.cwd) if config.cwd else None,
+ encoding="utf-8",
+ encoding_error_handler=config.encoding_error_handler,
+ ),
+ )
+
+ def _create_http_client(
+ self,
+ ) -> _AsyncGeneratorContextManager[Any]:
+ """Create an HTTP MCP client (SSE or streamable HTTP)."""
+ config = self.mcp_config
+
+ # Determine transport from URL
+ if config.url.endswith("/sse") or config.url.endswith("/messages/"):
+ return sse_client(
+ url=config.url,
+ headers=config.headers,
+ timeout=config.timeout,
+ )
+
+ # StreamableHTTP transport
+ http_client = None
+ if config.headers or config.timeout:
+ http_client = httpx.AsyncClient(
+ headers=config.headers,
+ timeout=config.timeout,
+ )
+ return streamable_http_client(
+ url=config.url,
+ http_client=http_client,
+ )
+
+ async def connect(self) -> None:
+ """Connect to the MCP server (for stateful connections only).
+
+ For stateless connections, this method does nothing.
+
+ Raises:
+ RuntimeError: If already connected.
+ """
+ if not self.is_stateful:
+ logger.debug(
+ "Stateless MCP '%s' does not require explicit connect.",
+ self.name,
+ )
+ return
+
+ if self._is_connected:
+ raise RuntimeError(
+ f"MCP '{self.name}' is already connected. "
+ "Call close() before reconnecting.",
+ )
+
+ # Create HTTP client if needed
+ if self._client is None and self.mcp_config.type == "http_mcp":
+ self._client = self._create_http_client()
+
+ self._stack = AsyncExitStack()
+
+ try:
+ context = await self._stack.enter_async_context(self._client)
+ read_stream, write_stream = context[0], context[1]
+ self._session = ClientSession(read_stream, write_stream)
+ await self._stack.enter_async_context(self._session)
+ await self._session.initialize()
+
+ self._is_connected = True
+ logger.info("MCP connected: %s", self.name)
+ except Exception:
+ await self._stack.aclose()
+ self._stack = None
+ raise
+
+ async def close(self, ignore_errors: bool = True) -> None:
+ """Close the MCP connection (for stateful connections only).
+
+ For stateless connections, this method does nothing.
+
+ Args:
+ ignore_errors: Whether to ignore errors during cleanup.
+
+ Raises:
+ RuntimeError: If not connected.
+ """
+ if not self.is_stateful:
+ logger.debug(
+ "Stateless MCP '%s' does not require explicit close.",
+ self.name,
+ )
+ return
+
+ if not self._is_connected:
+ raise RuntimeError(
+ f"MCP '{self.name}' is not connected. "
+ "Call connect() first.",
+ )
+
+ try:
+ await self._stack.aclose()
+ except Exception as e:
+ if not ignore_errors:
+ raise e
+ logger.warning(
+ "Error closing MCP '%s': %s",
+ self.name,
+ str(e),
+ )
+ finally:
+ self._stack = None
+ self._session = None
+ self._is_connected = False
+ logger.info("MCP closed: %s", self.name)
+
+ def _get_client_gen(self) -> _AsyncGeneratorContextManager[Any]:
+ """Get client generator for stateless connections."""
+ if self.mcp_config.type == "stdio_mcp":
+ return self._client
+ else:
+ return self._create_http_client()
+
+ async def list_tools(self) -> list[mcp.types.Tool]:
+ """List all available tools from the MCP server.
+
+ Returns:
+ List of available MCP tools.
+
+ Raises:
+ RuntimeError: If not connected (for stateful connections).
+ """
+ if not self.is_stateful:
+ # Stateless: create temporary session
+ async with self._get_client_gen() as cli:
+ read_stream, write_stream = cli[0], cli[1]
+ async with ClientSession(
+ read_stream,
+ write_stream,
+ ) as session:
+ await session.initialize()
+ res = await session.list_tools()
+ self._cached_tools = res.tools
+ return res.tools
+ else:
+ # Stateful: use existing session
+ self._validate_connection()
+ res = await self._session.list_tools()
+ self._cached_tools = res.tools
+ return res.tools
+
+ async def get_tool(
+ self,
+ name: str,
+ execution_timeout: float | None = None,
+ ) -> MCPTool:
+ """Get a tool by name from the MCP server.
+
+ The returned MCPTool object implements ToolProtocol and can be:
+ - Called directly: `await tool(arg1=val1)`
+ - Registered to toolkit: `toolkit.register_tool(tool)`
+
+ Args:
+ name: The name of the tool function to get.
+ execution_timeout: The preset timeout in seconds for calling
+ the tool function.
+
+ Returns:
+ A tool object that implements ToolProtocol.
+
+ Raises:
+ ValueError: If the tool is not found.
+ RuntimeError: If not connected (for stateful connections).
+ """
+ # Avoid circular import by importing here
+ from ..tool import MCPTool
+
+ # Fetch tools if not cached
+ if self._cached_tools is None:
+ await self.list_tools()
+
+ # Find target tool
+ target_tool = None
+ for tool in self._cached_tools:
+ if tool.name == name:
+ target_tool = tool
+ break
+
+ if target_tool is None:
+ raise ValueError(
+ f"Tool '{name}' not found in MCP server " f"'{self.name}'",
+ )
+
+ # Create MCPTool based on stateful/stateless
+ if not self.is_stateful:
+ # Stateless: pass client generator
+ return MCPTool(
+ mcp_name=self.name,
+ tool=target_tool,
+ client_gen=self._get_client_gen,
+ timeout=execution_timeout,
+ )
+ else:
+ # Stateful: pass session
+ self._validate_connection()
+ return MCPTool(
+ mcp_name=self.name,
+ tool=target_tool,
+ session=self._session,
+ timeout=execution_timeout,
+ )
+
+ def _validate_connection(self) -> None:
+ """Validate connection state for stateful connections.
+
+ Raises:
+ RuntimeError: If not connected or session not initialized.
+ """
+ if not self._is_connected:
+ raise RuntimeError(
+ f"MCP '{self.name}' is not connected. "
+ "Call connect() first.",
+ )
+ if not self._session:
+ raise RuntimeError(
+ f"MCP '{self.name}' session is not initialized. "
+ "Call connect() first.",
+ )
diff --git a/src/agentscope/mcp/_stateful_client_base.py b/src/agentscope/mcp/_stateful_client_base.py
deleted file mode 100644
index 97a150c9d..000000000
--- a/src/agentscope/mcp/_stateful_client_base.py
+++ /dev/null
@@ -1,174 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The base MCP stateful client class in AgentScope, that provides basic
- functionality for stateful MCP clients."""
-from abc import ABC
-from contextlib import AsyncExitStack
-from typing import List, TYPE_CHECKING, Any
-
-import mcp
-from mcp import ClientSession
-
-from ._client_base import MCPClientBase
-from .._logging import logger
-
-if TYPE_CHECKING:
- from ..tool import MCPTool
-else:
- MCPTool = Any
-
-
-class StatefulClientBase(MCPClientBase, ABC):
- """The base class for stateful MCP clients in AgentScope, which maintains
- the session state across multiple tool calls.
-
- The developers should use `connect()` and `close()` methods to manage
- the client lifecycle.
- """
-
- is_connected: bool
- """If connected to the MCP server"""
-
- def __init__(self, name: str) -> None:
- """Initialize the stateful MCP client.
-
- Args:
- name (`str`):
- The name to identify the MCP server, which should be unique
- across the MCP servers.
- """
-
- super().__init__(name=name)
-
- self.client = None
- self.stack = None
- self.session = None
- self.is_connected = False
-
- # Cache the tools to avoid fetching them multiple times
- self._cached_tools = None
-
- async def connect(self) -> None:
- """Connect to MCP server."""
- if self.is_connected:
- raise RuntimeError(
- "The MCP server is already connected. Call close() "
- "before connecting again.",
- )
-
- self.stack = AsyncExitStack()
-
- try:
- context = await self.stack.enter_async_context(
- self.client,
- )
- read_stream, write_stream = context[0], context[1]
- self.session = ClientSession(read_stream, write_stream)
- await self.stack.enter_async_context(self.session)
- await self.session.initialize()
-
- self.is_connected = True
- logger.info("MCP client connected.")
- except Exception:
- await self.stack.aclose()
- self.stack = None
- raise
-
- async def close(self, ignore_errors: bool = True) -> None:
- """Clean up the MCP client resources. You must call this method when
- your application is done.
-
- Args:
- ignore_errors (`bool`):
- Whether to ignore errors during cleanup. Defaults to `True`.
- """
- if not self.is_connected:
- raise RuntimeError(
- "The MCP server is not connected. Call connect() before "
- "closing.",
- )
-
- try:
- await self.stack.aclose()
- except Exception as e:
- if not ignore_errors:
- raise e
- logger.warning("Error during MCP client cleanup: %s", e)
- finally:
- self.stack = None
- self.session = None
- self.is_connected = False
-
- async def list_tools(self) -> List[mcp.types.Tool]:
- """Get all available tools from the server.
-
- Returns:
- `mcp.types.ListToolsResult`:
- A list of available MCP tools.
- """
- self._validate_connection()
-
- res = await self.session.list_tools()
-
- # Cache the tools for later use
- self._cached_tools = res.tools
- return res.tools
-
- async def get_tool(
- self,
- name: str,
- execution_timeout: float | None = None,
- ) -> MCPTool:
- """Get a tool object from the MCP server by its name.
-
- The returned MCPTool object implements ToolProtocol and can be:
- - Called directly: `await tool(arg1=val1)`
- - Registered to toolkit: `toolkit.register_tool(tool)`
-
- Args:
- name (`str`):
- The name of the tool function to get.
- execution_timeout (`float | None`, optional):
- The preset timeout in seconds for calling the tool function.
-
- Returns:
- `MCPTool`:
- A tool object that implements ToolProtocol.
- """
- self._validate_connection()
-
- if self._cached_tools is None:
- await self.list_tools()
-
- target_tool = None
- for tool in self._cached_tools:
- if tool.name == name:
- target_tool = tool
- break
-
- if target_tool is None:
- raise ValueError(
- f"Tool '{name}' not found in the MCP server",
- )
-
- from ..tool import MCPTool
-
- return MCPTool(
- mcp_name=self.name,
- tool=target_tool,
- session=self.session,
- timeout=execution_timeout,
- )
-
- def _validate_connection(self) -> None:
- """Validate the connection to the MCP server."""
- if not self.is_connected:
- raise RuntimeError(
- "The connection is not established. Call connect() "
- "before using the client.",
- )
-
- if not self.session:
- raise RuntimeError(
- "The session is not initialized. Call connect() "
- "before using the client.",
- )
diff --git a/src/agentscope/mcp/_stdio_stateful_client.py b/src/agentscope/mcp/_stdio_stateful_client.py
deleted file mode 100644
index 4a134c78a..000000000
--- a/src/agentscope/mcp/_stdio_stateful_client.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The StdIO MCP server implementation in AgentScope, which provides
-function-level fine-grained control over the MCP servers using standard IO."""
-from typing import Literal
-
-from mcp import stdio_client, StdioServerParameters
-
-from ._stateful_client_base import StatefulClientBase
-
-
-class StdIOStatefulClient(StatefulClientBase):
- """A client class that sets up and manage StdIO MCP server connections, and
- provides function-level fine-grained control over the MCP servers.
-
- .. tip:: The stateful client is recommended for MCP servers that need to
- maintain session states, e.g. web browsers or other interactive
- MCP servers.
-
- .. note:: The stateful client will maintain one session across multiple
- tool calls, until the client is closed by explicitly calling the
- `close()` method.
-
- .. note:: When multiple StdIOStatefulClient instances are connected,
- they should be closed following the Last In First Out (LIFO) principle
- to avoid potential errors. Always close the most recently registered
- client first, then work backwards to the first one.
- For more details, please refer to this `issue
- <https://github.com/modelcontextprotocol/python-sdk/issues/577>`_.
- """
-
- def __init__(
- self,
- name: str,
- command: str,
- args: list[str] | None = None,
- env: dict[str, str] | None = None,
- cwd: str | None = None,
- encoding: str = "utf-8",
- encoding_error_handler: Literal[
- "strict",
- "ignore",
- "replace",
- ] = "strict",
- ) -> None:
- """Initialize the MCP server with std IO.
-
- Args:
- name (`str`):
- The name to identify the MCP server, which should be unique
- across the MCP servers.
- command (`str`):
- The executable to run to start the server.
- args (`list[str] | None`, optional):
- Command line arguments to pass to the executable.
- env (`dict[str, str] | None`, optional):
- The environment to use when spawning the process.
- cwd (`str | None`, optional):
- The working directory to use when spawning the process.
- encoding (`str`, optional):
- The text encoding used when sending/receiving messages to the
- server. Defaults to "utf-8".
- encoding_error_handler (`Literal["strict", "ignore", "replace"]`, \
- defaults to "strict"):
- The text encoding error handler.
- """
- super().__init__(name=name)
-
- self.client = stdio_client(
- StdioServerParameters(
- command=command,
- args=args or [],
- env=env,
- cwd=cwd,
- encoding=encoding,
- encoding_error_handler=encoding_error_handler,
- ),
- )
diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.py
index 30990fa2e..0eb6c703c 100644
--- a/src/agentscope/tool/_toolkit.py
+++ b/src/agentscope/tool/_toolkit.py
@@ -34,10 +34,7 @@ from ..exception import (
ToolNotFoundError,
ToolGroupInactiveError,
)
-from ..mcp import (
- MCPClientBase,
- StatefulClientBase,
-)
+from ..mcp import MCPClient
from ..message import (
ToolCallBlock,
TextBlock,
@@ -614,7 +611,7 @@ class Toolkit:
async def register_mcp(
self,
- mcp_client: MCPClientBase,
+ mcp_client: MCPClient,
group_name: str = "basic",
enable_funcs: list[str] | None = None,
disable_funcs: list[str] | None = None,
@@ -622,11 +619,11 @@ class Toolkit:
"""Register tools from an MCP client.
.. note:: When registering tools from an MCP client, the tool will
- be renamed by template `mcp__{server_name}__{tool_name}` to avoid
+ be renamed by template `mcp__{mcp_name}__{tool_name}` to avoid
name conflicts.
Args:
- mcp_client (`MCPClientBase`):
+ mcp_client (`MCPClient`):
The MCP client instance to connect to the MCP server.
group_name (`str`, defaults to `"basic"`):
The group name that the tool functions will be added to.
@@ -637,10 +634,13 @@ class Toolkit:
The functions that will be filtered out. If `None`, no
tool functions will be filtered out.
"""
- if (
- isinstance(mcp_client, StatefulClientBase)
- and not mcp_client.is_connected
- ):
+ if not isinstance(mcp_client, MCPClient):
+ raise ValueError(
+ f"The 'mcp_client' should be an instance of "
+ f"'MCPClient' but got {type(mcp_client)}.",
+ )
+
+ if mcp_client.is_stateful and not mcp_client.is_connected:
raise RuntimeError(
"The MCP client is not connected to the server. Use the "
"`connect()` method first.",
diff --git a/tests/mcp_sse_client_test.py b/tests/mcp_sse_client_test.py
index b0dc8d3fd..d5ca92ce0 100644
--- a/tests/mcp_sse_client_test.py
+++ b/tests/mcp_sse_client_test.py
@@ -7,7 +7,7 @@ from unittest.async_case import IsolatedAsyncioTestCase
from mcp.server import FastMCP
-from agentscope.mcp import HttpStatelessClient, HttpStatefulClient
+from agentscope.mcp import MCPClient, HttpMCPConfig
from agentscope.message import ToolCallBlock
from agentscope.tool import ToolResponse, ToolChunk, Toolkit
from agentscope.state import AgentState
@@ -81,10 +81,14 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):
async def test_stateless_client(self) -> None:
"""Test the stateless sse MCP client."""
- stateless_client = HttpStatelessClient(
+ # Create stateless client (is_stateful=False)
+ stateless_client = MCPClient(
name="test_sse_client",
- transport="sse",
- url=f"http://127.0.0.1:{self.port}/sse",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(
+ type="http_mcp",
+ url=f"http://127.0.0.1:{self.port}/sse",
+ ),
)
mcp_tool_1 = await stateless_client.get_tool("tool_1")
@@ -159,11 +163,14 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):
async def test_stateful_client(self) -> None:
"""Test the stateful sse MCP client."""
- # Test stateful client
- stateful_client = HttpStatefulClient(
+ # Test stateful client (is_stateful=True)
+ stateful_client = MCPClient(
name="test_sse_client",
- transport="sse",
- url=f"http://127.0.0.1:{self.port}/sse",
+ is_stateful=True,
+ mcp_config=HttpMCPConfig(
+ type="http_mcp",
+ url=f"http://127.0.0.1:{self.port}/sse",
+ ),
)
self.assertFalse(stateful_client.is_connected)
diff --git a/tests/mcp_streamable_http_client_test.py b/tests/mcp_streamable_http_client_test.py
index 34cf06e4b..49a25a4fc 100644
--- a/tests/mcp_streamable_http_client_test.py
+++ b/tests/mcp_streamable_http_client_test.py
@@ -7,7 +7,7 @@ from unittest.async_case import IsolatedAsyncioTestCase
from mcp.server import FastMCP
from mcp.types import EmbeddedResource, TextResourceContents
-from agentscope.mcp import HttpStatelessClient, HttpStatefulClient
+from agentscope.mcp import MCPClient, HttpMCPConfig
from agentscope.tool import ToolChunk
@@ -68,10 +68,14 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):
async def test_streamable_http_stateless_client(self) -> None:
"""Test the MCP server connection functionality."""
- client = HttpStatelessClient(
+ # Test stateless client (is_stateful=False)
+ client = MCPClient(
name="test_streamable_http_stateless_client",
- transport="streamable_http",
- url=f"http://127.0.0.1:{self.port}/mcp",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(
+ type="http_mcp",
+ url=f"http://127.0.0.1:{self.port}/mcp",
+ ),
)
my_tool_1 = await client.get_tool("tool_1")
@@ -87,11 +91,14 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):
"arg1: 345, arg2: [4, 5, 6]",
)
- # Test stateful client connection
- client = HttpStatefulClient(
- name="test_streamable_http_stateless_client",
- transport="streamable_http",
- url=f"http://127.0.0.1:{self.port}/mcp",
+ # Test stateful client (is_stateful=True)
+ client = MCPClient(
+ name="test_streamable_http_stateful_client",
+ is_stateful=True,
+ mcp_config=HttpMCPConfig(
+ type="http_mcp",
+ url=f"http://127.0.0.1:{self.port}/mcp",
+ ),
)
self.assertFalse(client.is_connected)
@@ -117,10 +124,14 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):
async def test_embedded_content(self) -> None:
"""Test the EmbeddedContent functionality."""
- client = HttpStatelessClient(
+ # Test with stateless client (is_stateful=False)
+ client = MCPClient(
name="test_embedded_content",
- transport="streamable_http",
- url=f"http://127.0.0.1:{self.port}/mcp",
+ is_stateful=False,
+ mcp_config=HttpMCPConfig(
+ type="http_mcp",
+ url=f"http://127.0.0.1:{self.port}/mcp",
+ ),
)
my_tool_2 = await client.get_tool("tool_2")