* Restore upgraded dependency checks
Generated with Codex
* Clarify settings loading and teardown logging
Generated with Codex
* Align ty checks on the upgraded version
Generated with Codex
* Preserve simultaneous caller cancellation
Generated with Codex
* Delegate forked client protocol helpers to the SDK
Replace FastMCP's copies of _fold_extensions, _evicting_message_handler,
and _synthesize_discover with imports from mcp.client.client. The fork had
drifted: it was missing validate_extension_identifier, so non-reverse-DNS
extension identifiers were silently accepted.
Full lifecycle composition over mcp.Client stays blocked upstream —
mcp.Client hardcodes ClientSession construction (no session_class hook)
and forbids reentry.
* Drop duplicate local helpers reintroduced by the merge; use SDK versions
Resource/prompt error detail and proxy instructions/connection-error
surfacing now work on the modern protocol era, so the tests pinned to
mode="legacy" with a TODO(defect)/TODO(mode="legacy" pin) marker run
on the default auto mode again.
Three defects hidden by tests pinned to the handshake era, where a raw
exception reaches the wire as str(exc). At 2026-07-28 the runner masks
anything that is not an MCPError/ValidationError as "Internal server error".
- _on_read_resource / _on_get_prompt now translate FastMCPError through
to_mcp_error, mirroring _on_call_tool. Masking is unchanged.
- FastMCPProxy registers a server/discover handler so upstream instructions
reach modern clients; on_initialize only fires for the handshake.
- ProxyProvider's list methods normalize transport failures into MCPError.
Removes pins added while making the auto-default suite pass that weren't
actually testing older-protocol-only behavior, and keeps (with a stated
reason) the ones that are. Along the way, fixes two real defects the audit
surfaced in the modern protocol path: PingMiddleware could leak a
_active_sessions entry when a connection's exit_stack closed before its
keepalive task got its first scheduler turn, and FastMCP(experimental_
capabilities=...) was silently dropped from server/discover responses
(it only ever reached the legacy initialize handshake).
Most pins in tests/server/providers/proxy/ were added only to keep tests
green while unpinning changed which protocol era the proxy's backend
connection used, not because the test's subject cared about the era. With
proxy era-mirroring (#4573) landed, a front client on auto correctly moves
the whole chain to the modern protocol, so plain tool/resource/prompt calls
through a proxy no longer need a pin.
Kept pins fall into three buckets, each commented at the call site: tests
whose subject is genuinely handshake-only (sampling, roots, elicitation
push-forwarding, ping, initialize handshake mechanics); tests whose backend
is a directly-constructed ProxyClient/StatefulProxyClient, which always
defaults to legacy independent of the front era; and two tests left pinned
with a TODO documenting a real defect this audit surfaced (upstream
instructions not forwarded to a modern-era client through a proxy, and
ProxyProvider.list_tools leaking an unwrapped connection error instead of
an MCPError).
Remove 4 unjustified pins (proxy header passthrough, connect timeout,
two response_title validation tests that fail before any request is
dispatched). Keep 81 pins that genuinely exercise older-protocol-only
behavior (ctx.elicit back-channel, sampling, roots, ping, session IDs,
initialize handshake, client.set_logging_level).
Flags a real defect: _on_read_resource/_on_get_prompt only catch
(DisabledError, NotFoundError), unlike _on_call_tool which catches
FastMCPError broadly. A ResourceError/PromptError escapes as a raw
exception and the modern protocol's generic exception ladder masks it
as "Internal server error", losing the detailed message tool errors
still get. Left pinned with a TODO in test_client.py and
test_error_handling.py rather than hidden.
* Mirror front protocol era onto proxy backend connection
A proxy created from a non-Client target now negotiates, on its backend,
whatever era its front client negotiated, instead of pinning one era.
Explicit create_proxy(mode=...) still overrides. Guards the eager backend
initialize() so an explicit modern pin behind a handshake front no longer
crashes.
* Carry the mirrored proxy era into multi-server config backends
A multi-server MCPConfig target mounts one proxy per configured server on a
composite router, so setting the era on the outer client stopped at the router
and every real backend stayed on its default era. TransportOptions.backend_mode
carries it down, resolved per request alongside the outer mirroring.
The router is also sealed under a policy held on the transport rather than a
fresh per-router ephemeral key, so a guard tool's request_state survives the
router being rebuilt between rounds.
* Fix: gather() eagerly creates coroutines before scheduling them
AggregateProvider fans out Provider.get_tool() (and sibling calls) across
child providers via gather(*[p.get_tool(x) for p in providers]). The list
comprehension builds every coroutine up front, then gather()'s scheduling
loop hands them to an anyio task group one at a time. If that loop is
interrupted partway through - e.g. by pytest-timeout's SIGALRM-based
per-test timeout, which can fire between any two bytecode instructions,
unlike normal async cancellation - any coroutine not yet scheduled is
abandoned and silently garbage collected later, producing a "coroutine
'Provider.get_tool' was never awaited" warning attributed to whatever
unrelated test happens to be running when the GC gets to it.
Change gather() to take a single iterable consumed lazily, one awaitable
at a time, right before each is scheduled, and close any awaitable that
was just retrieved if scheduling it raises. Update call sites to pass
generator expressions instead of eagerly-built lists so coroutine
creation and scheduling stay tightly coupled.
* Close unscheduled awaitables from eager callers; make get_tasks lazy
The guard failed on any denial, so an agent falling back to an unlisted tool
during a GitHub outage tripped it — and the error blamed the allowlist, which
was intact. It now fails only when a command the workflow actually grants is
refused, which is the signal that a pattern was mangled.
mcp__github__get_pull_request was never granted, so on a PR the agent could
only read via get_issue and reached for denied fallbacks when that failed.
Client negotiates the newest mutual protocol era by default (probe
server/discover, fall back to the initialize handshake). ProxyClient and the
inspect utility explicitly pin the handshake era so proxy forwarding and
server_info reads are unchanged. SSE and multi-server config transports are
legacy-only. extensions= and result_claims= (SEP-2133) are thin passthroughs
to the SDK session.
* Make the SDK seam the root of FastMCP middleware dispatch (D3)
Notifications, cancellations, and malformed/unroutable messages now reach
on_message/on_request/on_notification at the SDK seam. Component methods keep
their interior dispatch (typed hooks, tool-exception visibility) unchanged; the
seam covers only messages the interior never dispatches, so each hook fires once.
* Document the middleware seam coverage and suspend semantics (D3)
* Align seam docs and ask-visibility test with the result-cycle MRTR model
An InputRequiredResult is the full result of a complete request->response
cycle, not a suspension: component hooks observe an asking round's
InputRequiredToolResult as an ordinary return value.
* Replace 'seam' language with plain dispatch terminology
* Keep the raw middleware __call__ signature; forward middleware message edits
* Cover fires-once across an MRTR continuation round
* Align cherry-picked coverage test with renamed recorder
* Rewrite only the message, never the dispatch destination
* Add guard-mode MRTR server support (SEP-2322)
* Add server-side MRTR guard tests
* Add MRTR guard docs, exports, and output-schema handling
* Apply formatting to MRTR guard changes
* Fix MRTR review round 1: middleware-safe suspend, Annotated strip, stable audience
- ToolInputRequired subclasses BaseException (CancelledError precedent) so
error middleware's broad except Exception cannot swallow a suspension
- Strip InputRequiredResult arms inside Annotated return types
- Reject a custom RequestStateSecurity without a stable audience (random
per-replica server names would break shared-key verification)
* Fix static analysis: rewrite tuple([...]) as tuple literal (C409)
* Recognize InputRequiredResult inside Annotated union arms
_is_input_required_type now peels Annotated first, so a metadata-carrying
guard arm (str | Annotated[InputRequiredResult, Field(...)]) is stripped
and the data arm's output schema survives.
* docs: frame multi-round tools as elicitation on the modern protocol
Fold multi-round-tools.mdx into elicitation.mdx as two eras of one
capability; drop pause/suspend framing for the stateless per-round model.
* Transport MRTR asks as InputRequiredToolResult, not a raised signal
An input-required result is the full result of a stateless MRTR leg, so it
flows through the middleware chain as an ordinary ToolResult subclass instead
of a raised ToolInputRequired(BaseException). Middleware observes it, caching
skips it, and response-limiting leaves it untouched.
* Document MRTR middleware interaction and the isinstance pattern
* Update MRTR change-register verify note to InputRequiredToolResult
* Align test module docstring with result-cycle framing
* Fix MRTR review: bypass cache on continuation legs; soften audience guard
- ResponseCachingMiddleware skips read AND write on continuation legs:
the cache key is name+arguments only, so a continuation's final result
would be served to later fresh calls, which would never be asked
- The stable-audience check is a warning, not an error: a policy object
cannot reveal whether its keys are shared, and single-process
customization (ephemeral ttl, custom codec) is legitimate unnamed
* Treat state-only rounds as continuations in the response cache
A round carrying request_state but no questions retries with
input_responses=None; request_state alone must bypass the cache or its
terminal result is stored under the fresh-call key.
* Fix MRTR review round: preserve asks through transforms, empty-name audience, docs predicate
- TransformedTool.run returns an InputRequiredToolResult intact instead of
reshaping it into an empty ToolResult for non-object output schemas
- audience warning uses a falsy-name check (empty string also autogenerates
a per-replica name)
- the elicitation docs continuation predicate checks request_state too
* Add create_proxy(mode=) opt-in for guard round-tripping through proxies
An auto-created proxy client stays handshake-era by default (a dual-era
backend serves both, and one proxy session is one era; handshake preserves
server-initiated push forwarding). Pass create_proxy(target, mode="auto")
to negotiate modern so an upstream guard's InputRequiredResult round-trips —
the two are mutually exclusive per session.
* Wrap raw InputRequiredResult returned by a transform_fn
A custom transform function may return the raw ask directly, like any tool
body — wrap it into InputRequiredToolResult so it survives output
normalization and reaches the wire, not only pre-wrapped forwarded guards.
* Reject input-required results from background tasks
* Unwrap type aliases before stripping guard arms
* Apply ruff format
* Recursively strip guard arms through nested and composed aliases
* Reflect MRTR continuation fields on the middleware message
* Suppress output schema for InputRequiredResult subclasses
* Forward progress on modern proxy tool calls
* Suppress output schema for bare aliased guard returns
* Suppress output schema for any surviving guard return wrapping
* docs: align server component docs
Generated with Codex.
* docs: clarify resource return shapes
Generated with Codex.
* docs: clarify initialize middleware response
Generated with Codex.
* docs: lead visibility filtering with names, scope keys to version targeting
* docs: correct initialize result semantics, template mime type, docket scope, visibility tip
* Warn when a visibility key omits the @ version delimiter
* Honor a resource template's declared mime_type and meta on read
* Strip internal visibility meta from resource content; document filter intersection
---------
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
* Add OAuthProxy issuer response parameter
* Cover OAuthProxy issuer error redirects
* Relax host origin guard defaults (#4439)
* Use exact issuer in authorize errors
* Restore HTTP host guard compatibility (#4472)
* Hugging Face Auth Integration (#4385)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
* Docs: add v3.4.4 changelog entries (#4473)
* Explain unnormalized issuer; cover consent-denial path base_url
* Revert "Merge remote-tracking branch 'origin/release/3.x' into codex/oauth-proxy-rfc9207-issuer"
This reverts commit 9e34b1686c, reversing
changes made to 640dc60fe0.
* Preserve callback query bytes when appending iss/code/state params
add_query_params previously decoded the existing query with parse_qsl
and re-encoded it, mutating opaque or signed query strings (a valueless
?flag became ?flag=, non-UTF-8 percent-encoded bytes got replaced).
Append the newly-encoded params to the existing query string instead of
round-tripping it through parse/encode.
Also fixes a stray bare `httpx` reference in a test that should use
httpx2 following the SDK v2 migration.
* Attach RFC 9207 iss to authorize() success redirects too
AuthorizationHandler only added iss to error redirects from the SDK's
base handler, not to code redirects returned directly by authorize()
overrides that bypass consent/upstream (as GitHub's mocked test does).
Since metadata now unconditionally advertises
authorization_response_iss_parameter_supported, any client-facing
redirect missing iss hard-fails RFC 9207-aware clients.
Also fixes HeadlessOAuth, which parsed code/state from the redirect
but silently dropped iss, so the same regression would have masked
itself across every other provider integration test too.
* Carry RFC 9207 iss through the production OAuth callback path
OAuthProxy advertises authorization_response_iss_parameter_supported and
sends iss on every authorization redirect, but the client's production
callback chain (CallbackResponse -> OAuthCallbackResult -> OAuth.callback_handler)
had no iss field, so it was silently dropped and the SDK's
validate_authorization_response_iss rejected the callback. HeadlessOAuth
already carried iss through, which is why CI stayed green while real
clients failed.
Add iss to CallbackResponse and OAuthCallbackResult, thread it through
store_result_once for both success and error branches, and pass it into
AuthorizationCodeResult in OAuth.callback_handler.
* Don't duplicate iss when a provider redirect already carries one
* Consolidate RFC 9207 iss handling into a single redirect helper
Every client-facing authorization redirect must carry exactly one iss.
That invariant was being enforced by hand at five separate call sites,
each building its own params dict -- which is how the success-redirect
path shipped without iss in the first place, and how a registered
redirect_uri that already carries its own iss could end up duplicated.
Route all five sites through build_client_redirect(), which owns the
idempotent replace-or-append behavior so no caller can get it wrong.
---------
Co-authored-by: shaun smith <1936278+evalstate@users.noreply.github.com>
* Reapply span attributes after creation to survive non-forwarding samplers
Tracer.start_span builds the span from sampling_result.attributes, not
the attributes kwarg — a custom Sampler that returns
SamplingResult(RECORD_AND_SAMPLE) without forwarding attributes
silently drops everything FastMCP passed at creation time. Reapply the
same attributes immediately after span creation (guarded by
is_recording()) so on_start hooks and samplers still see them, while
the finished span is guaranteed to carry FastMCP's telemetry
regardless of sampler behavior.
* Restore only missing span attributes, not a blanket reapply
Reapplying all attributes after span creation overwrote values a
sampler deliberately set (e.g. a redacted mcp.method.name) and
inflated dropped-attribute counts when the SDK's attribute limit was
hit. Compare against the span's existing attributes and restore only
the keys a non-forwarding sampler actually dropped, via a shared
restore_missing_attributes() helper in fastmcp.telemetry.
* Gate attribute restore on all-or-nothing, not per-key
Restoring only missing keys reinserted attributes the SDK's bounded
attribute map had already evicted under a low
OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, evicting a different retained key and
inflating dropped_attributes beyond what the sampler actually dropped.
Gate on none of our attributes being present (plus dropped_attributes
== 0) instead — the regression this exists to fix is a sampler
dropping everything, and eviction under a limit always leaves some.
Renamed restore_missing_attributes to restore_dropped_attributes to
match.
* Gate attribute restore on empty span, not per-key presence
A sampler that intentionally supplies only its own attributes (e.g. to
strip component names or resource URIs for privacy/cardinality
control) left none of FastMCP's keys on the span, so the previous
all-or-nothing gate treated it identically to a bare non-forwarding
sampler and restored everything, defeating the filter. Key off the
span having no attributes at all instead — a bare sampler leaves it
empty, a filtering sampler doesn't.
* Add FASTMCP_SSRF_TRUST_PROXY to allow SSRF fetches through a corporate proxy
🤖 Generated with Claude Code
* Make SSRF fetch client trust_env explicit for proxy routing
🤖 Generated with Claude Code
* Warn when SSRF proxy trust is enabled without a configured proxy
🤖 Generated with Claude Code
* Warn when NO_PROXY would send an SSRF-trust-proxy fetch direct
🤖 Generated with Claude Code
* Refuse SSRF-trust-proxy fetches when no proxy would route the target
🤖 Generated with Claude Code
* Fix TestProxyMode mocks to patch httpx2.AsyncClient
main's httpx -> httpx2 migration (#4503) landed after these tests were
written; ssrf.py's fetch path already uses httpx2.AsyncClient, but
TestProxyMode still patched the old httpx module, so the mock silently
stopped intercepting and requests escaped to the real network.
* Fix port-qualified NO_PROXY bypass in SSRF proxy-trust guard
proxy_bypass(hostname) discarded the port, so a NO_PROXY entry like
127.0.0.1:8443 went undetected while httpx2 honored it and sent the
request direct with the blocklist already disabled. Pass host:port
instead, except for IPv6 literals, where httpx2 ignores port when
matching NO_PROXY and neither bracketed nor unbracketed host:port
reliably matches through proxy_bypass()'s own parser.
* Replace NO_PROXY prediction with explicit proxy control in SSRF trust-proxy mode
Predicting httpx2's proxy routing (via proxy_bypass(), then via httpx2's own
get_environment_proxies()/URLPattern internals) kept diverging from its real
NO_PROXY handling — three rounds, three different divergences, always in the
unsafe direction. Read HTTPS_PROXY/ALL_PROXY directly and pass it to httpx2
explicitly with trust_env=False, so the request provably goes through that
proxy instead of being predicted to. NO_PROXY is no longer evaluated in this
mode: a NO_PROXY'd host is now routed through the proxy rather than refused,
since that's strictly safer than the alternative (direct with the blocklist
already off).
---------
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
* Fix typos
* Document Cachable* -> Cacheable* rename as v4 breaking change
Adds the response-cache model rename to the change register, per
maintainer decision to skip compatibility aliases in favor of clear
documentation.
* Skip invalid Before import in doc test; use inline codespell ignore
The Cachable* -> Cacheable* breaking-change entry showed the old,
now-invalid import for contrast, which the doc-example test picked up
as a real import and flagged as a regression. Comment out the
deliberately-broken "Before" line (matching the McpError entry just
above it) so only the working "After" import is exercised.
Also swap the blanket codespell ignore-words-list entry for a
narrower inline `codespell:ignore` directive on the one line that
needs it, so codespell keeps flagging "cachable" everywhere else.
---------
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
* Add subject field to AccessToken initialization
Fixes#4266
Add `subject` property to the AccessToken.
```python
return AccessToken(
token=access_token_as_dict["token"],
client_id=access_token_as_dict["client_id"],
scopes=access_token_as_dict["scopes"],
subject=access_token_as_dict["subject"],
# Optional fields
expires_at=access_token_as_dict.get("expires_at"),
resource=access_token_as_dict.get("resource"),
claims=access_token_as_dict.get("claims") or {},
)
```
* Populate AccessToken.subject across all token verifiers
Closes#4266. get_access_token().subject was always None: the SDK's
AccessToken.subject wasn't carried into FastMCP's AccessToken by the
dependency-layer conversion, and none of the built-in TokenVerifiers
(JWT, introspection, and the OAuth-provider verifiers for Discord,
Clerk, Google, WorkOS, HuggingFace, GitHub, and Cognito) populated it
from the sub claim/field they already extract.
---------
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>