Skip to content

Commit bba9596

Browse files
authored
Python: Clarify MCP client ownership and add workflow sample (#9532)
* Added mcp_client supplied workflow sample + tightened ownership checks in constructor * Tests, docs and sample edits * Adjusted MCPStdioTool * Fix caller-owned MCP sampling test setup * Address MCP lifecycle review feedback * PR feedback * Address workflow sample review feedback * Update MCP recovery tests for caller-owned clients
1 parent 8ff2ec9 commit bba9596

7 files changed

Lines changed: 471 additions & 47 deletions

File tree

‎docs/decisions/0045-python-mcp-v2-client-lifecycle.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,12 @@ For **caller-supplied** connections, the caller owns:
8282
- constructing and closing a **supplied** low-level `ClientSession`;
8383
- the transport, authentication, callbacks, and other configuration already captured by either supplied object.
8484

85+
Transport-specific tool constructors enforce the same ownership boundary. A URL or command selects
86+
framework-owned Client construction; a supplied high-level `mcp.Client` selects caller-owned construction and
87+
lifecycle. Constructor combinations that mix those ownership modes or configure a transport the caller already
88+
owns raise `ValueError` instead of silently ignoring parameters. Temporarily retained legacy constructor and
89+
`ClientSession` combinations remain compatible and will be removed in vNext.
90+
8591
The SDK `Client` owns:
8692

8793
- modern negotiation and legacy initialization fallback;
@@ -245,4 +251,4 @@ Committed contract tests cover:
245251
- [MCP caching specification](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching)
246252
- [ADR 0043: MCP runtime context](0043-python-mcp-runtime-context.md)
247253

248-
This ADR remains `proposed` until accepted through the repository ADR review process.
254+
This ADR was accepted through the repository ADR review process.

‎python/packages/core/AGENTS.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,11 @@ The vector store API is experimental under the shared `VECTOR_STORES` feature ID
221221
- **`MCPStdioTool`** / **`MCPStreamableHTTPTool`** - Supported transport-specific subclasses.
222222
**`MCPWebsocketTool`** remains only as a deprecated compatibility symbol because MCP v2 removed WebSocket
223223
transport; it cannot create a connection.
224+
- **MCP transport construction ownership** - For `MCPStreamableHTTPTool`, `url` selects framework-owned
225+
construction; for `MCPStdioTool`, `command` does. Supplying an already-entered `mcp_client` instead makes the
226+
caller responsible for transport configuration and Client lifecycle. Constructors reject mixed ownership modes
227+
and framework-owned transport options with `mcp_client` rather than ignoring them. Deprecated caller-owned
228+
`ClientSession` combinations remain compatible until their vNext removal.
224229
- **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.
225230
- **`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.
226231
- **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.

‎python/packages/core/agent_framework/_mcp.py‎

Lines changed: 95 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3655,7 +3655,7 @@ class MCPStdioTool(MCPTool):
36553655
def __init__(
36563656
self,
36573657
name: str,
3658-
command: str,
3658+
command: str | None = None,
36593659
*,
36603660
tool_name_prefix: str | None = None,
36613661
load_tools: bool = True,
@@ -3687,13 +3687,18 @@ def __init__(
36873687
"""Initialize the MCP stdio tool.
36883688
36893689
Note:
3690-
The arguments are used to create a StdioServerParameters object,
3691-
which is then used to create a stdio client. See ``mcp.client.stdio.stdio_client``
3690+
Supply either ``command`` for a framework-owned high-level Client, or an already-entered
3691+
``mcp_client`` for a caller-owned high-level Client. The deprecated ``session`` path
3692+
remains caller-owned and may continue to be combined with ``command`` for compatibility.
3693+
3694+
In framework-owned command mode, the arguments are used to create a
3695+
``StdioServerParameters`` object and stdio client. See ``mcp.client.stdio.stdio_client``
36923696
and ``mcp.client.stdio.stdio_server_parameters`` for more details.
36933697
36943698
Args:
36953699
name: The name of the tool.
3696-
command: The command to run the MCP server.
3700+
command: The command to run for framework-owned stdio Client construction. Mutually exclusive
3701+
with ``mcp_client``. May be omitted when supplying ``mcp_client`` or the deprecated ``session``.
36973702
36983703
Keyword Args:
36993704
tool_name_prefix: Optional prefix to prepend to exposed MCP function names.
@@ -3714,9 +3719,10 @@ def __init__(
37143719
request_timeout: The default timeout in seconds for all requests.
37153720
mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership;
37163721
closing or resetting this wrapper does not close or replace that client. Mutually exclusive
3717-
with ``session``. Sampling options configured on this wrapper do not modify the supplied Client.
3718-
The supplied Client also owns its transport and authentication configuration, so it cannot be
3719-
combined with this wrapper's ``header_provider``.
3722+
with ``command`` and ``session``. ``request_timeout``, ``args``, ``env``, ``encoding``, and
3723+
additional stdio keyword arguments configure framework-owned process construction and cannot be
3724+
supplied with ``mcp_client``. Sampling options configured on this wrapper do not modify the
3725+
supplied Client.
37203726
session: A deprecated low-level MCP ``ClientSession`` compatibility path. Prefer ``mcp_client`` for new
37213727
usage. The caller retains ownership; closing or resetting this wrapper does not close or replace
37223728
that session. Sampling options configured on this wrapper do not modify the supplied session.
@@ -3783,8 +3789,35 @@ def __init__(
37833789
transports. ``None`` disables the limit.
37843790
tool_result_content: How to choose model-visible text when both ``content`` and
37853791
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
3786-
kwargs: Any extra arguments to pass to the stdio client.
3792+
kwargs: Additional arguments for framework-owned ``StdioServerParameters`` construction.
37873793
"""
3794+
if mcp_client is not None and session is not None:
3795+
raise ValueError("`mcp_client` and `session` are mutually exclusive. If possible, prefer `mcp_client`.")
3796+
if mcp_client is not None and command is not None:
3797+
raise ValueError(
3798+
"`command` and `mcp_client` are mutually exclusive; configure the process on the supplied Client."
3799+
)
3800+
if mcp_client is None and session is None and command is None:
3801+
raise ValueError("`command` is required when neither `mcp_client` nor `session` supplies a connection.")
3802+
if mcp_client is not None:
3803+
conflicting_options = [
3804+
option
3805+
for option, is_configured in (
3806+
("request_timeout", request_timeout is not None),
3807+
("args", args is not None),
3808+
("env", env is not None),
3809+
("encoding", encoding is not None),
3810+
("kwargs", bool(kwargs)),
3811+
)
3812+
if is_configured
3813+
]
3814+
if conflicting_options:
3815+
formatted_options = ", ".join(f"`{option}`" for option in conflicting_options)
3816+
raise ValueError(
3817+
f"`mcp_client` cannot be combined with framework-owned stdio options: {formatted_options}. "
3818+
"Configure these settings on the supplied Client instead."
3819+
)
3820+
37883821
super().__init__(
37893822
name=name,
37903823
description=description,
@@ -3818,7 +3851,8 @@ def __init__(
38183851

38193852
def _mcp_base_span_attributes(self) -> dict[str, Any]:
38203853
attrs = super()._mcp_base_span_attributes()
3821-
attrs[OtelAttr.NETWORK_TRANSPORT] = "pipe"
3854+
if self.command is not None:
3855+
attrs[OtelAttr.NETWORK_TRANSPORT] = "pipe"
38223856
return attrs
38233857

38243858
def get_mcp_client(self) -> _AsyncGeneratorContextManager[Any, None]:
@@ -3827,6 +3861,11 @@ def get_mcp_client(self) -> _AsyncGeneratorContextManager[Any, None]:
38273861
Returns:
38283862
An async context manager for the stdio client transport.
38293863
"""
3864+
if self.command is None:
3865+
raise RuntimeError(
3866+
"Internal invariant violated: MCPStdioTool requires `command` to create a framework-owned Client."
3867+
)
3868+
38303869
args: dict[str, Any] = {
38313870
"command": self.command,
38323871
"args": self.args,
@@ -3870,7 +3909,7 @@ class MCPStreamableHTTPTool(MCPTool):
38703909
def __init__(
38713910
self,
38723911
name: str,
3873-
url: str,
3912+
url: str | None = None,
38743913
*,
38753914
tool_name_prefix: str | None = None,
38763915
load_tools: bool = True,
@@ -3903,15 +3942,20 @@ def __init__(
39033942
"""Initialize the MCP streamable HTTP tool.
39043943
39053944
Note:
3906-
The arguments are used to create a streamable HTTP client using the
3907-
new ``mcp.client.streamable_http.streamable_http_client`` API.
3908-
If an ``httpx2.AsyncClient`` is provided via ``http_client``, it will be used as the underlying transport
3909-
client.
3910-
Otherwise, the tool creates and manages a default client without response-cookie persistence.
3945+
Supply either ``url`` for a framework-owned high-level Client, or an already-entered
3946+
``mcp_client`` for a caller-owned high-level Client. The deprecated ``session`` path
3947+
remains caller-owned and may continue to be combined with ``url`` for compatibility.
3948+
3949+
In framework-owned URL mode, the arguments are used to create a streamable HTTP client
3950+
using the new ``mcp.client.streamable_http.streamable_http_client`` API. If an
3951+
``httpx2.AsyncClient`` is provided via ``http_client``, it will be used as the underlying
3952+
transport client. Otherwise, the tool creates and manages a default client without
3953+
response-cookie persistence.
39113954
39123955
Args:
39133956
name: The name of the tool.
3914-
url: The URL of the MCP server.
3957+
url: The URL of the MCP server for framework-owned Client construction. Mutually exclusive
3958+
with ``mcp_client``. May be omitted when supplying ``mcp_client`` or the deprecated ``session``.
39153959
39163960
Keyword Args:
39173961
tool_name_prefix: Optional prefix to prepend to exposed MCP function names.
@@ -3932,7 +3976,10 @@ def __init__(
39323976
request_timeout: The default timeout in seconds for all requests.
39333977
mcp_client: An already-entered high-level MCP ``Client`` to use. The caller retains ownership;
39343978
closing or resetting this wrapper does not close or replace that client. Mutually exclusive
3935-
with ``session``. Sampling options configured on this wrapper do not modify the supplied Client.
3979+
with ``url`` and ``session``. ``request_timeout``, ``terminate_on_close``, ``http_client``,
3980+
``static_headers``, and ``header_provider`` configure framework-owned HTTP construction and
3981+
cannot be supplied with ``mcp_client``. Sampling options configured on this wrapper do not
3982+
modify the supplied Client.
39363983
session: A deprecated low-level MCP ``ClientSession`` compatibility path. Prefer ``mcp_client`` for new
39373984
usage. The caller retains ownership; closing or resetting this wrapper does not close or replace
39383985
that session. Sampling options configured on this wrapper do not modify the supplied session.
@@ -4070,11 +4117,32 @@ def __init__(
40704117
``structuredContent`` are present. See :data:`MCPToolResultContentMode`.
40714118
kwargs: Additional keyword arguments (accepted for backward compatibility but not used).
40724119
"""
4073-
if mcp_client is not None and header_provider is not None:
4120+
if mcp_client is not None and session is not None:
4121+
raise ValueError("`mcp_client` and `session` are mutually exclusive. If possible, prefer `mcp_client`.")
4122+
if mcp_client is not None and url is not None:
40744123
raise ValueError(
4075-
"`header_provider` cannot be used in combination with a user-supplied `mcp_client`; "
4076-
"configure per-request headers on the supplied Client's transport."
4124+
"`url` and `mcp_client` are mutually exclusive; configure the endpoint on the supplied Client."
40774125
)
4126+
if mcp_client is None and session is None and url is None:
4127+
raise ValueError("`url` is required when neither `mcp_client` nor `session` supplies a connection.")
4128+
if mcp_client is not None:
4129+
conflicting_options = [
4130+
option
4131+
for option, is_configured in (
4132+
("request_timeout", request_timeout is not None),
4133+
("terminate_on_close", terminate_on_close is not None),
4134+
("http_client", http_client is not None),
4135+
("static_headers", static_headers is not None),
4136+
("header_provider", header_provider is not None),
4137+
)
4138+
if is_configured
4139+
]
4140+
if conflicting_options:
4141+
formatted_options = ", ".join(f"`{option}`" for option in conflicting_options)
4142+
raise ValueError(
4143+
f"`mcp_client` cannot be combined with framework-owned HTTP options: {formatted_options}. "
4144+
"Configure these settings on the supplied Client instead."
4145+
)
40784146

40794147
super().__init__(
40804148
name=name,
@@ -4130,6 +4198,8 @@ def __init__(
41304198

41314199
def _mcp_base_span_attributes(self) -> dict[str, Any]:
41324200
attrs = super()._mcp_base_span_attributes()
4201+
if self.url is None:
4202+
return attrs
41334203
attrs[OtelAttr.NETWORK_TRANSPORT] = "tcp"
41344204
attrs[OtelAttr.NETWORK_PROTOCOL_NAME] = "http"
41354205
try:
@@ -4158,6 +4228,11 @@ def get_mcp_client(self) -> _AsyncGeneratorContextManager[Any, None]:
41584228
Returns:
41594229
An async context manager for the streamable HTTP client transport.
41604230
"""
4231+
if self.url is None:
4232+
raise RuntimeError(
4233+
"Internal invariant violated: MCPStreamableHTTPTool requires `url` to create a framework-owned Client."
4234+
)
4235+
41614236
from httpx2 import URL, AsyncClient, Timeout
41624237

41634238
self._promote_pending_session_headers()

0 commit comments

Comments
 (0)