Skip to content

Commit 9127b89

Browse files
authored
Python: Document MCP v2 client lifecycle and update samples (#9237)
* Document MCP v2 client lifecycle * Update MCP v2 samples and documentation * Added mcp_client constructor param * Updated the ADR * Documentation, AGENTS and ADR updates * Fix supplied MCP client test typing * Logging warning for sampling options with incompatible params in the ctx * Reject constructor supplied header provider if an mcp_client is also provided * Address MCP lifecycle review feedback * deprecated session setters * More PR feedback * Task availability clarification * documentation gaps in _skills related features
1 parent 05a3196 commit 9127b89

16 files changed

Lines changed: 822 additions & 329 deletions

File tree

Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
---
2+
status: approved
3+
date: 2026-10-15
4+
deciders: jpalvarezl, eavanvalkenburg
5+
---
6+
7+
# Use the MCP SDK Client as the primary Python MCP client
8+
9+
## Context and Problem Statement
10+
11+
The Python `MCPTool` implementation originally owned an MCP transport, constructed a low-level `ClientSession`, and
12+
used that session for every operation. The MCP Python SDK 2.x adds a high-level `Client` that owns protocol
13+
negotiation and standard client behavior across modern and legacy peers.
14+
15+
Using `Client` only for negotiation and then routing operations through `client.session` would bypass high-level
16+
behavior such as multi-round-trip request (MRTR) handling and response caching. At the same time, existing callers
17+
can supply an already-created `ClientSession` and expect Agent Framework not to take ownership of it, while callers
18+
using the modern API need to supply an already-entered high-level `Client` without transferring its ownership.
19+
20+
This decision defines the lasting boundary between the two SDK levels and three ownership modes, including lifecycle,
21+
caching, subscription recovery, and the meaning of `MCPTool.session`.
22+
23+
This ADR covers the outbound Python MCP client. Hosting/server code continues to use the SDK server APIs.
24+
25+
## Decision Drivers
26+
27+
- One Agent Framework API must support modern and legacy MCP peers.
28+
- Standard protocol behavior should remain owned by the MCP SDK rather than be duplicated in Agent Framework.
29+
- Framework-created resources must be closed by the task that opened them, including cancellation and failed
30+
connection attempts.
31+
- Caller-supplied Clients, sessions, and HTTP clients must remain caller-owned.
32+
- Reconnect, authenticated header identity, catalog publication, security, tracing, and result conversion remain
33+
Agent Framework policy.
34+
- Tools, prompts, and resources should follow one operation-routing rule.
35+
- Tasks and durable human-input continuation are separate from base MRTR support.
36+
37+
## Considered Options
38+
39+
- Retain the high-level SDK `Client` and use it for standard operations in both ownership modes, with `ClientSession`
40+
as a deprecated caller-owned low-level compatibility path.
41+
- Use `Client` only for negotiation while continuing operations through `client.session`.
42+
- Reimplement negotiation, MRTR, caching, and subscriptions around `ClientSession`.
43+
- Add separate modern and legacy Agent Framework tool classes or a public protocol-mode switch.
44+
45+
## Decision Outcome
46+
47+
Chosen option: use the high-level SDK `Client` for both framework-owned and caller-owned high-level connections.
48+
The caller-owned `ClientSession` path is retained for backward compatibility but is considered deprecated for new
49+
usage; callers should prefer supplying a high-level `Client`.
50+
51+
The private `_MCPConnection` protocol is the operation seam. Its implementations deliberately do not expose both
52+
SDK levels:
53+
54+
- `_ClientMCPConnection` uses an entered high-level `mcp.Client`. Its `is_framework_owned` flag records whether
55+
Agent Framework created and manages the Client or the caller supplied and manages it. Its `client` property
56+
references that Client and its `session` property remains `None`. Tool, prompt, resource, catalog, logging, and
57+
liveness operations route through `Client`; they never use `client.session` as the operation provider.
58+
- `_SessionMCPConnection` wraps a caller-supplied `ClientSession`. This is a deprecated low-level compatibility
59+
path retained for existing applications. Its `session` property references that session and its `client` property
60+
remains `None`. Operations call the session directly and do not gain high-level caching or automatic MRTR behavior.
61+
62+
`MCPTool.session` is therefore meaningful only for the deprecated caller-supplied low-level path. High-level Client
63+
connections do not publish the SDK Client's internal compatibility session through that property.
64+
65+
### Ownership model
66+
67+
Agent Framework owns:
68+
69+
- transport and Client construction, Client entry, and resource cleanup for framework-created connections;
70+
- the lifecycle-owner task, locks, connection publication, reset coordination, and cancellation cleanup;
71+
- request-scoped HTTP header identity and reconnects caused by identity changes;
72+
- tool argument filtering and trusted request metadata merging;
73+
- result parsing, Agent Framework content conversion, tracing, and error translation;
74+
- atomic catalog publication and rollback after a failed complete fetch;
75+
- the background catalog-subscription task for any high-level Client, including refresh scheduling, retry/backoff,
76+
cancellation, and recovery after a subscription ends or is lost;
77+
- security and approval policy.
78+
79+
For **caller-supplied** connections, the caller owns:
80+
81+
- entering and closing a **supplied** high-level `Client`;
82+
- constructing and closing a **supplied** low-level `ClientSession`;
83+
- the transport, authentication, callbacks, and other configuration already captured by either supplied object.
84+
85+
The SDK `Client` owns:
86+
87+
- modern negotiation and legacy initialization fallback;
88+
- standard tool, prompt, and resource operations;
89+
- MRTR callback dispatch, retries, round limits, request state, and input responses;
90+
- response-cache storage and protocol-driven invalidation;
91+
- `Client.listen()` acknowledgment and the subscription event stream;
92+
- protocol, client, and capability metadata.
93+
94+
### Operation ownership
95+
96+
| Operation | Framework-owned `Client` | Caller-owned `Client` | Caller-owned `ClientSession` |
97+
|---|---|---|---|
98+
| Connection lifecycle | Agent Framework constructs, enters, and closes the Client | Caller constructs, enters, and closes the Client | Caller constructs and closes the session |
99+
| Connection negotiation | Enter `Client` in automatic mode | Reuse the already-entered Client | Initialize only when required for legacy compatibility |
100+
| `tools/list`, `tools/call` | High-level `Client` operation | High-level `Client` operation | Direct `ClientSession` operation |
101+
| `prompts/list`, `prompts/get` | High-level `Client` operation | High-level `Client` operation | Direct `ClientSession` operation |
102+
| Resource reads | `Client` with SDK cache behavior | `Client` with SDK cache behavior | Direct, uncached session call |
103+
| Catalog subscriptions | Agent Framework owns recovery around `Client.listen()` | Agent Framework owns recovery around `Client.listen()` | Legacy notification handling only |
104+
| `MCPTool.session` | `None` | `None` | The caller-supplied `ClientSession` |
105+
| Tasks or arbitrary extension RPCs | Future supported Client API | Future supported Client API | Raw session request only at an explicit extension boundary |
106+
107+
### Cache policy
108+
109+
High-level Clients use SDK response caching for catalog and resource operations regardless of whether Agent Framework
110+
or the caller owns the Client. Modern server `ttlMs` and `cacheScope` hints control reuse and invalidation. Legacy
111+
peers do not provide those hints and remain effectively uncached under the default zero TTL.
112+
113+
Caller-supplied `ClientSession` connections always call the server directly. Agent Framework does not expose a
114+
shared cache store or cache-mode configuration. Reconnect or an effective header-identity change replaces the
115+
framework-owned Client and its per-client cache.
116+
117+
### MRTR
118+
119+
For both framework-owned and caller-owned high-level connections, `tools/call`, `prompts/get`, and `resources/read`
120+
use the Client. The SDK drives embedded elicitation, sampling, and roots requests and retries the original operation
121+
with the required responses and state.
122+
123+
Agent Framework does not import the SDK's private MRTR driver or implement parallel MRTR loops. A caller-supplied
124+
session remains a raw low-level path and does not gain automatic MRTR merely because callbacks are configured on it.
125+
126+
Durable pause/resume across processes would require a separate continuation design and function-calling-loop review;
127+
it is not part of this decision.
128+
129+
### Subscription recovery
130+
131+
The SDK Client owns protocol-level `listen` acknowledgment and event delivery. Agent Framework owns the long-running
132+
subscription lifecycle around it:
133+
134+
- one background subscription task per active high-level Client;
135+
- tool and prompt catalog refresh when events arrive;
136+
- refresh before reopening after stream loss or completion;
137+
- retry with bounded backoff for recoverable subscription failures;
138+
- cancellation when the connection is reset, replaced, or closed;
139+
- fallback to legacy catalog notifications when the peer does not support `listen`.
140+
141+
The recovery task always verifies that the Client is still the active connection before refreshing or reopening, so
142+
an obsolete subscription cannot mutate a replacement connection's catalogs.
143+
144+
### Caller-supplied high-level Clients
145+
146+
A caller-supplied `Client` is the preferred way to provide an existing connection:
147+
148+
- The Client must already be entered before the MCP tool connects.
149+
- Agent Framework does not enter, close, replace, or recreate it.
150+
- Standard operations continue through the high-level Client and retain SDK MRTR and response-cache behavior.
151+
- Agent Framework manages its own catalog-subscription task around `Client.listen()` while the wrapper is connected.
152+
- `MCPTool.session` remains `None`.
153+
- Closing or resetting the wrapper preserves the supplied Client so the caller can continue using or closing it.
154+
155+
### Caller-supplied low-level sessions
156+
157+
A caller-supplied `ClientSession` remains a deprecated low-level compatibility path:
158+
159+
- Agent Framework does not enter, close, replace, wrap, or reconnect it.
160+
- An already negotiated session is reused.
161+
- An unnegotiated session retains legacy initialization compatibility.
162+
- Standard calls remain direct and do not gain high-level MRTR or SDK response caching.
163+
- `MCPTool.session` returns this session and can replace or clear this low-level connection path.
164+
165+
The SDK does not provide a public API that adopts an existing `ClientSession` into a high-level Client without
166+
opening a separate connection, so Agent Framework does not simulate adoption.
167+
168+
### Legacy callbacks, logging, and liveness
169+
170+
Framework-created connections use automatic protocol negotiation even when sampling is configured. The SDK routes
171+
the same callback through the legacy server-to-client back-channel and through modern embedded MRTR requests.
172+
173+
Modern request metadata carries log-level preference. Legacy `logging/setLevel` and ping behavior remain explicitly
174+
protocol-gated compatibility operations; they are not universal preflights.
175+
176+
### Tasks
177+
178+
The supported MCP Python SDK 2.x runtime does not expose the current `io.modelcontextprotocol/tasks` extension.
179+
Tools that may require Tasks are not presented as ordinary supported calls, and the removed long-running Tasks
180+
sample remains deferred. An MRTR `InputRequiredResult` is not a Tasks `input_required` status.
181+
182+
## Consequences
183+
184+
- Good, because modern and legacy peers use one public Agent Framework API.
185+
- Good, because standard operations, MRTR, and caching stay on the supported high-level SDK surface.
186+
- Good, because the connection seam distinguishes framework-owned and caller-owned high-level Clients from the
187+
deprecated low-level session path.
188+
- Good, because reconnect, cancellation, header identity, subscription recovery, parsing, and policy remain Agent
189+
Framework concerns.
190+
- Neutral, because caller-supplied low-level sessions intentionally have fewer protocol conveniences.
191+
- Neutral, because `MCPTool.session` returns `None` for all high-level Client connections.
192+
- Bad, because integrations that previously treated `session` as a universal connection handle must instead use the
193+
operation seam, a caller-owned Client, or the deprecated caller-owned session path.
194+
195+
## Validation
196+
197+
Committed contract tests cover:
198+
199+
- modern negotiation and legacy fallback;
200+
- framework-owned Client publication, failure cleanup, reset, reconnect, cancellation, and header identity changes;
201+
- caller-owned Client publication, high-level operation routing, capability reuse, reset preservation, and cleanup;
202+
- standard operations routing through the active Client;
203+
- tool, prompt, and resource MRTR;
204+
- cache TTL, pagination, invalidation, reconnect, and identity changes;
205+
- caller-owned session behavior remaining direct, uncached, and caller-owned;
206+
- subscription refresh, stream loss, retry/backoff, replacement, cancellation, and legacy notification fallback;
207+
- legacy sampling, logging, and ping compatibility.
208+
209+
## Pros and Cons of the Options
210+
211+
### Use Client for high-level operations
212+
213+
- Good, because it uses the SDK's supported high-level surface.
214+
- Good, because it avoids duplicate negotiation, MRTR, and caching code.
215+
- Good, because the low-level session remains available as a deprecated caller-owned compatibility path.
216+
- Bad, because code cannot assume every MCP connection exposes a `ClientSession`.
217+
218+
### Use Client only for negotiation
219+
220+
- Good, because it would minimize immediate routing changes.
221+
- Bad, because calling `client.session` for operations bypasses SDK-owned MRTR and caching.
222+
- Bad, because each new protocol feature would reopen the same ownership question.
223+
224+
### Reimplement behavior around ClientSession
225+
226+
- Good, because Agent Framework could expose every intermediate protocol round.
227+
- Bad, because it would duplicate SDK protocol policy, cancellation behavior, round limits, and cache invalidation.
228+
- Bad, because it would add continuation complexity without a durable continuation requirement.
229+
230+
### Add era-specific public classes
231+
232+
- Good, because callers could force a known protocol era.
233+
- Bad, because callers should not need to know the peer's era before connecting.
234+
- Bad, because it would fragment public classes, samples, and tests.
235+
236+
## More Information
237+
238+
- [Python MCP 2026-07-28 umbrella issue](https://github.com/microsoft/agent-framework/issues/8245)
239+
- [MCP Python SDK client guide](https://py.sdk.modelcontextprotocol.io/client/)
240+
- [MCP Python SDK MRTR guide](https://py.sdk.modelcontextprotocol.io/handlers/multi-round-trip/)
241+
- [MCP Python SDK caching guide](https://py.sdk.modelcontextprotocol.io/client/caching/)
242+
- [MCP Python SDK subscriptions guide](https://py.sdk.modelcontextprotocol.io/client/subscriptions/)
243+
- [MCP MRTR specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr)
244+
- [MCP subscriptions specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/subscriptions)
245+
- [MCP caching specification](https://modelcontextprotocol.io/specification/2026-07-28/server/utilities/caching)
246+
- [ADR 0043: MCP runtime context](0043-python-mcp-runtime-context.md)
247+
248+
This ADR remains `proposed` until accepted through the repository ADR review process.

0 commit comments

Comments
 (0)