Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions docs/decisions/0045-python-mcp-v2-client-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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;
- 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.
Expand All @@ -80,14 +82,20 @@ 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 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
lifecycle. Constructor combinations that mix those ownership modes or configure a transport the caller already
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;
Expand Down Expand Up @@ -153,6 +161,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`.
Expand Down
20 changes: 19 additions & 1 deletion python/packages/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,17 @@ 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`, 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.
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.
`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"`,
Expand All @@ -263,7 +274,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.
Expand Down
Loading
Loading