Skip to content

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

feat(mcp): support MCP SDK 2.x and tool progress streaming (#3325)

qbc44b5d5208f09
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index 91b971ab1..95f032262 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -514,6 +514,8 @@ export interface HttpMCPConfig {
export interface MCPClient {
name: string;
is_stateful: boolean;
+ /** Opt in to tool progress streaming; omitted means false. */
+ stream_progress?: boolean;
mcp_config: StdioMCPConfig | HttpMCPConfig;
}
diff --git a/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx b/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx
index 26fcacfdb..eb71b7d0a 100644
--- a/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx
+++ b/examples/web_ui/frontend/src/components/dialog/MCPConfigForm.tsx
@@ -39,6 +39,11 @@ function parseMcpConfig(
}
return entries.map(([name, config]) => {
+ const streamProgress =
+ config.stream_progress === undefined ? false : config.stream_progress;
+ if (typeof streamProgress !== 'boolean') {
+ throw new Error(t('dialog-mcp-create.invalidStreamProgress', { name }));
+ }
let mcp_config: StdioMCPConfig | HttpMCPConfig;
if ('url' in config) {
mcp_config = {
@@ -56,7 +61,7 @@ function parseMcpConfig(
cwd: (config.cwd as string | undefined) ?? null,
};
}
- return { name, is_stateful: keepAlive, mcp_config };
+ return { name, is_stateful: keepAlive, stream_progress: streamProgress, mcp_config };
});
}
diff --git a/examples/web_ui/frontend/src/i18n/locales/en.json b/examples/web_ui/frontend/src/i18n/locales/en.json
index aa3afff06..810e1acb4 100644
--- a/examples/web_ui/frontend/src/i18n/locales/en.json
+++ b/examples/web_ui/frontend/src/i18n/locales/en.json
@@ -501,6 +501,7 @@
"keepAlive": "Keep Alive",
"keepAliveDesc": "Maintain state across interactions. Enable for browser-use or other long-running MCPs.",
"parseError": "Invalid JSON configuration: {{message}}",
+ "invalidStreamProgress": "{{name}}.stream_progress must be a boolean (true or false).",
"missingMcpServers": "Configuration must contain a \"mcpServers\" object.",
"emptyMcpServers": "No MCP servers found in configuration."
},
diff --git a/examples/web_ui/frontend/src/i18n/locales/zh.json b/examples/web_ui/frontend/src/i18n/locales/zh.json
index f79787048..22c482414 100644
--- a/examples/web_ui/frontend/src/i18n/locales/zh.json
+++ b/examples/web_ui/frontend/src/i18n/locales/zh.json
@@ -501,6 +501,7 @@
"keepAlive": "保持连接",
"keepAliveDesc": "在交互间保持状态。适用于浏览器操作或其他长时间运行的 MCP。",
"parseError": "JSON 配置无效:{{message}}",
+ "invalidStreamProgress": "{{name}}.stream_progress 必须为布尔值(true 或 false)。",
"missingMcpServers": "配置中必须包含 \"mcpServers\" 对象。",
"emptyMcpServers": "配置中未找到 MCP 服务器。"
},
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.py
index b8f110d1e..fc8f8f4ab 100644
--- a/src/agentscope/agent/_agent.py
+++ b/src/agentscope/agent/_agent.py
@@ -35,6 +35,7 @@ from .._utils._common import (
)
from ..event import (
AgentEvent,
+ CustomEvent,
ModelCallEndEvent,
ModelCallStartEvent,
ReplyEndEvent,
@@ -2142,7 +2143,8 @@ class Agent:
| ToolResultStartEvent
| ToolResultTextDeltaEvent
| ToolResultDataDeltaEvent
- | ToolResultEndEvent,
+ | ToolResultEndEvent
+ | CustomEvent,
None,
]:
"""Execute the given tool calls sequentially and yield the events.
@@ -2161,7 +2163,8 @@ class Agent:
| ToolResultStartEvent \
| ToolResultTextDeltaEvent \
| ToolResultDataDeltaEvent \
- | ToolResultEndEvent`:
+ | ToolResultEndEvent \
+ | CustomEvent`:
The events generated during the execution of the tool calls.
"""
break_execution = False
@@ -2192,7 +2195,8 @@ class Agent:
| ToolResultStartEvent
| ToolResultTextDeltaEvent
| ToolResultDataDeltaEvent
- | ToolResultEndEvent,
+ | ToolResultEndEvent
+ | CustomEvent,
None,
]:
"""Execute the given tool calls concurrently and yield the events.
@@ -2224,7 +2228,8 @@ class Agent:
| ToolResultStartEvent \
| ToolResultTextDeltaEvent \
| ToolResultDataDeltaEvent \
- | ToolResultEndEvent`:
+ | ToolResultEndEvent \
+ | CustomEvent`:
The events generated during the execution of the tool calls.
Raises:
@@ -2433,7 +2438,8 @@ class Agent:
| ToolResultStartEvent
| ToolResultTextDeltaEvent
| ToolResultDataDeltaEvent
- | ToolResultEndEvent,
+ | ToolResultEndEvent
+ | CustomEvent,
None,
]:
"""Execute a single tool call with permission checking and context
@@ -2465,7 +2471,8 @@ class Agent:
| ToolResultStartEvent \
| ToolResultTextDeltaEvent \
| ToolResultDataDeltaEvent \
- | ToolResultEndEvent`:
+ | ToolResultEndEvent \
+ | CustomEvent`:
The events generated during the tool call execution.
"""
# ===================================================================
@@ -2699,6 +2706,16 @@ class Agent:
else:
# Intermediate ToolChunk — convert to streaming events
+ progress = chunk.metadata.get("mcp_progress")
+ if progress is not None:
+ yield CustomEvent(
+ name="mcp_progress",
+ value={
+ **progress,
+ "reply_id": self.state.reply_id,
+ "tool_call_id": tool_call.id,
+ },
+ )
async for evt in self._convert_tool_chunk_to_event(
tool_call.id,
chunk.content,
diff --git a/src/agentscope/event/_event.py b/src/agentscope/event/_event.py
index 2e37fceb1..d6179e48f 100644
--- a/src/agentscope/event/_event.py
+++ b/src/agentscope/event/_event.py
@@ -550,6 +550,9 @@ class CustomEvent(EventBase):
changed during a tool call.
- ``"team_updated"`` — team membership changed (member
added / team created or dissolved).
+ - ``"mcp_progress"`` — transient MCP tool progress, with
+ ``reply_id``, ``tool_call_id``, ``progress``, ``total`` and
+ ``message`` in ``value``. Not part of the final tool result.
value (`dict`):
Arbitrary JSON-serializable payload whose schema depends
diff --git a/src/agentscope/mcp/_mcp_client.py b/src/agentscope/mcp/_mcp_client.py
index 61158b69e..d054fad3c 100644
--- a/src/agentscope/mcp/_mcp_client.py
+++ b/src/agentscope/mcp/_mcp_client.py
@@ -5,14 +5,13 @@ import re
from contextlib import (
AbstractAsyncContextManager,
asynccontextmanager,
- AsyncExitStack,
)
from typing import Any, AsyncGenerator, ClassVar, TYPE_CHECKING
from urllib.parse import urlsplit
import httpx2
import mcp.types
-from mcp import ClientSession, stdio_client, StdioServerParameters
+from mcp import Client as SDKClient, stdio_client, StdioServerParameters
from mcp.client.sse import sse_client
from mcp.client.streamable_http import (
create_mcp_http_client,
@@ -36,13 +35,13 @@ class MCPClient(BaseModel):
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
+ - Stateful: Requires explicit connect() and close(), maintains a client
+ - Stateless: No connect() needed, creates a temporary client 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
+ - _client: The connected MCP SDK client for stateful connections
+ - _lifecycle_task: Owns the stateful client context from enter to exit
+ - _close_requested: Signals the lifecycle task to exit the client context
- _is_connected: Connection state flag
- _cached_tools: Cached list of tools
- _http_client: The live HTTP client, while one is open
@@ -122,10 +121,19 @@ class MCPClient(BaseModel):
execution_timeout: float | None = None
"""The execution timeout in seconds for calling the tools from this MCP."""
+ stream_progress: bool = Field(
+ default=False,
+ description=(
+ "Whether local tools return a progress/result stream instead of "
+ "the final ToolChunk. Sandbox gateway tools return final results "
+ "only."
+ ),
+ )
+
# Private attributes
- _client: Any = PrivateAttr(default=None)
- _session: ClientSession | None = PrivateAttr(default=None)
- _stack: AsyncExitStack | None = PrivateAttr(default=None)
+ _client: SDKClient | None = PrivateAttr(default=None)
+ _lifecycle_task: asyncio.Task[None] | None = PrivateAttr(default=None)
+ _close_requested: asyncio.Event | None = PrivateAttr(default=None)
_is_connected: bool = PrivateAttr(default=False)
_cached_tools: list[mcp.types.Tool] | None = PrivateAttr(default=None)
_http_client: httpx2.AsyncClient | None = PrivateAttr(default=None)
@@ -187,28 +195,38 @@ class MCPClient(BaseModel):
f"should not overlap, but got {intersection}.",
)
- # Initialize the underlying client
- self._initialize_client()
+ def _create_stdio_transport(
+ self,
+ ) -> AbstractAsyncContextManager[Any]:
+ """Build a fresh stdio transport."""
+ assert isinstance(self.mcp_config, StdioMCPConfig)
+ config = self.mcp_config
+ return 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 _initialize_client(self) -> None:
- """Pre-build the stdio client context manager."""
+ def _create_sdk_client(self) -> SDKClient:
+ """Build an MCP 2.x client with automatic protocol negotiation."""
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,
- ),
- )
+ transport = self._create_stdio_transport()
+ else:
+ transport = self._create_http_client()
+ return SDKClient(
+ transport,
+ mode="auto",
+ )
def _create_http_client(
self,
) -> AbstractAsyncContextManager[Any]:
- """Create an HTTP MCP client (SSE or streamable HTTP)."""
+ """Create an HTTP MCP transport (SSE or Streamable HTTP)."""
config = self.mcp_config
if self._is_sse:
return sse_client(
@@ -337,40 +355,59 @@ class MCPClient(BaseModel):
"Call close() before reconnecting.",
)
- # Transports are one-shot context managers. Recreate them before every
- # connection so connect() -> close() -> connect() starts a fresh one.
- if self._client is None:
- if self.mcp_config.type == "http_mcp":
- self._client = self._create_http_client()
- else:
- self._initialize_client()
-
- assert self._client is not None
- stack = AsyncExitStack()
- self._stack = stack
+ client = self._create_sdk_client()
+ ready = asyncio.Event()
+ close_requested = asyncio.Event()
+ startup_result: list[SDKClient | BaseException] = []
+ lifecycle_task = asyncio.create_task(
+ self._run_client_lifecycle(
+ client,
+ ready,
+ close_requested,
+ startup_result,
+ ),
+ )
+ self._lifecycle_task = lifecycle_task
+ self._close_requested = close_requested
try:
- context = await stack.enter_async_context(self._client)
- read_stream, write_stream = context[0], context[1]
- self._session = ClientSession(read_stream, write_stream)
- await stack.enter_async_context(self._session)
- await self._session.initialize()
-
+ await asyncio.shield(ready.wait())
+ result = startup_result[0]
+ if isinstance(result, BaseException):
+ raise result
+ self._client = result
self._is_connected = True
logger.info("MCP connected: %s", self.name)
except BaseException:
- # asyncio.CancelledError inherits BaseException, so a cancelled
- # initialization must close every context entered so far. The
- # close is shielded because an anyio cancel scope (a cancelled
- # FastAPI request, for one) keeps cancelling every await inside
- # it, which would otherwise abandon a live stdio subprocess.
+ if not lifecycle_task.done():
+ lifecycle_task.cancel()
try:
- await asyncio.shield(stack.aclose())
- finally:
- self._client = None
- self._stack = None
- self._session = None
- self._is_connected = False
+ await asyncio.shield(lifecycle_task)
+ except BaseException:
+ pass
+ self._client = None
+ self._lifecycle_task = None
+ self._close_requested = None
+ self._is_connected = False
+ raise
+
+ @staticmethod
+ async def _run_client_lifecycle(
+ client: SDKClient,
+ ready: asyncio.Event,
+ close_requested: asyncio.Event,
+ startup_result: list[SDKClient | BaseException],
+ ) -> None:
+ """Own one stateful client context from initialization to close."""
+ try:
+ async with client as connected_client:
+ startup_result.append(connected_client)
+ ready.set()
+ await close_requested.wait()
+ except BaseException as error:
+ if not ready.is_set():
+ startup_result.append(error)
+ ready.set()
raise
async def close(self, ignore_errors: bool = True) -> None:
@@ -397,8 +434,16 @@ class MCPClient(BaseModel):
"Call connect() first.",
)
+ lifecycle_task = self._lifecycle_task
+ close_requested = self._close_requested
+ if lifecycle_task is None or close_requested is None:
+ raise RuntimeError(
+ f"MCP '{self.name}' lifecycle is not initialized.",
+ )
+
+ close_requested.set()
try:
- await self._stack.aclose()
+ await lifecycle_task
except Exception as e:
if not ignore_errors:
raise e
@@ -409,17 +454,14 @@ class MCPClient(BaseModel):
)
finally:
self._client = None
- self._stack = None
- self._session = None
+ self._lifecycle_task = None
+ self._close_requested = None
self._is_connected = False
logger.info("MCP closed: %s", self.name)
def _get_client_gen(self) -> AbstractAsyncContextManager[Any]:
- """Get client generator for stateless connections."""
- if self.mcp_config.type == "stdio_mcp":
- return self._client
- else:
- return self._create_http_client()
+ """Build a fresh MCP SDK client for a stateless operation."""
+ return self._create_sdk_client()
async def list_raw_tools(self) -> list[mcp.types.Tool]:
"""List available tools from the MCP server in raw
@@ -437,20 +479,14 @@ class MCPClient(BaseModel):
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
+ # Stateless: create a temporary auto-negotiating client.
+ async with self._get_client_gen() as client:
+ res = await client.list_tools(cache_mode="refresh")
+ self._cached_tools = res.tools
else:
- # Stateful: use existing session
+ # Stateful: use the existing high-level client.
self._validate_connection()
- res = await self._session.list_tools()
+ res = await self._client.list_tools(cache_mode="refresh")
self._cached_tools = res.tools
available_tools: list = self._cached_tools
@@ -489,7 +525,9 @@ class MCPClient(BaseModel):
"""Get a tool by name from the MCP server.
The returned MCPTool object implements ToolProtocol and can be:
- - Called directly: `await tool(arg1=val1)`
+ - Called directly for its final result: `await tool(arg1=val1)`
+ - Streamed when `stream_progress=True`:
+ `async for chunk in await tool(arg1=val1)`
- Registered to toolkit: `toolkit.register_tool(tool)`
Args:
@@ -505,21 +543,15 @@ class MCPClient(BaseModel):
# Avoid circular import by importing here
from ..tool import MCPTool
- # Fetch tools if not cached. Use list_raw_tools() to avoid the
- # recursion list_tools() → get_tool() → list_tools().
if self._cached_tools is None:
await self.list_raw_tools()
-
- # Find target tool
- target_tool = None
- for tool in self._cached_tools:
- if tool.name == name:
- target_tool = tool
- break
-
+ target_tool = next(
+ (tool for tool in self._cached_tools or [] if tool.name == name),
+ None,
+ )
if target_tool is None:
raise ValueError(
- f"Tool '{name}' not found in MCP server " f"'{self.name}'",
+ f"Tool {name!r} not found in MCP server {self.name!r}",
)
# Create MCPTool based on stateful/stateless
@@ -530,6 +562,7 @@ class MCPClient(BaseModel):
tool=target_tool,
client_gen=self._get_client_gen,
timeout=self.execution_timeout,
+ stream_progress=self.stream_progress,
)
else:
# Stateful: pass session
@@ -537,8 +570,9 @@ class MCPClient(BaseModel):
return MCPTool(
mcp_name=self.name,
tool=target_tool,
- session=self._session,
+ session=self._client,
timeout=self.execution_timeout,
+ stream_progress=self.stream_progress,
)
def _validate_connection(self) -> None:
@@ -552,8 +586,8 @@ class MCPClient(BaseModel):
f"MCP '{self.name}' is not connected. "
"Call connect() first.",
)
- if not self._session:
+ if not self._client:
raise RuntimeError(
- f"MCP '{self.name}' session is not initialized. "
+ f"MCP '{self.name}' client is not initialized. "
"Call connect() first.",
)
diff --git a/src/agentscope/message/_base.py b/src/agentscope/message/_base.py
index ba955251c..3cf9c81ac 100644
--- a/src/agentscope/message/_base.py
+++ b/src/agentscope/message/_base.py
@@ -250,6 +250,7 @@ class Msg(BaseModel):
content blocks are appended/updated by block-level events,
``finished_at`` is stamped by ``REPLY_END``, and ``usage`` is
initialized then accumulated across each ``MODEL_CALL_END``.
+ Custom events are skipped because they do not update message content.
Events whose ``reply_id`` does not match ``self.id`` are skipped with
a warning. Block-level delta/end events whose target block cannot be
found are also skipped with a warning.
@@ -260,6 +261,9 @@ class Msg(BaseModel):
"""
from ..event import EventType # local import to avoid circular dep
+ if event.type == EventType.CUSTOM:
+ return self
+
if event.reply_id != self.id:
logger.warning(
"Event %s with reply_id %r does not match message id %r, "
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.py
index 72a39190a..b8098a092 100644
--- a/src/agentscope/tool/_adapters.py
+++ b/src/agentscope/tool/_adapters.py
@@ -1,14 +1,16 @@
# -*- coding: utf-8 -*-
"""Adapters to convert functions and MCP tools to ToolProtocol."""
+import asyncio
import inspect
import json
import re
-from contextlib import AbstractAsyncContextManager
+import warnings
+from contextlib import AbstractAsyncContextManager, AsyncExitStack
from typing import Callable, Any, AsyncGenerator, Generator
-from mcp import ClientSession
+import anyio
import mcp
-from pydantic import BaseModel
+from pydantic import AnyUrl, BaseModel, ValidationError
from ._types import Function
from ._base import ToolBase, ToolMiddlewareBase
@@ -26,11 +28,11 @@ from ._utils import (
)
from .._logging import logger
from ..message import (
+ Base64Source,
TextBlock,
DataBlock,
- Base64Source,
- URLSource,
ToolResultState,
+ URLSource,
)
@@ -214,6 +216,7 @@ class MCPTool(ToolBase):
session: Any | None = None,
timeout: float | None = None,
middlewares: list[ToolMiddlewareBase] | None = None,
+ stream_progress: bool = False,
) -> None:
"""Initialize the MCPTool.
@@ -225,17 +228,23 @@ class MCPTool(ToolBase):
client_gen (`Callable[..., AbstractAsyncContextManager[Any]] \
| None`, optional):
The MCP client generator function for stateless clients.
+ Its context manager should yield a connected ``mcp.Client``.
+ Legacy transport tuples are accepted with a deprecation
+ warning; only their read and write streams are used.
Either this or ``session`` must be provided.
- session (`mcp.ClientSession | None`, optional):
- The MCP client session for stateful clients.
+ session (`mcp.Client | None`, optional):
+ The MCP high-level client for stateful clients.
Either this or ``client_gen`` must be provided.
timeout (`float | None`, optional):
The timeout in seconds for tool execution.
middlewares (`list[ToolMiddlewareBase] | None`, optional):
Tool middlewares wrapping the tool execution.
+ stream_progress (`bool`, defaults to `False`):
+ Return a progress/result stream instead of the final chunk.
"""
super().__init__(middlewares=middlewares)
self.mcp_name = mcp_name
+ self.stream_progress = stream_progress
# LLM providers enforce ^[a-zA-Z0-9_-]+$ on tool names.
# mcp_name is validated in MCPClient.model_post_init;
@@ -317,122 +326,220 @@ class MCPTool(ToolBase):
async def call(
self,
**kwargs: Any,
- ) -> ToolChunk:
- """Invoke the MCP tool and convert the result to ToolChunk.
+ ) -> ToolChunk | AsyncGenerator[ToolChunk, None]:
+ """Return the final result, or stream when ``stream_progress=True``.
+
+ Progress is best-effort snapshot delivery, not a lossless event log.
+ At most 1024 pending progress updates are retained; overflow drops
+ the oldest updates without reporting a dropped count. Consumers
+ must not depend on receiving every update. Buffer overflow does not
+ discard the final result, which is emitted separately.
Args:
**kwargs: Arguments to pass to the MCP tool.
Returns:
- `ToolChunk`: The converted tool execution result.
+ `ToolChunk | AsyncGenerator[ToolChunk, None]`:
+ The final result by default. When streaming is enabled,
+ progress chunks followed by the converted tool result.
"""
-
- # Call the MCP tool
- if self._client_gen:
- # Stateless client: create temporary session
- async with self._client_gen() as cli:
- read_stream, write_stream = cli[0], cli[1]
- async with ClientSession(read_stream, write_stream) as session:
- await session.initialize()
- result = await session.call_tool(
- self._tool.name,
- arguments=kwargs,
- read_timeout_seconds=self._timeout,
- )
- else:
- # Stateful client: use existing session
- result = await self._session.call_tool(
- self._tool.name,
- arguments=kwargs,
- read_timeout_seconds=self._timeout,
+ if self.stream_progress:
+ return self._stream_call(kwargs)
+ final_chunk: ToolChunk | None = None
+ async for chunk in self._stream_call(kwargs):
+ if chunk.is_last:
+ final_chunk = chunk
+ if final_chunk is None:
+ raise RuntimeError(
+ f"MCP tool {self.name!r} returned no final chunk.",
)
+ return final_chunk
- # Convert MCP result to AgentScope blocks
- content = self._convert_mcp_content_to_blocks(result.content)
+ async def _stream_call(
+ self,
+ kwargs: dict[str, Any],
+ ) -> AsyncGenerator[ToolChunk, None]:
+ """Run one MCP call and expose request-scoped progress updates."""
+ # Progress is a snapshot; retain the newest 1024 pending updates.
+ progress_queue: asyncio.Queue[ToolChunk] = asyncio.Queue(maxsize=1024)
+ accepting_progress = True
+
+ async def _on_progress(
+ progress: float,
+ total: float | None,
+ message: str | None,
+ ) -> None:
+ if accepting_progress:
+ if progress_queue.full():
+ progress_queue.get_nowait()
+ progress_queue.put_nowait(
+ ToolChunk(
+ content=[],
+ state=ToolResultState.RUNNING,
+ is_last=False,
+ metadata={
+ "mcp_progress": {
+ "progress": progress,
+ "total": total,
+ "message": message,
+ },
+ },
+ ),
+ )
- # Fall back to structured JSON when no text block is available.
- # Preserve existing text content without appending JSON.
- if result.structured_content is not None and not any(
- isinstance(block, TextBlock) for block in content
- ):
- content.append(
- TextBlock(
- text=json.dumps(
- result.structured_content,
- ensure_ascii=False,
+ async def _invoke() -> mcp.types.CallToolResult:
+ async with AsyncExitStack() as stack:
+ client = self._session
+ if self._client_gen:
+ client = await stack.enter_async_context(
+ self._client_gen(),
+ )
+ if isinstance(client, tuple):
+ warnings.warn(
+ "MCPTool client_gen yielding transport tuples "
+ "is deprecated; yield a connected mcp.Client "
+ "instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ client = await stack.enter_async_context(
+ mcp.ClientSession(client[0], client[1]),
+ )
+ await client.initialize()
+ return await client.call_tool(
+ self._tool.name,
+ arguments=kwargs,
+ read_timeout_seconds=self._timeout,
+ progress_callback=_on_progress,
+ )
+
+ call_task = asyncio.create_task(_invoke())
+ progress_task: asyncio.Task[ToolChunk] | None = None
+ try:
+ while not call_task.done():
+ progress_task = asyncio.create_task(progress_queue.get())
+ done, _ = await asyncio.wait(
+ {call_task, progress_task},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if progress_task in done:
+ yield progress_task.result()
+ progress_task = None
+ else:
+ progress_task.cancel()
+ try:
+ await progress_task
+ except asyncio.CancelledError:
+ pass
+ progress_task = None
+
+ accepting_progress = False
+ while not progress_queue.empty():
+ yield progress_queue.get_nowait()
+ result = await call_task
+
+ content = self._convert_mcp_content_to_blocks(result.content)
+ if result.structured_content is not None and not any(
+ isinstance(block, TextBlock) for block in content
+ ):
+ content.append(
+ TextBlock(
+ text=json.dumps(
+ result.structured_content,
+ ensure_ascii=False,
+ ),
),
+ )
+
+ yield ToolChunk(
+ content=content,
+ state=(
+ ToolResultState.ERROR
+ if result.is_error
+ else ToolResultState.RUNNING
),
+ is_last=True,
)
-
- return ToolChunk(
- content=content,
- state=ToolResultState.ERROR
- if result.is_error
- else ToolResultState.RUNNING,
- )
+ finally:
+ accepting_progress = False
+ # Repeated AnyIO cancellation must not interrupt the SDK's
+ # cancellation notification while we wait for its cleanup.
+ with anyio.CancelScope(shield=True):
+ if progress_task is not None and not progress_task.done():
+ progress_task.cancel()
+ try:
+ await progress_task
+ except asyncio.CancelledError:
+ pass
+ if not call_task.done():
+ call_task.cancel()
+ try:
+ await call_task
+ except asyncio.CancelledError:
+ pass
@staticmethod
def _convert_mcp_content_to_blocks(
mcp_content_blocks: list,
) -> list[TextBlock | DataBlock]:
- """Convert MCP content to AgentScope blocks.
-
- Args:
- mcp_content_blocks (`list`):
- The MCP content blocks to convert.
-
- Returns:
- `list[TextBlock | DataBlock]`: Converted AgentScope blocks.
- """
-
- as_content = []
+ """Convert MCP content directly to AgentScope message blocks."""
+ blocks: list[TextBlock | DataBlock] = []
for content in mcp_content_blocks:
if isinstance(content, mcp.types.TextContent):
- as_content.append(TextBlock(text=content.text))
+ blocks.append(TextBlock(text=content.text))
elif isinstance(
content,
(mcp.types.ImageContent, mcp.types.AudioContent),
):
- as_content.append(
+ blocks.append(
DataBlock(
source=Base64Source(
- type="base64",
media_type=content.mime_type,
data=content.data,
),
),
)
-
elif isinstance(content, mcp.types.EmbeddedResource):
if isinstance(
content.resource,
mcp.types.TextResourceContents,
):
- as_content.append(
+ blocks.append(
TextBlock(
- text=content.resource.model_dump_json(indent=2),
+ text=content.resource.model_dump_json(
+ indent=2,
+ ),
),
)
else:
logger.error(
- "Unsupported EmbeddedResource content type: %s. "
- "Skipping this content.",
+ "Unsupported EmbeddedResource content type: %s.",
type(content.resource),
)
-
- elif isinstance(content, mcp.types.ResourceContents):
- as_content.append(
+ elif isinstance(
+ content,
+ (mcp.types.ResourceLink, mcp.types.ResourceContents),
+ ):
+ media_type = content.mime_type
+ if isinstance(content, mcp.types.ResourceLink):
+ media_type = media_type or "application/octet-stream"
+ try:
+ url = AnyUrl(str(content.uri))
+ except ValidationError:
+ message = (
+ f"<unconvertible MCP resource URI: {content.uri}>"
+ )
+ logger.warning(message)
+ blocks.append(TextBlock(text=message))
+ continue
+ blocks.append(
DataBlock(
- source=URLSource(
- media_type=content.mime_type,
- url=content.uri,
- ),
+ source=URLSource(media_type=media_type, url=url),
),
)
-
else:
logger.warning(
"Unsupported content type: %s. Skipping this content.",
type(content),
)
- return as_content
+ return blocks
diff --git a/src/agentscope/tool/_response.py b/src/agentscope/tool/_response.py
index 999e284e7..c77e5dde2 100644
--- a/src/agentscope/tool/_response.py
+++ b/src/agentscope/tool/_response.py
@@ -41,7 +41,8 @@ class ToolChunk(BaseModel):
metadata: dict = Field(default_factory=dict)
"""The metadata to be accessed within the agent, so that we don't need to
- parse the tool result block."""
+ parse the tool result block. The reserved ``mcp_progress`` key carries
+ transient progress and is not accumulated into ``ToolResponse``."""
id: str = Field(default_factory=_generate_id)
"""The identity of the tool chunk."""
@@ -54,7 +55,8 @@ class ToolResponse(BaseModel):
content: List[TextBlock | DataBlock] = Field(default_factory=list)
"""The completed tool result data blocks."""
- state: Literal[
+ # Incremental mypy checks may skip the imported enum definition.
+ state: Literal[ # type: ignore[valid-type]
ToolResultState.ERROR,
ToolResultState.DENIED,
ToolResultState.INTERRUPTED,
@@ -146,7 +148,13 @@ class ToolResponse(BaseModel):
):
self.state = ToolResultState.DENIED
- self.metadata.update(chunk.metadata)
+ self.metadata.update(
+ {
+ key: value
+ for key, value in chunk.metadata.items()
+ if key != "mcp_progress"
+ },
+ )
# Post-processing: merge consecutive TextBlocks
# DataBlocks are kept separate and only merged by explicit id matching
diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.py
index f08980ff8..4b6de307e 100644
--- a/src/agentscope/workspace/_gateway_client.py
+++ b/src/agentscope/workspace/_gateway_client.py
@@ -178,8 +178,8 @@ class GatewayMCPClient(MCPClient):
from user input via :meth:`GatewayClient.make_client`). The local
MCP machinery is short-circuited entirely:
- * ``model_post_init`` does nothing (parent's ``_initialize_client``
- is never called — no stdio context manager is built).
+ * ``model_post_init`` skips local configuration validation; no local
+ transport is constructed by the proxy.
* ``connect`` registers the MCP on the gateway via ``POST /mcps``.
* ``close`` deregisters via ``DELETE /mcps/{name}``.
* ``set_runtime_headers`` updates the registered live client.
@@ -191,9 +191,7 @@ class GatewayMCPClient(MCPClient):
_session_id: str = PrivateAttr(default="")
def model_post_init(self, __context: Any) -> None:
- """No-op — the parent builds local stdio/HTTP transport, which
- the gateway-relayed client does not need.
- """
+ """Leave configuration validation to the gateway-side MCP client."""
return
# ── lifecycle ─────────────────────────────────────────────────
diff --git a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py
index 2c70f6bd2..76b68f870 100644
--- a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py
+++ b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py
@@ -214,6 +214,8 @@ def _build_app(
arguments = body.get("arguments") or {}
try:
tool_obj = await client.get_tool(tool)
+ # Sandbox calls return only the final result in this gateway.
+ tool_obj.stream_progress = False
chunk = await tool_obj(**arguments)
except ValueError as e:
raise HTTPException(404, str(e)) from e
diff --git a/tests/event_to_message_test.py b/tests/event_to_message_test.py
index 3fdc7c7c5..50a5e4d29 100644
--- a/tests/event_to_message_test.py
+++ b/tests/event_to_message_test.py
@@ -31,6 +31,7 @@ from utils import AnyString
from agentscope.event import (
ConfirmResult,
+ CustomEvent,
DataBlockDeltaEvent,
DataBlockEndEvent,
DataBlockStartEvent,
@@ -992,6 +993,27 @@ class EventToMessageTest(IsolatedAsyncioTestCase):
msg=f"Mismatch after event[{idx}] ({event.type})",
)
+ async def test_custom_events_are_skipped(self) -> None:
+ """Custom notifications must not modify the accumulated message."""
+ original_dump = self.msg.model_dump()
+ events = [
+ CustomEvent(name="state_updated"),
+ CustomEvent(
+ name="mcp_progress",
+ value={
+ "reply_id": _REPLY_ID,
+ "tool_call_id": _TC_ALLOW,
+ "progress": 1,
+ "total": 2,
+ "message": "Processing",
+ },
+ ),
+ ]
+ for event in events:
+ with self.subTest(name=event.name):
+ self.assertIs(self.msg.append_event(event), self.msg)
+ self.assertDictEqual(self.msg.model_dump(), original_dump)
+
async def test_wrong_reply_id_is_skipped(self) -> None:
"""An event whose reply_id does not match msg.id must be ignored."""
original_dump = self.msg.model_dump()
diff --git a/tests/mcp_client_reconnect_test.py b/tests/mcp_client_reconnect_test.py
index 9977d5322..3d2d7b605 100644
--- a/tests/mcp_client_reconnect_test.py
+++ b/tests/mcp_client_reconnect_test.py
@@ -34,16 +34,30 @@ class _OneShotTransport:
return False
-class _FakeSession:
- """Small ClientSession stand-in for lifecycle-only tests."""
+class _FakeClient:
+ """Small MCP 2.x Client stand-in for lifecycle-only tests."""
- def __init__(self, read_stream: object, write_stream: object) -> None:
- self.read_stream = read_stream
- self.write_stream = write_stream
+ def __init__(
+ self,
+ transport: _OneShotTransport,
+ *,
+ mode: str,
+ ) -> None:
+ self.transport = transport
+ self.mode = mode
self.exit_count = 0
-
- async def __aenter__(self) -> "_FakeSession":
- """Enter the fake session context."""
+ self._entered = False
+
+ async def __aenter__(self) -> "_FakeClient":
+ """Enter the fake client and clean partial connections on failure."""
+ await self.transport.__aenter__()
+ self._entered = True
+ try:
+ await self.connect()
+ except BaseException:
+ await self.transport.__aexit__(None, None, None)
+ self._entered = False
+ raise
return self
async def __aexit__(
@@ -52,15 +66,55 @@ class _FakeSession:
exc: BaseException | None,
traceback: TracebackType | None,
) -> bool:
- """Leave the fake session context."""
+ """Leave the fake client context."""
self.exit_count += 1
+ if self._entered:
+ await self.transport.__aexit__(exc_type, exc, traceback)
+ self._entered = False
return False
- async def initialize(self) -> None:
- """Initialize the fake session."""
+ async def connect(self) -> None:
+ """Hook used by failure and cancellation tests."""
return None
+class _TaskBoundClient(_FakeClient):
+ """Client that requires context entry and exit in the same task."""
+
+ instance: "_TaskBoundClient | None" = None
+
+ def __init__(
+ self,
+ transport: _OneShotTransport,
+ *,
+ mode: str,
+ ) -> None:
+ super().__init__(transport, mode=mode)
+ self.enter_task: asyncio.Task[Any] | None = None
+ self.exit_task: asyncio.Task[Any] | None = None
+ _TaskBoundClient.instance = self
+
+ async def __aenter__(self) -> "_TaskBoundClient":
+ """Record the task that owns the client context."""
+ self.enter_task = asyncio.current_task()
+ await super().__aenter__()
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> bool:
+ """Reject the AnyIO-invalid cross-task context exit."""
+ self.exit_task = asyncio.current_task()
+ if self.exit_task is not self.enter_task:
+ raise RuntimeError(
+ "Attempted to exit cancel scope in a different task",
+ )
+ return await super().__aexit__(exc_type, exc, traceback)
+
+
class MCPClientReconnectTest(IsolatedAsyncioTestCase):
"""Stateful MCP transports must be recreated for every connection."""
@@ -78,8 +132,8 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
"agentscope.mcp._mcp_client.stdio_client",
side_effect=create_transport,
), patch(
- "agentscope.mcp._mcp_client.ClientSession",
- _FakeSession,
+ "agentscope.mcp._mcp_client.SDKClient",
+ _FakeClient,
):
client = MCPClient(
name="reconnect_stdio",
@@ -95,6 +149,45 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
self.assertEqual(len(transports), 2)
self.assertTrue(all(_.enter_count == 1 for _ in transports))
+ async def test_client_context_is_closed_by_its_owner_task(self) -> None:
+ """Connect and close requests may run in different caller tasks."""
+ transport = _OneShotTransport()
+ with patch(
+ "agentscope.mcp._mcp_client.stdio_client",
+ return_value=transport,
+ ), patch(
+ "agentscope.mcp._mcp_client.SDKClient",
+ _TaskBoundClient,
+ ):
+ client = MCPClient(
+ name="task_bound",
+ is_stateful=True,
+ mcp_config=StdioMCPConfig(command="unused"),
+ )
+
+ connect_task = asyncio.create_task(client.connect())
+ await connect_task
+ close_task = asyncio.create_task(client.close())
+ await close_task
+
+ sdk_client = _TaskBoundClient.instance
+ assert sdk_client is not None
+ self.assertIs(sdk_client.enter_task, sdk_client.exit_task)
+ self.assertIsNot(sdk_client.enter_task, connect_task)
+ self.assertIsNot(sdk_client.exit_task, close_task)
+ self.assertEqual(
+ {
+ "transport_enters": transport.enter_count,
+ "transport_exits": transport.exit_count,
+ "client_exits": sdk_client.exit_count,
+ },
+ {
+ "transport_enters": 1,
+ "transport_exits": 1,
+ "client_exits": 1,
+ },
+ )
+
async def test_failed_connect_can_be_retried(self) -> None:
"""A failed connection must discard its one-shot transport."""
transports: list[_OneShotTransport] = []
@@ -105,22 +198,22 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
transports.append(transport)
return transport
- class _FailOnceSession(_FakeSession):
- """Fail the first initialization, then allow a retry."""
+ class _FailOnceClient(_FakeClient):
+ """Fail the first connection, then allow a retry."""
attempts = 0
- async def initialize(self) -> None:
- _FailOnceSession.attempts += 1
- if _FailOnceSession.attempts == 1:
+ async def connect(self) -> None:
+ _FailOnceClient.attempts += 1
+ if _FailOnceClient.attempts == 1:
raise RuntimeError("initialization failed")
with patch(
"agentscope.mcp._mcp_client.stdio_client",
side_effect=create_transport,
), patch(
- "agentscope.mcp._mcp_client.ClientSession",
- _FailOnceSession,
+ "agentscope.mcp._mcp_client.SDKClient",
+ _FailOnceClient,
):
client = MCPClient(
name="retry_after_failed_connect",
@@ -148,32 +241,33 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
transports.append(transport)
return transport
- class _BlockingSession(_FakeSession):
- """Block initialization until the test cancels the connection."""
+ class _BlockingClient(_FakeClient):
+ """Block connection until the test cancels it."""
- instance: "_BlockingSession | None" = None
+ instance: "_BlockingClient | None" = None
attempts = 0
def __init__(
self,
- read_stream: object,
- write_stream: object,
+ transport: _OneShotTransport,
+ *,
+ mode: str,
) -> None:
- super().__init__(read_stream, write_stream)
- _BlockingSession.instance = self
+ super().__init__(transport, mode=mode)
+ _BlockingClient.instance = self
- async def initialize(self) -> None:
- _BlockingSession.attempts += 1
+ async def connect(self) -> None:
+ _BlockingClient.attempts += 1
initialize_started.set()
- if _BlockingSession.attempts == 1:
+ if _BlockingClient.attempts == 1:
await never_finish.wait()
with patch(
"agentscope.mcp._mcp_client.stdio_client",
side_effect=create_transport,
), patch(
- "agentscope.mcp._mcp_client.ClientSession",
- _BlockingSession,
+ "agentscope.mcp._mcp_client.SDKClient",
+ _BlockingClient,
):
client = MCPClient(
name="cancelled_connect",
@@ -187,11 +281,11 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
with self.assertRaises(asyncio.CancelledError):
await task
- session = _BlockingSession.instance
- assert session is not None
+ sdk_client = _BlockingClient.instance
+ assert sdk_client is not None
self.assertFalse(client.is_connected)
self.assertEqual(transports[0].exit_count, 1)
- self.assertEqual(session.exit_count, 1)
+ self.assertEqual(sdk_client.exit_count, 0)
await client.connect()
await client.close()
@@ -219,10 +313,10 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
transport_closed.set()
return False
- class _BlockingSession(_FakeSession):
- """Never finish initializing, so the scope cancels mid-connect."""
+ class _BlockingClient(_FakeClient):
+ """Never finish connecting, so the scope cancels mid-connect."""
- async def initialize(self) -> None:
+ async def connect(self) -> None:
initialize_started.set()
await asyncio.Event().wait()
@@ -231,8 +325,8 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
"agentscope.mcp._mcp_client.stdio_client",
return_value=transport,
), patch(
- "agentscope.mcp._mcp_client.ClientSession",
- _BlockingSession,
+ "agentscope.mcp._mcp_client.SDKClient",
+ _BlockingClient,
):
client = MCPClient(
name="cancel_scope",
@@ -272,8 +366,8 @@ class MCPClientReconnectTest(IsolatedAsyncioTestCase):
"_create_http_client",
side_effect=create_transport,
), patch(
- "agentscope.mcp._mcp_client.ClientSession",
- _FakeSession,
+ "agentscope.mcp._mcp_client.SDKClient",
+ _FakeClient,
):
client = MCPClient(
name="reconnect_http",
diff --git a/tests/mcp_progress_test.py b/tests/mcp_progress_test.py
new file mode 100644
index 000000000..cc8f36418
--- /dev/null
+++ b/tests/mcp_progress_test.py
@@ -0,0 +1,1168 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Tests for local MCP progress and sandbox final-result compatibility."""
+import asyncio
+import json
+import unittest
+import warnings
+from itertools import product
+from typing import Any
+from unittest.mock import AsyncMock, Mock, patch
+
+import anyio
+from fastapi.testclient import TestClient
+from mcp.types import (
+ CallToolResult,
+ ImageContent,
+ ResourceLink,
+ TextContent,
+ Tool,
+)
+from utils import AnyString, MockModel
+
+from agentscope.agent import Agent, InjectionConfig
+from agentscope.event import (
+ CustomEvent,
+ ToolResultEndEvent,
+ ToolResultStartEvent,
+ ToolResultTextDeltaEvent,
+)
+from agentscope.message import (
+ TextBlock,
+ ToolCallBlock,
+ ToolResultState,
+ UserMsg,
+)
+from agentscope.mcp import MCPClient
+from agentscope.model import ChatResponse
+from agentscope.state import AgentState
+from agentscope.tool import (
+ MCPTool,
+ ToolChunk,
+ ToolResponse,
+ ToolMiddlewareBase,
+ Toolkit,
+)
+from agentscope.workspace._gateway_client import (
+ GatewayClient,
+ GatewayMCPTool,
+)
+from agentscope.workspace._mcp_gateway._mcp_gateway_app import (
+ _build_app,
+ _State,
+)
+
+
+def _chunk_view(chunk: ToolChunk) -> dict[str, Any]:
+ """Return a deterministic full view without generated identifiers."""
+ return {
+ "content": [
+ block.model_dump(
+ mode="json",
+ exclude={"id", "created_at", "finished_at"},
+ )
+ for block in chunk.content
+ ],
+ "state": chunk.state,
+ "is_last": chunk.is_last,
+ "metadata": chunk.metadata,
+ }
+
+
+class _ProgressClient:
+ """MCP client stand-in that reports progress before its final result."""
+
+ def __init__(self) -> None:
+ self.cancelled = asyncio.Event()
+ self.call: dict[str, Any] = {}
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any],
+ read_timeout_seconds: float | None,
+ progress_callback: Any,
+ ) -> CallToolResult:
+ """Emit two progress notifications and one final text result."""
+ self.call = {
+ "name": name,
+ "arguments": arguments,
+ "read_timeout_seconds": read_timeout_seconds,
+ }
+ await progress_callback(1.0, 2.0, "first")
+ await progress_callback(2.0, 2.0, "second")
+ return CallToolResult(
+ content=[TextContent(type="text", text="done")],
+ is_error=False,
+ )
+
+
+class _BlockingProgressClient(_ProgressClient):
+ """MCP client stand-in that blocks until its call is cancelled."""
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any],
+ read_timeout_seconds: float | None,
+ progress_callback: Any,
+ ) -> CallToolResult:
+ """Emit one update, then expose cancellation to the test."""
+ await progress_callback(1.0, None, "waiting")
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ self.cancelled.set()
+ raise
+
+
+class _CleanupProgressClient(_ProgressClient):
+ """Model the SDK's shielded asynchronous cancellation notification."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.started = asyncio.Event()
+ self.cleanup_completed = False
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any],
+ read_timeout_seconds: float | None,
+ progress_callback: Any,
+ ) -> CallToolResult:
+ """Block until cancelled, then simulate a delayed cancel write."""
+ self.started.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ self.cancelled.set()
+ with anyio.CancelScope(shield=True):
+ await anyio.sleep(0.02)
+ self.cleanup_completed = True
+ raise
+
+
+class _FailingProgressClient(_ProgressClient):
+ """MCP client stand-in that fails after reporting progress."""
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any],
+ read_timeout_seconds: float | None,
+ progress_callback: Any,
+ ) -> CallToolResult:
+ """Emit one update before raising a tool execution error."""
+ await progress_callback(1.0, 2.0, "first")
+ raise RuntimeError("tool failed")
+
+
+class _ResourceLinkClient(_ProgressClient):
+ """MCP client stand-in returning a link without a MIME type."""
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any],
+ read_timeout_seconds: float | None,
+ progress_callback: Any,
+ ) -> CallToolResult:
+ """Return one valid resource link without reporting progress."""
+ return CallToolResult(
+ content=[
+ ResourceLink(
+ name="download",
+ uri="https://example.com/file",
+ ),
+ ],
+ is_error=False,
+ )
+
+
+class _RegisteredClient:
+ """Gateway registry stand-in returning an AgentScope MCP tool."""
+
+ def __init__(self, client: _ProgressClient) -> None:
+ self.client = client
+
+ async def get_tool(self, name: str) -> MCPTool:
+ """Wrap the SDK stand-in using the real MCP adapter."""
+ if name != "work":
+ raise ValueError(f"Unknown tool {name!r}.")
+ return MCPTool(
+ mcp_name="remote",
+ tool=Tool(name=name, input_schema={"type": "object"}),
+ session=self.client,
+ )
+
+
+class _GatewayFacade:
+ """Host-side gateway stand-in returning one final result."""
+
+ def __init__(self, final: ToolChunk) -> None:
+ self.requests: list[tuple[str, str, dict[str, Any]]] = []
+ self.responses = [
+ (
+ 200,
+ json.dumps({"chunk": final.model_dump(mode="json")}).encode(),
+ ),
+ ]
+
+ async def exec_request(
+ self,
+ method: str,
+ path: str,
+ **kwargs: Any,
+ ) -> tuple[int, bytes]:
+ """Record a single gateway request and return its result."""
+ self.requests.append((method, path, kwargs))
+ return self.responses.pop(0)
+
+
+def _make_tool(client: Any, *, stream_progress: bool = True) -> MCPTool:
+ """Build one MCP tool around a supplied client stand-in."""
+ return MCPTool(
+ mcp_name="remote",
+ tool=Tool(
+ name="work",
+ description="Work with progress.",
+ input_schema={
+ "type": "object",
+ "properties": {"value": {"type": "integer"}},
+ "required": ["value"],
+ },
+ ),
+ session=client,
+ timeout=7.0,
+ stream_progress=stream_progress,
+ )
+
+
+class MCPProgressTest(unittest.IsolatedAsyncioTestCase):
+ """MCP progress must remain transient and ordered."""
+
+ async def test_client_gen_compatibility(self) -> None:
+ """Accept connected clients and legacy two/three-item transports."""
+ for streaming, transport_size in product((False, True), (0, 2, 3)):
+ with self.subTest(streaming=streaming, size=transport_size):
+ sdk = _ProgressClient()
+ session = AsyncMock()
+ session.__aenter__.return_value = session
+ session.call_tool.side_effect = sdk.call_tool
+ streams = tuple(object() for _ in range(transport_size))
+ transport = AsyncMock()
+ transport.__aenter__.return_value = streams or session
+ factory = Mock(return_value=transport)
+ tool = MCPTool(
+ mcp_name="remote",
+ tool=Tool(name="work", input_schema={}),
+ client_gen=factory,
+ stream_progress=streaming,
+ )
+ with (
+ patch(
+ "agentscope.tool._adapters.mcp.ClientSession",
+ return_value=session,
+ ) as session_class,
+ warnings.catch_warnings(record=True) as caught,
+ ):
+ warnings.simplefilter("always", DeprecationWarning)
+ result = await tool(value=3)
+ chunks = (
+ [chunk async for chunk in result]
+ if streaming
+ else [result]
+ )
+
+ self.assertEqual(
+ [_chunk_view(chunk) for chunk in chunks],
+ (
+ [
+ {
+ "content": [],
+ "state": ToolResultState.RUNNING,
+ "is_last": False,
+ "metadata": {
+ "mcp_progress": {
+ "progress": progress,
+ "total": 2.0,
+ "message": message,
+ },
+ },
+ }
+ for progress, message in (
+ (1.0, "first"),
+ (2.0, "second"),
+ )
+ ]
+ if streaming
+ else []
+ )
+ + [
+ {
+ "content": [{"type": "text", "text": "done"}],
+ "state": ToolResultState.RUNNING,
+ "is_last": True,
+ "metadata": {},
+ },
+ ],
+ )
+ self.assertEqual(
+ [warning.category for warning in caught],
+ [DeprecationWarning] if transport_size else [],
+ )
+ if transport_size:
+ self.assertIn(
+ "connected mcp.Client",
+ str(caught[0].message),
+ )
+ session_class.assert_called_once_with(*streams[:2])
+ session.initialize.assert_awaited_once_with()
+ session.__aexit__.assert_awaited_once()
+ else:
+ session_class.assert_not_called()
+ session.initialize.assert_not_awaited()
+ factory.assert_called_once_with()
+ transport.__aenter__.assert_awaited_once()
+ transport.__aexit__.assert_awaited_once()
+
+ async def test_default_calls_return_final_chunks(self) -> None:
+ """Old direct calls keep returning a result without opting in."""
+ for entry in ("__call__", "call"):
+ with self.subTest(entry=entry):
+ sdk = _ProgressClient()
+ tool = MCPTool(
+ mcp_name="remote",
+ tool=Tool(name="work", input_schema={}),
+ session=sdk,
+ )
+ result = await getattr(tool, entry)(value=3)
+ self.assertIsInstance(result, ToolChunk)
+ self.assertEqual(
+ _chunk_view(result),
+ {
+ "content": [{"type": "text", "text": "done"}],
+ "state": ToolResultState.RUNNING,
+ "is_last": True,
+ "metadata": {},
+ },
+ )
+ self.assertFalse(tool.stream_progress)
+ self.assertEqual(
+ sdk.call,
+ {
+ "name": "work",
+ "arguments": {"value": 3},
+ "read_timeout_seconds": None,
+ },
+ )
+
+ async def test_client_progress_configuration_reaches_tools(self) -> None:
+ """Progress settings survive serialization and tool wrapping."""
+ for setting in (None, False, True):
+ for stateful in (False, True):
+ with self.subTest(setting=setting, stateful=stateful):
+ spec = {
+ "name": "remote",
+ "is_stateful": stateful,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://example.com/mcp",
+ },
+ }
+ if setting is not None:
+ spec["stream_progress"] = setting
+ client = MCPClient.model_validate(spec)
+ serialized = client.model_dump(mode="json")
+ restored = MCPClient.model_validate(serialized)
+ flags = []
+ for current in (client, restored):
+ current._cached_tools = [
+ Tool(name="work", input_schema={}),
+ ]
+ current._is_connected = True
+ current._client = _ProgressClient()
+ tool = await current.get_tool("work")
+ flags.append(tool.stream_progress)
+ expected = setting is True
+ self.assertEqual(
+ {
+ "serialized": serialized["stream_progress"],
+ "tools": flags,
+ },
+ {
+ "serialized": expected,
+ "tools": [expected, expected],
+ },
+ )
+
+ async def test_agent_streams_progress_without_persisting_it(self) -> None:
+ """Only local tools expose progress to sequential/concurrent agents."""
+ final = ToolChunk(
+ content=[TextBlock(text="done")],
+ metadata={"source": "tool", "trace_id": "trace"},
+ )
+
+ class _Metadata(ToolMiddlewareBase):
+ """Add ordinary metadata without changing progress delivery."""
+
+ async def on_tool_call( # pylint: disable=unused-argument
+ self,
+ tool: Any,
+ input_kwargs: dict,
+ next_handler: Any,
+ ) -> Any:
+ """Attach metadata while forwarding the tool's chunks."""
+ async for chunk in next_handler(**input_kwargs):
+ chunk.metadata["trace_id"] = "trace"
+ if chunk.is_last:
+ chunk.metadata["source"] = "tool"
+ yield chunk
+
+ for path in ("local", "gateway"):
+ for concurrent, stream_progress in (
+ (False, False),
+ (False, True),
+ (True, False),
+ (True, True),
+ ):
+ with self.subTest(
+ path=path,
+ concurrent=concurrent,
+ stream_progress=stream_progress,
+ ):
+ if path == "local":
+ tool = _make_tool(_ProgressClient())
+ tool._middlewares = [_Metadata()]
+ expected_progress = [
+ {
+ "progress": 1.0,
+ "total": 2.0,
+ "message": "first",
+ },
+ {
+ "progress": 2.0,
+ "total": 2.0,
+ "message": "second",
+ },
+ ]
+ else:
+ tool = GatewayMCPTool(
+ mcp_name="remote",
+ tool=Tool(
+ name="work",
+ input_schema={
+ "type": "object",
+ },
+ ),
+ gateway=_GatewayFacade(final),
+ agent_id="agent",
+ session_id="session",
+ )
+ expected_progress = []
+ if path == "local":
+ tool.stream_progress = stream_progress
+ if not stream_progress:
+ expected_progress = []
+ tool.is_read_only = True
+ tool.is_concurrency_safe = concurrent
+ tool_call = ToolCallBlock(
+ id="call-1",
+ name=tool.name,
+ input='{"value": 3}',
+ )
+ model = MockModel()
+ model.set_responses(
+ [
+ ChatResponse(content=[tool_call], is_last=True),
+ ChatResponse(
+ content=[TextBlock(text="finished")],
+ is_last=True,
+ ),
+ ],
+ )
+ agent = Agent(
+ name="progress",
+ system_prompt="Test progress.",
+ model=model,
+ toolkit=Toolkit(tools=[tool]),
+ injection_config=InjectionConfig(
+ inject_runtime_state=False,
+ ),
+ )
+ events = [
+ event
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content="Run the tool."),
+ )
+ ]
+ reply_id = agent.state.reply_id
+ expected_metadata = {
+ "trace_id": "trace",
+ "source": "tool",
+ }
+ base = {"metadata": {}}
+ self.assertEqual(
+ [
+ event.model_dump(exclude={"id", "created_at"})
+ for event in events
+ if isinstance(
+ event,
+ (
+ CustomEvent,
+ ToolResultStartEvent,
+ ToolResultTextDeltaEvent,
+ ToolResultEndEvent,
+ ),
+ )
+ ],
+ [
+ {
+ **base,
+ "type": "TOOL_RESULT_START",
+ "reply_id": reply_id,
+ "tool_call_id": "call-1",
+ "tool_call_name": tool.name,
+ },
+ *[
+ {
+ **base,
+ "type": "CUSTOM",
+ "name": "mcp_progress",
+ "value": {
+ **update,
+ "reply_id": reply_id,
+ "tool_call_id": "call-1",
+ },
+ }
+ for update in expected_progress
+ ],
+ {
+ **base,
+ "type": "TOOL_RESULT_TEXT_DELTA",
+ "reply_id": reply_id,
+ "tool_call_id": "call-1",
+ "delta": "done",
+ },
+ {
+ "type": "TOOL_RESULT_END",
+ "reply_id": reply_id,
+ "tool_call_id": "call-1",
+ "state": "success",
+ "metadata": expected_metadata,
+ },
+ ],
+ )
+ results = [
+ block
+ for msg in agent.state.context
+ for block in msg.content
+ if block.type == "tool_result"
+ ]
+ self.assertEqual(
+ [block.model_dump() for block in results],
+ [
+ {
+ "type": "tool_result",
+ "id": "call-1",
+ "name": tool.name,
+ "state": "success",
+ "created_at": AnyString(),
+ "finished_at": None,
+ "metadata": expected_metadata,
+ "output": [
+ {
+ "type": "text",
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ "text": "done",
+ },
+ ],
+ },
+ ],
+ )
+
+ async def test_terminal_responses_do_not_accumulate_progress(self) -> None:
+ """Failure and interruption cannot retain transient progress data."""
+ for error in (RuntimeError("failed"), asyncio.CancelledError()):
+ with self.subTest(error=type(error).__name__):
+ client = _ProgressClient()
+
+ async def _invoke(
+ *_args: Any,
+ call_error: BaseException = error,
+ **kwargs: Any,
+ ) -> Any:
+ await kwargs["progress_callback"](1.0, None, "working")
+ raise call_error
+
+ client.call_tool = AsyncMock(side_effect=_invoke)
+ tool = _make_tool(client)
+ toolkit = Toolkit(tools=[tool])
+ chunks = [
+ chunk
+ async for chunk in toolkit.call_tool(
+ ToolCallBlock(
+ id="call-1",
+ name=tool.name,
+ input='{"value": 3}',
+ ),
+ AgentState(),
+ )
+ ]
+ self.assertEqual(
+ [chunk.metadata for chunk in chunks],
+ [
+ {
+ "mcp_progress": {
+ "progress": 1.0,
+ "total": None,
+ "message": "working",
+ },
+ },
+ {},
+ {},
+ ],
+ )
+ self.assertEqual(
+ chunks[-1].state,
+ (
+ ToolResultState.ERROR
+ if isinstance(error, RuntimeError)
+ else ToolResultState.INTERRUPTED
+ ),
+ )
+
+ async def test_local_progress_is_not_model_content(self) -> None:
+ """Progress chunks stream, but only the result becomes content."""
+ client = _ProgressClient()
+ tool = _make_tool(client)
+
+ stream = await tool(value=3)
+ chunks = [chunk async for chunk in stream]
+
+ self.assertEqual(
+ [_chunk_view(chunk) for chunk in chunks],
+ [
+ {
+ "content": [],
+ "state": ToolResultState.RUNNING,
+ "is_last": False,
+ "metadata": {
+ "mcp_progress": {
+ "progress": 1.0,
+ "total": 2.0,
+ "message": "first",
+ },
+ },
+ },
+ {
+ "content": [],
+ "state": ToolResultState.RUNNING,
+ "is_last": False,
+ "metadata": {
+ "mcp_progress": {
+ "progress": 2.0,
+ "total": 2.0,
+ "message": "second",
+ },
+ },
+ },
+ {
+ "content": [{"type": "text", "text": "done"}],
+ "state": ToolResultState.RUNNING,
+ "is_last": True,
+ "metadata": {},
+ },
+ ],
+ )
+ response = ToolResponse()
+ for chunk in chunks:
+ response.append_chunk(chunk)
+ self.assertEqual(
+ {
+ "content": [
+ block.model_dump(
+ mode="json",
+ exclude={"id", "created_at", "finished_at"},
+ )
+ for block in response.content
+ ],
+ "state": response.state,
+ "metadata": response.metadata,
+ "call": client.call,
+ },
+ {
+ "content": [{"type": "text", "text": "done"}],
+ "state": ToolResultState.SUCCESS,
+ "metadata": {},
+ "call": {
+ "name": "work",
+ "arguments": {"value": 3},
+ "read_timeout_seconds": 7.0,
+ },
+ },
+ )
+
+ async def test_calls_preserve_middleware_interception(self) -> None:
+ """Local MCP tools respect middleware with or without progress."""
+ expected = ToolChunk(content=[TextBlock(text="blocked")])
+
+ class _Block(ToolMiddlewareBase):
+ """Return a result without calling the upstream tool."""
+
+ async def on_tool_call( # pylint: disable=unused-argument
+ self,
+ tool: Any,
+ input_kwargs: Any,
+ next_handler: Any,
+ ) -> Any:
+ """Short-circuit execution with the prepared result."""
+ yield expected
+
+ sdk = _ProgressClient()
+ tool = _make_tool(sdk)
+ for stream_progress in (False, True):
+ tool.stream_progress = stream_progress
+ tool._middlewares = [_Block()]
+ chunks = [chunk async for chunk in await tool(value=3)]
+ self.assertEqual(
+ [chunk.model_dump() for chunk in chunks],
+ [expected.model_dump()],
+ )
+ self.assertEqual(sdk.call, {})
+
+ async def test_local_progress_buffer_retains_latest_snapshots(
+ self,
+ ) -> None:
+ """A paused consumer retains bounded progress and the final result."""
+ resume = asyncio.Event()
+ flooded = asyncio.Event()
+
+ class _Flood(_ProgressClient):
+ """Emit many updates while the consumer is paused."""
+
+ async def call_tool(
+ self,
+ name: str,
+ arguments: dict[str, Any],
+ read_timeout_seconds: float | None,
+ progress_callback: Any,
+ ) -> CallToolResult:
+ await progress_callback(0, None, "start")
+ await resume.wait()
+ for value in range(1, 3001):
+ await progress_callback(value, 3000, None)
+ flooded.set()
+ return CallToolResult(
+ content=[TextContent(type="text", text="done")],
+ )
+
+ stream = await _make_tool(_Flood())()
+ try:
+ first = await anext(stream)
+ resume.set()
+ await asyncio.wait_for(flooded.wait(), 2)
+ chunks = [chunk async for chunk in stream]
+ finally:
+ await stream.aclose()
+ self.assertEqual(
+ {
+ "first": first.metadata["mcp_progress"]["progress"],
+ "retained": [
+ chunk.metadata["mcp_progress"]["progress"]
+ for chunk in chunks[:-1]
+ ],
+ "final": _chunk_view(chunks[-1]),
+ },
+ {
+ "first": 0,
+ "retained": list(range(1977, 3001)),
+ "final": {
+ "content": [{"type": "text", "text": "done"}],
+ "state": ToolResultState.RUNNING,
+ "is_last": True,
+ "metadata": {},
+ },
+ },
+ )
+
+ async def test_resource_link_without_mime_type_uses_fallback(self) -> None:
+ """A valid MCP resource link may omit its MIME type."""
+ tool = _make_tool(_ResourceLinkClient(), stream_progress=False)
+
+ result = await tool(value=3)
+
+ self.assertEqual(
+ [
+ block.model_dump(
+ mode="json",
+ exclude={"id", "created_at", "finished_at"},
+ )
+ for block in result.content
+ ],
+ [
+ {
+ "type": "data",
+ "source": {
+ "type": "url",
+ "url": "https://example.com/file",
+ "media_type": "application/octet-stream",
+ },
+ "name": None,
+ },
+ ],
+ )
+
+ async def test_invalid_resource_uri_preserves_other_content(self) -> None:
+ """Local and gateway conversions isolate invalid resource URLs."""
+ for uri in ("reports/q3.pdf", "http://[broken"):
+ with self.subTest(uri=uri):
+ result = CallToolResult(
+ content=[
+ TextContent(type="text", text="before"),
+ ResourceLink(name="report", uri=uri),
+ ResourceLink(
+ name="valid",
+ uri="https://example.com/file",
+ ),
+ TextContent(type="text", text="after"),
+ ],
+ )
+ client = _ProgressClient()
+ with patch.object(
+ client,
+ "call_tool",
+ new=AsyncMock(return_value=result),
+ ):
+ local = await _make_tool(client, stream_progress=False)()
+ state = _State()
+ state.clients[("", "")] = {
+ "remote": _RegisteredClient(client),
+ }
+ with TestClient(_build_app(state)) as http:
+ response = http.post(
+ "/mcps/remote/tools/work",
+ json={"arguments": {}},
+ )
+ self.assertEqual(response.status_code, 200)
+ gateway = ToolChunk.model_validate(
+ response.json()["chunk"],
+ )
+ expected = {
+ "content": [
+ {"type": "text", "text": "before"},
+ {
+ "type": "text",
+ "text": f"<unconvertible MCP resource URI: {uri}>",
+ },
+ {
+ "type": "data",
+ "source": {
+ "type": "url",
+ "url": "https://example.com/file",
+ "media_type": "application/octet-stream",
+ },
+ "name": None,
+ },
+ {"type": "text", "text": "after"},
+ ],
+ "state": ToolResultState.RUNNING,
+ "is_last": True,
+ "metadata": {},
+ }
+ self.assertEqual(
+ {
+ "local": _chunk_view(local),
+ "gateway": _chunk_view(gateway),
+ },
+ {"local": expected, "gateway": expected},
+ )
+
+ async def test_gateway_ignores_progress_setting(self) -> None:
+ """Sandbox tools make one request and always return the final chunk."""
+ final = ToolChunk(content=[TextBlock(text="done")])
+ for setting in (False, True):
+ with self.subTest(stream_progress=setting):
+ gateway = GatewayClient(
+ backend=object(), # type: ignore[arg-type]
+ gateway_port=5600,
+ )
+ proxy = gateway.make_client(
+ {
+ "name": "remote",
+ "is_stateful": True,
+ "stream_progress": setting,
+ "mcp_config": {
+ "type": "http_mcp",
+ "url": "https://example.com/mcp",
+ },
+ },
+ agent_id="agent",
+ session_id="session",
+ connected=True,
+ )
+ facade = _GatewayFacade(final)
+ proxy._gateway = facade
+ proxy._cached_tools = [Tool(name="work", input_schema={})]
+ tool = await proxy.get_tool("work")
+ result = await tool(value=3)
+ self.assertEqual(result.model_dump(), final.model_dump())
+ self.assertEqual(
+ facade.requests,
+ [
+ (
+ "POST",
+ "/mcps/remote/tools/work",
+ {
+ "params": {
+ "agent_id": "agent",
+ "session_id": "session",
+ },
+ "body": {"arguments": {"value": 3}},
+ },
+ ),
+ ],
+ )
+
+ async def test_anyio_cancellation_preserves_sdk_cleanup(self) -> None:
+ """Finish SDK cleanup before propagating an AnyIO cancellation."""
+ for stream_progress, connection in product(
+ (False, True),
+ ("session", "client", "transport"),
+ ):
+ with (
+ self.subTest(
+ stream_progress=stream_progress,
+ connection=connection,
+ ),
+ patch(
+ "agentscope.tool._adapters.mcp.ClientSession",
+ ) as session_class,
+ warnings.catch_warnings(record=True) as caught,
+ ):
+ warnings.simplefilter("always", DeprecationWarning)
+ client = _CleanupProgressClient()
+ tool = _make_tool(client, stream_progress=stream_progress)
+ session = AsyncMock()
+ session.__aenter__.return_value = session
+ session.call_tool.side_effect = client.call_tool
+ session_class.return_value = session
+ transport = AsyncMock()
+ transport.__aenter__.return_value = (
+ (object(), object())
+ if connection == "transport"
+ else session
+ )
+ if connection != "session":
+ tool._session = None
+ tool._client_gen = Mock(return_value=transport)
+ async with anyio.create_task_group() as tasks:
+ with anyio.CancelScope() as scope:
+
+ async def cancel_call(
+ started: asyncio.Event,
+ cancel_scope: anyio.CancelScope,
+ ) -> None:
+ """Cancel only after the SDK call has started."""
+ await started.wait()
+ cancel_scope.cancel()
+
+ tasks.start_soon(cancel_call, client.started, scope)
+ if stream_progress:
+ stream = await tool(value=3)
+ async for _ in stream:
+ pass
+ else:
+ await tool(value=3)
+
+ self.assertEqual(
+ {
+ "call_cancelled": client.cancelled.is_set(),
+ "cleanup_completed": client.cleanup_completed,
+ "cancel_propagated": scope.cancelled_caught,
+ },
+ {
+ "call_cancelled": True,
+ "cleanup_completed": True,
+ "cancel_propagated": True,
+ },
+ )
+ self.assertEqual(
+ [warning.category for warning in caught],
+ [DeprecationWarning] if connection == "transport" else [],
+ )
+ if connection != "session":
+ transport.__aexit__.assert_awaited_once()
+ if connection == "transport":
+ session.__aexit__.assert_awaited_once()
+
+ async def test_closing_local_stream_cancels_mcp_call(self) -> None:
+ """Closing a progress stream cancels its in-flight MCP request."""
+ client = _BlockingProgressClient()
+ tool = _make_tool(client)
+
+ stream = await tool(value=3)
+ first = await anext(stream)
+ await stream.aclose()
+
+ self.assertEqual(
+ {
+ "first": _chunk_view(first),
+ "cancelled": client.cancelled.is_set(),
+ },
+ {
+ "first": {
+ "content": [],
+ "state": ToolResultState.RUNNING,
+ "is_last": False,
+ "metadata": {
+ "mcp_progress": {
+ "progress": 1.0,
+ "total": None,
+ "message": "waiting",
+ },
+ },
+ },
+ "cancelled": True,
+ },
+ )
+
+
+class GatewayResultRouteTest(unittest.TestCase):
+ """The in-workspace gateway returns only final tool results."""
+
+ def test_gateway_routes_preserve_structured_results(self) -> None:
+ """The final-result route retains structured-only and mixed results."""
+ structured = {"city": "Paris", "temperature_c": 21.5}
+ text = {
+ "type": "text",
+ "text": '{"city": "Paris", "temperature_c": 21.5}',
+ }
+ cases = [
+ (
+ CallToolResult(content=[], structured_content=structured),
+ [text],
+ ),
+ (
+ CallToolResult(content=[], structured_content={}),
+ [
+ {"type": "text", "text": "{}"},
+ ],
+ ),
+ (
+ CallToolResult(content=[], structured_content={"city": "北京"}),
+ [
+ {"type": "text", "text": '{"city": "北京"}'},
+ ],
+ ),
+ (
+ CallToolResult(
+ content=[TextContent(type="text", text="existing")],
+ structured_content=structured,
+ ),
+ [{"type": "text", "text": "existing"}],
+ ),
+ (
+ CallToolResult(
+ content=[
+ ImageContent(
+ type="image",
+ data="aW1hZ2U=",
+ mime_type="image/png",
+ ),
+ ],
+ structured_content=structured,
+ ),
+ [
+ {
+ "type": "data",
+ "source": {
+ "type": "base64",
+ "data": "aW1hZ2U=",
+ "media_type": "image/png",
+ },
+ "name": None,
+ },
+ text,
+ ],
+ ),
+ (
+ CallToolResult(
+ content=[],
+ structured_content={"error": "unknown city"},
+ is_error=True,
+ ),
+ [{"type": "text", "text": '{"error": "unknown city"}'}],
+ ),
+ (CallToolResult(content=[]), []),
+ ]
+ for result, expected_content in cases:
+ with self.subTest(result=result):
+ state = _State()
+ registered = _RegisteredClient(_ProgressClient())
+ state.clients[("agent", "session")] = {
+ "remote": registered, # type: ignore[dict-item]
+ }
+ params = {"agent_id": "agent", "session_id": "session"}
+ expected = {
+ "content": expected_content,
+ "state": "error" if result.is_error else "running",
+ "is_last": True,
+ "metadata": {},
+ }
+ with (
+ patch.object(
+ registered.client,
+ "call_tool",
+ new=AsyncMock(return_value=result),
+ ),
+ TestClient(_build_app(state)) as client,
+ ):
+ direct = client.post(
+ "/mcps/remote/tools/work",
+ params=params,
+ json={"arguments": {}},
+ )
+ self.assertEqual(
+ (
+ direct.status_code,
+ {
+ "chunk": _chunk_view(
+ ToolChunk.model_validate(
+ direct.json()["chunk"],
+ ),
+ ),
+ },
+ ),
+ (200, {"chunk": expected}),
+ )
+
+ def test_gateway_discards_progress_when_enabled_on_client(self) -> None:
+ """A streaming client still yields a final-only gateway response."""
+ sdk = _ProgressClient()
+ state = _State()
+ tool = _make_tool(sdk, stream_progress=True)
+ registered = _RegisteredClient(sdk)
+ state.clients[("", "")] = {"remote": registered}
+ with (
+ patch.object(registered, "get_tool", AsyncMock(return_value=tool)),
+ TestClient(_build_app(state)) as client,
+ ):
+ response = client.post(
+ "/mcps/remote/tools/work",
+ json={"arguments": {"value": 3}},
+ )
+ self.assertEqual(response.status_code, 200)
+ result = ToolChunk.model_validate(response.json()["chunk"])
+ self.assertEqual(
+ _chunk_view(result),
+ {
+ "content": [{"type": "text", "text": "done"}],
+ "state": ToolResultState.RUNNING,
+ "is_last": True,
+ "metadata": {},
+ },
+ )
diff --git a/tests/mcp_runtime_headers_test.py b/tests/mcp_runtime_headers_test.py
index b355208b3..67fb702be 100644
--- a/tests/mcp_runtime_headers_test.py
+++ b/tests/mcp_runtime_headers_test.py
@@ -240,6 +240,7 @@ class MCPRuntimeHeadersTest(IsolatedAsyncioTestCase):
"enable_tools": None,
"disable_tools": None,
"execution_timeout": None,
+ "stream_progress": False,
},
)
@@ -457,6 +458,7 @@ class GatewayMCPClientRuntimeHeadersTest(IsolatedAsyncioTestCase):
"enable_tools": None,
"disable_tools": None,
"execution_timeout": None,
+ "stream_progress": False,
},
)
@@ -492,6 +494,7 @@ class GatewayMCPClientRuntimeHeadersTest(IsolatedAsyncioTestCase):
"enable_tools": None,
"disable_tools": None,
"execution_timeout": None,
+ "stream_progress": False,
"runtime_headers": {"Authorization": "Bearer runtime"},
},
)
diff --git a/tests/mcp_sse_client_test.py b/tests/mcp_sse_client_test.py
index cf82bca7c..621a8e253 100644
--- a/tests/mcp_sse_client_test.py
+++ b/tests/mcp_sse_client_test.py
@@ -129,9 +129,9 @@ 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])
- res_3: ToolChunk = await mcp_tool_1(arg1="345", arg2=[4, 5, 6])
+ res_1 = await mcp_tool_1(arg1="123", arg2=[1, 2, 3])
+ res_2 = await mcp_tool_1(arg1="345", arg2=[4, 5, 6])
+ res_3 = await mcp_tool_1(arg1="345", arg2=[4, 5, 6])
self.assertEqual(
res_1.content[0].text,
@@ -217,9 +217,9 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):
mcp_tool_1 = await stateful_client.get_tool("tool_1")
# Repeat to ensure idempotency
- res_1: ToolChunk = await mcp_tool_1(arg1="12", arg2=[1, 2])
- res_2: ToolChunk = await mcp_tool_1(arg1="34", arg2=[4, 5])
- res_3: ToolChunk = await mcp_tool_1(arg1="34", arg2=[4, 5])
+ res_1 = await mcp_tool_1(arg1="12", arg2=[1, 2])
+ res_2 = await mcp_tool_1(arg1="34", arg2=[4, 5])
+ res_3 = await mcp_tool_1(arg1="34", arg2=[4, 5])
self.assertEqual(
res_1.content[0].text,
@@ -293,7 +293,7 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):
shape for key-based SSE MCP servers, e.g. the Amap MCP at
https://mcp.amap.com/sse?key=API_KEY). Such URLs were misdetected as
streamable HTTP, and the client then failed to handshake against the
- SSE server with ``McpError: Session terminated``.
+ SSE server with ``MCPError: Session terminated``.
After the fix, only the URL path is inspected, so the query string no
longer affects transport detection.
@@ -308,7 +308,7 @@ class SseMCPClientTest(IsolatedAsyncioTestCase):
)
mcp_tool_1 = await client.get_tool("tool_1")
- res: ToolChunk = await mcp_tool_1(arg1="123", arg2=[1, 2, 3])
+ res = await mcp_tool_1(arg1="123", arg2=[1, 2, 3])
self.assertEqual(
res.content[0].text,
"arg1: 123, arg2: [1, 2, 3]",
diff --git a/tests/mcp_streamable_http_client_test.py b/tests/mcp_streamable_http_client_test.py
index ef2bdd62f..8fbfe222f 100644
--- a/tests/mcp_streamable_http_client_test.py
+++ b/tests/mcp_streamable_http_client_test.py
@@ -8,7 +8,6 @@ from mcp.server import MCPServer
from mcp.types import EmbeddedResource, TextResourceContents
from agentscope.mcp import MCPClient, HttpMCPConfig
-from agentscope.tool import ToolChunk
async def tool_1(arg1: str, arg2: list[int]) -> str:
@@ -79,13 +78,13 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):
)
my_tool_1 = await client.get_tool("tool_1")
- res_1: ToolChunk = await my_tool_1(arg1="123", arg2=[1, 2, 3])
+ res_1 = await my_tool_1(arg1="123", arg2=[1, 2, 3])
self.assertEqual(
res_1.content[0].text,
"arg1: 123, arg2: [1, 2, 3]",
)
- res_2: ToolChunk = await my_tool_1(arg1="345", arg2=[4, 5, 6])
+ res_2 = await my_tool_1(arg1="345", arg2=[4, 5, 6])
self.assertEqual(
res_2.content[0].text,
"arg1: 345, arg2: [4, 5, 6]",
@@ -107,13 +106,13 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):
self.assertTrue(client.is_connected)
my_tool_1 = await client.get_tool("tool_1")
- res_3: ToolChunk = await my_tool_1(arg1="12", arg2=[1, 2])
+ res_3 = await my_tool_1(arg1="12", arg2=[1, 2])
self.assertEqual(
res_3.content[0].text,
"arg1: 12, arg2: [1, 2]",
)
- res_4: ToolChunk = await my_tool_1(arg1="34", arg2=[4, 5])
+ res_4 = await my_tool_1(arg1="34", arg2=[4, 5])
self.assertEqual(
res_4.content[0].text,
"arg1: 34, arg2: [4, 5]",
@@ -135,7 +134,7 @@ class StreamableHttpMCPClientTest(IsolatedAsyncioTestCase):
)
my_tool_2 = await client.get_tool("tool_2")
- res: ToolChunk = await my_tool_2()
+ res = await my_tool_2()
self.assertEqual(
res.content[0].text,
"""{
diff --git a/tests/mcp_tool_result_test.py b/tests/mcp_tool_result_test.py
index 31559387b..8f8ad1656 100644
--- a/tests/mcp_tool_result_test.py
+++ b/tests/mcp_tool_result_test.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""Tests for keeping the MCP tool result content that carries the payload."""
import base64
+import json
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
@@ -25,6 +26,7 @@ class _FakeSession:
name: str,
arguments: dict[str, Any] | None = None,
read_timeout_seconds: float | None = None,
+ progress_callback: Any | None = None,
) -> mcp.types.CallToolResult:
"""Record the call and return the prepared result."""
self.calls.append((name, arguments or {}))
@@ -61,6 +63,43 @@ class MCPStructuredResultTest(IsolatedAsyncioTestCase):
"""The model must not lose a result that only lives in
``structuredContent``."""
+ async def test_embedded_resource_preserves_json_field_names(self) -> None:
+ """Embedded resource text retains snake-case fields and metadata."""
+ resource = {
+ "uri": "https://example.com/report.txt",
+ "mime_type": "text/plain",
+ "meta": {"source": "report"},
+ "text": "Report content",
+ }
+ chunk = await _tool(
+ mcp.types.CallToolResult(
+ content=[
+ mcp.types.EmbeddedResource(
+ type="resource",
+ resource=mcp.types.TextResourceContents(**resource),
+ ),
+ ],
+ ),
+ )()
+ self.assertEqual(
+ chunk.model_dump(),
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": json.dumps(resource, indent=2),
+ "id": AnyString(),
+ "created_at": AnyString(),
+ "finished_at": None,
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
async def test_structured_result_is_kept_when_content_is_empty(
self,
) -> None:
@@ -71,7 +110,7 @@ class MCPStructuredResultTest(IsolatedAsyncioTestCase):
content=[],
structured_content=structured,
),
- ).call(city="Paris")
+ )(city="Paris")
self.assertEqual(
chunk.model_dump(),
diff --git a/tests/workspace_bubblewrap_test.py b/tests/workspace_bubblewrap_test.py
index 76f5d9762..01a7e54f5 100644
--- a/tests/workspace_bubblewrap_test.py
+++ b/tests/workspace_bubblewrap_test.py
@@ -1053,7 +1053,8 @@ class TestBubblewrapWorkspace(CheckoutWheelTestCase):
self.assertGreater(len(tools), 0)
tool = await mcps[0].get_tool("get_current_time")
result = await tool(timezone="Asia/Tokyo")
- self.assertIsNotNone(result)
+ self.assertTrue(result.is_last)
+ self.assertGreater(len(result.content), 0)
@unittest.skipUnless(
diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.py
index eed3bbe22..ac5227f96 100644
--- a/tests/workspace_daytona_test.py
+++ b/tests/workspace_daytona_test.py
@@ -1180,6 +1180,7 @@ class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):
"enable_tools": None,
"disable_tools": None,
"execution_timeout": None,
+ "stream_progress": False,
},
],
},