From 5d32c1bd3d23dafa1e1ab0b8db654a640143e4ba Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 13:55:18 +0100 Subject: [PATCH 01/18] Added helper for page fetch and better method isolation. using tenacity for retry logic --- python/packages/core/agent_framework/_mcp.py | 97 ++++++++++++-------- 1 file changed, 57 insertions(+), 40 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index e3ca013f908..8a02d415aaf 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -3113,7 +3113,6 @@ async def load_tools(self) -> None: await self._load_tools_locked() async def _load_tools_locked(self) -> None: - from anyio import ClosedResourceError from mcp import types if not self._supports_tools: @@ -3138,47 +3137,10 @@ async def _load_tools_locked(self) -> None: params: types.PaginatedRequestParams | None = None while True: - tool_list: types.ListToolsResult | None = None - for attempt in range(2): - try: - # Ensure connection is still valid before each page request - await self._ensure_connected() - if not self._supports_tools: - logger.debug("Skipping MCP tool loading because the server did not advertise tools support.") - return - with create_mcp_client_span( - "tools/list", - attributes=self._mcp_base_span_attributes(), - capture_unhandled_exceptions=False, - ) as list_span: - try: - tool_list = await self._require_connection().list_tools_page(params) - except Exception as list_ex: - set_mcp_span_error(list_span, type(list_ex).__name__, str(list_ex)) - raise - break - except ClosedResourceError as cl_ex: - if attempt == 0: - await self._recover_connection_after_loss( - operation="tool discovery", - inner_exception=cl_ex, - load_configured=False, - ) - continue - _log_mcp_exception( - logging.ERROR, - cl_ex, - "MCP connection closed unexpectedly after reconnection: %s", - cl_ex, - redacted_message="MCP tool discovery connection closed after reconnection", - ) - raise _mcp_tool_execution_exception( - "Failed to load tools - connection lost.", - inner_exception=cl_ex, - ) from cl_ex + tool_list = await self._try_list_tools_page_with_recovery(params) if tool_list is None: - raise _mcp_tool_execution_exception("Failed to load tools.") + return for tool in tool_list.tools: task_support = getattr(getattr(tool, "execution", None), "task_support", None) @@ -3285,6 +3247,61 @@ async def _load_tools_locked(self) -> None: self._tool_param_names_by_name = tool_param_names_by_name self._progressive_loaded_tool_names.difference_update(existing_tools.keys() - reused_tool_names) + async def _try_list_tools_page_with_recovery( + self, params: types.PaginatedRequestParams | None + ) -> types.ListToolsResult | None: + """Fetches a page of tools retrying on connection failure.""" + from anyio import ClosedResourceError + from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt + + async def recover_connection(retry_state: RetryCallState) -> None: + outcome = retry_state.outcome + exception = outcome.exception() if outcome else None + + if not isinstance(exception, ClosedResourceError): + return + + await self._recover_connection_after_loss( + operation="tool discovery", inner_exception=exception, load_configured=False + ) + + @retry( + retry=retry_if_exception_type(ClosedResourceError), + stop=stop_after_attempt(2), + before_sleep=recover_connection, + reraise=True, + ) + async def request_page() -> types.ListToolsResult | None: + await self._ensure_connected() + + if not self._supports_tools: + logger.debug("Skipping MCP tool loading because the server did not advertise tools support.") + return None + + with create_mcp_client_span( + "tools/list", attributes=self._mcp_base_span_attributes(), capture_unhandled_exceptions=False + ) as list_span: + try: + return await self._require_connection().list_tools_page(params) + except Exception as exc: + set_mcp_span_error(list_span, type(exc).__name__, str(exc)) + raise + + try: + return await request_page() + except ClosedResourceError as exc: + _log_mcp_exception( + logging.ERROR, + exc, + "MCP connection closed unexpectedly after reconnection: %s", + exc, + redacted_message="MCP tool discovery connection closed after reconnection", + ) + raise _mcp_tool_execution_exception( + "Failed to load tools - connection lost.", + inner_exception=exc, + ) from exc + async def _cancel_pending_reload_tasks(self) -> None: """Cancel session-bound discovery reloads and wait for them to finish.""" tasks = list(self._pending_reload_tasks) From 37bd4437fd3e8a2254bf320f6d00ec7e126e1c4f Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 13:58:08 +0100 Subject: [PATCH 02/18] inbetween page fetch failure test and double connection failure test --- python/packages/core/tests/core/test_mcp.py | 70 +++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 0284baeb5ae..18cb5d1e854 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -9284,6 +9284,76 @@ async def reconnect() -> None: second_session.list_tools.assert_awaited_once() +async def test_load_tools_retries_continuation_page_after_closed_resource() -> None: + from anyio import ClosedResourceError + + tool = MCPTool(name="test_tool", load_tools=True) # type: ignore[abstract] # ty: ignore[call-non-callable] + tool._ping_available = False + + first_page = types.ListToolsResult( + tools=[types.Tool(name="first", input_schema={"type": "object", "properties": {}})], + next_cursor="second", + ) + + async def list_tools(params: types.PaginatedRequestParams | None = None) -> types.ListToolsResult: + if params is None: + return first_page + assert params.cursor == "second" + raise ClosedResourceError + + first_session = Mock() + first_session.list_tools = AsyncMock(side_effect=list_tools) + _set_framework_owned_session(tool, first_session) + + second_page = types.ListToolsResult( + tools=[types.Tool(name="second", input_schema={"type": "object", "properties": {}})] + ) + second_session = Mock() + second_session.list_tools = AsyncMock(return_value=second_page) + + async def reconnect() -> None: + tool.session = second_session + tool._supports_tools = True + + with patch.object(tool, "_reconnect_without_loading", AsyncMock(side_effect=reconnect)) as mock_reconnect: + await tool.load_tools() + + assert [function.name for function in tool.functions] == ["first", "second"] + assert first_session.list_tools.await_count == 2 + mock_reconnect.assert_awaited_once_with() + continuation_params = second_session.list_tools.await_args.kwargs["params"] + assert continuation_params.cursor == "second" + + +async def test_load_tools_fails_after_closed_resource_retry_is_exhausted() -> None: + from anyio import ClosedResourceError + + tool = MCPTool(name="test_tool", load_tools=True) # type: ignore[abstract] # ty: ignore[call-non-callable] + tool._ping_available = False + + first_session = Mock() + first_session.list_tools = AsyncMock(side_effect=ClosedResourceError()) + _set_framework_owned_session(tool, first_session) + + second_session = Mock() + second_session.list_tools = AsyncMock(side_effect=ClosedResourceError()) + + async def reconnect() -> None: + tool.session = second_session + tool._supports_tools = True + + with ( + patch.object(tool, "_reconnect_without_loading", AsyncMock(side_effect=reconnect)) as mock_reconnect, + pytest.raises(ToolExecutionException, match="Failed to load tools - connection lost"), + ): + await tool.load_tools() + + first_session.list_tools.assert_awaited_once() + mock_reconnect.assert_awaited_once_with() + second_session.list_tools.assert_awaited_once() + assert tool.functions == [] + + async def test_load_prompts_reconnects_on_closed_resource_when_ping_is_unavailable() -> None: from anyio import ClosedResourceError From 4b344e12a9861442948c423033bf5675f01054b9 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 14:16:30 +0100 Subject: [PATCH 03/18] Added page limit check to prevent unbounded fetch --- python/packages/core/agent_framework/_mcp.py | 46 ++++++++++++++++---- python/packages/core/tests/core/test_mcp.py | 43 ++++++++++++++++++ 2 files changed, 80 insertions(+), 9 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 8a02d415aaf..5232e195bbb 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -250,6 +250,8 @@ class MCPSpecificApproval(TypedDict, total=False): MCP_DEFAULT_SSE_READ_TIMEOUT = 60 * 5 _MCP_SUBSCRIPTION_RETRY_INITIAL_DELAY = 0.1 _MCP_SUBSCRIPTION_RETRY_MAX_DELAY = 2.0 + +_DEFAULT_MCP_DISCOVERY_MAX_PAGES = 100 _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES = 1024 * 1024 @@ -1181,6 +1183,7 @@ def __init__( use_progressive_disclosure: bool = False, always_load: Collection[str] | None = None, *, + max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", ) -> None: @@ -1205,6 +1208,8 @@ def __init__( object_name="MCP progressive disclosure", category=ExperimentalWarning, ) + if max_discovery_pages is not None and max_discovery_pages <= 0: + raise ValueError("max_discovery_pages must be positive or None.") if max_host_payload_size_bytes is not None and max_host_payload_size_bytes <= 0: raise ValueError("max_host_payload_size_bytes must be positive or None.") if request_timeout is not None and request_timeout <= 0: @@ -1233,6 +1238,7 @@ def __init__( self.tool_result_content = tool_result_content self.load_prompts_flag = load_prompts self.parse_prompt_results = parse_prompt_results + self._max_discovery_pages = max_discovery_pages self.max_host_payload_size_bytes = max_host_payload_size_bytes self._exit_stack = AsyncExitStack() self._lifecycle_lock = asyncio.Lock() @@ -3135,13 +3141,12 @@ async def _load_tools_locked(self) -> None: tool_param_names_by_name: dict[str, set[str]] = {} tool_annotations_by_name: dict[str, Any] = {} - params: types.PaginatedRequestParams | None = None - while True: - tool_list = await self._try_list_tools_page_with_recovery(params) - - if tool_list is None: - return + tool_list = await self._try_list_tools_page_with_recovery(None) + if tool_list is None: + return + pages_loaded = 1 + while True: for tool in tool_list.tools: task_support = getattr(getattr(tool, "execution", None), "task_support", None) if task_support == "required": @@ -3219,10 +3224,21 @@ async def _load_tools_locked(self) -> None: ) new_functions.append(func) - # Check if there are more pages - if not tool_list.next_cursor: + if tool_list.next_cursor is None: break - params = types.PaginatedRequestParams(cursor=tool_list.next_cursor) + + if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: + raise _mcp_tool_execution_exception( + f"MCP tool discovery reached the configured maximum of " + f"{self._max_discovery_pages} pages before the server completed pagination." + ) + + tool_list = await self._try_list_tools_page_with_recovery( + types.PaginatedRequestParams(cursor=tool_list.next_cursor) + ) + if tool_list is None: + return + pages_loaded += 1 current_functions = [ func @@ -3772,6 +3788,7 @@ def __init__( additional_properties: dict[str, Any] | None = None, task_options: Any | None = None, additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None, + max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", **kwargs: Any, @@ -3880,6 +3897,8 @@ def __init__( ``function_invocation_kwargs`` - for example through ``env`` - for servers whose process you do not control. task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. + max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. + ``None`` disables the limit. max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host transports. ``None`` disables the limit. tool_result_content: How to choose model-visible text when both ``content`` and @@ -3935,6 +3954,7 @@ def __init__( sampling_max_tokens=sampling_max_tokens, sampling_max_requests=sampling_max_requests, task_options=task_options, + max_discovery_pages=max_discovery_pages, max_host_payload_size_bytes=max_host_payload_size_bytes, tool_result_content=tool_result_content, ) @@ -4030,6 +4050,7 @@ def __init__( header_provider: Callable[[dict[str, Any]], dict[str, str]] | None = None, additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None, task_options: Any = None, + max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", **kwargs: Any, @@ -4209,6 +4230,8 @@ def __init__( still allows a different value per request), or configure a custom ``http_client``. task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. + max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. + ``None`` disables the limit. max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host transports. ``None`` disables the limit. tool_result_content: How to choose model-visible text when both ``content`` and @@ -4264,6 +4287,7 @@ def __init__( sampling_max_tokens=sampling_max_tokens, sampling_max_requests=sampling_max_requests, task_options=task_options, + max_discovery_pages=max_discovery_pages, max_host_payload_size_bytes=max_host_payload_size_bytes, tool_result_content=tool_result_content, ) @@ -4695,6 +4719,7 @@ def __init__( additional_properties: dict[str, Any] | None = None, additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None, task_options: Any = None, + max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", **kwargs: Any, @@ -4788,6 +4813,8 @@ def __init__( transport has no header hook, so source credentials outside ``function_invocation_kwargs`` for servers you do not control. task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. + max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. + ``None`` disables the limit. max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host transports. ``None`` disables the limit. tool_result_content: How to choose model-visible text when both ``content`` and @@ -4815,6 +4842,7 @@ def __init__( sampling_max_tokens=sampling_max_tokens, sampling_max_requests=sampling_max_requests, task_options=task_options, + max_discovery_pages=max_discovery_pages, max_host_payload_size_bytes=max_host_payload_size_bytes, tool_result_content=tool_result_content, ) diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 18cb5d1e854..7a6ce2e7861 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -319,6 +319,18 @@ def test_mcp_transport_subclasses_accept_tool_name_prefix() -> None: ) +def test_mcp_transport_subclasses_default_discovery_page_limit() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + tools = [ + MCPStdioTool(name="stdio", command="python"), + MCPStreamableHTTPTool(name="http", url="https://example.com/mcp"), + MCPWebsocketTool(name="websocket", url="wss://example.com/mcp"), # ty: ignore[deprecated] + ] + + assert all(tool._max_discovery_pages == 100 for tool in tools) + + @pytest.mark.parametrize("configured_name", ["search_docs", "docs_search_docs"]) async def test_load_tools_with_tool_name_prefix_preserves_matching_configuration(configured_name: str): """Prefixed MCP tool names should still honor unprefixed allow/approval configuration.""" @@ -6873,6 +6885,37 @@ async def mock_list_tools(params=None): assert [f.name for f in tool._functions] == ["tool_1", "tool_2", "tool_3", "tool_4"] +async def test_load_tools_rejects_catalog_exceeding_page_limit() -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_pages=2, + ) + mock_session = AsyncMock() + tool.session = mock_session + + async def list_tools(params: types.PaginatedRequestParams | None = None) -> types.ListToolsResult: + cursor = params.cursor if params is not None else None + if cursor is None: + return types.ListToolsResult( + tools=[types.Tool(name="first", input_schema={"type": "object", "properties": {}})], + next_cursor="second", + ) + if cursor == "second": + return types.ListToolsResult( + tools=[types.Tool(name="second", input_schema={"type": "object", "properties": {}})], + next_cursor="third", + ) + pytest.fail(f"Unexpected tools/list cursor: {cursor!r}") + + mock_session.list_tools = AsyncMock(side_effect=list_tools) + + with pytest.raises(ToolExecutionException, match="configured maximum of 2 pages"): + await tool.load_tools() + + assert mock_session.list_tools.await_count == 2 + assert tool.functions == [] + + async def test_load_tools_adds_properties_to_zero_arg_tool_schema(): """Test that load_tools normalizes inputSchema for zero-argument MCP tools. From 9edeb705d1b2190fb61ec0e8d2f52295b14d03bc Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 14:31:24 +0100 Subject: [PATCH 04/18] refactored tool page drain and tests --- python/packages/core/agent_framework/_mcp.py | 22 +++--- python/packages/core/tests/core/test_mcp.py | 77 ++++++++++++++++++++ 2 files changed, 88 insertions(+), 11 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 5232e195bbb..4660e5c6b9a 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -3141,12 +3141,7 @@ async def _load_tools_locked(self) -> None: tool_param_names_by_name: dict[str, set[str]] = {} tool_annotations_by_name: dict[str, Any] = {} - tool_list = await self._try_list_tools_page_with_recovery(None) - if tool_list is None: - return - pages_loaded = 1 - - while True: + def stage_tool_page(tool_list: types.ListToolsResult) -> None: for tool in tool_list.tools: task_support = getattr(getattr(tool, "execution", None), "task_support", None) if task_support == "required": @@ -3224,21 +3219,26 @@ async def _load_tools_locked(self) -> None: ) new_functions.append(func) - if tool_list.next_cursor is None: - break + tool_list = await self._try_list_tools_page_with_recovery(None) + if tool_list is None: + return + pages_loaded = 1 + stage_tool_page(tool_list) + cursor = tool_list.next_cursor + while cursor is not None: if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: raise _mcp_tool_execution_exception( f"MCP tool discovery reached the configured maximum of " f"{self._max_discovery_pages} pages before the server completed pagination." ) - tool_list = await self._try_list_tools_page_with_recovery( - types.PaginatedRequestParams(cursor=tool_list.next_cursor) - ) + tool_list = await self._try_list_tools_page_with_recovery(types.PaginatedRequestParams(cursor=cursor)) if tool_list is None: return pages_loaded += 1 + stage_tool_page(tool_list) + cursor = tool_list.next_cursor current_functions = [ func diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 7a6ce2e7861..9c69fe7c7d0 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -331,6 +331,31 @@ def test_mcp_transport_subclasses_default_discovery_page_limit() -> None: assert all(tool._max_discovery_pages == 100 for tool in tools) +def test_mcp_transport_subclasses_forward_discovery_page_limit() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + tools = [ + MCPStdioTool(name="stdio", command="python", max_discovery_pages=101), + MCPStreamableHTTPTool(name="http", url="https://example.com/mcp", max_discovery_pages=102), + MCPWebsocketTool( # ty: ignore[deprecated] + name="websocket", + url="wss://example.com/mcp", + max_discovery_pages=103, + ), + ] + + assert [tool._max_discovery_pages for tool in tools] == [101, 102, 103] + + +@pytest.mark.parametrize("max_discovery_pages", [0, -1]) +def test_mcp_tool_rejects_non_positive_discovery_page_limit(max_discovery_pages: int) -> None: + with pytest.raises(ValueError, match="max_discovery_pages must be positive or None"): + MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_pages=max_discovery_pages, + ) + + @pytest.mark.parametrize("configured_name", ["search_docs", "docs_search_docs"]) async def test_load_tools_with_tool_name_prefix_preserves_matching_configuration(configured_name: str): """Prefixed MCP tool names should still honor unprefixed allow/approval configuration.""" @@ -6916,6 +6941,58 @@ async def list_tools(params: types.PaginatedRequestParams | None = None) -> type assert tool.functions == [] +async def test_load_tools_accepts_catalog_completing_at_page_limit() -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_pages=2, + ) + mock_session = AsyncMock() + tool.session = mock_session + mock_session.list_tools = AsyncMock( + side_effect=[ + types.ListToolsResult( + tools=[types.Tool(name="first", input_schema={"type": "object", "properties": {}})], + next_cursor="second", + ), + types.ListToolsResult(tools=[types.Tool(name="second", input_schema={"type": "object", "properties": {}})]), + ] + ) + + await tool.load_tools() + + assert mock_session.list_tools.await_count == 2 + assert [function.name for function in tool.functions] == ["first", "second"] + + +async def test_load_tools_allows_unbounded_pagination_when_limit_is_none() -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_pages=None, + ) + mock_session = AsyncMock() + tool.session = mock_session + pages_served = 0 + + async def list_tools(params: types.PaginatedRequestParams | None = None) -> types.ListToolsResult: + nonlocal pages_served + if pages_served == 0: + assert params is None + else: + assert params is not None + assert params.cursor == str(pages_served) + + pages_served += 1 + next_cursor = str(pages_served) if pages_served < 101 else None + return types.ListToolsResult(tools=[], next_cursor=next_cursor) + + mock_session.list_tools = AsyncMock(side_effect=list_tools) + + await tool.load_tools() + + assert pages_served == 101 + assert mock_session.list_tools.await_count == 101 + + async def test_load_tools_adds_properties_to_zero_arg_tool_schema(): """Test that load_tools normalizes inputSchema for zero-argument MCP tools. From 455f290dcd658b5383fc953ee3369c8571fedeae Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 14:41:11 +0100 Subject: [PATCH 05/18] refactored prompt page list drain --- python/packages/core/agent_framework/_mcp.py | 127 +++++++++++-------- 1 file changed, 76 insertions(+), 51 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 4660e5c6b9a..ce77879fcd4 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -2977,7 +2977,6 @@ async def load_prompts(self) -> None: await self._load_prompts_locked() async def _load_prompts_locked(self) -> None: - from anyio import ClosedResourceError from mcp import types if not self._supports_prompts: @@ -2997,52 +2996,7 @@ async def _load_prompts_locked(self) -> None: retained_prompt_names: set[str] = set() new_functions: list[FunctionTool] = [] - params: types.PaginatedRequestParams | None = None - while True: - prompt_list: types.ListPromptsResult | None = None - for attempt in range(2): - try: - # Ensure connection is still valid before each page request - await self._ensure_connected() - if not self._supports_prompts: - logger.debug( - "Skipping MCP prompt loading because the server did not advertise prompts support." - ) - return - with create_mcp_client_span( - "prompts/list", - attributes=self._mcp_base_span_attributes(), - capture_unhandled_exceptions=False, - ) as list_span: - try: - prompt_list = await self._require_connection().list_prompts_page(params) - except Exception as list_ex: - set_mcp_span_error(list_span, type(list_ex).__name__, str(list_ex)) - raise - break - except ClosedResourceError as cl_ex: - if attempt == 0: - await self._recover_connection_after_loss( - operation="prompt discovery", - inner_exception=cl_ex, - load_configured=False, - ) - continue - _log_mcp_exception( - logging.ERROR, - cl_ex, - "MCP connection closed unexpectedly after reconnection: %s", - cl_ex, - redacted_message="MCP prompt discovery connection closed after reconnection", - ) - raise _mcp_tool_execution_exception( - "Failed to load prompts - connection lost.", - inner_exception=cl_ex, - ) from cl_ex - - if prompt_list is None: - raise _mcp_tool_execution_exception("Failed to load prompts.") - + def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: for prompt in prompt_list.prompts: normalized_name = _normalize_mcp_name(prompt.name) local_name = _build_prefixed_mcp_name(normalized_name, self.tool_name_prefix) @@ -3088,10 +3042,26 @@ async def _load_prompts_locked(self) -> None: prompt_functions.append(func) new_functions.append(func) - # Check if there are more pages - if not prompt_list.next_cursor: - break - params = types.PaginatedRequestParams(cursor=prompt_list.next_cursor) + prompt_list = await self._try_list_prompts_page_with_recovery(None) + if prompt_list is None: + return + pages_loaded = 1 + stage_prompt_page(prompt_list) + cursor = prompt_list.next_cursor + + while cursor is not None: + if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: + raise _mcp_tool_execution_exception( + f"MCP prompt discovery reached the configured maximum of " + f"{self._max_discovery_pages} pages before the server completed pagination." + ) + + prompt_list = await self._try_list_prompts_page_with_recovery(types.PaginatedRequestParams(cursor=cursor)) + if prompt_list is None: + return + pages_loaded += 1 + stage_prompt_page(prompt_list) + cursor = prompt_list.next_cursor current_functions = [func for func in self._functions if not _is_mcp_prompt_function(func)] current_functions.extend(prompt_functions) @@ -3104,6 +3074,61 @@ async def _load_prompts_locked(self) -> None: # different remote prompt that normalizes to the same local name must start unloaded. self._progressive_loaded_tool_names.difference_update(existing_prompts.keys() - retained_prompt_names) + async def _try_list_prompts_page_with_recovery( + self, params: types.PaginatedRequestParams | None + ) -> types.ListPromptsResult | None: + """Fetch a page of prompts, retrying after connection loss.""" + from anyio import ClosedResourceError + from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt + + async def recover_connection(retry_state: RetryCallState) -> None: + outcome = retry_state.outcome + exception = outcome.exception() if outcome else None + + if not isinstance(exception, ClosedResourceError): + return + + await self._recover_connection_after_loss( + operation="prompt discovery", inner_exception=exception, load_configured=False + ) + + @retry( + retry=retry_if_exception_type(ClosedResourceError), + stop=stop_after_attempt(2), + before_sleep=recover_connection, + reraise=True, + ) + async def request_page() -> types.ListPromptsResult | None: + await self._ensure_connected() + + if not self._supports_prompts: + logger.debug("Skipping MCP prompt loading because the server did not advertise prompts support.") + return None + + with create_mcp_client_span( + "prompts/list", attributes=self._mcp_base_span_attributes(), capture_unhandled_exceptions=False + ) as list_span: + try: + return await self._require_connection().list_prompts_page(params) + except Exception as exc: + set_mcp_span_error(list_span, type(exc).__name__, str(exc)) + raise + + try: + return await request_page() + except ClosedResourceError as exc: + _log_mcp_exception( + logging.ERROR, + exc, + "MCP connection closed unexpectedly after reconnection: %s", + exc, + redacted_message="MCP prompt discovery connection closed after reconnection", + ) + raise _mcp_tool_execution_exception( + "Failed to load prompts - connection lost.", + inner_exception=exc, + ) from exc + async def load_tools(self) -> None: """Load tools from the MCP server. From bd4e9f2ac2026a01e3274fb0662f5828cd3e2edb Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 14:43:30 +0100 Subject: [PATCH 06/18] Added tests for prompt load pagination --- python/packages/core/tests/core/test_mcp.py | 146 ++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 9c69fe7c7d0..24441510a7f 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -7146,6 +7146,88 @@ async def mock_list_prompts(params=None): assert [f.name for f in tool._functions] == ["prompt_1", "prompt_2", "prompt_3"] +async def test_load_prompts_rejects_catalog_exceeding_page_limit() -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_pages=2, + ) + mock_session = AsyncMock() + tool.session = mock_session + + async def list_prompts(params: types.PaginatedRequestParams | None = None) -> types.ListPromptsResult: + cursor = params.cursor if params is not None else None + if cursor is None: + return types.ListPromptsResult(prompts=[types.Prompt(name="first")], next_cursor="second") + if cursor == "second": + return types.ListPromptsResult(prompts=[types.Prompt(name="second")], next_cursor="third") + pytest.fail(f"Unexpected prompts/list cursor: {cursor!r}") + + mock_session.list_prompts = AsyncMock(side_effect=list_prompts) + + with pytest.raises(ToolExecutionException, match="configured maximum of 2 pages"): + await tool.load_prompts() + + assert mock_session.list_prompts.await_count == 2 + assert tool.functions == [] + + +async def test_load_prompts_accepts_catalog_completing_at_page_limit() -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_pages=2, + ) + mock_session = AsyncMock() + tool.session = mock_session + mock_session.list_prompts = AsyncMock( + side_effect=[ + types.ListPromptsResult(prompts=[types.Prompt(name="first")], next_cursor="second"), + types.ListPromptsResult(prompts=[types.Prompt(name="second")]), + ] + ) + + await tool.load_prompts() + + assert mock_session.list_prompts.await_count == 2 + assert [function.name for function in tool.functions] == ["first", "second"] + + +@pytest.mark.parametrize("catalog_kind", ["tools", "prompts"]) +async def test_catalog_discovery_follows_empty_string_cursor(catalog_kind: str) -> None: + tool = MCPTool(name="test_tool") # type: ignore[abstract] # ty: ignore[call-non-callable] + mock_session = AsyncMock() + tool.session = mock_session + + if catalog_kind == "tools": + + async def list_tools(params: types.PaginatedRequestParams | None = None) -> types.ListToolsResult: + if params is None: + return types.ListToolsResult( + tools=[types.Tool(name="first", input_schema={"type": "object", "properties": {}})], + next_cursor="", + ) + assert params.cursor == "" + return types.ListToolsResult( + tools=[types.Tool(name="second", input_schema={"type": "object", "properties": {}})] + ) + + mock_session.list_tools = AsyncMock(side_effect=list_tools) + await tool.load_tools() + assert mock_session.list_tools.await_count == 2 + else: + + async def list_prompts(params: types.PaginatedRequestParams | None = None) -> types.ListPromptsResult: + if params is None: + return types.ListPromptsResult(prompts=[types.Prompt(name="first")], next_cursor="") + assert params.cursor == "" + return types.ListPromptsResult(prompts=[types.Prompt(name="second")]) + + mock_session.list_prompts = AsyncMock(side_effect=list_prompts) + await tool.load_prompts() + assert mock_session.list_prompts.await_count == 2 + + assert [function.name for function in tool.functions] == ["first", "second"] + + async def test_load_tools_pagination_with_duplicates(): """Test that load_tools prevents duplicates across paginated results.""" from unittest.mock import AsyncMock, MagicMock @@ -9503,6 +9585,70 @@ async def reconnect() -> None: second_session.list_prompts.assert_awaited_once() +async def test_load_prompts_retries_continuation_page_after_closed_resource() -> None: + from anyio import ClosedResourceError + + tool = MCPTool(name="test_tool", load_prompts=True) # type: ignore[abstract] # ty: ignore[call-non-callable] + tool._ping_available = False + + first_page = types.ListPromptsResult(prompts=[types.Prompt(name="first")], next_cursor="second") + + async def list_prompts(params: types.PaginatedRequestParams | None = None) -> types.ListPromptsResult: + if params is None: + return first_page + assert params.cursor == "second" + raise ClosedResourceError + + first_session = Mock() + first_session.list_prompts = AsyncMock(side_effect=list_prompts) + _set_framework_owned_session(tool, first_session) + + second_session = Mock() + second_session.list_prompts = AsyncMock(return_value=types.ListPromptsResult(prompts=[types.Prompt(name="second")])) + + async def reconnect() -> None: + tool.session = second_session + tool._supports_prompts = True + + with patch.object(tool, "_reconnect_without_loading", AsyncMock(side_effect=reconnect)) as mock_reconnect: + await tool.load_prompts() + + assert [function.name for function in tool.functions] == ["first", "second"] + assert first_session.list_prompts.await_count == 2 + mock_reconnect.assert_awaited_once_with() + continuation_params = second_session.list_prompts.await_args.kwargs["params"] + assert continuation_params.cursor == "second" + + +async def test_load_prompts_fails_after_closed_resource_retry_is_exhausted() -> None: + from anyio import ClosedResourceError + + tool = MCPTool(name="test_tool", load_prompts=True) # type: ignore[abstract] # ty: ignore[call-non-callable] + tool._ping_available = False + + first_session = Mock() + first_session.list_prompts = AsyncMock(side_effect=ClosedResourceError()) + _set_framework_owned_session(tool, first_session) + + second_session = Mock() + second_session.list_prompts = AsyncMock(side_effect=ClosedResourceError()) + + async def reconnect() -> None: + tool.session = second_session + tool._supports_prompts = True + + with ( + patch.object(tool, "_reconnect_without_loading", AsyncMock(side_effect=reconnect)) as mock_reconnect, + pytest.raises(ToolExecutionException, match="Failed to load prompts - connection lost"), + ): + await tool.load_prompts() + + first_session.list_prompts.assert_awaited_once() + mock_reconnect.assert_awaited_once_with() + second_session.list_prompts.assert_awaited_once() + assert tool.functions == [] + + async def test_mcp_tool_filters_framework_kwargs(): """Test that call_tool filters out framework-specific kwargs before calling MCP session. From 41eb445c870dc1aa5a19943c5e6fc7ac2e500f34 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 14:54:22 +0100 Subject: [PATCH 07/18] unified page fetch logic into single generic method --- python/packages/core/agent_framework/_mcp.py | 115 ++++++++----------- 1 file changed, 50 insertions(+), 65 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index ce77879fcd4..0b112cb1da5 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -10,7 +10,7 @@ import sys import warnings from abc import abstractmethod -from collections.abc import Callable, Collection, Coroutine, Mapping, Sequence +from collections.abc import Awaitable, Callable, Collection, Coroutine, Mapping, Sequence from contextlib import AsyncExitStack, _AsyncGeneratorContextManager # type: ignore from contextvars import ContextVar from copy import copy @@ -18,7 +18,7 @@ from datetime import date, datetime from http.cookiejar import CookieJar, DefaultCookiePolicy from inspect import currentframe, isawaitable -from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias, TypedDict, cast +from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias, TypedDict, TypeVar, cast if sys.version_info >= (3, 13): from warnings import deprecated # pragma: no cover @@ -75,6 +75,8 @@ logger = logging.getLogger(__name__) +_MCPListResultT = TypeVar("_MCPListResultT") + def _mcp_exception_log_level() -> Literal[10] | None: """Return the automatic exception log level allowed by observability settings.""" @@ -3074,13 +3076,21 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: # different remote prompt that normalizes to the same local name must start unloaded. self._progressive_loaded_tool_names.difference_update(existing_prompts.keys() - retained_prompt_names) - async def _try_list_prompts_page_with_recovery( - self, params: types.PaginatedRequestParams | None - ) -> types.ListPromptsResult | None: - """Fetch a page of prompts, retrying after connection loss.""" + async def _try_list_page_with_recovery( + self, + params: types.PaginatedRequestParams | None, + *, + kind: Literal["tool", "prompt"], + is_supported: Callable[[], bool], + request_page: Callable[[types.PaginatedRequestParams | None], Awaitable[_MCPListResultT]], + ) -> _MCPListResultT | None: + """Fetch one catalog page, retrying after connection loss.""" from anyio import ClosedResourceError from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt + catalog_name = f"{kind}s" + operation = f"{kind} discovery" + async def recover_connection(retry_state: RetryCallState) -> None: outcome = retry_state.outcome exception = outcome.exception() if outcome else None @@ -3089,7 +3099,9 @@ async def recover_connection(retry_state: RetryCallState) -> None: return await self._recover_connection_after_loss( - operation="prompt discovery", inner_exception=exception, load_configured=False + operation=operation, + inner_exception=exception, + load_configured=False, ) @retry( @@ -3098,37 +3110,54 @@ async def recover_connection(retry_state: RetryCallState) -> None: before_sleep=recover_connection, reraise=True, ) - async def request_page() -> types.ListPromptsResult | None: + async def request_page_with_retry() -> _MCPListResultT | None: await self._ensure_connected() - if not self._supports_prompts: - logger.debug("Skipping MCP prompt loading because the server did not advertise prompts support.") + if not is_supported(): + logger.debug( + "Skipping MCP %s loading because the server did not advertise %s support.", + kind, + catalog_name, + ) return None with create_mcp_client_span( - "prompts/list", attributes=self._mcp_base_span_attributes(), capture_unhandled_exceptions=False + f"{catalog_name}/list", + attributes=self._mcp_base_span_attributes(), + capture_unhandled_exceptions=False, ) as list_span: try: - return await self._require_connection().list_prompts_page(params) + return await request_page(params) except Exception as exc: set_mcp_span_error(list_span, type(exc).__name__, str(exc)) raise try: - return await request_page() + return await request_page_with_retry() except ClosedResourceError as exc: _log_mcp_exception( logging.ERROR, exc, "MCP connection closed unexpectedly after reconnection: %s", exc, - redacted_message="MCP prompt discovery connection closed after reconnection", + redacted_message=f"MCP {operation} connection closed after reconnection", ) raise _mcp_tool_execution_exception( - "Failed to load prompts - connection lost.", + f"Failed to load {catalog_name} - connection lost.", inner_exception=exc, ) from exc + async def _try_list_prompts_page_with_recovery( + self, params: types.PaginatedRequestParams | None + ) -> types.ListPromptsResult | None: + """Fetch a page of prompts, retrying after connection loss.""" + return await self._try_list_page_with_recovery( + params, + kind="prompt", + is_supported=lambda: self._supports_prompts, + request_page=lambda page_params: self._require_connection().list_prompts_page(page_params), + ) + async def load_tools(self) -> None: """Load tools from the MCP server. @@ -3291,57 +3320,13 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: async def _try_list_tools_page_with_recovery( self, params: types.PaginatedRequestParams | None ) -> types.ListToolsResult | None: - """Fetches a page of tools retrying on connection failure.""" - from anyio import ClosedResourceError - from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt - - async def recover_connection(retry_state: RetryCallState) -> None: - outcome = retry_state.outcome - exception = outcome.exception() if outcome else None - - if not isinstance(exception, ClosedResourceError): - return - - await self._recover_connection_after_loss( - operation="tool discovery", inner_exception=exception, load_configured=False - ) - - @retry( - retry=retry_if_exception_type(ClosedResourceError), - stop=stop_after_attempt(2), - before_sleep=recover_connection, - reraise=True, + """Fetch a page of tools, retrying after connection loss.""" + return await self._try_list_page_with_recovery( + params, + kind="tool", + is_supported=lambda: self._supports_tools, + request_page=lambda page_params: self._require_connection().list_tools_page(page_params), ) - async def request_page() -> types.ListToolsResult | None: - await self._ensure_connected() - - if not self._supports_tools: - logger.debug("Skipping MCP tool loading because the server did not advertise tools support.") - return None - - with create_mcp_client_span( - "tools/list", attributes=self._mcp_base_span_attributes(), capture_unhandled_exceptions=False - ) as list_span: - try: - return await self._require_connection().list_tools_page(params) - except Exception as exc: - set_mcp_span_error(list_span, type(exc).__name__, str(exc)) - raise - - try: - return await request_page() - except ClosedResourceError as exc: - _log_mcp_exception( - logging.ERROR, - exc, - "MCP connection closed unexpectedly after reconnection: %s", - exc, - redacted_message="MCP tool discovery connection closed after reconnection", - ) - raise _mcp_tool_execution_exception( - "Failed to load tools - connection lost.", - inner_exception=exc, - ) from exc async def _cancel_pending_reload_tasks(self) -> None: """Cancel session-bound discovery reloads and wait for them to finish.""" From 4efc33245cb8fcc4ead4f26642477e3f1716a6fd Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 15:10:59 +0100 Subject: [PATCH 08/18] Added default timeout if undefined --- python/packages/core/agent_framework/_mcp.py | 16 +++++++---- python/packages/core/tests/core/test_mcp.py | 29 +++++++++++++++++--- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 0b112cb1da5..c54b17df0af 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -248,7 +248,7 @@ class MCPSpecificApproval(TypedDict, total=False): _MCP_HEADER_OWNER_EXTENSION = "agent_framework.mcp_header_owner" _MCP_INJECTED_HEADER_KEYS_EXTENSION = "agent_framework.mcp_injected_header_keys" _MCPHeaderIdentity: TypeAlias = tuple[tuple[str, str], ...] -MCP_DEFAULT_TIMEOUT = 30 +_MCP_DEFAULT_READ_TIMEOUT_SECONDS = 30 MCP_DEFAULT_SSE_READ_TIMEOUT = 60 * 5 _MCP_SUBSCRIPTION_RETRY_INITIAL_DELAY = 0.1 _MCP_SUBSCRIPTION_RETRY_MAX_DELAY = 2.0 @@ -2471,7 +2471,11 @@ async def _connect_on_owner( mcp_client = await self._exit_stack.enter_async_context( Client( server=self.get_mcp_client(), - read_timeout_seconds=self.request_timeout, + read_timeout_seconds=( + self.request_timeout + if self.request_timeout is not None + else _MCP_DEFAULT_READ_TIMEOUT_SECONDS + ), message_handler=self.message_handler, logging_callback=self.logging_callback, log_level=log_level, @@ -3835,7 +3839,7 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The default timeout in seconds for all requests. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``command`` and ``session``. ``request_timeout``, ``args``, ``env``, ``encoding``, and @@ -4099,7 +4103,7 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The default timeout in seconds for all requests. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``url`` and ``session``. ``request_timeout``, ``terminate_on_close``, ``http_client``, @@ -4376,7 +4380,7 @@ def get_mcp_client(self) -> _AsyncGeneratorContextManager[Any, None]: if http_client is None: http_client = AsyncClient( follow_redirects=True, - timeout=Timeout(MCP_DEFAULT_TIMEOUT, read=MCP_DEFAULT_SSE_READ_TIMEOUT), + timeout=Timeout(_MCP_DEFAULT_READ_TIMEOUT_SECONDS, read=MCP_DEFAULT_SSE_READ_TIMEOUT), cookies=CookieJar(policy=DefaultCookiePolicy(allowed_domains=[])), ) self._httpx_client = http_client @@ -4761,7 +4765,7 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The default timeout in seconds for all requests. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds. session: An existing MCP client session to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that session. description: The description of the tool. diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 24441510a7f..51cbde4cd62 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -5742,6 +5742,23 @@ async def test_connect_preserves_request_timeout_over_24_hours() -> None: assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == 90_000 +async def test_connect_uses_default_read_timeout_when_request_timeout_is_none() -> None: + from agent_framework._mcp import _MCP_DEFAULT_READ_TIMEOUT_SECONDS + + tool = MCPStdioTool( + name="test", + command="test-command", + load_tools=False, + load_prompts=False, + ) + + with patch("mcp.Client") as mock_client_class: + mock_client_class.return_value = _mock_sdk_client(protocol_version="2026-07-28") + + async with tool: + assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == _MCP_DEFAULT_READ_TIMEOUT_SECONDS + + async def test_connect_revalidates_request_timeout_cleared_after_construction() -> None: tool = MCPStdioTool( name="test", @@ -6629,7 +6646,7 @@ def test_mcp_stdio_tool_get_mcp_client_with_env_and_kwargs(): async def test_mcp_streamable_http_tool_get_mcp_client_all_params(): """Test MCPStreamableHTTPTool.get_mcp_client() with all parameters.""" - from agent_framework._mcp import MCP_DEFAULT_SSE_READ_TIMEOUT, MCP_DEFAULT_TIMEOUT + from agent_framework._mcp import _MCP_DEFAULT_READ_TIMEOUT_SECONDS, MCP_DEFAULT_SSE_READ_TIMEOUT tool = MCPStreamableHTTPTool( name="test", @@ -6643,7 +6660,7 @@ async def test_mcp_streamable_http_tool_get_mcp_client_all_params(): http_client = tool._httpx_client assert http_client is not None assert http_client.follow_redirects is True - assert http_client.timeout.connect == MCP_DEFAULT_TIMEOUT + assert http_client.timeout.connect == _MCP_DEFAULT_READ_TIMEOUT_SECONDS assert http_client.timeout.read == MCP_DEFAULT_SSE_READ_TIMEOUT assert not http_client.event_hooks["request"] assert mock_http_client.call_args.kwargs["http_client"]._client is http_client @@ -10264,7 +10281,11 @@ def get_mcp_client(self): # pyrefly: ignore[bad-override] async def test_mcp_streamable_http_tool_header_provider_with_httpx_event_hook(): """Test that the httpx event hook injects headers from the contextvar.""" - from agent_framework._mcp import MCP_DEFAULT_SSE_READ_TIMEOUT, MCP_DEFAULT_TIMEOUT, _mcp_call_headers + from agent_framework._mcp import ( + _MCP_DEFAULT_READ_TIMEOUT_SECONDS, + MCP_DEFAULT_SSE_READ_TIMEOUT, + _mcp_call_headers, + ) tool = MCPStreamableHTTPTool( name="test", @@ -10280,7 +10301,7 @@ async def test_mcp_streamable_http_tool_header_provider_with_httpx_event_hook(): # The tool should have created an httpx client with the event hook assert tool._httpx_client is not None assert tool._httpx_client.follow_redirects is True - assert tool._httpx_client.timeout.connect == MCP_DEFAULT_TIMEOUT + assert tool._httpx_client.timeout.connect == _MCP_DEFAULT_READ_TIMEOUT_SECONDS assert tool._httpx_client.timeout.read == MCP_DEFAULT_SSE_READ_TIMEOUT hooks = tool._httpx_client.event_hooks.get("request", []) assert len(hooks) == 1, "Expected one request event hook" From f358e659882a94c895ee3d05591097db389ccec6 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 15:20:15 +0100 Subject: [PATCH 09/18] security labeling also using new tool fetch refresh --- python/packages/core/agent_framework/_mcp.py | 5 +++ .../packages/core/agent_framework/security.py | 18 ++------- python/packages/core/tests/core/test_mcp.py | 37 +++++++++++++++++++ python/packages/core/tests/test_security.py | 36 +++++------------- 4 files changed, 55 insertions(+), 41 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index c54b17df0af..a93742ce321 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -1289,6 +1289,7 @@ def __init__( self._progressive_loaded_tool_names: set[str] = set() self._tool_call_meta_by_name: dict[str, dict[str, Any]] = {} self._tool_param_names_by_name: dict[str, set[str]] = {} + self._tool_annotations_by_name: dict[str, Any] = {} self._global_extra_arg_names, self._tool_extra_arg_names = _normalize_additional_tool_argument_names( additional_tool_argument_names ) @@ -2336,6 +2337,7 @@ def _reset_session_discovery_state(self) -> None: ] self._tool_call_meta_by_name.clear() self._tool_param_names_by_name.clear() + self._tool_annotations_by_name.clear() self._progressive_loaded_tool_names.clear() def _reset_session_state(self) -> None: @@ -2573,6 +2575,7 @@ async def _connect_on_owner( functions_before_discovery = self._functions.copy() call_meta_before_discovery = self._tool_call_meta_by_name param_names_before_discovery = self._tool_param_names_by_name + annotations_before_discovery = self._tool_annotations_by_name try: connection = self._require_connection() logger.debug("Connected to MCP server: %s", connection.client or connection.session) @@ -2608,6 +2611,7 @@ async def _connect_on_owner( self._functions[:] = functions_before_discovery self._tool_call_meta_by_name = call_meta_before_discovery self._tool_param_names_by_name = param_names_before_discovery + self._tool_annotations_by_name = annotations_before_discovery raise async def _prepare_for_run(self, kwargs: Mapping[str, Any]) -> None: @@ -3319,6 +3323,7 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: self._functions[:] = current_functions self._tool_call_meta_by_name = tool_call_meta_by_name self._tool_param_names_by_name = tool_param_names_by_name + self._tool_annotations_by_name = tool_annotations_by_name self._progressive_loaded_tool_names.difference_update(existing_tools.keys() - reused_tool_names) async def _try_list_tools_page_with_recovery( diff --git a/python/packages/core/agent_framework/security.py b/python/packages/core/agent_framework/security.py index 0ae5b5e77de..521c056b69a 100644 --- a/python/packages/core/agent_framework/security.py +++ b/python/packages/core/agent_framework/security.py @@ -4412,7 +4412,8 @@ def _apply_mcp_security_label_to_function( @experimental(feature_id=ExperimentalFeature.FIDES) -async def apply_mcp_security_labels( +# Keep this async for public API compatibility now that annotations come from the retained catalog snapshot. +async def apply_mcp_security_labels( # ruff: ignore[unused-async] mcp_tool: Any, *, default_integrity: IntegrityLabel = IntegrityLabel.UNTRUSTED, @@ -4478,19 +4479,7 @@ async def apply_mcp_security_labels( "MCPTool is not connected. Call connect() or use 'async with' before applying security labels." ) - connection = mcp_tool._require_connection() - - from mcp import types as mcp_types - - annotation_map: dict[str, Any] = {} - params: mcp_types.PaginatedRequestParams | None = None - while True: - tool_list = await connection.list_tools_page(params) - for remote_tool in tool_list.tools: - annotation_map[remote_tool.name] = remote_tool.annotations - if not tool_list.next_cursor: - break - params = mcp_types.PaginatedRequestParams(cursor=tool_list.next_cursor) + annotation_map = dict(mcp_tool._tool_annotations_by_name) loaded_functions = getattr(mcp_tool, "_functions", None) if not isinstance(loaded_functions, list): @@ -4828,6 +4817,7 @@ async def refresh_labels(self) -> None: raise RuntimeError("MCPTool is not connected. Connect before refreshing labels.") callback_bound = self._bind_function_load_callback() try: + await self._mcp_tool.load_tools() await self._apply_labels() except BaseException: if callback_bound: diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 51cbde4cd62..76a5136ae3b 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -548,9 +548,12 @@ async def test_tool_refresh_replaces_snapshot_and_preserves_other_functions(empt tool = MCPTool(name="docs", tool_name_prefix="docs") # type: ignore[abstract] # ty: ignore[call-non-callable] mock_session = AsyncMock() tool.session = mock_session + initial_annotations = types.ToolAnnotations(read_only_hint=True, open_world_hint=False) + refreshed_annotations = types.ToolAnnotations(read_only_hint=True, open_world_hint=True) keep = types.Tool( name="keep", input_schema={"type": "object", "properties": {"query": {"type": "string"}}}, + annotations=initial_annotations, _meta={"version": 1}, ) removed = types.Tool( @@ -573,6 +576,7 @@ async def test_tool_refresh_replaces_snapshot_and_preserves_other_functions(empt original_functions = list(original_list) original_meta = dict(tool._tool_call_meta_by_name) keep.meta = {"version": 2} + keep.annotations = refreshed_annotations async def list_tools(params: types.PaginatedRequestParams | None = None) -> types.ListToolsResult: assert tool._functions == original_functions @@ -596,6 +600,39 @@ async def list_tools(params: types.PaginatedRequestParams | None = None) -> type assert kept_function.result_parser is parser assert tool._tool_call_meta_by_name == ({} if empty_snapshot else {"keep": {"version": 2}}) assert tool._tool_param_names_by_name == ({} if empty_snapshot else {"keep": {"query"}}) + assert tool._tool_annotations_by_name == ({} if empty_snapshot else {"keep": refreshed_annotations}) + + +async def test_failed_tool_refresh_preserves_previous_annotation_snapshot() -> None: + tool = MCPTool(name="docs") # type: ignore[abstract] # ty: ignore[call-non-callable] + mock_session = AsyncMock() + tool.session = mock_session + original_annotations = types.ToolAnnotations(read_only_hint=True, open_world_hint=False) + replacement_annotations = types.ToolAnnotations(read_only_hint=True, open_world_hint=True) + original = types.Tool( + name="search", + input_schema={"type": "object", "properties": {}}, + annotations=original_annotations, + ) + mock_session.list_tools = AsyncMock(return_value=types.ListToolsResult(tools=[original])) + await tool.load_tools() + + replacement = types.Tool( + name="search", + input_schema={"type": "object", "properties": {}}, + annotations=replacement_annotations, + ) + mock_session.list_tools = AsyncMock( + side_effect=[ + types.ListToolsResult(tools=[replacement], next_cursor="second"), + RuntimeError("refresh failed"), + ] + ) + + with pytest.raises(RuntimeError, match="refresh failed"): + await tool.load_tools() + + assert tool._tool_annotations_by_name == {"search": original_annotations} async def test_load_tools_skips_only_task_required_tools(caplog: pytest.LogCaptureFixture) -> None: diff --git a/python/packages/core/tests/test_security.py b/python/packages/core/tests/test_security.py index 46de415b2e9..d5aeeed8755 100644 --- a/python/packages/core/tests/test_security.py +++ b/python/packages/core/tests/test_security.py @@ -10,7 +10,7 @@ from datetime import datetime, timedelta, timezone from types import MappingProxyType, SimpleNamespace from typing import Annotated, Any, cast -from unittest.mock import AsyncMock, call +from unittest.mock import AsyncMock import pytest from pydantic import AfterValidator, BaseModel, field_validator @@ -6348,12 +6348,7 @@ async def fake_call(**kwargs: Any) -> list[Content]: mcp_tool.is_connected = True mock_session = AsyncMock() mcp_tool.session = mock_session - mock_session.list_tools = AsyncMock( # type: ignore[method-assign] - return_value=SimpleNamespace( - tools=[SimpleNamespace(name="remote_tool", annotations=annotations)], - next_cursor=None, - ) - ) + mcp_tool._tool_annotations_by_name = {"remote_tool": annotations} mcp_tool.functions.append(function) return mcp_tool, function @@ -6786,22 +6781,17 @@ async def test_wrap_mcp_function_reads_refreshed_local_policy_at_invocation(self server_meta=server_meta, confidentiality=ConfidentialityLabel.PUBLIC, ) - mcp_tool.session.list_tools.side_effect = [ - SimpleNamespace( - tools=[SimpleNamespace(name="remote_tool", annotations=trusted_annotations)], next_cursor=None - ), - SimpleNamespace( - tools=[SimpleNamespace(name="remote_tool", annotations=untrusted_annotations)], next_cursor=None - ), - ] + mcp_tool.load_tools = AsyncMock() # type: ignore[method-assign] proxy = SecureMCPToolProxy(mcp_tool, default_integrity=IntegrityLabel.TRUSTED) await proxy.refresh_labels() props = function.additional_properties assert props is not None assert props["source_integrity"] == "trusted" + mcp_tool._tool_annotations_by_name["remote_tool"] = untrusted_annotations await proxy.refresh_labels() assert props["source_integrity"] == "untrusted" + assert mcp_tool.load_tools.await_count == 2 # type: ignore[union-attr] assert function.func is not None result = await function.func() @@ -6918,7 +6908,7 @@ async def test_apply_mcp_security_labels_configures_result_authority(self, trust ) assert result[0].additional_properties["security_label"] == expected_label - async def test_apply_mcp_security_labels_uses_high_level_client_connection(self) -> None: + async def test_apply_mcp_security_labels_uses_loaded_annotation_snapshot(self) -> None: from agent_framework._mcp import _ClientMCPConnection from agent_framework.security import apply_mcp_security_labels @@ -6927,21 +6917,11 @@ async def test_apply_mcp_security_labels_uses_high_level_client_connection(self) sdk_client = AsyncMock() mock_session = AsyncMock() sdk_client.session = mock_session - sdk_client.list_tools.side_effect = [ - SimpleNamespace( - tools=[SimpleNamespace(name="remote_tool", annotations=annotations)], - next_cursor="next-page", - ), - SimpleNamespace(tools=[], next_cursor=None), - ] mcp_tool._connection = _ClientMCPConnection(sdk_client, is_framework_owned=True) await apply_mcp_security_labels(mcp_tool) - assert sdk_client.list_tools.await_args_list == [ - call(cursor=None), - call(cursor="next-page"), - ] + sdk_client.list_tools.assert_not_awaited() mock_session.list_tools.assert_not_awaited() async def test_framework_stamped_mcp_label_remains_authoritative_through_tracking(self) -> None: @@ -6999,6 +6979,7 @@ async def test_secure_mcp_proxy_configures_result_authority(self, trust_server_i annotations = SimpleNamespace(read_only_hint=True, open_world_hint=False) server_meta = {"ifc": {"integrity": "trusted", "confidentiality": "public"}} mcp_tool, function = _make_connected_mcp_tool_for_ifc(annotations=annotations, server_meta=server_meta) + mcp_tool.load_tools = AsyncMock() # type: ignore[method-assign] proxy = ( SecureMCPToolProxy(mcp_tool, trust_server_ifc=True) if trust_server_ifc else SecureMCPToolProxy(mcp_tool) ) @@ -7227,6 +7208,7 @@ async def test_secure_mcp_proxy_refresh_failure_only_removes_new_binding( mcp_tool = _make_connected_mcp_discovery_tool() proxy = SecureMCPToolProxy(mcp_tool) + mcp_tool.load_tools = AsyncMock() # type: ignore[method-assign] if already_bound: mcp_tool._function_load_callback = proxy._function_load_callback proxy._apply_labels = AsyncMock(side_effect=failure_type("label refresh failed")) # type: ignore[method-assign] From 99ae067f1291dc612d853baaad37ace169b6ebf7 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 16:53:38 +0100 Subject: [PATCH 10/18] doc updates --- .../0045-python-mcp-v2-client-lifecycle.md | 9 +++++++-- python/packages/core/AGENTS.md | 15 ++++++++++++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md index 57d389fc760..0700bb9279a 100644 --- a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md +++ b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md @@ -68,10 +68,12 @@ Agent Framework owns: - transport and Client construction, Client entry, and resource cleanup for framework-created connections; - the lifecycle-owner task, locks, connection publication, reset coordination, and cancellation cleanup; +- the default request read timeout for framework-created Clients and the configurable page bound for + Agent Framework-driven tool and prompt catalog discovery; - request-scoped HTTP header identity and reconnects caused by identity changes; - tool argument filtering and trusted request metadata merging; - result parsing, Agent Framework content conversion, tracing, and error translation; -- atomic catalog publication and rollback after a failed complete fetch; +- atomic catalog publication, including retained server annotations, and rollback after a failed complete fetch; - the background catalog-subscription task for any high-level Client, including refresh scheduling, retry/backoff, cancellation, and recovery after a subscription ends or is lost; - security and approval policy. @@ -80,7 +82,9 @@ For **caller-supplied** connections, the caller owns: - entering and closing a **supplied** high-level `Client`; - constructing and closing a **supplied** low-level `ClientSession`; -- the transport, authentication, callbacks, and other configuration already captured by either supplied object. +- the transport, authentication, callbacks, request timeout, and other configuration already captured by either + supplied object. Agent Framework does not overwrite that request policy, while its own catalog-materialization + page bound still applies. Transport-specific tool constructors enforce the same ownership boundary. A URL or command selects framework-owned Client construction; a supplied high-level `mcp.Client` selects caller-owned construction and @@ -153,6 +157,7 @@ A caller-supplied `Client` is the preferred way to provide an existing connectio - The Client must already be entered before the MCP tool connects. - Agent Framework does not enter, close, replace, or recreate it. +- Agent Framework does not replace its request timeout or transport-level resource policy. - Standard operations continue through the high-level Client and retain SDK MRTR and response-cache behavior. - Agent Framework manages its own catalog-subscription task around `Client.listen()` while the wrapper is connected. - `MCPTool.session` remains `None`. diff --git a/python/packages/core/AGENTS.md b/python/packages/core/AGENTS.md index 3acfc513d51..2e77d61d60c 100644 --- a/python/packages/core/AGENTS.md +++ b/python/packages/core/AGENTS.md @@ -251,6 +251,12 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID caller responsible for transport configuration and Client lifecycle. Constructors reject mixed ownership modes and framework-owned transport options with `mcp_client` rather than ignoring them. Deprecated caller-owned `ClientSession` combinations remain compatible until their vNext removal. +- **MCP request and discovery bounds** - Framework-created high-level Clients use the configured + `request_timeout`, or a 30-second read timeout when it is omitted. Caller-supplied Clients and + `ClientSession`s retain their caller-owned request policy. Agent Framework tool and prompt discovery follows at + most `max_discovery_pages` pages per complete catalog fetch (default 100); `None` explicitly restores legacy + unbounded pagination for a trusted server. Continuation cursors remain opaque, and every non-`None` cursor, + including an empty string, is forwarded unchanged. - **Argument allowlist (`_prepare_call_kwargs`)** - Before each `tools/call`, kwargs are filtered to an **allowlist** built from the tool's declared parameters (`inputSchema.properties`) plus any user-configured extras. **The declared half comes from the server's advertised schema**, and runtime kwargs (`FunctionInvocationContext.kwargs`, seeded from `function_invocation_kwargs`) are merged with the model-supplied arguments upstream in `_call_tool_with_runtime_kwargs`, so provenance is gone by the time the filter runs. A runtime kwarg is therefore forwarded whenever the server declares a property of that name, without the model mentioning it — the server, not the caller, decides which runtime kwarg names it receives. A tool that declares no usable `properties` (including schemas with `additionalProperties: true`) forwards only the configured extras. `_MCP_FRAMEWORK_DENYLIST` is a narrow safety net covering only non-serializable framework objects a server *declares* in its schema (those are dropped); it does not generalize to arbitrary caller-chosen names, and explicit extras always win. The reserved `_meta` key is never forwarded as an argument; trusted caller/runtime `_meta` is validated as MCP request metadata, model-supplied `_meta` is discarded in generated MCP functions, and metadata precedence is caller/runtime < OpenTelemetry < tools/list metadata. - **`allowed_tools`** (constructor arg on all `MCPTool` subclasses) - Restricts exposed MCP tools by raw remote MCP tool identity. Prefixed local names remain accepted only when the raw remote name already matches its normalized form; normalized/local aliases do not authorize a different raw remote name. Configured allow/approval names must identify at most one raw remote name across loaded tools and prompts: a raw name that overlaps another tool's prefixed alias raises `ToolExecutionException`. Discovery validates all pages before publishing new functions; a failed reload retains the previous functions and metadata. The allowlist is also revalidated when exposing functions so runtime changes cannot select an ambiguous name. If multiple raw remote tool names map to the same local function name, tool loading raises `ToolExecutionException` instead of first-one-wins shadowing. - **`approval_mode`** (constructor arg on all `MCPTool` subclasses) - Accepts `"always_require"`, `"never_require"`, @@ -263,7 +269,14 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID prompts discovered later (for example after `tools/list_changed`) use the policy at discovery time; retained functions keep their resolved mode. - **Progressive MCP disclosure** (`use_progressive_disclosure`, `always_load`) - When enabled on any `MCPTool` subclass, the initial model-facing surface is loader tools (`list_mcp_tools` / `load_tool` / `unload_tool`, prefixed by `tool_name_prefix` when configured) plus allowed tools selected by `always_load` and tools loaded earlier on the same `MCPTool` instance. `list_mcp_tools` only reports tools that pass `allowed_tools`; filtered tools are not listed or loadable. Loader tool names are reserved in progressive mode: remote MCP tools whose local generated name collides with a loader name are omitted from the initial/listed surface, and explicit `load_tool` calls return a model-visible message pointing callers to `tool_name_prefix` or excluding the colliding tool. `load_tool` accepts one tool name or a list of tool names and uses `FunctionInvocationContext.add_tools(...)` so the selected generated MCP `FunctionTool`s become available on the next function-calling iteration while keeping existing approval mode, argument filtering, header-provider runtime kwargs, result parsing, and OTel. `unload_tool` accepts one dynamically loaded tool name or a list of names and removes them from the live tool list and persisted progressive surface, but it does not remove tools configured in `always_load`. Invalid `always_load` entries are ignored like unmatched `allowed_tools` entries. -- **Tool discovery refresh** - Validate the complete current tool snapshot alongside retained non-tool functions, not stale tool wrappers. Successful refreshes atomically replace the previous tool set and metadata, including empty snapshots, while preserving prompts, custom functions, and unchanged tool wrappers (including caller customizations). Removed or replaced tool identities lose their persisted progressive-loaded state; failed refreshes preserve the previous state. +- **Tool discovery refresh** - Validate the complete current tool snapshot alongside retained non-tool functions, + not stale tool wrappers. Successful refreshes atomically replace the previous tool set and metadata, including + call metadata, declared parameter names, and server annotations, while preserving prompts, custom functions, and + unchanged tool wrappers (including caller customizations). Empty snapshots clear all session-derived tool + metadata. Removed or replaced tool identities lose their persisted progressive-loaded state; failed refreshes + preserve the previous complete state. MCP security labeling reads the retained annotation snapshot instead of + independently listing tools; `SecureMCPToolProxy.refresh_labels()` explicitly performs a bounded tool refresh + before reapplying local policy. - **`additional_tool_argument_names`** (constructor arg on all `MCPTool` subclasses) - Opt extra argument names back into the allowlist. Accepts a `Sequence[str]` (applied to every tool) or a `Mapping[str, Sequence[str]]` keyed by **remote tool name**, where the reserved key `"*"` denotes global extras. It is configured only in user code at construction; there is **no per-call/runtime override**, so a model-issued tool call cannot change which names pass through — but note this constrains the *model*, not the *server*, which still widens the effective allowlist through its schema. To use a server that accepts `additionalProperties: true`, list the extra names here and then either (1) manually extend that tool's `inputSchema` (via the `.functions` list after connecting) so the model is prompted to supply them, or (2) supply the values yourself via `function_invocation_kwargs`. If a normal forwarded argument name is supplied by both the model and `function_invocation_kwargs`, the model-supplied value wins; `_meta` is the exception and only trusted runtime/caller metadata is used. - **MCP HTTP header request scoping** - `static_headers` supplies fixed, origin-scoped headers without serializing concurrent calls. Generated tool and prompt calls give `header_provider` only host runtime kwargs, separately from model arguments; direct `call_tool` calls give it caller kwargs. Model-over-runtime precedence is confined to outbound tool arguments. Fixed and dynamic headers form the session's complete effective identity (case-insensitive names, case-sensitive values), with dynamic values overriding fixed values of the same name. Agent runs reconcile a connected tool before copying its functions; generated tool and prompt calls perform the same check at invocation. Connected run preparation defers when a provider needs runtime values supplied by invocation middleware; invocation-time resolution remains strict. A different identity waits for in-flight discovery, reconnects framework-created sessions without loading, then refreshes session-derived discovery under the same lock. Because a caller-supplied session's established identity is unknown and the wrapper cannot reconnect it, dynamic header resolution on that wrapper is rejected even while disconnected. Ambient requests retain the bound set. With a shared `http_client`, processing stays scoped to the originating `MCPStreamableHTTPTool`, and every injected header is stripped from cross-origin redirects. The session exit stack removes its request hook after transport shutdown, including failed initialization or discovery, and closes framework-created HTTP clients. Failed discovery resets the connection and discovery flags and rolls back partial function/metadata additions. Framework-created sessions are discarded; constructor-supplied sessions remain caller-owned and reusable across cleanup, close, and reset. - **MCP lifecycle caller cancellation** - The lifecycle owner skips cancelled queued connect requests and waits for the caller to acknowledge successful setup. If the caller cancels before accepting a newly established connection, the owner tears it down before processing the next request. Cancelling a close waiter does not interrupt teardown, and cancelling a redundant connect does not discard a previously established session. From 863cb18fc4cd1596a2a6c59f9906979d6dd5e330 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Mon, 2 Nov 2026 16:59:19 +0100 Subject: [PATCH 11/18] test type check --- python/packages/core/tests/core/test_mcp.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 76a5136ae3b..cddb31d3c3f 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -9577,7 +9577,9 @@ async def reconnect() -> None: assert [function.name for function in tool.functions] == ["first", "second"] assert first_session.list_tools.await_count == 2 mock_reconnect.assert_awaited_once_with() - continuation_params = second_session.list_tools.await_args.kwargs["params"] + continuation_call = second_session.list_tools.await_args + assert continuation_call is not None + continuation_params = continuation_call.kwargs["params"] assert continuation_params.cursor == "second" @@ -9670,7 +9672,9 @@ async def reconnect() -> None: assert [function.name for function in tool.functions] == ["first", "second"] assert first_session.list_prompts.await_count == 2 mock_reconnect.assert_awaited_once_with() - continuation_params = second_session.list_prompts.await_args.kwargs["params"] + continuation_call = second_session.list_prompts.await_args + assert continuation_call is not None + continuation_params = continuation_call.kwargs["params"] assert continuation_params.cursor == "second" From 907d87eee6e37709e9b4e6bddcd6ba6615238e85 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Tue, 3 Nov 2026 15:02:45 +0100 Subject: [PATCH 12/18] Item cap implemented and documentation updates --- .../0045-python-mcp-v2-client-lifecycle.md | 8 +- python/packages/core/AGENTS.md | 9 +- python/packages/core/agent_framework/_mcp.py | 53 +++++++++++- python/packages/core/tests/core/test_mcp.py | 86 ++++++++++++++++++- 4 files changed, 143 insertions(+), 13 deletions(-) diff --git a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md index 0700bb9279a..12e6c01a242 100644 --- a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md +++ b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md @@ -68,7 +68,7 @@ Agent Framework owns: - transport and Client construction, Client entry, and resource cleanup for framework-created connections; - the lifecycle-owner task, locks, connection publication, reset coordination, and cancellation cleanup; -- the default request read timeout for framework-created Clients and the configurable page bound for +- the default request read timeout for framework-created Clients and configurable page/item bounds for Agent Framework-driven tool and prompt catalog discovery; - request-scoped HTTP header identity and reconnects caused by identity changes; - tool argument filtering and trusted request metadata merging; @@ -84,7 +84,7 @@ For **caller-supplied** connections, the caller owns: - constructing and closing a **supplied** low-level `ClientSession`; - the transport, authentication, callbacks, request timeout, and other configuration already captured by either supplied object. Agent Framework does not overwrite that request policy, while its own catalog-materialization - page bound still applies. + page and item bounds still apply. Transport-specific tool constructors enforce the same ownership boundary. A URL or command selects framework-owned Client construction; a supplied high-level `mcp.Client` selects caller-owned construction and @@ -92,6 +92,10 @@ lifecycle. Constructor combinations that mix those ownership modes or configure owns raise `ValueError` instead of silently ignoring parameters. Temporarily retained legacy constructor and `ClientSession` combinations remain compatible and will be removed in vNext. +Catalog page and item limits apply after the MCP SDK parses each response. They do not establish a universal +transport response-size bound; applications must connect to MCP servers trusted to return reasonably sized responses +and configure transport-specific limits where the selected transport exposes them. + The SDK `Client` owns: - modern negotiation and legacy initialization fallback; diff --git a/python/packages/core/AGENTS.md b/python/packages/core/AGENTS.md index 2e77d61d60c..ae26d3972be 100644 --- a/python/packages/core/AGENTS.md +++ b/python/packages/core/AGENTS.md @@ -254,9 +254,12 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID - **MCP request and discovery bounds** - Framework-created high-level Clients use the configured `request_timeout`, or a 30-second read timeout when it is omitted. Caller-supplied Clients and `ClientSession`s retain their caller-owned request policy. Agent Framework tool and prompt discovery follows at - most `max_discovery_pages` pages per complete catalog fetch (default 100); `None` explicitly restores legacy - unbounded pagination for a trusted server. Continuation cursors remain opaque, and every non-`None` cursor, - including an empty string, is forwarded unchanged. + most `max_discovery_pages` pages (default 100) and accepts at most `max_discovery_items` entries (default 1,000) + per complete catalog fetch; `None` explicitly disables the corresponding limit for a trusted server. + Continuation cursors remain opaque, and every non-`None` cursor, including an empty string, is forwarded + unchanged. These limits apply after the MCP SDK parses each page and do not bound the encoded response size; + applications remain responsible for connecting to servers trusted to return reasonably sized responses and for + configuring transport-specific size limits where the selected transport exposes them. - **Argument allowlist (`_prepare_call_kwargs`)** - Before each `tools/call`, kwargs are filtered to an **allowlist** built from the tool's declared parameters (`inputSchema.properties`) plus any user-configured extras. **The declared half comes from the server's advertised schema**, and runtime kwargs (`FunctionInvocationContext.kwargs`, seeded from `function_invocation_kwargs`) are merged with the model-supplied arguments upstream in `_call_tool_with_runtime_kwargs`, so provenance is gone by the time the filter runs. A runtime kwarg is therefore forwarded whenever the server declares a property of that name, without the model mentioning it — the server, not the caller, decides which runtime kwarg names it receives. A tool that declares no usable `properties` (including schemas with `additionalProperties: true`) forwards only the configured extras. `_MCP_FRAMEWORK_DENYLIST` is a narrow safety net covering only non-serializable framework objects a server *declares* in its schema (those are dropped); it does not generalize to arbitrary caller-chosen names, and explicit extras always win. The reserved `_meta` key is never forwarded as an argument; trusted caller/runtime `_meta` is validated as MCP request metadata, model-supplied `_meta` is discarded in generated MCP functions, and metadata precedence is caller/runtime < OpenTelemetry < tools/list metadata. - **`allowed_tools`** (constructor arg on all `MCPTool` subclasses) - Restricts exposed MCP tools by raw remote MCP tool identity. Prefixed local names remain accepted only when the raw remote name already matches its normalized form; normalized/local aliases do not authorize a different raw remote name. Configured allow/approval names must identify at most one raw remote name across loaded tools and prompts: a raw name that overlaps another tool's prefixed alias raises `ToolExecutionException`. Discovery validates all pages before publishing new functions; a failed reload retains the previous functions and metadata. The allowlist is also revalidated when exposing functions so runtime changes cannot select an ambiguous name. If multiple raw remote tool names map to the same local function name, tool loading raises `ToolExecutionException` instead of first-one-wins shadowing. - **`approval_mode`** (constructor arg on all `MCPTool` subclasses) - Accepts `"always_require"`, `"never_require"`, diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index a93742ce321..dd70e02d3aa 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -254,6 +254,7 @@ class MCPSpecificApproval(TypedDict, total=False): _MCP_SUBSCRIPTION_RETRY_MAX_DELAY = 2.0 _DEFAULT_MCP_DISCOVERY_MAX_PAGES = 100 +_DEFAULT_MCP_DISCOVERY_MAX_ITEMS = 1_000 _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES = 1024 * 1024 @@ -1186,6 +1187,7 @@ def __init__( always_load: Collection[str] | None = None, *, max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, + max_discovery_items: int | None = _DEFAULT_MCP_DISCOVERY_MAX_ITEMS, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", ) -> None: @@ -1212,6 +1214,8 @@ def __init__( ) if max_discovery_pages is not None and max_discovery_pages <= 0: raise ValueError("max_discovery_pages must be positive or None.") + if max_discovery_items is not None and max_discovery_items <= 0: + raise ValueError("max_discovery_items must be positive or None.") if max_host_payload_size_bytes is not None and max_host_payload_size_bytes <= 0: raise ValueError("max_host_payload_size_bytes must be positive or None.") if request_timeout is not None and request_timeout <= 0: @@ -1241,6 +1245,7 @@ def __init__( self.load_prompts_flag = load_prompts self.parse_prompt_results = parse_prompt_results self._max_discovery_pages = max_discovery_pages + self._max_discovery_items = max_discovery_items self.max_host_payload_size_bytes = max_host_payload_size_bytes self._exit_stack = AsyncExitStack() self._lifecycle_lock = asyncio.Lock() @@ -3005,8 +3010,18 @@ async def _load_prompts_locked(self) -> None: prompt_functions: list[FunctionTool] = [] retained_prompt_names: set[str] = set() new_functions: list[FunctionTool] = [] + items_loaded = 0 def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: + nonlocal items_loaded + items_loaded += len(prompt_list.prompts) + if self._max_discovery_items is not None and items_loaded > self._max_discovery_items: + raise _mcp_tool_execution_exception( + f"MCP prompt discovery exceeded max_discovery_items={self._max_discovery_items}; " + f"the server returned {items_loaded} prompts. Increase max_discovery_items, " + "or set it to None only for a trusted MCP server." + ) + for prompt in prompt_list.prompts: normalized_name = _normalize_mcp_name(prompt.name) local_name = _build_prefixed_mcp_name(normalized_name, self.tool_name_prefix) @@ -3062,8 +3077,9 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: while cursor is not None: if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: raise _mcp_tool_execution_exception( - f"MCP prompt discovery reached the configured maximum of " - f"{self._max_discovery_pages} pages before the server completed pagination." + f"MCP prompt discovery exceeded max_discovery_pages={self._max_discovery_pages}; " + f"the server returned a continuation cursor after page {pages_loaded}. " + "Increase max_discovery_pages, or set it to None only for a trusted MCP server." ) prompt_list = await self._try_list_prompts_page_with_recovery(types.PaginatedRequestParams(cursor=cursor)) @@ -3202,8 +3218,18 @@ async def _load_tools_locked(self) -> None: tool_call_meta_by_name: dict[str, dict[str, Any]] = {} tool_param_names_by_name: dict[str, set[str]] = {} tool_annotations_by_name: dict[str, Any] = {} + items_loaded = 0 def stage_tool_page(tool_list: types.ListToolsResult) -> None: + nonlocal items_loaded + items_loaded += len(tool_list.tools) + if self._max_discovery_items is not None and items_loaded > self._max_discovery_items: + raise _mcp_tool_execution_exception( + f"MCP tool discovery exceeded max_discovery_items={self._max_discovery_items}; " + f"the server returned {items_loaded} tools. Increase max_discovery_items, " + "or set it to None only for a trusted MCP server." + ) + for tool in tool_list.tools: task_support = getattr(getattr(tool, "execution", None), "task_support", None) if task_support == "required": @@ -3291,8 +3317,9 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: while cursor is not None: if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: raise _mcp_tool_execution_exception( - f"MCP tool discovery reached the configured maximum of " - f"{self._max_discovery_pages} pages before the server completed pagination." + f"MCP tool discovery exceeded max_discovery_pages={self._max_discovery_pages}; " + f"the server returned a continuation cursor after page {pages_loaded}. " + "Increase max_discovery_pages, or set it to None only for a trusted MCP server." ) tool_list = await self._try_list_tools_page_with_recovery(types.PaginatedRequestParams(cursor=cursor)) @@ -3808,6 +3835,7 @@ def __init__( task_options: Any | None = None, additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None, max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, + max_discovery_items: int | None = _DEFAULT_MCP_DISCOVERY_MAX_ITEMS, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", **kwargs: Any, @@ -3918,6 +3946,10 @@ def __init__( task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. ``None`` disables the limit. + max_discovery_items: Maximum number of tools or prompts accepted across all discovery pages. + Defaults to 1,000. ``None`` disables the limit. Discovery limits apply after the MCP SDK parses + each page and do not bound the encoded response size; connect only to servers trusted to return + reasonably sized responses and configure transport-specific size limits where available. max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host transports. ``None`` disables the limit. tool_result_content: How to choose model-visible text when both ``content`` and @@ -3974,6 +4006,7 @@ def __init__( sampling_max_requests=sampling_max_requests, task_options=task_options, max_discovery_pages=max_discovery_pages, + max_discovery_items=max_discovery_items, max_host_payload_size_bytes=max_host_payload_size_bytes, tool_result_content=tool_result_content, ) @@ -4070,6 +4103,7 @@ def __init__( additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None, task_options: Any = None, max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, + max_discovery_items: int | None = _DEFAULT_MCP_DISCOVERY_MAX_ITEMS, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", **kwargs: Any, @@ -4251,6 +4285,10 @@ def __init__( task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. ``None`` disables the limit. + max_discovery_items: Maximum number of tools or prompts accepted across all discovery pages. + Defaults to 1,000. ``None`` disables the limit. Discovery limits apply after the MCP SDK parses + each page and do not bound the encoded response size; connect only to servers trusted to return + reasonably sized responses and configure transport-specific size limits where available. max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host transports. ``None`` disables the limit. tool_result_content: How to choose model-visible text when both ``content`` and @@ -4307,6 +4345,7 @@ def __init__( sampling_max_requests=sampling_max_requests, task_options=task_options, max_discovery_pages=max_discovery_pages, + max_discovery_items=max_discovery_items, max_host_payload_size_bytes=max_host_payload_size_bytes, tool_result_content=tool_result_content, ) @@ -4739,6 +4778,7 @@ def __init__( additional_tool_argument_names: Sequence[str] | Mapping[str, Sequence[str]] | None = None, task_options: Any = None, max_discovery_pages: int | None = _DEFAULT_MCP_DISCOVERY_MAX_PAGES, + max_discovery_items: int | None = _DEFAULT_MCP_DISCOVERY_MAX_ITEMS, max_host_payload_size_bytes: int | None = _DEFAULT_MCP_HOST_PAYLOAD_SIZE_BYTES, tool_result_content: MCPToolResultContentMode = "structured_first", **kwargs: Any, @@ -4834,6 +4874,10 @@ def __init__( task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. ``None`` disables the limit. + max_discovery_items: Maximum number of tools or prompts accepted across all discovery pages. + Defaults to 1,000. ``None`` disables the limit. Discovery limits apply after the MCP SDK parses + each page and do not bound the encoded response size; connect only to servers trusted to return + reasonably sized responses and configure transport-specific size limits where available. max_host_payload_size_bytes: Maximum encoded MCP result size retained for Host transports. ``None`` disables the limit. tool_result_content: How to choose model-visible text when both ``content`` and @@ -4862,6 +4906,7 @@ def __init__( sampling_max_requests=sampling_max_requests, task_options=task_options, max_discovery_pages=max_discovery_pages, + max_discovery_items=max_discovery_items, max_host_payload_size_bytes=max_host_payload_size_bytes, tool_result_content=tool_result_content, ) diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index cddb31d3c3f..77dbe04b727 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -329,22 +329,30 @@ def test_mcp_transport_subclasses_default_discovery_page_limit() -> None: ] assert all(tool._max_discovery_pages == 100 for tool in tools) + assert all(tool._max_discovery_items == 1_000 for tool in tools) def test_mcp_transport_subclasses_forward_discovery_page_limit() -> None: with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) tools = [ - MCPStdioTool(name="stdio", command="python", max_discovery_pages=101), - MCPStreamableHTTPTool(name="http", url="https://example.com/mcp", max_discovery_pages=102), + MCPStdioTool(name="stdio", command="python", max_discovery_pages=101, max_discovery_items=1_001), + MCPStreamableHTTPTool( + name="http", + url="https://example.com/mcp", + max_discovery_pages=102, + max_discovery_items=1_002, + ), MCPWebsocketTool( # ty: ignore[deprecated] name="websocket", url="wss://example.com/mcp", max_discovery_pages=103, + max_discovery_items=1_003, ), ] assert [tool._max_discovery_pages for tool in tools] == [101, 102, 103] + assert [tool._max_discovery_items for tool in tools] == [1_001, 1_002, 1_003] @pytest.mark.parametrize("max_discovery_pages", [0, -1]) @@ -356,6 +364,15 @@ def test_mcp_tool_rejects_non_positive_discovery_page_limit(max_discovery_pages: ) +@pytest.mark.parametrize("max_discovery_items", [0, -1]) +def test_mcp_tool_rejects_non_positive_discovery_item_limit(max_discovery_items: int) -> None: + with pytest.raises(ValueError, match="max_discovery_items must be positive or None"): + MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_items=max_discovery_items, + ) + + @pytest.mark.parametrize("configured_name", ["search_docs", "docs_search_docs"]) async def test_load_tools_with_tool_name_prefix_preserves_matching_configuration(configured_name: str): """Prefixed MCP tool names should still honor unprefixed allow/approval configuration.""" @@ -6988,7 +7005,7 @@ async def list_tools(params: types.PaginatedRequestParams | None = None) -> type mock_session.list_tools = AsyncMock(side_effect=list_tools) - with pytest.raises(ToolExecutionException, match="configured maximum of 2 pages"): + with pytest.raises(ToolExecutionException, match="max_discovery_pages=2"): await tool.load_tools() assert mock_session.list_tools.await_count == 2 @@ -7047,6 +7064,67 @@ async def list_tools(params: types.PaginatedRequestParams | None = None) -> type assert mock_session.list_tools.await_count == 101 +@pytest.mark.parametrize("catalog_kind", ["tools", "prompts"]) +async def test_catalog_discovery_accepts_items_at_limit(catalog_kind: str) -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_items=2, + ) + mock_session = AsyncMock() + tool.session = mock_session + + if catalog_kind == "tools": + mock_session.list_tools = AsyncMock( + return_value=types.ListToolsResult( + tools=[ + types.Tool(name="first", input_schema={"type": "object", "properties": {}}), + types.Tool(name="second", input_schema={"type": "object", "properties": {}}), + ] + ) + ) + await tool.load_tools() + else: + mock_session.list_prompts = AsyncMock( + return_value=types.ListPromptsResult(prompts=[types.Prompt(name="first"), types.Prompt(name="second")]) + ) + await tool.load_prompts() + + assert [function.name for function in tool.functions] == ["first", "second"] + + +@pytest.mark.parametrize("catalog_kind", ["tools", "prompts"]) +async def test_catalog_discovery_rejects_items_exceeding_limit(catalog_kind: str) -> None: + tool = MCPTool( # type: ignore[abstract] # ty: ignore[call-non-callable] + name="test_tool", + max_discovery_items=2, + ) + mock_session = AsyncMock() + tool.session = mock_session + + if catalog_kind == "tools": + mock_session.list_tools = AsyncMock( + return_value=types.ListToolsResult( + tools=[ + types.Tool(name=name, input_schema={"type": "object", "properties": {}}) + for name in ("first", "second", "third") + ] + ) + ) + load_catalog = tool.load_tools + else: + mock_session.list_prompts = AsyncMock( + return_value=types.ListPromptsResult( + prompts=[types.Prompt(name=name) for name in ("first", "second", "third")] + ) + ) + load_catalog = tool.load_prompts + + with pytest.raises(ToolExecutionException, match="max_discovery_items=2"): + await load_catalog() + + assert tool.functions == [] + + async def test_load_tools_adds_properties_to_zero_arg_tool_schema(): """Test that load_tools normalizes inputSchema for zero-argument MCP tools. @@ -7218,7 +7296,7 @@ async def list_prompts(params: types.PaginatedRequestParams | None = None) -> ty mock_session.list_prompts = AsyncMock(side_effect=list_prompts) - with pytest.raises(ToolExecutionException, match="configured maximum of 2 pages"): + with pytest.raises(ToolExecutionException, match="max_discovery_pages=2"): await tool.load_prompts() assert mock_session.list_prompts.await_count == 2 From 9f20a93e0c84f97beff46d41ec34edf83d5de869 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Tue, 3 Nov 2026 15:15:38 +0100 Subject: [PATCH 13/18] Python: Make pagination test failure paths explicit --- python/packages/core/tests/core/test_mcp.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 205863dbaa8..e125be8faa3 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -6996,7 +6996,7 @@ async def list_tools(params: types.PaginatedRequestParams | None = None) -> type tools=[types.Tool(name="second", input_schema={"type": "object", "properties": {}})], next_cursor="third", ) - pytest.fail(f"Unexpected tools/list cursor: {cursor!r}") + raise AssertionError(f"Unexpected tools/list cursor: {cursor!r}") mock_session.list_tools = AsyncMock(side_effect=list_tools) @@ -7287,7 +7287,7 @@ async def list_prompts(params: types.PaginatedRequestParams | None = None) -> ty return types.ListPromptsResult(prompts=[types.Prompt(name="first")], next_cursor="second") if cursor == "second": return types.ListPromptsResult(prompts=[types.Prompt(name="second")], next_cursor="third") - pytest.fail(f"Unexpected prompts/list cursor: {cursor!r}") + raise AssertionError(f"Unexpected prompts/list cursor: {cursor!r}") mock_session.list_prompts = AsyncMock(side_effect=list_prompts) From fd83523f515d89a40bc708c315ccbe7cfbf25a47 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Wed, 4 Nov 2026 10:42:28 +0100 Subject: [PATCH 14/18] PR feedback --- python/packages/core/agent_framework/_mcp.py | 57 ++++++++++---------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 4bbc48101bf..5202e57c3b1 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -71,7 +71,11 @@ logger = logging.getLogger(__name__) -_MCPListResultT = TypeVar("_MCPListResultT") +_MCPListResultT = TypeVar( + "_MCPListResultT", + "types.ListToolsResult", + "types.ListPromptsResult", +) def _mcp_exception_log_level() -> Literal[10] | None: @@ -3060,7 +3064,11 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: prompt_functions.append(func) new_functions.append(func) - prompt_list = await self._try_list_prompts_page_with_recovery(None) + prompt_list = await self._try_list_page_with_recovery( + None, + kind="prompt", + request_page=lambda page_params: self._require_connection().list_prompts_page(page_params), + ) if prompt_list is None: return pages_loaded = 1 @@ -3075,7 +3083,11 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: "Increase max_discovery_pages, or set it to None only for a trusted MCP server." ) - prompt_list = await self._try_list_prompts_page_with_recovery(types.PaginatedRequestParams(cursor=cursor)) + prompt_list = await self._try_list_page_with_recovery( + types.PaginatedRequestParams(cursor=cursor), + kind="prompt", + request_page=lambda page_params: self._require_connection().list_prompts_page(page_params), + ) if prompt_list is None: return pages_loaded += 1 @@ -3098,7 +3110,6 @@ async def _try_list_page_with_recovery( params: types.PaginatedRequestParams | None, *, kind: Literal["tool", "prompt"], - is_supported: Callable[[], bool], request_page: Callable[[types.PaginatedRequestParams | None], Awaitable[_MCPListResultT]], ) -> _MCPListResultT | None: """Fetch one catalog page, retrying after connection loss.""" @@ -3130,7 +3141,9 @@ async def recover_connection(retry_state: RetryCallState) -> None: async def request_page_with_retry() -> _MCPListResultT | None: await self._ensure_connected() - if not is_supported(): + # on reconnect we may have different capabilities. + is_supported = self._supports_tools if kind == "tool" else self._supports_prompts + if not is_supported: logger.debug( "Skipping MCP %s loading because the server did not advertise %s support.", kind, @@ -3164,17 +3177,6 @@ async def request_page_with_retry() -> _MCPListResultT | None: inner_exception=exc, ) from exc - async def _try_list_prompts_page_with_recovery( - self, params: types.PaginatedRequestParams | None - ) -> types.ListPromptsResult | None: - """Fetch a page of prompts, retrying after connection loss.""" - return await self._try_list_page_with_recovery( - params, - kind="prompt", - is_supported=lambda: self._supports_prompts, - request_page=lambda page_params: self._require_connection().list_prompts_page(page_params), - ) - async def load_tools(self) -> None: """Load tools from the MCP server. @@ -3300,7 +3302,11 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: ) new_functions.append(func) - tool_list = await self._try_list_tools_page_with_recovery(None) + tool_list = await self._try_list_page_with_recovery( + None, + kind="tool", + request_page=lambda page_params: self._require_connection().list_tools_page(page_params), + ) if tool_list is None: return pages_loaded = 1 @@ -3315,7 +3321,11 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: "Increase max_discovery_pages, or set it to None only for a trusted MCP server." ) - tool_list = await self._try_list_tools_page_with_recovery(types.PaginatedRequestParams(cursor=cursor)) + tool_list = await self._try_list_page_with_recovery( + types.PaginatedRequestParams(cursor=cursor), + kind="tool", + request_page=lambda page_params: self._require_connection().list_tools_page(page_params), + ) if tool_list is None: return pages_loaded += 1 @@ -3346,17 +3356,6 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: self._tool_annotations_by_name = tool_annotations_by_name self._progressive_loaded_tool_names.difference_update(existing_tools.keys() - reused_tool_names) - async def _try_list_tools_page_with_recovery( - self, params: types.PaginatedRequestParams | None - ) -> types.ListToolsResult | None: - """Fetch a page of tools, retrying after connection loss.""" - return await self._try_list_page_with_recovery( - params, - kind="tool", - is_supported=lambda: self._supports_tools, - request_page=lambda page_params: self._require_connection().list_tools_page(page_params), - ) - async def _cancel_pending_reload_tasks(self) -> None: """Cancel session-bound discovery reloads and wait for them to finish.""" tasks = list(self._pending_reload_tasks) From 9d1d22cc57a2a6849301bceb7cb3f9e63651f570 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Wed, 4 Nov 2026 10:47:34 +0100 Subject: [PATCH 15/18] Python: Expose MCP discovery limits --- python/packages/core/agent_framework/_mcp.py | 32 ++++++++++---------- python/packages/core/tests/core/test_mcp.py | 8 ++--- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 5202e57c3b1..dbae82e1f6a 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -1241,8 +1241,8 @@ def __init__( self.tool_result_content = tool_result_content self.load_prompts_flag = load_prompts self.parse_prompt_results = parse_prompt_results - self._max_discovery_pages = max_discovery_pages - self._max_discovery_items = max_discovery_items + self.max_discovery_pages = max_discovery_pages + self.max_discovery_items = max_discovery_items self.max_host_payload_size_bytes = max_host_payload_size_bytes self._exit_stack = AsyncExitStack() self._lifecycle_lock = asyncio.Lock() @@ -3012,9 +3012,9 @@ async def _load_prompts_locked(self) -> None: def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: nonlocal items_loaded items_loaded += len(prompt_list.prompts) - if self._max_discovery_items is not None and items_loaded > self._max_discovery_items: + if self.max_discovery_items is not None and items_loaded > self.max_discovery_items: raise _mcp_tool_execution_exception( - f"MCP prompt discovery exceeded max_discovery_items={self._max_discovery_items}; " + f"MCP prompt discovery exceeded max_discovery_items={self.max_discovery_items}; " f"the server returned {items_loaded} prompts. Increase max_discovery_items, " "or set it to None only for a trusted MCP server." ) @@ -3076,9 +3076,9 @@ def stage_prompt_page(prompt_list: types.ListPromptsResult) -> None: cursor = prompt_list.next_cursor while cursor is not None: - if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: + if self.max_discovery_pages is not None and pages_loaded >= self.max_discovery_pages: raise _mcp_tool_execution_exception( - f"MCP prompt discovery exceeded max_discovery_pages={self._max_discovery_pages}; " + f"MCP prompt discovery exceeded max_discovery_pages={self.max_discovery_pages}; " f"the server returned a continuation cursor after page {pages_loaded}. " "Increase max_discovery_pages, or set it to None only for a trusted MCP server." ) @@ -3218,9 +3218,9 @@ async def _load_tools_locked(self) -> None: def stage_tool_page(tool_list: types.ListToolsResult) -> None: nonlocal items_loaded items_loaded += len(tool_list.tools) - if self._max_discovery_items is not None and items_loaded > self._max_discovery_items: + if self.max_discovery_items is not None and items_loaded > self.max_discovery_items: raise _mcp_tool_execution_exception( - f"MCP tool discovery exceeded max_discovery_items={self._max_discovery_items}; " + f"MCP tool discovery exceeded max_discovery_items={self.max_discovery_items}; " f"the server returned {items_loaded} tools. Increase max_discovery_items, " "or set it to None only for a trusted MCP server." ) @@ -3314,9 +3314,9 @@ def stage_tool_page(tool_list: types.ListToolsResult) -> None: cursor = tool_list.next_cursor while cursor is not None: - if self._max_discovery_pages is not None and pages_loaded >= self._max_discovery_pages: + if self.max_discovery_pages is not None and pages_loaded >= self.max_discovery_pages: raise _mcp_tool_execution_exception( - f"MCP tool discovery exceeded max_discovery_pages={self._max_discovery_pages}; " + f"MCP tool discovery exceeded max_discovery_pages={self.max_discovery_pages}; " f"the server returned a continuation cursor after page {pages_loaded}. " "Increase max_discovery_pages, or set it to None only for a trusted MCP server." ) @@ -3936,9 +3936,9 @@ def __init__( ``function_invocation_kwargs`` - for example through ``env`` - for servers whose process you do not control. task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. - max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. + max_discovery_pages: Maximum pages accepted independently for each tool or prompt catalog fetch. ``None`` disables the limit. - max_discovery_items: Maximum number of tools or prompts accepted across all discovery pages. + max_discovery_items: Maximum entries accepted independently for each tool or prompt catalog fetch. Defaults to 1,000. ``None`` disables the limit. Discovery limits apply after the MCP SDK parses each page and do not bound the encoded response size; connect only to servers trusted to return reasonably sized responses and configure transport-specific size limits where available. @@ -4275,9 +4275,9 @@ def __init__( still allows a different value per request), or configure a custom ``http_client``. task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. - max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. + max_discovery_pages: Maximum pages accepted independently for each tool or prompt catalog fetch. ``None`` disables the limit. - max_discovery_items: Maximum number of tools or prompts accepted across all discovery pages. + max_discovery_items: Maximum entries accepted independently for each tool or prompt catalog fetch. Defaults to 1,000. ``None`` disables the limit. Discovery limits apply after the MCP SDK parses each page and do not bound the encoded response size; connect only to servers trusted to return reasonably sized responses and configure transport-specific size limits where available. @@ -4864,9 +4864,9 @@ def __init__( transport has no header hook, so source credentials outside ``function_invocation_kwargs`` for servers you do not control. task_options: Deprecated compatibility parameter. Non-``None`` values are ignored with a warning. - max_discovery_pages: Maximum number of pages accepted while discovering tools or prompts. + max_discovery_pages: Maximum pages accepted independently for each tool or prompt catalog fetch. ``None`` disables the limit. - max_discovery_items: Maximum number of tools or prompts accepted across all discovery pages. + max_discovery_items: Maximum entries accepted independently for each tool or prompt catalog fetch. Defaults to 1,000. ``None`` disables the limit. Discovery limits apply after the MCP SDK parses each page and do not bound the encoded response size; connect only to servers trusted to return reasonably sized responses and configure transport-specific size limits where available. diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index e125be8faa3..0bbd3ec7f60 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -328,8 +328,8 @@ def test_mcp_transport_subclasses_default_discovery_page_limit() -> None: MCPWebsocketTool(name="websocket", url="wss://example.com/mcp"), # ty: ignore[deprecated] ] - assert all(tool._max_discovery_pages == 100 for tool in tools) - assert all(tool._max_discovery_items == 1_000 for tool in tools) + assert all(tool.max_discovery_pages == 100 for tool in tools) + assert all(tool.max_discovery_items == 1_000 for tool in tools) def test_mcp_transport_subclasses_forward_discovery_page_limit() -> None: @@ -351,8 +351,8 @@ def test_mcp_transport_subclasses_forward_discovery_page_limit() -> None: ), ] - assert [tool._max_discovery_pages for tool in tools] == [101, 102, 103] - assert [tool._max_discovery_items for tool in tools] == [1_001, 1_002, 1_003] + assert [tool.max_discovery_pages for tool in tools] == [101, 102, 103] + assert [tool.max_discovery_items for tool in tools] == [1_001, 1_002, 1_003] @pytest.mark.parametrize("max_discovery_pages", [0, -1]) From c5bc92ed3a93c7d7a2b79e7221fce1430d1e6480 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Wed, 4 Nov 2026 12:32:08 +0100 Subject: [PATCH 16/18] Python: Preserve MCP discovery configuration across adapters --- .../0045-python-mcp-v2-client-lifecycle.md | 3 +- python/packages/core/AGENTS.md | 4 ++- python/packages/core/agent_framework/_mcp.py | 33 +++++++++++-------- .../packages/core/agent_framework/security.py | 21 +++++++++--- python/packages/core/tests/core/test_mcp.py | 26 ++++++++++++--- python/packages/core/tests/test_security.py | 27 +++++++++++++++ python/packages/declarative/AGENTS.md | 2 ++ .../_workflows/_mcp_handler.py | 14 ++++++++ .../tests/test_default_mcp_tool_handler.py | 15 +++++++++ 9 files changed, 120 insertions(+), 25 deletions(-) diff --git a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md index 12e6c01a242..3c0d6ff3802 100644 --- a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md +++ b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md @@ -68,7 +68,8 @@ Agent Framework owns: - transport and Client construction, Client entry, and resource cleanup for framework-created connections; - the lifecycle-owner task, locks, connection publication, reset coordination, and cancellation cleanup; -- the default request read timeout for framework-created Clients and configurable page/item bounds for +- the default request read timeout for framework-created Clients (with an explicit `None` opt-out) and configurable + page/item bounds for Agent Framework-driven tool and prompt catalog discovery; - request-scoped HTTP header identity and reconnects caused by identity changes; - tool argument filtering and trusted request metadata merging; diff --git a/python/packages/core/AGENTS.md b/python/packages/core/AGENTS.md index ae26d3972be..b66484a40ec 100644 --- a/python/packages/core/AGENTS.md +++ b/python/packages/core/AGENTS.md @@ -252,7 +252,8 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID and framework-owned transport options with `mcp_client` rather than ignoring them. Deprecated caller-owned `ClientSession` combinations remain compatible until their vNext removal. - **MCP request and discovery bounds** - Framework-created high-level Clients use the configured - `request_timeout`, or a 30-second read timeout when it is omitted. Caller-supplied Clients and + `request_timeout`, which defaults to a 30-second read timeout; `None` explicitly disables the timeout. + Caller-supplied Clients and `ClientSession`s retain their caller-owned request policy. Agent Framework tool and prompt discovery follows at most `max_discovery_pages` pages (default 100) and accepts at most `max_discovery_items` entries (default 1,000) per complete catalog fetch; `None` explicitly disables the corresponding limit for a trusted server. @@ -260,6 +261,7 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID unchanged. These limits apply after the MCP SDK parses each page and do not bound the encoded response size; applications remain responsible for connecting to servers trusted to return reasonably sized responses and for configuring transport-specific size limits where the selected transport exposes them. + `SecureMCPToolProxy(url=...)` forwards both discovery limits to its internal HTTP tool. - **Argument allowlist (`_prepare_call_kwargs`)** - Before each `tools/call`, kwargs are filtered to an **allowlist** built from the tool's declared parameters (`inputSchema.properties`) plus any user-configured extras. **The declared half comes from the server's advertised schema**, and runtime kwargs (`FunctionInvocationContext.kwargs`, seeded from `function_invocation_kwargs`) are merged with the model-supplied arguments upstream in `_call_tool_with_runtime_kwargs`, so provenance is gone by the time the filter runs. A runtime kwarg is therefore forwarded whenever the server declares a property of that name, without the model mentioning it — the server, not the caller, decides which runtime kwarg names it receives. A tool that declares no usable `properties` (including schemas with `additionalProperties: true`) forwards only the configured extras. `_MCP_FRAMEWORK_DENYLIST` is a narrow safety net covering only non-serializable framework objects a server *declares* in its schema (those are dropped); it does not generalize to arbitrary caller-chosen names, and explicit extras always win. The reserved `_meta` key is never forwarded as an argument; trusted caller/runtime `_meta` is validated as MCP request metadata, model-supplied `_meta` is discarded in generated MCP functions, and metadata precedence is caller/runtime < OpenTelemetry < tools/list metadata. - **`allowed_tools`** (constructor arg on all `MCPTool` subclasses) - Restricts exposed MCP tools by raw remote MCP tool identity. Prefixed local names remain accepted only when the raw remote name already matches its normalized form; normalized/local aliases do not authorize a different raw remote name. Configured allow/approval names must identify at most one raw remote name across loaded tools and prompts: a raw name that overlaps another tool's prefixed alias raises `ToolExecutionException`. Discovery validates all pages before publishing new functions; a failed reload retains the previous functions and metadata. The allowlist is also revalidated when exposing functions so runtime changes cannot select an ambiguous name. If multiple raw remote tool names map to the same local function name, tool loading raises `ToolExecutionException` instead of first-one-wins shadowing. - **`approval_mode`** (constructor arg on all `MCPTool` subclasses) - Accepts `"always_require"`, `"never_require"`, diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index dbae82e1f6a..4a80154f55b 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -1172,7 +1172,7 @@ def __init__( parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, mcp_client: Client | None = None, session: ClientSession | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, client: SupportsChatGetResponse | None = None, sampling_approval_callback: SamplingApprovalCallback | None = None, sampling_max_tokens: int | None = _DEFAULT_SAMPLING_MAX_TOKENS, @@ -2475,11 +2475,7 @@ async def _connect_on_owner( mcp_client = await self._exit_stack.enter_async_context( Client( server=self.get_mcp_client(), - read_timeout_seconds=( - self.request_timeout - if self.request_timeout is not None - else _MCP_DEFAULT_READ_TIMEOUT_SECONDS - ), + read_timeout_seconds=self.request_timeout, message_handler=self.message_handler, logging_callback=self.logging_callback, log_level=log_level, @@ -3808,7 +3804,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, mcp_client: Client | None = None, session: ClientSession | None = None, description: str | None = None, @@ -3864,7 +3860,8 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; + ``None`` disables the timeout. Caller-owned clients retain their own timeout policy. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``command`` and ``session``. ``request_timeout``, ``args``, ``env``, ``encoding``, and @@ -3960,7 +3957,10 @@ def __init__( conflicting_options = [ option for option, is_configured in ( - ("request_timeout", request_timeout is not None), + ( + "request_timeout", + request_timeout not in (None, _MCP_DEFAULT_READ_TIMEOUT_SECONDS), + ), ("args", args is not None), ("env", env is not None), ("encoding", encoding is not None), @@ -4075,7 +4075,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, mcp_client: Client | None = None, session: ClientSession | None = None, description: str | None = None, @@ -4134,7 +4134,8 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; + ``None`` disables the timeout. Caller-owned clients retain their own timeout policy. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``url`` and ``session``. ``request_timeout``, ``terminate_on_close``, ``http_client``, @@ -4299,7 +4300,10 @@ def __init__( conflicting_options = [ option for option, is_configured in ( - ("request_timeout", request_timeout is not None), + ( + "request_timeout", + request_timeout not in (None, _MCP_DEFAULT_READ_TIMEOUT_SECONDS), + ), ("terminate_on_close", terminate_on_close is not None), ("http_client", http_client is not None), ("static_headers", static_headers is not None), @@ -4755,7 +4759,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, session: ClientSession | None = None, description: str | None = None, approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None, @@ -4802,7 +4806,8 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; + ``None`` disables the timeout. Caller-owned sessions retain their own timeout policy. session: An existing MCP client session to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that session. description: The description of the tool. diff --git a/python/packages/core/agent_framework/security.py b/python/packages/core/agent_framework/security.py index 521c056b69a..954b7ce3043 100644 --- a/python/packages/core/agent_framework/security.py +++ b/python/packages/core/agent_framework/security.py @@ -4670,6 +4670,10 @@ class SecureMCPToolProxy: name: Tool name used when creating the internal ``MCPStreamableHTTPTool`` (defaults to ``"mcp"``). description: Tool description for the internal tool. + max_discovery_pages: Maximum pages accepted independently for each tool or prompt catalog fetch in + *url* mode. Defaults to 100; ``None`` disables the limit. + max_discovery_items: Maximum entries accepted independently for each tool or prompt catalog fetch in + *url* mode. Defaults to 1,000; ``None`` disables the limit. default_integrity: Default integrity for tools without annotations. annotation_overrides: Per-tool-name label overrides (keyed by remote MCP tool name), applied only to this proxy's MCP connection. @@ -4691,6 +4695,8 @@ def __init__( headers: dict[str, str] | None = None, name: str | None = None, description: str | None = None, + max_discovery_pages: int | None = 100, + max_discovery_items: int | None = 1_000, default_integrity: IntegrityLabel = IntegrityLabel.UNTRUSTED, annotation_overrides: dict[str, tuple[IntegrityLabel, ConfidentialityLabel | None]] | None = None, mark_write_tools_as_sinks: bool = True, @@ -4711,6 +4717,10 @@ def __init__( name: Tool name used when creating the internal ``MCPStreamableHTTPTool`` (defaults to ``"mcp"``). description: Tool description for the internal tool. + max_discovery_pages: Maximum pages accepted independently for each tool or prompt catalog fetch in + ``url`` mode. Defaults to 100; ``None`` disables the limit. + max_discovery_items: Maximum entries accepted independently for each tool or prompt catalog fetch in + ``url`` mode. Defaults to 1,000; ``None`` disables the limit. default_integrity: Default integrity for tools without annotations. Defaults to ``IntegrityLabel.UNTRUSTED``. annotation_overrides: Per-tool-name label overrides keyed by remote MCP tool name, @@ -4741,6 +4751,8 @@ def __init__( url=url, description=description, static_headers=static_headers, + max_discovery_pages=max_discovery_pages, + max_discovery_items=max_discovery_items, ) # The validation above guarantees a tool is set (passed directly or built @@ -4808,16 +4820,17 @@ async def disconnect(self) -> None: self._unbind_function_load_callback() async def refresh_labels(self) -> None: - """Re-apply labels and wrappers to all currently discovered functions. + """Refresh enabled tool discovery, then re-apply labels to discovered functions. - Later-discovered functions are labeled automatically while the proxy - is active. + When tool loading is disabled, this only reapplies labels to the existing catalog snapshot. + Later-discovered functions are labeled automatically while the proxy is active. """ if not self.is_connected: raise RuntimeError("MCPTool is not connected. Connect before refreshing labels.") callback_bound = self._bind_function_load_callback() try: - await self._mcp_tool.load_tools() + if self._mcp_tool.load_tools_flag: + await self._mcp_tool.load_tools() await self._apply_labels() except BaseException: if callback_bound: diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 0bbd3ec7f60..23ee4ea01a1 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -5812,7 +5812,7 @@ async def test_connect_preserves_request_timeout_over_24_hours() -> None: assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == 90_000 -async def test_connect_uses_default_read_timeout_when_request_timeout_is_none() -> None: +async def test_connect_uses_default_read_timeout_when_request_timeout_is_omitted() -> None: from agent_framework._mcp import _MCP_DEFAULT_READ_TIMEOUT_SECONDS tool = MCPStdioTool( @@ -5829,6 +5829,22 @@ async def test_connect_uses_default_read_timeout_when_request_timeout_is_none() assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == _MCP_DEFAULT_READ_TIMEOUT_SECONDS +async def test_connect_allows_disabling_request_timeout() -> None: + tool = MCPStdioTool( + name="test", + command="test-command", + load_tools=False, + load_prompts=False, + request_timeout=None, + ) + + with patch("mcp.Client") as mock_client_class: + mock_client_class.return_value = _mock_sdk_client(protocol_version="2026-07-28") + + async with tool: + assert mock_client_class.call_args.kwargs["read_timeout_seconds"] is None + + async def test_connect_revalidates_request_timeout_cleared_after_construction() -> None: tool = MCPStdioTool( name="test", @@ -8914,7 +8930,7 @@ def test_mcp_streamable_http_rejects_header_provider_with_supplied_client() -> N @pytest.mark.parametrize( ("option_name", "option_value"), [ - ("request_timeout", 30), + ("request_timeout", 31), ("terminate_on_close", False), ("http_client", Mock(spec=AsyncClient)), ("static_headers", {}), @@ -8943,7 +8959,7 @@ def test_mcp_streamable_http_lists_all_framework_owned_http_options_with_supplie MCPStreamableHTTPTool( name="test", mcp_client=Mock(), - request_timeout=30, + request_timeout=31, terminate_on_close=False, http_client=Mock(spec=AsyncClient), static_headers={}, @@ -9011,7 +9027,7 @@ def test_mcp_streamable_http_get_mcp_client_requires_framework_owned_url() -> No @pytest.mark.parametrize( ("option_name", "option_value"), [ - ("request_timeout", 30), + ("request_timeout", 31), ("args", []), ("env", {}), ("encoding", ""), @@ -9043,7 +9059,7 @@ def test_mcp_stdio_lists_all_framework_owned_options_with_supplied_client() -> N MCPStdioTool( name="test", mcp_client=Mock(), - request_timeout=30, + request_timeout=31, args=[], env={}, encoding="", diff --git a/python/packages/core/tests/test_security.py b/python/packages/core/tests/test_security.py index d5aeeed8755..32a128775ed 100644 --- a/python/packages/core/tests/test_security.py +++ b/python/packages/core/tests/test_security.py @@ -6109,6 +6109,18 @@ def test_user_identity_requires_matching_principals( class TestSecureMCPToolProxyURLMode: """Tests for origin-scoped headers in the proxy's URL mode.""" + def test_forwards_discovery_limits(self) -> None: + from agent_framework.security import SecureMCPToolProxy + + proxy = SecureMCPToolProxy( + url="https://mcp.example/mcp", + max_discovery_pages=12, + max_discovery_items=345, + ) + + assert proxy.mcp_tool.max_discovery_pages == 12 + assert proxy.mcp_tool.max_discovery_items == 345 + async def test_static_headers_do_not_serialize_tool_calls(self) -> None: from unittest.mock import patch @@ -7001,6 +7013,21 @@ async def test_secure_mcp_proxy_configures_result_authority(self, trust_server_i ) assert result[0].additional_properties["security_label"] == expected_label + async def test_secure_mcp_proxy_refresh_respects_disabled_tool_loading(self) -> None: + from agent_framework.security import SecureMCPToolProxy + + annotations = SimpleNamespace(read_only_hint=True, open_world_hint=False) + mcp_tool, function = _make_connected_mcp_tool_for_ifc(annotations=annotations, server_meta={}) + mcp_tool.load_tools_flag = False + mcp_tool.load_tools = AsyncMock() # type: ignore[method-assign] + proxy = SecureMCPToolProxy(mcp_tool) + + await proxy.refresh_labels() + + mcp_tool.load_tools.assert_not_awaited() # type: ignore[union-attr] + assert function.additional_properties is not None + assert function.additional_properties["source_integrity"] == "untrusted" + async def test_secure_mcp_proxy_labels_notification_reload_before_publication(self): from mcp import types as mcp_types diff --git a/python/packages/declarative/AGENTS.md b/python/packages/declarative/AGENTS.md index 059c1c605d7..1c725aff316 100644 --- a/python/packages/declarative/AGENTS.md +++ b/python/packages/declarative/AGENTS.md @@ -27,6 +27,8 @@ series because response caching and default-header integration use its internals With a provider, every invocation (including `tools/list`) gets a fresh tool/session, even if the provider returns `None` or a shared HTTP client. Invocation cleanup closes the session and any internally owned fallback client, never caller-owned HTTP clients. +The handler forwards its configurable `max_discovery_pages` and `max_discovery_items` +limits to every internally created `MCPStreamableHTTPTool`. Shutdown waits for active provider-backed invocations to clean up. Calling `aclose()` from an active invocation's context (including inherited child tasks and cleanup) raises `RuntimeError` before changing handler state; shutdown must run outside that diff --git a/python/packages/declarative/agent_framework_declarative/_workflows/_mcp_handler.py b/python/packages/declarative/agent_framework_declarative/_workflows/_mcp_handler.py index 3dee698de35..f7ec768a6a9 100644 --- a/python/packages/declarative/agent_framework_declarative/_workflows/_mcp_handler.py +++ b/python/packages/declarative/agent_framework_declarative/_workflows/_mcp_handler.py @@ -202,6 +202,10 @@ class DefaultMCPToolHandler: When exceeded, the least-recently-used entry is evicted and its owned client closed. Defaults to ``32``. Does not enable session caching when a provider is configured. + max_discovery_pages: Maximum pages accepted independently for each tool catalog fetch. + Defaults to 100; ``None`` disables the limit. + max_discovery_items: Maximum tools accepted across each tool catalog fetch. + Defaults to 1,000; ``None`` disables the limit. """ LIST_TOOLS_TOOL_NAME: ClassVar[str] = "tools/list" @@ -224,11 +228,19 @@ def __init__( *, client_provider: ClientProvider | None = None, cache_max_size: int = _DEFAULT_CACHE_MAX_SIZE, + max_discovery_pages: int | None = 100, + max_discovery_items: int | None = 1_000, ) -> None: if cache_max_size <= 0: raise ValueError(f"cache_max_size must be positive, got {cache_max_size}") + if max_discovery_pages is not None and max_discovery_pages <= 0: + raise ValueError("max_discovery_pages must be positive or None.") + if max_discovery_items is not None and max_discovery_items <= 0: + raise ValueError("max_discovery_items must be positive or None.") self._client_provider = client_provider self._cache_max_size = cache_max_size + self._max_discovery_pages = max_discovery_pages + self._max_discovery_items = max_discovery_items self._cache: OrderedDict[tuple[str, str, str, str], _CacheEntry] = OrderedDict() # Outer lock guards the cache + in-flight-future map only — never # held across network I/O. @@ -603,6 +615,8 @@ def _header_provider(_kwargs: dict[str, Any]) -> dict[str, str]: load_prompts=False, http_client=provided_client, header_provider=_header_provider if captured_headers else None, + max_discovery_pages=self._max_discovery_pages, + max_discovery_items=self._max_discovery_items, ) try: await tool.connect() diff --git a/python/packages/declarative/tests/test_default_mcp_tool_handler.py b/python/packages/declarative/tests/test_default_mcp_tool_handler.py index 1c5f4476749..03a1f880465 100644 --- a/python/packages/declarative/tests/test_default_mcp_tool_handler.py +++ b/python/packages/declarative/tests/test_default_mcp_tool_handler.py @@ -828,11 +828,26 @@ def test_invalid_cache_size_raises(self) -> None: with pytest.raises(ValueError): DefaultMCPToolHandler(cache_max_size=-3) + def test_invalid_discovery_limit_raises(self) -> None: + with pytest.raises(ValueError, match="max_discovery_pages must be positive or None"): + DefaultMCPToolHandler(max_discovery_pages=0) + with pytest.raises(ValueError, match="max_discovery_items must be positive or None"): + DefaultMCPToolHandler(max_discovery_items=-1) + # ---------- Tool kwargs ---------------------------------------------------- class TestToolKwargs: + @pytest.mark.asyncio + async def test_discovery_limits_passed_to_tool(self) -> None: + handler = DefaultMCPToolHandler(max_discovery_pages=12, max_discovery_items=345) + with _patch_tool(): + await handler.invoke_tool(_invocation()) + + assert FakeTool.instances[0].kwargs["max_discovery_pages"] == 12 + assert FakeTool.instances[0].kwargs["max_discovery_items"] == 345 + @pytest.mark.asyncio async def test_load_prompts_false_passed_to_tool(self) -> None: handler = DefaultMCPToolHandler() From 6fbda2d8df2a4302973367c49f4efa8c2b1cb939 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Wed, 4 Nov 2026 12:55:59 +0100 Subject: [PATCH 17/18] Python: Preserve MCP adapter configuration semantics --- .../0045-python-mcp-v2-client-lifecycle.md | 4 +-- python/packages/core/AGENTS.md | 3 +- python/packages/core/agent_framework/_mcp.py | 27 ++++++------------ python/packages/core/tests/core/test_mcp.py | 28 ++++--------------- 4 files changed, 16 insertions(+), 46 deletions(-) diff --git a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md index 3c0d6ff3802..c7af03dd1fa 100644 --- a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md +++ b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md @@ -68,9 +68,7 @@ Agent Framework owns: - transport and Client construction, Client entry, and resource cleanup for framework-created connections; - the lifecycle-owner task, locks, connection publication, reset coordination, and cancellation cleanup; -- the default request read timeout for framework-created Clients (with an explicit `None` opt-out) and configurable - page/item bounds for - Agent Framework-driven tool and prompt catalog discovery; +- configurable page/item bounds for Agent Framework-driven tool and prompt catalog discovery; - request-scoped HTTP header identity and reconnects caused by identity changes; - tool argument filtering and trusted request metadata merging; - result parsing, Agent Framework content conversion, tracing, and error translation; diff --git a/python/packages/core/AGENTS.md b/python/packages/core/AGENTS.md index b66484a40ec..83fbfef77d6 100644 --- a/python/packages/core/AGENTS.md +++ b/python/packages/core/AGENTS.md @@ -252,8 +252,7 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID and framework-owned transport options with `mcp_client` rather than ignoring them. Deprecated caller-owned `ClientSession` combinations remain compatible until their vNext removal. - **MCP request and discovery bounds** - Framework-created high-level Clients use the configured - `request_timeout`, which defaults to a 30-second read timeout; `None` explicitly disables the timeout. - Caller-supplied Clients and + `request_timeout`; `None` preserves the MCP SDK's unlimited request timeout. Caller-supplied Clients and `ClientSession`s retain their caller-owned request policy. Agent Framework tool and prompt discovery follows at most `max_discovery_pages` pages (default 100) and accepts at most `max_discovery_items` entries (default 1,000) per complete catalog fetch; `None` explicitly disables the corresponding limit for a trusted server. diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 4a80154f55b..92c9a0175d8 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -1172,7 +1172,7 @@ def __init__( parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, mcp_client: Client | None = None, session: ClientSession | None = None, - request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, + request_timeout: int | None = None, client: SupportsChatGetResponse | None = None, sampling_approval_callback: SamplingApprovalCallback | None = None, sampling_max_tokens: int | None = _DEFAULT_SAMPLING_MAX_TOKENS, @@ -3804,7 +3804,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, + request_timeout: int | None = None, mcp_client: Client | None = None, session: ClientSession | None = None, description: str | None = None, @@ -3860,8 +3860,7 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; - ``None`` disables the timeout. Caller-owned clients retain their own timeout policy. + request_timeout: The default timeout in seconds for all requests. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``command`` and ``session``. ``request_timeout``, ``args``, ``env``, ``encoding``, and @@ -3957,10 +3956,7 @@ def __init__( conflicting_options = [ option for option, is_configured in ( - ( - "request_timeout", - request_timeout not in (None, _MCP_DEFAULT_READ_TIMEOUT_SECONDS), - ), + ("request_timeout", request_timeout is not None), ("args", args is not None), ("env", env is not None), ("encoding", encoding is not None), @@ -4075,7 +4071,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, + request_timeout: int | None = None, mcp_client: Client | None = None, session: ClientSession | None = None, description: str | None = None, @@ -4134,8 +4130,7 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; - ``None`` disables the timeout. Caller-owned clients retain their own timeout policy. + request_timeout: The default timeout in seconds for all requests. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``url`` and ``session``. ``request_timeout``, ``terminate_on_close``, ``http_client``, @@ -4300,10 +4295,7 @@ def __init__( conflicting_options = [ option for option, is_configured in ( - ( - "request_timeout", - request_timeout not in (None, _MCP_DEFAULT_READ_TIMEOUT_SECONDS), - ), + ("request_timeout", request_timeout is not None), ("terminate_on_close", terminate_on_close is not None), ("http_client", http_client is not None), ("static_headers", static_headers is not None), @@ -4759,7 +4751,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, + request_timeout: int | None = None, session: ClientSession | None = None, description: str | None = None, approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None, @@ -4806,8 +4798,7 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; - ``None`` disables the timeout. Caller-owned sessions retain their own timeout policy. + request_timeout: The default timeout in seconds for all requests. session: An existing MCP client session to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that session. description: The description of the tool. diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 23ee4ea01a1..2ba46bd57c5 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -5812,30 +5812,12 @@ async def test_connect_preserves_request_timeout_over_24_hours() -> None: assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == 90_000 -async def test_connect_uses_default_read_timeout_when_request_timeout_is_omitted() -> None: - from agent_framework._mcp import _MCP_DEFAULT_READ_TIMEOUT_SECONDS - - tool = MCPStdioTool( - name="test", - command="test-command", - load_tools=False, - load_prompts=False, - ) - - with patch("mcp.Client") as mock_client_class: - mock_client_class.return_value = _mock_sdk_client(protocol_version="2026-07-28") - - async with tool: - assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == _MCP_DEFAULT_READ_TIMEOUT_SECONDS - - -async def test_connect_allows_disabling_request_timeout() -> None: +async def test_connect_preserves_unlimited_request_timeout_by_default() -> None: tool = MCPStdioTool( name="test", command="test-command", load_tools=False, load_prompts=False, - request_timeout=None, ) with patch("mcp.Client") as mock_client_class: @@ -8930,7 +8912,7 @@ def test_mcp_streamable_http_rejects_header_provider_with_supplied_client() -> N @pytest.mark.parametrize( ("option_name", "option_value"), [ - ("request_timeout", 31), + ("request_timeout", 30), ("terminate_on_close", False), ("http_client", Mock(spec=AsyncClient)), ("static_headers", {}), @@ -8959,7 +8941,7 @@ def test_mcp_streamable_http_lists_all_framework_owned_http_options_with_supplie MCPStreamableHTTPTool( name="test", mcp_client=Mock(), - request_timeout=31, + request_timeout=30, terminate_on_close=False, http_client=Mock(spec=AsyncClient), static_headers={}, @@ -9027,7 +9009,7 @@ def test_mcp_streamable_http_get_mcp_client_requires_framework_owned_url() -> No @pytest.mark.parametrize( ("option_name", "option_value"), [ - ("request_timeout", 31), + ("request_timeout", 30), ("args", []), ("env", {}), ("encoding", ""), @@ -9059,7 +9041,7 @@ def test_mcp_stdio_lists_all_framework_owned_options_with_supplied_client() -> N MCPStdioTool( name="test", mcp_client=Mock(), - request_timeout=31, + request_timeout=30, args=[], env={}, encoding="", From 5f71784ba7b7d9a9e948d602756b6995b6b3fd47 Mon Sep 17 00:00:00 2001 From: Jose Alvarez Date: Wed, 4 Nov 2026 13:04:28 +0100 Subject: [PATCH 18/18] Python: Default owned MCP requests to a finite timeout --- .../0045-python-mcp-v2-client-lifecycle.md | 1 + python/packages/core/AGENTS.md | 3 +- python/packages/core/agent_framework/_mcp.py | 27 ++++++++++++------ python/packages/core/tests/core/test_mcp.py | 28 +++++++++++++++---- 4 files changed, 44 insertions(+), 15 deletions(-) diff --git a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md index c7af03dd1fa..6e51ab6266f 100644 --- a/docs/decisions/0045-python-mcp-v2-client-lifecycle.md +++ b/docs/decisions/0045-python-mcp-v2-client-lifecycle.md @@ -68,6 +68,7 @@ Agent Framework owns: - transport and Client construction, Client entry, and resource cleanup for framework-created connections; - the lifecycle-owner task, locks, connection publication, reset coordination, and cancellation cleanup; +- the default request read timeout for framework-created Clients, with an explicit `None` opt-out; - configurable page/item bounds for Agent Framework-driven tool and prompt catalog discovery; - request-scoped HTTP header identity and reconnects caused by identity changes; - tool argument filtering and trusted request metadata merging; diff --git a/python/packages/core/AGENTS.md b/python/packages/core/AGENTS.md index 83fbfef77d6..b66484a40ec 100644 --- a/python/packages/core/AGENTS.md +++ b/python/packages/core/AGENTS.md @@ -252,7 +252,8 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID and framework-owned transport options with `mcp_client` rather than ignoring them. Deprecated caller-owned `ClientSession` combinations remain compatible until their vNext removal. - **MCP request and discovery bounds** - Framework-created high-level Clients use the configured - `request_timeout`; `None` preserves the MCP SDK's unlimited request timeout. Caller-supplied Clients and + `request_timeout`, which defaults to a 30-second read timeout; `None` explicitly disables the timeout. + Caller-supplied Clients and `ClientSession`s retain their caller-owned request policy. Agent Framework tool and prompt discovery follows at most `max_discovery_pages` pages (default 100) and accepts at most `max_discovery_items` entries (default 1,000) per complete catalog fetch; `None` explicitly disables the corresponding limit for a trusted server. diff --git a/python/packages/core/agent_framework/_mcp.py b/python/packages/core/agent_framework/_mcp.py index 92c9a0175d8..4a80154f55b 100644 --- a/python/packages/core/agent_framework/_mcp.py +++ b/python/packages/core/agent_framework/_mcp.py @@ -1172,7 +1172,7 @@ def __init__( parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, mcp_client: Client | None = None, session: ClientSession | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, client: SupportsChatGetResponse | None = None, sampling_approval_callback: SamplingApprovalCallback | None = None, sampling_max_tokens: int | None = _DEFAULT_SAMPLING_MAX_TOKENS, @@ -3804,7 +3804,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, mcp_client: Client | None = None, session: ClientSession | None = None, description: str | None = None, @@ -3860,7 +3860,8 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The default timeout in seconds for all requests. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; + ``None`` disables the timeout. Caller-owned clients retain their own timeout policy. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``command`` and ``session``. ``request_timeout``, ``args``, ``env``, ``encoding``, and @@ -3956,7 +3957,10 @@ def __init__( conflicting_options = [ option for option, is_configured in ( - ("request_timeout", request_timeout is not None), + ( + "request_timeout", + request_timeout not in (None, _MCP_DEFAULT_READ_TIMEOUT_SECONDS), + ), ("args", args is not None), ("env", env is not None), ("encoding", encoding is not None), @@ -4071,7 +4075,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, mcp_client: Client | None = None, session: ClientSession | None = None, description: str | None = None, @@ -4130,7 +4134,8 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The default timeout in seconds for all requests. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; + ``None`` disables the timeout. Caller-owned clients retain their own timeout policy. mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that client. Mutually exclusive with ``url`` and ``session``. ``request_timeout``, ``terminate_on_close``, ``http_client``, @@ -4295,7 +4300,10 @@ def __init__( conflicting_options = [ option for option, is_configured in ( - ("request_timeout", request_timeout is not None), + ( + "request_timeout", + request_timeout not in (None, _MCP_DEFAULT_READ_TIMEOUT_SECONDS), + ), ("terminate_on_close", terminate_on_close is not None), ("http_client", http_client is not None), ("static_headers", static_headers is not None), @@ -4751,7 +4759,7 @@ def __init__( parse_tool_results: Callable[[types.CallToolResult], str | list[Content]] | None = None, load_prompts: bool = True, parse_prompt_results: Callable[[types.GetPromptResult], str] | None = None, - request_timeout: int | None = None, + request_timeout: int | None = _MCP_DEFAULT_READ_TIMEOUT_SECONDS, session: ClientSession | None = None, description: str | None = None, approval_mode: (Literal["always_require", "never_require"] | MCPSpecificApproval | None) = None, @@ -4798,7 +4806,8 @@ def __init__( MCP prompt results to a string. If you need per-function result parsing, access the ``.functions`` list after connecting and set ``result_parser`` on individual ``FunctionTool`` instances. - request_timeout: The default timeout in seconds for all requests. + request_timeout: The timeout in seconds for all requests. Framework-owned clients default to 30 seconds; + ``None`` disables the timeout. Caller-owned sessions retain their own timeout policy. session: An existing MCP client session to use. The caller retains ownership; closing or resetting this wrapper does not close or replace that session. description: The description of the tool. diff --git a/python/packages/core/tests/core/test_mcp.py b/python/packages/core/tests/core/test_mcp.py index 2ba46bd57c5..23ee4ea01a1 100644 --- a/python/packages/core/tests/core/test_mcp.py +++ b/python/packages/core/tests/core/test_mcp.py @@ -5812,12 +5812,30 @@ async def test_connect_preserves_request_timeout_over_24_hours() -> None: assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == 90_000 -async def test_connect_preserves_unlimited_request_timeout_by_default() -> None: +async def test_connect_uses_default_read_timeout_when_request_timeout_is_omitted() -> None: + from agent_framework._mcp import _MCP_DEFAULT_READ_TIMEOUT_SECONDS + + tool = MCPStdioTool( + name="test", + command="test-command", + load_tools=False, + load_prompts=False, + ) + + with patch("mcp.Client") as mock_client_class: + mock_client_class.return_value = _mock_sdk_client(protocol_version="2026-07-28") + + async with tool: + assert mock_client_class.call_args.kwargs["read_timeout_seconds"] == _MCP_DEFAULT_READ_TIMEOUT_SECONDS + + +async def test_connect_allows_disabling_request_timeout() -> None: tool = MCPStdioTool( name="test", command="test-command", load_tools=False, load_prompts=False, + request_timeout=None, ) with patch("mcp.Client") as mock_client_class: @@ -8912,7 +8930,7 @@ def test_mcp_streamable_http_rejects_header_provider_with_supplied_client() -> N @pytest.mark.parametrize( ("option_name", "option_value"), [ - ("request_timeout", 30), + ("request_timeout", 31), ("terminate_on_close", False), ("http_client", Mock(spec=AsyncClient)), ("static_headers", {}), @@ -8941,7 +8959,7 @@ def test_mcp_streamable_http_lists_all_framework_owned_http_options_with_supplie MCPStreamableHTTPTool( name="test", mcp_client=Mock(), - request_timeout=30, + request_timeout=31, terminate_on_close=False, http_client=Mock(spec=AsyncClient), static_headers={}, @@ -9009,7 +9027,7 @@ def test_mcp_streamable_http_get_mcp_client_requires_framework_owned_url() -> No @pytest.mark.parametrize( ("option_name", "option_value"), [ - ("request_timeout", 30), + ("request_timeout", 31), ("args", []), ("env", {}), ("encoding", ""), @@ -9041,7 +9059,7 @@ def test_mcp_stdio_lists_all_framework_owned_options_with_supplied_client() -> N MCPStdioTool( name="test", mcp_client=Mock(), - request_timeout=30, + request_timeout=31, args=[], env={}, encoding="",