Compare commits

..

298 commits

Author SHA1 Message Date
marvin-context-protocol[bot]
8a1820f1c3
chore: Update SDK documentation (#4782)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-08-07 15:49:36 -05:00
Sai Mouli
06fee6d300
Serialize the event store's stream list read-modify-write (#4758)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-08-06 20:09:36 -04:00
Jamie Zieziula
706f7d2695
feat(renovate): migrate to Renovate, retire Dependabot (#4754)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-06 20:02:29 -04:00
Chris Guidry
1ac8fc6060
Encrypt task context snapshots at rest (#4772)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 20:01:40 -04:00
Jeremiah Lowin
04f9971120
Delegate typed tool output serialization to Pydantic (#4771) 2026-08-06 19:59:19 -04:00
marvin-context-protocol[bot]
803da5319c
chore: Update SDK documentation (#4679) 2026-08-06 19:56:40 -04:00
Jake Kaplan
9feb1f378b
Forward proxy server metadata across protocol eras (#4776)
* Forward proxy negotiation metadata

🤖 Generated with OpenAI Codex

* Limit forwarded proxy metadata

🤖 Generated with OpenAI Codex

* Tighten negotiation metadata forwarding

🤖 Generated with OpenAI Codex

* Tighten proxy metadata docs

🤖 Generated with OpenAI Codex

* Keep proxy metadata middleware with provider

🤖 Generated with OpenAI Codex

* Simplify proxy negotiation middleware API

🤖 Generated with OpenAI Codex

* Name proxy metadata middleware directly

🤖 Generated with OpenAI Codex

* Preserve discovery middleware contracts

🤖 Generated with OpenAI Codex

* Clarify proxy metadata ownership

🤖 Generated with OpenAI Codex

* Align proxy metadata wording

🤖 Generated with OpenAI Codex

* Call forwarded values server metadata

🤖 Generated with OpenAI Codex

* Harden proxy metadata reads

🤖 Generated with OpenAI Codex

* Expose configured discovery result

🤖 Generated with OpenAI Codex

* Preserve proxy discovery compatibility

🤖 Generated with OpenAI Codex

* Preserve deprecated initialization middleware

🤖 Generated with OpenAI Codex

* Harden proxy metadata boundaries

🤖 Generated with OpenAI Codex

* Restore deprecated middleware location

🤖 Generated with OpenAI Codex

* Simplify proxy metadata client lifecycle

🤖 Generated with OpenAI Codex

* Clarify proxy metadata lifecycle

🤖 Generated with OpenAI Codex

* Preserve proxy factory errors

🤖 Generated with OpenAI Codex

* Detach forwarded proxy metadata

🤖 Generated with OpenAI Codex

* Simplify proxy metadata implementation

🤖 Generated with OpenAI Codex

* Distinguish proxy metadata failures

🤖 Generated with OpenAI Codex

* Narrow proxy metadata validation fallback

🤖 Generated with OpenAI Codex

* Retrigger CI

🤖 Generated with OpenAI Codex
2026-08-06 19:09:05 -04:00
nate nowack
75fb116e36
Support EdDSA verification in JWTVerifier (#4752) 2026-08-06 14:09:37 -04:00
Jeremiah Lowin
6fb34e9383
Document MCP protocol support and conformance (#4781) 2026-08-06 11:15:38 -04:00
Yonatan
c8b88b3a37
fix(context): move elicit overload docs inside the stubs so mypy sees the chain (#4774) 2026-08-06 09:35:49 -04:00
Jeremiah Lowin
2bee9aeb58
Clarify review of closed contributor PRs (#4780) 2026-08-06 09:34:11 -04:00
Jeremiah Lowin
875e8e18bd
Preserve legacy httpx compatibility without importing it (#4766) 2026-08-05 18:09:16 -04:00
Jake Kaplan
959daf2321
Sanitize forwarded request metadata where the proxy copies it (#4770)
* Separate proxy protocol policy from client construction

🤖 Generated with OpenAI Codex

* Strip connection-owned request metadata at the proxy backend boundary

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Sanitize forwarded request metadata where the proxy copies it

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Forward hop-safe request metadata for proxied resources, templates, and prompts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:46:10 -04:00
nate nowack
8661193411
Quote run-claude allowed tools argument (#4741)
Generated with Codex
2026-08-05 11:15:51 -04:00
Jeremiah Lowin
e4d8ca648a
Avoid loading MCP and CLI stacks during lightweight imports (#4763) 2026-08-05 10:56:13 -04:00
Jeremiah Lowin
2c2f98691f
Docs: mirror v3.4.6 release notes (#4764) 2026-08-05 10:53:15 -04:00
nate nowack
b9b7ea6914
Declare run-claude extra allowed tools input (#4740)
Generated with Codex
2026-08-05 10:39:35 -04:00
Sai Mouli
4f28dceac8
Don't cache error results in ResponseCachingMiddleware (#4705) 2026-08-04 17:15:01 -04:00
LHMQ878
db92d44ef5
Serve empty list results from the response cache (#4738) 2026-08-04 17:11:42 -04:00
Jeremiah Lowin
886776f5fc
Canonicalize response cache arguments (#4753)
Co-authored-by: LHMQ878 <LHMQ878@users.noreply.github.com>
2026-08-04 15:25:46 -04:00
Jeremiah Lowin
d267792653
docs: clarify external OAuth consent mode (#4746) 2026-08-03 18:02:09 -04:00
nate nowack
a7e9b70919
Fix static analysis with latest ty (#4739)
* Fix upgrade static analysis

Generated with Codex

* Preserve concrete transport return types

Generated with Codex

* Avoid widening transport return types

Generated with Codex

* Model transforming transport return types

Generated with Codex

* Exclude standalone screenshot examples from ty

Generated with Codex
2026-08-03 10:53:23 -05:00
Jeremiah Lowin
022547ad8c
Preserve string-compatible prompt arguments (#4730) 2026-08-02 14:56:05 -04:00
Jeremiah Lowin
34bdd480c9
Improve HTTP server startup performance (#4729) 2026-08-02 14:11:26 -04:00
Shuying
c428a08fea
fix: preserve valid servers during CLI discovery (#4714)
Co-authored-by: Shuying <zsy@u.northwestern.edu>
2026-08-02 09:42:26 -04:00
Martin Styk
10b158baf3
Forward enable_cimd to Auth0, AWS Cognito and OCI providers (#4719)
Signed-off-by: Martin Styk <mart.styk@gmail.com>
2026-08-02 09:42:06 -04:00
YAO_001
9034a2eb4b
Fix CodeMode tool error propagation (#4704)
Co-authored-by: nate nowack <thrast36@gmail.com>
2026-08-02 09:41:36 -04:00
nate nowack
40c3e122e8
Write downloaded skill text as UTF-8 (#4715) 2026-08-02 09:33:32 -04:00
Jake Kaplan
bc07264529
Fix self-referential connection error causes (#4720)
🤖 Generated with OpenAI Codex
2026-07-30 16:23:33 -04:00
Jeremiah Lowin
bcef61d806
Route published docs through pull requests (#4713) 2026-07-30 10:18:03 -04:00
Nicholas Brown
0f18a258d4
add language dropdown (#4716) 2026-07-30 09:32:58 -04:00
nate nowack
44c0907dda
Give parallel Windows CI more timeout headroom (#4680)
pytest-timeout falls back to its thread method on Windows, which os._exit()s
the process instead of failing the test. A single slow test therefore kills an
xdist worker and fails whichever unrelated test it was running.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 10:22:17 -05:00
Jeremiah Lowin
07f6eafd99
Add comprehensive Codex code review rules (#4710) 2026-07-29 09:51:36 -04:00
Jeremiah Lowin
a22f778dbf
Rewrite the FastMCP docs welcome page (#4709) 2026-07-29 09:51:22 -04:00
Jeremiah Lowin
0792ac812c
Improve the v4 docs (#4707) 2026-07-29 09:51:13 -04:00
Jeremiah Lowin
7339936980
Rewrite the v4 What's New page and document server extensions (#4698)
* Rewrite the v4 What's New page

Teach the headline features with code instead of asserting them, drop the
major-version throat-clearing and SEP list, and correct the elicitation
claim: ctx.elicit() is unchanged and handshake-only, while sampling and
roots are removed outright.

* Fix broken doc links and stale version references

Repoint five dead links and anchors, refresh v3-era version examples on the
v4 docs, and add the missing FastMCP 3 entry to the installation page's
upgrade section.

* Document server extensions

add_extension() shipped in v4 with no documentation page. Covers the
extension interface, request methods, tool-call interception, lifespan
ownership, and the client half.

* Link the FastMCP TypeScript library

* Address Codex review feedback

Gate the extension interceptor on the client's per-request opt-in rather
than claiming negotiation does it; show the v4 beta pin on the install
page instead of a version a reader cannot get; note that UserSession
requires authentication.
2026-07-28 20:05:45 -04:00
Jeremiah Lowin
7a77805159
Use mcp.types directly instead of aliasing to mcp_types in docs (#4696) 2026-07-28 19:08:44 -04:00
Jeremiah Lowin
baced6281c
Always emit a tool title, derived from name when unset (#4694)
* Always emit a tool title, derived from name when unset

Some MCP clients (e.g. ChatGPT) drop tools with no `title` instead of
falling back to `name` for display as the spec allows. Deriving a
default title in Tool.to_mcp_tool() fixes this for every tool built on
top of it, including the search-transform, code-mode, and session
proxy tools that never set one explicitly.

Fixes #4414

* Derive fallback title from the overridden name, document it

Addresses Codex review on #4694.

* Resolve title precedence from effective overrides

* Normalize mapping annotations before deriving the title
2026-07-28 17:30:20 -04:00
Jeremiah Lowin
5a98ceb5ca
Add v4.0.0b1 changelog and updates entries (#4681)
* Add v4.0.0b1 changelog and updates entries

* Drop meta note from b1 intro; add #4682 under enhancements

* File #4682 under fixes

* Correct the camelCase rename claim: Python model fields, not the wire

* Baseline the b1 changelog on v3.4.5

* Simplify the beta banner
2026-07-28 17:15:48 -04:00
Jeremiah Lowin
8b76710e66
Move to the stable MCP Python SDK 2.0.0 (#4655) 2026-07-28 16:31:49 -04:00
Jeremiah Lowin
81b1e818e5
Apply app visibility where no host can (#4692) 2026-07-28 16:12:38 -04:00
Jeremiah Lowin
a8b5da9770
Late-bind app tool names so UIs survive composition (#4682) 2026-07-28 10:54:19 -04:00
Jeremiah Lowin
0175bc9235
Split the SDK upgrade guides by SDK version (#4684) 2026-07-28 10:47:39 -04:00
Jeremiah Lowin
d6b9daecb1
Read CLI-scanned MCP config files as UTF-8 explicitly (#4690) 2026-07-28 08:12:17 -04:00
Jeremiah Lowin
78c61415b5
Resolve review threads on fix, reply on decline (#4685)
* Resolve review threads on fix, reply on decline

* Use a placeholder PR number in the resolve example
2026-07-27 21:41:02 -04:00
Jeremiah Lowin
90ea26f337
Soften the review-comment reply guidance (#4683) 2026-07-27 21:06:12 -04:00
Jeremiah Lowin
f4ae8bb0af
Let maintenance releases publish without fastmcp-tasks (#4676) 2026-07-27 16:07:54 -04:00
Jeremiah Lowin
d382943012
Note that review comment threads should get an acknowledgement (#4678) 2026-07-27 16:07:39 -04:00
Jeremiah Lowin
7674645761
Flatten OpenAPI discriminator subtypes into request bodies (#4677)
* Flatten OpenAPI discriminator subtypes into request bodies

* Resolve schema-name discriminator mappings and union conflicting variant fields

* Advertise discriminator values for propertyless variants and document the behavior
2026-07-27 16:06:54 -04:00
Bill Easton
75b9f92504
feat: Add telemetry interop mode for FastMCP (#4046)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-27 16:05:29 -04:00
苏紫辰
c3cbe8b9a3
Fix OpenAPI allOf reference fields (#4653)
* Fix OpenAPI allOf reference fields

🤖 Generated with Codex

* Add allOf reference crash regression

🤖 Generated with Codex

* Handle OpenAPI component refs in allOf

🤖 Generated with Codex

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-27 15:25:22 -04:00
Jeremiah Lowin
ffea4d6a3e
Docs: add v3.4.5 changelog entries to main (#4674)
* Docs: add v3.4.5 changelog entries

* Condense the 3.4.5 entries to patch-release length
2026-07-27 15:13:03 -04:00
Eduardo Cruz Guedes
794bfe9567
Add valid_scopes parameter to OIDC proxy valid scopes (#4660)
* Accept valid_scopes on OIDCProxy

* Keep valid_scopes when verify_id_token restores scopes

* Document valid_scopes on the OIDC proxy

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-27 15:12:15 -04:00
marvin-context-protocol[bot]
11ee46bf3b
chore: Update SDK documentation (#4647)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-07-27 15:03:41 -04:00
Jeremiah Lowin
cc02df94c5
Audit v4 docs: fix missing version badges, fill whats-new gaps (#4668)
* Fix missing/wrong 4.0.0 version badges

* Fill v4 badge and whats-new gaps found in docs audit
2026-07-27 15:03:18 -04:00
Jeremiah Lowin
ea7fb8cb2e
Remove 3.x-era compatibility shims (#4661)
* Remove 3.x-era compatibility shims

* Require response_type in ctx.elicit()

* Name the utilities path for the two non-re-exported auth helpers

* Point sampling handler migration at its submodule
2026-07-27 14:59:43 -04:00
Jeremiah Lowin
1550eea886
Copy schemas iteratively so deep nesting still compresses (#4671)
* Copy schemas iteratively so deep nesting still compresses

* Keep $defs when the reference scan hits its depth limit
2026-07-27 14:58:13 -04:00
Jeremiah Lowin
e4ccf06baf
Fix FAQ: sampling/roots/elicitation legacy-mode advice, SessionProvider registration (#4672)
* Fix FAQ: narrow the legacy-mode recommendation, note SessionProvider registration

* Correct sampling's modern-protocol claim: guard pattern works, just isn't the recommended path
2026-07-27 14:57:35 -04:00
Jeremiah Lowin
886c85e5f5
Cover require_roles in the v4 highlights (#4666)
* Cover require_roles in whats-new

* Decouple require_roles from the SEP-990 example; require a claim-validating provider
2026-07-27 14:57:23 -04:00
Jeremiah Lowin
95edc1d2f3
Record effective scopes on the OAuth transaction (#4670) 2026-07-27 14:33:57 -04:00
Jeremiah Lowin
4e136e60d6
Document the issuer_url identity change for upgraders (#4658)
* Document the issuer_url identity change for upgraders

Adds an upgrade note covering the one-time re-authorization, fixes the MultiAuth examples that pointed issuer_url at the upstream IdP, and corrects the OCI docstring.

* Address review: valid docstring example, narrower reauth scope

* Scope the reauth checklist item to token-minting providers
2026-07-27 12:45:24 -04:00
Jeremiah Lowin
27a5921bff
Expand the FAQ for the v4 transition (#4649) 2026-07-27 12:41:32 -04:00
Jeremiah Lowin
920cb47778
Add require_roles auth check (#4656)
* Add require_roles auth check

* Make role docs runnable standalone and fully annotated

* Treat a scalar role claim as one role; correct step-up docs

* Add v4 version badge to require_roles docs
2026-07-27 12:36:58 -04:00
Jeremiah Lowin
0c1c42f151
Bind CIMD assertion audience to the advertised token endpoint (#4659)
A bare-authority base_url renders with a trailing slash, so the expected aud was https://host//token while the metadata advertised https://host/token.
2026-07-27 11:46:03 -04:00
Jeremiah Lowin
6c4ba6b420
Use the snake_case field name in the task return-type test (#4657) 2026-07-27 10:56:03 -04:00
Jeremiah Lowin
a42faab783
Use issuer_url for OAuth issuer identity (#4652)
* Use issuer_url for OAuth issuer identity, not base_url

* Apply ruff format to issuer identity tests

* Align ID-JAG audience docstring with issuer_url

* Make InMemoryOAuthProvider keyword-only like its parent

* Keep ID-JAG audience on base_url, out of scope for issuer identity

* Remove stray scratch script

* Make AuthorizationHandler keyword-only

* Bind ID-JAG audience to the issuer identifier

* Fix double slash in issuer_url well-known log hint
2026-07-27 10:43:12 -04:00
Jeremiah Lowin
b1e0586d4e
Remove server-initiated sampling and roots from the server API (#4648)
* Remove server-initiated sampling and roots from the server API

Deletes fastmcp/server/sampling/, Context.sample/sample_step/list_roots, and
FastMCP(sampling_handler=). The proxy's handshake-era relay now reaches the
front session through the SDK directly.

* Update tests for the removed sampling and roots server API

* Era-gate client.set_logging_level on modern connections

* Document that server-initiated sampling and roots are not in FastMCP 4

* Silence ty deprecation diagnostics and drop stale sampling doc mentions

* Baseline tools-call-sampling; fix removal leftovers flagged by ruff

* Document sampling handlers on both protocol routes; qualify log-level override

* Docs: sampling and roots work on modern via the guard pattern

The imperative ctx.sample()/ctx.list_roots() stay removed, but both
capabilities survive as input-required requests, as tests/conformance
exercises on 2026-07-28. Direct LLM calls remain the recommendation for
generation; roots has no round-trip-budget objection.

* Change register: record the guard route for sampling and roots

* Editorial pass on the sampling and roots docs

* Flag the sampling removal at the top of the page

* Restore the version badge and point sampling users at 3.x

* Keep the sampling conformance scenario live; fix roots example URIs

* Upgrade guide: staying on 3.x is an option for sampling servers

* Elicitation: state the era split once, not twice
2026-07-27 10:32:31 -04:00
Jeremiah Lowin
9ea5a40728
Drop stale label-noting instructions from CLAUDE.md and review-pr skill (#4654)
Labels are bot-assigned from title/body/code; noting a "suggested" label
in the PR body was a leftover from an unrelated PR (#4392) and doesn't
match how this repo actually labels things.
2026-07-27 10:31:58 -04:00
Jeremiah Lowin
b2b2b0f918
Elicitation: state the era split once, not twice 2026-07-27 09:43:52 -04:00
Jeremiah Lowin
a2bec08e76
Fix double slash in issuer_url well-known log hint 2026-07-27 09:43:29 -04:00
Jeremiah Lowin
62afdca775
Bind ID-JAG audience to the issuer identifier 2026-07-27 09:37:38 -04:00
Jeremiah Lowin
c4dcf833ca
Upgrade guide: staying on 3.x is an option for sampling servers 2026-07-27 09:37:15 -04:00
Jeremiah Lowin
0172e4c4d4
Keep the sampling conformance scenario live; fix roots example URIs 2026-07-27 09:35:30 -04:00
Jeremiah Lowin
aaaca09a91
Make AuthorizationHandler keyword-only 2026-07-26 21:11:55 -04:00
Jeremiah Lowin
0e9cab86fd
Restore the version badge and point sampling users at 3.x 2026-07-26 21:10:41 -04:00
Jeremiah Lowin
4a616d6e39
Flag the sampling removal at the top of the page 2026-07-26 20:42:12 -04:00
Jeremiah Lowin
7fe3c1e8bd Editorial pass on the sampling and roots docs 2026-07-26 20:23:23 -04:00
Jeremiah Lowin
d5ff831602
Change register: record the guard route for sampling and roots 2026-07-26 19:33:40 -04:00
Jeremiah Lowin
cf7edc895c
Docs: sampling and roots work on modern via the guard pattern
The imperative ctx.sample()/ctx.list_roots() stay removed, but both
capabilities survive as input-required requests, as tests/conformance
exercises on 2026-07-28. Direct LLM calls remain the recommendation for
generation; roots has no round-trip-budget objection.
2026-07-26 19:22:37 -04:00
Jeremiah Lowin
46c3b74346
Remove stray scratch script 2026-07-26 17:48:11 -04:00
Jeremiah Lowin
98ac0402df
Keep ID-JAG audience on base_url, out of scope for issuer identity 2026-07-26 17:48:01 -04:00
Jeremiah Lowin
dec25ba6be
Merge remote-tracking branch 'origin/main' into r4648
# Conflicts:
#	tests/conformance/expected-failures.yml
2026-07-26 17:40:14 -04:00
Jeremiah Lowin
fecced2b5c
Merge pull request #4650 from PrefectHQ/claude/mcp-conformance-tests-7ec13f
Pass the MCP conformance suite's draft and pending scenarios
2026-07-26 17:38:13 -04:00
Jeremiah Lowin
5745323ecd
Cover trace propagation through the modern proxy relay 2026-07-26 17:15:30 -04:00
Jeremiah Lowin
46cd0c7933
Format the split guard-components test module 2026-07-26 17:03:04 -04:00
Jeremiah Lowin
f7eed91aa8
Forward guard asks through prompt, resource, and template proxies
A proxy has no back-channel to the real user, so driving a backend ask inside
it failed outright. Surface it as a result for the parent, as ProxyTool does.
2026-07-26 16:58:58 -04:00
Jeremiah Lowin
8768921fd9
Split guard caching tests into their own module
Keeps test_caching.py under its size limit by topic rather than by
compressing the new tests.
2026-07-26 16:46:21 -04:00
Jeremiah Lowin
2d3ad9ca0d
Make a contended tasks/update wait instead of dropping its answer
Partial fulfillment means two in-flight updates can carry different answers,
so acknowledging the one that loses the update lock stranded the task on a key
the client had already sent.
2026-07-26 16:40:33 -04:00
Jeremiah Lowin
4ef7d16419
Keep multi-round-trip asks out of the response cache
Prompt and resource asks carry no content, so caching one stored an empty
result and the client never saw the question. Bypass the cache on
continuation legs and return asks unwrapped, as tool calls already did.
2026-07-26 16:06:17 -04:00
Jeremiah Lowin
7ca58583fd
Document the guard pattern for prompts and resources 2026-07-26 15:49:45 -04:00
Jeremiah Lowin
96e12569b1
Address review: durable re-entry, resource guards, deterministic test
Keep the final outstanding input marker until the next task leg is durable,
so a racing tasks/get cannot read a parked leg as complete. Let resources and
resource templates return InputRequiredResult like tools and prompts. Identify
parked requests by their question rather than sort order.
2026-07-26 15:36:40 -04:00
Jeremiah Lowin
a7248480e2
Make InMemoryOAuthProvider keyword-only like its parent 2026-07-26 15:34:06 -04:00
Jeremiah Lowin
18aa6a09d6
Document sampling handlers on both protocol routes; qualify log-level override 2026-07-26 15:19:11 -04:00
Jeremiah Lowin
66d842d6e9
Align ID-JAG audience docstring with issuer_url 2026-07-26 15:13:58 -04:00
Jeremiah Lowin
681d5a7120
Apply ruff format to issuer identity tests 2026-07-26 15:12:50 -04:00
Jeremiah Lowin
c4c72ac240
Use issuer_url for OAuth issuer identity, not base_url 2026-07-26 15:10:15 -04:00
Jeremiah Lowin
b9fcef1889
Baseline tools-call-sampling; fix removal leftovers flagged by ruff 2026-07-26 15:07:24 -04:00
Jeremiah Lowin
7699deb99c
Pass the MCP conformance suite's draft and pending scenarios
Pin the suite, build out the fixture, and fix the protocol gaps it found.
2026-07-26 15:00:08 -04:00
Jeremiah Lowin
1593257f2a
Merge remote-tracking branch 'origin/main' into modern-merge
# Conflicts:
#	tests/client/test_roots.py
2026-07-26 14:53:31 -04:00
Jeremiah Lowin
90f2e190d0
Silence ty deprecation diagnostics and drop stale sampling doc mentions 2026-07-26 14:45:55 -04:00
Shuying
2a93404e8c
fix: accept callable roots handlers (#4639)
* Accept callable roots handlers

🤖 Generated with OpenAI Codex

* fix: cover callable object roots handlers

🤖 Generated with OpenAI Codex

---------

Co-authored-by: Shuying <zsy@u.northwestern.edu>
2026-07-26 14:43:41 -04:00
Jeremiah Lowin
1a43a3b8e9
Document that server-initiated sampling and roots are not in FastMCP 4 2026-07-26 14:43:18 -04:00
Jeremiah Lowin
fca339084b
Era-gate client.set_logging_level on modern connections 2026-07-26 14:39:31 -04:00
Jeremiah Lowin
704b74b3ab
Update tests for the removed sampling and roots server API 2026-07-26 14:38:26 -04:00
Jeremiah Lowin
e056a3946e
Remove server-initiated sampling and roots from the server API
Deletes fastmcp/server/sampling/, Context.sample/sample_step/list_roots, and
FastMCP(sampling_handler=). The proxy's handshake-era relay now reaches the
front session through the SDK directly.
2026-07-26 14:34:21 -04:00
Jeremiah Lowin
b07f9ce9ae
Honor OAuth application_type in DCR (SEP-837) (#4621)
* Honor OAuth application_type in DCR (SEP-837)

* Simplify web redirect check per ruff SIM103

* Enforce application_type over HTTP, at auth time, and tighten native scheme rules

Recover the DCR application_type the SDK RegistrationHandler drops (P1), enforce the stored type on the authorization redirect path (P2), restrict native to loopback http + custom schemes (P2), and document the web/native rules (P2).

* Fix loopback range detection and use a positive scheme allowlist

Classify loopback hosts with ipaddress.is_loopback so all of 127.0.0.0/8 counts (a web client could bypass the non-loopback rule with 127.0.0.2). Replace the NON_REDIRECT_NETWORK_SCHEMES denylist with STANDARD_URI_SCHEMES: native now accepts only https, loopback http, and unregistered private-use schemes per RFC 8252, so smb/smtp/nfs and other unlisted standard schemes no longer pass.

* Vendor the IANA scheme registry and consolidate the loopback classifier

Replace the hand-picked STANDARD_URI_SCHEMES with a vendored snapshot of the IANA URI scheme registry (423 schemes), so registered transports nobody enumerated (coap, coaps, stun, turn, mqtt) fail closed instead of passing as private-use. Delete the stale duplicate _is_loopback_host in oauth_proxy/models.py and reuse the ipaddress-based classifier from redirect_validation, restoring loopback port flexibility across all of 127.0.0.0/8.

* Treat the reserved localhost namespace and absolute host forms as loopback

RFC 6761 6.3 reserves the whole localhost namespace for the local machine, so app.localhost and localhost. are loopback just as much as localhost. Previously a web client could register https://app.localhost/callback and bypass the non-loopback rule, while native clients were wrongly refused legitimate http://app.localhost:3000 dev callbacks. The suffix test is anchored on a leading dot so localhost.evil.com and notlocalhost stay non-loopback.

* Narrow scope: drop native scheme classification, keep the web rule

Registry membership cannot separate app-dispatch schemes from network transports (vscode is registered because it is an app scheme), so classifying a native client's scheme rejected callbacks that real MCP clients need. Remove the vendored registry and the private-use test; native now accepts any scheme outside the unsafe set, with cleartext http still limited to loopback. Also reject web registrations that omit redirect_uris rather than storing an unusable localhost placeholder.
2026-07-26 14:24:50 -04:00
Aman Gupta
e4a87f2afe
fix : canonical mime type mapping from formats to remove inconsistency #4627 (#4628)
* fix : canonical mime type mapping from formats to remove inconsistency

* Apply ruff format to _get_mime_type

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-26 14:15:08 -04:00
Jeremiah Lowin
4ebb3fd5e6
Emit scope step-up challenges for incremental authorization (SEP-2350) (#4623)
* Signal component-level scope shortfalls as insufficient_scope (SEP-2350)

* Fix ty type narrowing in scope step-up test

* Respect check short-circuit when reporting scope shortfall (P2)

* Report union of unmet scopes and document step-up contract

* Aggregate scope shortfall across the AuthMiddleware chain

* Stop chain scope aggregation at the first unevaluated gate
2026-07-26 14:13:26 -04:00
dependabot[bot]
c4cb1910a3
chore(deps): bump mcp from 1.27.2 to 1.28.1 in /examples/testing_demo in the uv group across 1 directory (#4614)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-26 14:10:21 -04:00
dependabot[bot]
bc770c6fc0
Bump actions/setup-python from 6 to 7 (#4641)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-26 14:10:03 -04:00
dependabot[bot]
ac83711ff8
Bump actions/upload-artifact from 4 to 7 (#4640)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-26 14:09:51 -04:00
Jeremiah Lowin
4b09a040be
Unpublish v4 development notes; prep docs for beta 1 (#4644)
* Unpublish v4 development notes; prep docs for beta 1

* Nest development notes under dev-docs/

* Rewrite site-root links in dev notes as absolute URLs for GitHub rendering
2026-07-26 14:08:34 -04:00
Jeremiah Lowin
387a063aec
Pin Claude Code to 2.1.215 in the sandboxed Marvin workflows (#4645)
2.1.216 regressed the bubblewrap sandbox the action wraps Bash in when
allowed_non_write_users is set, so every command failed and triage applied
zero labels while reporting success. Also fail the triage job on sandbox
errors, which the existing denial guard could not see.
2026-07-26 13:57:14 -04:00
andrew-stelmach-fleet
caadfe6413
docs: fix ProxyProvider docstring example using nonexistent with_namespace() (#4633)
The example called proxy.with_namespace("remote"), which is not defined
anywhere in the codebase and raises AttributeError. Namespacing a provider
is done via the add_provider() keyword argument.
2026-07-26 13:50:13 -04:00
Jeremiah Lowin
2f992f71ea
Support routable transport headers for gateways (SEP-2243) (#4622) 2026-07-26 13:40:09 -04:00
marvin-context-protocol[bot]
37fb0ad803
chore: Update SDK documentation (#4615) 2026-07-23 20:52:17 -04:00
Jeremiah Lowin
cb5f6abdd0
Pin burner-redis below the Windows-crashing 0.1.7 release (#4618)
* Pin burner-redis below the Windows-crashing 0.1.7 release

burner-redis 0.1.7 crashes the interpreter (native fault, no Python traceback)
running the memory:// task backend under pytest-xdist on Windows — reproduced on
GitHub Actions windows-latest via the 'Upgrade checks' workflow, confirmed
absent on macOS/Linux with the identical dependency versions.

pydocket only floors burner-redis at >=0.1.6, so capping pydocket's own version
is not enough: a resolver remains free to pick the newest burner-redis
satisfying that floor. fastmcp-tasks previously pinned pydocket>=0.20.0 with no
upper bound, so a fresh 'pip install fastmcp[tasks]' today can resolve straight
into the broken combination for a real Windows user on the default backend.

Pin burner-redis<0.1.7 directly, which in turn caps pydocket to <0.20.2 (the
last release that doesn't itself require burner-redis>=0.1.7). Verified the pin
holds under both locked and --upgrade (highest) resolution.

* Scope the burner-redis pin to Windows only

burner-redis 0.1.7 is confirmed fine on macOS/Linux (full suite green there with
the identical upgraded dependencies) - only Windows crashes. The previous
unconditional pin blocked every platform from newer pydocket/burner-redis
releases unnecessarily. Add sys_platform == 'win32' to the burner-redis
constraint so only Windows installs are capped.

Verified via uv pip compile --python-platform: macOS/Linux resolve to
burner-redis 0.1.7 / pydocket 0.23.0 (unblocked); Windows resolves to
burner-redis 0.1.6 / pydocket 0.20.1 (still capped).
2026-07-23 20:51:43 -04:00
Jeremiah Lowin
cf021d1a70
whats-new: add the argument completion capability (#4620)
Server-side completions (@mcp.completion) shipped in #4582 but the
What's New page didn't mention it. Adds it to the authoring-capabilities
cluster with a runnable example and a link to the servers/completions page.
2026-07-23 20:44:16 -04:00
Jeremiah Lowin
f896f5acb5
v4 docs quality pass: stale task/era claims, broken links, polish (#4619)
* v4 docs quality pass: fix stale task/era claims, broken links, writing polish

* whats-new: add the client-side protocol negotiation story

The page told the server half of the era story (serves every era) but
never the client half — that a default Client(url) now negotiates the
modern era, where earlier versions pinned the handshake. Completes the
mental model and links to the client negotiation docs.

* Address review: drop 'complete' over-claim; link mounted-state to Session State
2026-07-23 20:42:13 -04:00
Jeremiah Lowin
078c44d835
Fix stale Mac/Windows-vs-Linux OAuth key/storage docs (#4617)
* Fix stale Mac/Windows-vs-Linux OAuth key/storage docs

#2223 replaced platform-aware keyring/MemoryStore defaults with
deterministic key derivation and an always-on-disk encrypted store,
but the docs update in that PR missed several spots.

* Fix OIDCProxy doc referring to internal upstream_client_secret name

Codex review: the public OIDCProxy constructor takes client_secret;
upstream_client_secret is only OAuthProxy's internal parameter name.
2026-07-23 20:30:05 -04:00
Jeremiah Lowin
39148870af
Merge pull request #4603 from PrefectHQ/feat/tasks-sep2663
Add background tasks via the io.modelcontextprotocol/tasks extension (SEP-2663)
2026-07-23 20:16:11 -04:00
Jeremiah Lowin
601903436b
Pass task-creation results through ToolResult-only middleware
A task-augmented tools/call returns a CreateTaskResult up through the middleware
chain. Response caching and response limiting assumed a ToolResult and accessed
.content/.wrap(), crashing after the task was already enqueued (a client retry
could duplicate side effects). Both now pass any non-ToolResult through
untouched, alongside the existing InputRequiredToolResult bypass.
2026-07-23 20:09:47 -04:00
Jeremiah Lowin
79ba8f180d
Merge remote-tracking branch 'origin/main' into claude/mcp-background-tasks-v2-0f883f
# Conflicts:
#	uv.lock
2026-07-23 20:07:13 -04:00
Jeremiah Lowin
76c6f1a64e
Session-in-task Context API, task telemetry, settings dotenv, guard fail-loud
Five review fixes. ctx.session_id / get_state / set_state now work in a Docket
worker by falling back to the snapshotted session id. Task management wire calls
(submission, tasks/get/update/cancel) create client spans and propagate trace
context. TasksClientSettings loads .env like DocketSettings, and the docs use
its real env var name. A state-only guard round (request_state, no input
requests) fails with a clear error instead of silently completing wrong.
2026-07-23 20:05:54 -04:00
nate nowack
856844cae7
Document targeted v4 prerelease installation (#4598)
🤖 Generated with Codex

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-23 20:00:28 -04:00
nate nowack
cc3d1c18a3
Allow FastMCP prereleases through the repository cooldown (#4596)
* Allow FastMCP prerelease resolution

🤖 Generated with Codex

* Include fastmcp-remote in prerelease resolution

🤖 Generated with Codex

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-23 20:00:23 -04:00
nate nowack
d8ac6cbfde
Fix OAuth proxy override typing (#4612) 2026-07-23 19:52:42 -04:00
Jeremiah Lowin
c556f07a66
Archive v3 docs and publish v4 as the primary version (#4613)
* Archive v3 docs under /v3 and publish v4 as the primary version

* Label primary docs version v4.0.0 (alpha 1)

* Add What's New in v4 page; fix upgrade-guide phrasing; point banner at What's New

* Rewrite What's New around v4's new capabilities, not the sampling deprecation

* Lead What's New with the SDK v2 engine swap and the SEPs it brings

* State ships now (link Session State); tasks arrive next alpha

* Exclude docs/v3 frozen snapshots from doc-example import validation
2026-07-23 19:47:57 -04:00
Jeremiah Lowin
1c57079b9b
Verify UserSession state works inside background tasks
Lock in the tasks x stateless-session-state (#4604) integration: a
session: UserSession parameter resolves in a Docket worker via the task-aware
get_server() and the principal restored from the task snapshot, sharing state
across a principal's tasked calls and staying isolated between principals.
2026-07-23 19:38:19 -04:00
Jeremiah Lowin
3f746b91fc
Merge remote-tracking branch 'origin/main' into claude/mcp-background-tasks-v2-0f883f
# Conflicts:
#	fastmcp_slim/fastmcp/server/dependencies.py
2026-07-23 19:32:52 -04:00
Jeremiah Lowin
cb4419ed02
Fix broken Docket links in task docs
The example README pointed at github.com/PrefectHQ/docket (404); the canonical
repo is chrisguidry/docket. Point the docs' Docket-docs link at the canonical
docket.lol.
2026-07-23 19:24:45 -04:00
Jeremiah Lowin
8363ec4d26
Add stateless session state (UserSession / SessionId) (#4604)
* Design doc: stateless session state

* Add stateless session-state primitives: Scope, SessionCodec, scoped state

* Add SessionProvider and Session() annotation for stateless session state

* Rewrite session-state design to final shape (Session object, two patterns, no seal)

* Rework stateless session state to final Session/SessionId design

Remove Scope, SessionCodec/sealing, and scoped ctx.get_state. Add the
Session object (get/set/delete/clear over one dict per (principal,
session_id) key), injected session: Session (keyed by principal, requires
auth), session_id: SessionId argument with auto-filled description, and
SessionProvider contributing create_session/end_session.

* Rename injected marker to UserSession; auto-wire SessionProvider on SessionId

* Document stateless session state as a v4 feature

* Require SessionProvider and make sessions create-then-validate

Remove the implicit SessionProvider auto-wiring; a SessionProvider must now be
registered explicitly. create_session records an owned session and get_session
validates the id, rejecting uncreated or foreign ids.

* Add Session.id (public id for session_id sessions, None for UserSession)

* Fix ty: narrow Tool | None and ToolResult.structured_content in session tests

* Fix session-provider enforcement gap for non-local tools; stop embedding raw principal in UserSession key

* Fix disabled session_id tools blocking listing; reject local tools shadowing SessionProvider lifecycle names

* Decouple SessionId description from lifecycle tool name so it survives namespaced mounts

* Remove SessionProvider enforcement; get_session validation is the guarantee

* Fix stale enforcement/key-format docs; document store-owned session TTL

* Dedup SessionId contract description; tighten context.mdx session-state lead

* Make session store/description resolution work in Docket task workers and for partial tools

* Expose get_session as a standalone task-safe function; drop foreground-only Context.get_session

* Move get_session to dependencies alongside the other request accessors

* Reframe context state docs as Request State; cross-request persistence points to Session State

* Address UserSession injection edge cases from review

- inject a UserSession instance (not bare Session) so isinstance holds
- support session: UserSession | None = None (inject None when unauth)
- detect SessionId params past a partial's positional binding
2026-07-23 19:21:00 -04:00
Jeremiah Lowin
53741dc9c7
Keep task routing keys alive via sliding TTL; version-aware worker server resolution
A resumed leg that runs longer than its pointer's wall-clock TTL stranded
_lookup_task on the base leg (false completion / not found). Each poll now
refreshes the routing keys' TTL (sliding expiration), so an actively-polled
task keeps them alive regardless of execution duration, and the resumed-leg
write uses the same buffered TTL as creation. Separately, remote-worker server
resolution now respects the requested tool version, so two versions of the same
mounted tool name resolve to their own child server.
2026-07-23 19:18:51 -04:00
Jeremiah Lowin
95f766cb74
Normalize asyncio.TimeoutError to builtin in task input timeout (py3.10)
asyncio.wait_for raises asyncio.TimeoutError, a distinct type from the builtin
before Python 3.11, so an elicitation-callback timeout leaked an uncaught type
on 3.10. Convert it to the builtin TimeoutError the rest of the drive raises.
2026-07-23 18:35:57 -04:00
Jeremiah Lowin
f81d6c07d8
Load task settings from .env; gate root publish on fastmcp-tasks; fix worker command
DocketSettings now loads the same dotenv source as core settings, so a
FASTMCP_DOCKET_* value in .env configures the backend instead of silently
using memory://. The root fastmcp publish waits for the matching fastmcp-tasks
to appear on PyPI before uploading, so the [tasks] extra is never installable
but unresolvable. And the example README uses the real worker entry point
(python -m fastmcp_tasks.worker_cli worker).
2026-07-23 18:30:52 -04:00
Jeremiah Lowin
c3ad5e9ecb
Clear stale auth in reused workers; bound elicitation; version explicit tasks
Three review fixes. A Docket worker may reuse an asyncio context across tasks,
so snapshot restore now always resets auth and headers to the current task's
state — an anonymous task following an authenticated one no longer inherits the
prior caller's identity. A stalled in-task elicitation handler is now bounded by
the call's remaining timeout, like polling and sleeps. And call_tool_task takes
a version= to task a specific component version rather than the highest.
2026-07-23 18:25:48 -04:00
Jeremiah Lowin
a194acdc5f
Resolve mounted server and headers correctly in remote task workers
Two remote-worker fixes. A separate worker process cannot reach the submitting
process's server map, so a mounted task's ctx.fastmcp/CurrentFastMCP() fell back
to the root; the worker now re-resolves the owning child from the root using the
snapshotted tool name. And restoring headers no longer fabricates a live Request
— get_http_headers() reads a dedicated task-headers context var while
get_http_request()/CurrentRequest() correctly keep raising inside a task.
2026-07-23 18:19:35 -04:00
Jeremiah Lowin
fbee629ed9
Advertise only supported token endpoint auth methods in OAuthProxy metadata (#4608)
* Advertise only supported token endpoint auth methods in OAuthProxy metadata

* Normalize DCR registration response to the stored public client
2026-07-23 18:11:18 -04:00
Jeremiah Lowin
9019a7af70
Add PyPI publish workflow for fastmcp-tasks
The fastmcp[tasks] extra pins fastmcp-tasks=={version}, but no workflow
published it — pip install "fastmcp[tasks]" would fail to resolve. Mirror the
fastmcp-remote workflow: build on release, wait for the matching fastmcp-slim to
appear on PyPI, then publish.
2026-07-23 16:54:31 -04:00
Jeremiah Lowin
f627170088
Bound task drive by one deadline; version-aware tasking; serialize cancel
Three review fixes: transparent call_tool(timeout=N) now enforces one deadline
across the whole poll loop (not per-request), matching the sync timeout; the
tools/call interceptor resolves the client-requested component version instead
of the highest; tasks/cancel runs under the per-task update lock and re-resolves
the live leg, so it can't cancel a stale leg while an update enqueues the next.
2026-07-23 16:53:08 -04:00
Jeremiah Lowin
733801ed6c
Rework tasks example into a runnable HTTP client/server pair
Server runs over HTTP on the default memory:// backend (no Redis needed); the
client drives it transparently, via an explicit handle, and with a parallel
command that fires several tasks at once to show them overlap. A 1s poll
interval keeps the demo snappy.
2026-07-23 16:44:53 -04:00
Liang Hu
99327084d2
Preserve raw CallToolResult returns (#4587)
Co-authored-by: nate nowack <thrast36@gmail.com>
2026-07-23 15:10:42 -05:00
nate nowack
06aa84943c
Expose era-neutral client server metadata (#4599)
* Expose era-neutral client metadata

🤖 Generated with Codex

* Clarify pinned modern client metadata
2026-07-23 15:06:26 -05:00
Jeremiah Lowin
1d442ffa36
Make tasks/cancel actually cancel input_required tasks
A guard task parked on input has an already-COMPLETED Docket execution, so
docket.cancel on it was a no-op: tasks/get reported input_required forever and
tasks/update could still resume it. Record a durable logical-cancellation
marker that tasks/get reports as cancelled and tasks/update refuses to resume,
and clear the parked leg's outstanding requests on cancel.
2026-07-23 08:15:21 -04:00
Jeremiah Lowin
110943fc61
Skip expired snapshot tokens; bound task wait polls by deadline
A queued task can outlive its submitter's token expiry: install the snapshot
token only if still valid, matching the SDK bearer check, so a delayed task
never runs under credentials a live request would reject. ToolTask.wait now
bounds each tasks/get by the remaining deadline so a stalled poll cannot block
past the caller's timeout.
2026-07-23 08:12:42 -04:00
Jeremiah Lowin
1c7ade215b
Merge remote-tracking branch 'origin/main' into claude/mcp-background-tasks-v2-0f883f 2026-07-23 08:00:29 -04:00
Jeremiah Lowin
edb54bddf3
Merge pull request #4602 from PrefectHQ/feat/server-extension-api
Add FastMCP-native server extension API (SEP-2133)
2026-07-23 07:59:59 -04:00
Jeremiah Lowin
b75dde3b5c
Mask raised task errors regardless of ctx param
Resolve the error-masking policy via the worker-server resolver instead of
the active Context: a task tool that raises without requesting a ctx param
has no active context, so the old lookup leaked unmasked error text past
mask_error_details=True. Also route custom Tool subclasses through the same
error-conversion wrapper as FunctionTool.
2026-07-23 07:59:54 -04:00
Jeremiah Lowin
19c5c507cc
Address review feedback on SEP-2663 tasks
- Client task support is opt-in via importing fastmcp_tasks (drop the core
  auto-load of companion packages); a plain Client never advertises tasks.
- A worker restores the submitting caller's auth token and headers from the
  task snapshot into the standard ambient context, so get_access_token() /
  get_http_headers() work in a distributed worker with no new core hooks.
- worker_cli validates the loaded extension's resolved backend, not env defaults,
  so a constructor-configured Redis worker starts.
- Thread the per-call read timeout through task polling; bound ToolTask.wait by
  its deadline; set_elicitation_callback rebuilds internal extensions so a
  later-set handler answers in-task input.
- README imports TaskConfig from fastmcp.utilities.tasks.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-22 19:14:16 -04:00
Jeremiah Lowin
e5ca0269cb
docs: rewrite background tasks pages for SEP-2663
Server (servers/tasks.mdx) and client (clients/tasks.mdx) docs rewritten for
the extension model: add_extension(TasksExtension()), the guard pattern for
in-task input (no imperative ctx.elicit()), tools-only, and the modern-protocol
requirement (the inverse of the old SEP-1686 legacy-only note). Mechanical
fixes elsewhere for the same reason: telemetry.mdx's tasks/{operation} method
list (get/update/cancel, not result/list), client.mdx's legacy-only feature
list (tasks moved to modern-only) and extension-composition paragraph
(describes the tasks ClientExtension, not the removed notification binding),
and stale SEP-1686 references in the FastMCP 2 upgrade guide. v4-notes status
lines updated to Shipped (#4602, #4603).
2026-07-22 17:24:56 -04:00
Jeremiah Lowin
bb3ef39a89
Close SEP-2663 compliance gaps: -32003 on task methods, raised-error semantics, update race
- tasks/get|update|cancel now return -32003 when the client did not declare the
  tasks extension for the request (SEP-2663 MUST).
- A task tool that raises is a completed task with an is_error result, not a
  failed task; failed is reserved for protocol faults, matching a live tools/call.
- A per-task lock serializes concurrent tasks/update so two racing answers cannot
  each enqueue a next leg (double execution).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-22 16:59:13 -04:00
Jeremiah Lowin
74e01d5e08
Add SEP-2663 client half: transparent call_tool, ResultClaim, Task handle
A FastMCP client now transparently completes tasked tools/call: the tasks
ClientExtension advertises the capability and claims the CreateTaskResult, and
the resolver drives the tasks/get poll loop to completion, answering in-task
input through the client's elicitation handler and returning the tool's real
result. call_tool is transparent, call_tool_mcp exposes the raw result, and
call_tool_task yields a Task handle. The client half moves to fastmcp-tasks;
the [tasks] client extension auto-wires into Client (ProxyClient opts out).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-22 15:21:10 -04:00
nate nowack
8efa405833
Bridge camelCase ToolAnnotations reads (#4597)
🤖 Generated with Codex
2026-07-22 13:55:41 -05:00
Jeremiah Lowin
d41ff5bcd8
Rebuild guard tasks as end-and-reenter; remove imperative in-task elicit
A task tool that returns InputRequiredResult now ends its leg (freeing the
worker) and stores the ask as durable state; tasks/update enqueues a fresh
Docket execution (the next leg) with accumulated request_state/input_responses
injected via ctx. No worker ever blocks on input, so a parked task no longer
holds up shutdown. Imperative ctx.elicit() inside a task is removed and raises
with guard-pattern guidance.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-22 12:38:46 -04:00
Jeremiah Lowin
ef29b731ea
Add server-side claim production for tasks; emit resultType discriminator
Widen the tools/call result serialization (via a refcounted, modern-gated wrap
installed by TasksExtension) so a CreateTaskResult reaches the client instead of
being stripped by the CallToolResult|InputRequiredResult surface — the SDK ships
claim consumption but no production. Emit the resultType discriminator the
protocol requires (task on CreateTaskResult, complete on the tasks/* results);
the draft schema forbids it (additionalProperties:false), a contradiction
reported upstream. Closes compliance gaps G1/G4/G5.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-22 08:03:32 -04:00
Jeremiah Lowin
b0d3e653b9
Fix flaky stdio crash-recovery tests: assert eventual recovery (#4594) 2026-07-22 08:01:37 -04:00
Jeremiah Lowin
bc22e517fd
Fix ty diagnostics in task tests, scope ty exclusion to client-task files 2026-07-21 23:10:00 -04:00
Jeremiah Lowin
5fa2883670
Implement SEP-2663 tasks extension: TasksExtension, poll-based task lifecycle
TasksExtension serves io.modelcontextprotocol/tasks on the extension API:
a decide-and-task tools/call interceptor (era-gated to modern connections),
tasks/get with inlined results and inputRequests, tasks/update delivering
poll-based in-task elicitation, tasks/cancel, durable creation, and
auth-scoped task isolation. Wire models validate against the vendored
ext-tasks schema. Worker-side Context hooks are refcounted so sibling
servers cannot strand each other's workers.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-21 23:00:38 -04:00
Jeremiah Lowin
6fce4e538f
Move task subsystem to fastmcp-tasks package, disconnect SEP-1686 wire from core
Engine modules (keys, context snapshot, docket lifespan, worker CLI,
client handles) move intact; SEP-1686 wire modules park in _legacy_wire
for adaptation to SEP-2663. Core keeps task=True declaration on tools
only and raises at serve time until the tasks extension is registered.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-21 21:51:45 -04:00
Jeremiah Lowin
d756b99bf6
Sort imports in extensions.py 2026-07-21 20:44:54 -04:00
Jeremiah Lowin
242850c0f3
Scaffold fastmcp-tasks workspace package
Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-21 20:44:54 -04:00
Jeremiah Lowin
094738f68a
Add server extension API: add_extension with capability, methods, tool-call interception, and lifespan
Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-21 20:36:38 -04:00
Jeremiah Lowin
4402b48954
test: vendor ext-tasks draft schema as fixture 2026-07-21 20:19:28 -04:00
Jeremiah Lowin
44d6d739ea
docs: v4 background-tasks design — rebuild on SEP-2663 as fastmcp-tasks 2026-07-21 20:18:58 -04:00
Jeremiah Lowin
36caaa6f56
Document v3->v4 removals and add upgrade-reality tests (#4585)
* Document v3->v4 removals and add upgrade-reality tests

* Check canonical imports in a clean subprocess to avoid suite import pollution

* Address review: import_server semantics note, pin traversal error, drop redundant import

* Address review round 2: real screening test, Depends factory, remove_tool/create_proxy notes

* Validate canonical imports in-process; fix lifespan/timeout/error-code/starlette doc notes

* Reconcile with fastmcp.types trim: import protocol types from mcp_types

* Record v4 release codename arc in dev notes
2026-07-21 17:12:59 -04:00
Jeremiah Lowin
30044c7864
Fix percent-encoded skill file names unreadable in resources mode (#4590)
* Fix percent-encoded skill file names unreadable in resources mode

Encode supporting-file paths explicitly (quote/unquote) when building
and resolving skill:// resource URIs, instead of relying on AnyUrl's
implicit encoding. This also closes the ambiguity where a file literally
named "setup%20guide.md" would collide with "setup guide.md" once both
were percent-encoded.

Fixes #4545

* Quote main_file_name when building its resource URI

Keeps the main-file URI on the same explicit quote/unquote round-trip
as supporting files, so a custom main_file_name containing a literal
'%' still resolves after the shared unquote() in _get_resource().
2026-07-21 15:34:09 -04:00
marvin-context-protocol[bot]
d0f1468fce
chore: Update SDK documentation (#4589)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-07-21 13:10:24 -05:00
VectorPeak
74b8f1bc1c
Fix File helper extension handling (#4531)
Preserve explicit suffixes when building data-backed File resource URIs, while keeping the inferred-extension fallback for names without a suffix.

Closes #4530

Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>
2026-07-21 13:04:15 -05:00
苏紫辰
16a09f0151
Fix skill frontmatter with UTF-8 BOM (#4533)
🤖 Generated with Codex
2026-07-21 12:48:40 -05:00
Jeremiah Lowin
f038cf3be7
Add machine-to-machine client authentication (#4583)
* Add M2M client credentials auth providers

Wrap the SDK's client_credentials and private_key_jwt OAuth providers as
FastMCP-idiomatic ClientCredentialsOAuthProvider and PrivateKeyJWTOAuthProvider,
enabling browser-free client authentication via Client(auth=...).

* Fix M2M token cache collision and explicit-scope drop

Namespace the token cache by client_id so distinct clients sharing one store don't overwrite each other's tokens; pin caller-supplied scopes so the token request keeps them; fix CodeQL URL-substring check in tests; drop unused logger.

* Preserve step-up scope union, scope-aware token cache, restore token expiry

Only pin the caller's explicit scopes on initial authorization, leaving the SDK's step-up scope union intact; namespace the token cache by requested scopes as well as client_id; restore persisted absolute expiry on init so an expired stored token is re-fetched.

* Skip expiry restore for non-expiring reloaded tokens

* Distinguish expires_in=0 from omitted when restoring expiry

* Scope step-up flag to the flow via ContextVar; runnable JWT signing example
2026-07-21 12:27:08 -04:00
Jeremiah Lowin
7417e974f4
Let a server answer argument-completion requests (#4582)
* Add server-side argument completion (@mcp.completion)

* Reference CompletionValues directly in cast so the import reads as used

* Import completion types from mcp_types, not the fastmcp.types mirror

* Fix test imports after dropping the fastmcp.types mirror

* Fix change-register example import after dropping the types mirror

* Enforce 100-value completion cap; make docs example runnable

* Document completion authorization contract

* Offload sync completion handlers to threadpool

* Exclude bare str from completion return type

* Pass Any-typed value in bare-string rejection test

* Point completion authoring types to mcp_types in v4 notes
2026-07-21 12:26:24 -04:00
Jeremiah Lowin
611a35861d
Trim fastmcp.types to FastMCP-unique types (#4584)
* Trim fastmcp.types to FastMCP-unique types only

fastmcp.types re-exported 29 mcp_types symbols verbatim, which was
pointless indirection users had to discover. It now holds only Textarea,
the one type FastMCP actually defines; everything else imports from
mcp_types directly. These mirrors were added during unreleased SDK v2
migration work and never shipped, so this is not a breaking change.

* Keep historical mcp.types import in v2/v3 migration examples
2026-07-21 09:45:41 -04:00
Jeremiah Lowin
10af989563
Keep historical mcp.types import in v2/v3 migration examples 2026-07-20 21:04:01 -04:00
Jeremiah Lowin
7814d95990
Merge pull request #4581 from PrefectHQ/docs/v4-notes-refresh
Bring the v4 developer notes up to date with what shipped
2026-07-20 20:58:26 -04:00
Jeremiah Lowin
e32a2098f9
Trim fastmcp.types to FastMCP-unique types only
fastmcp.types re-exported 29 mcp_types symbols verbatim, which was
pointless indirection users had to discover. It now holds only Textarea,
the one type FastMCP actually defines; everything else imports from
mcp_types directly. These mirrors were added during unreleased SDK v2
migration work and never shipped, so this is not a breaking change.
2026-07-20 20:53:11 -04:00
Jeremiah Lowin
07fa270652
Address review: drop tasks from modern capability table; note the reentrancy blocker too 2026-07-20 20:28:23 -04:00
Jeremiah Lowin
2db431f5e5
Refresh v4 notes index overview to match shipped work 2026-07-20 20:02:49 -04:00
Jeremiah Lowin
18b898e42a
Refresh v4 developer notes to match shipped work 2026-07-20 20:00:37 -04:00
nate nowack
9d9bf2b717
Restore upgraded dependency checks (#4576)
* 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
2026-07-20 18:46:30 -04:00
marvin-context-protocol[bot]
4ec2757b6d
chore: Update SDK documentation (#4569)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-07-20 18:44:54 -04:00
Jeremiah Lowin
d927762003
Drop forked client protocol helpers in favor of the SDK's (#4574)
* 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
2026-07-20 18:21:56 -04:00
Jeremiah Lowin
2bcfae3412
Merge pull request #4572 from PrefectHQ/feature/client-auto-default
Negotiate the best mutual protocol era by default
2026-07-20 18:16:40 -04:00
Jeremiah Lowin
afbe342587
Document on_initialize and session-state loss under the auto default 2026-07-20 18:04:29 -04:00
Jeremiah Lowin
e01c5932bf
Unpin tests whose defects #4579 fixed
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.
2026-07-20 18:02:21 -04:00
Jeremiah Lowin
5f428aaced
Merge remote-tracking branch 'origin/main' into feature/client-auto-default 2026-07-20 17:53:27 -04:00
Jeremiah Lowin
57bbc9859e
Surface resource, prompt, and proxy errors on the modern protocol era (#4579)
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.
2026-07-20 17:52:12 -04:00
Jeremiah Lowin
52b37b9a0c
Mark transforming single-server config wrapper legacy-only 2026-07-20 16:34:42 -04:00
Jeremiah Lowin
d048c7e690
Merge branch 'audit/pins-server' into feature/client-auto-default 2026-07-20 16:27:59 -04:00
Jeremiah Lowin
de14ed1b7c
Audit mode="legacy" pins in server tests and top-level stragglers
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).
2026-07-20 16:00:27 -04:00
Jeremiah Lowin
f2ccb6a32c
Merge branch 'audit/pins-proxy' into feature/client-auto-default 2026-07-20 16:00:18 -04:00
Jeremiah Lowin
bcf90d5ae7
Remove unnecessary mode="legacy" pins from proxy tests
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).
2026-07-20 15:50:35 -04:00
Jeremiah Lowin
ae43039d8e
Audit tests/client/ mode="legacy" pins
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.
2026-07-20 15:43:04 -04:00
Jeremiah Lowin
bf352d8a4a
Make protocol-version notes scannable and drop era jargon from client docs 2026-07-20 15:00:58 -04:00
Jeremiah Lowin
1e1882851d
Keep the CLI URL proxy era-agnostic; monitor claimed-result resolution 2026-07-20 12:46:34 -04:00
Jeremiah Lowin
35c2b52652
Merge remote-tracking branch 'origin/main' into feature/client-auto-default
# Conflicts:
#	fastmcp_slim/fastmcp/server/providers/proxy.py
2026-07-20 12:33:38 -04:00
Jeremiah Lowin
0ba3db1a56
Mirror the frontend's protocol era on a proxy's backend connection (#4573)
* 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.
2026-07-20 12:31:02 -04:00
Jeremiah Lowin
1a788cf349
Merge remote-tracking branch 'origin/main' into feature/client-auto-default
# Conflicts:
#	tests/client/test_streamable_http.py
#	tests/server/middleware/test_initialization_middleware.py
#	tests/server/tasks/test_task_status_notifications.py
2026-07-20 12:02:38 -04:00
Jeremiah Lowin
effbc568ff
Document Windows CI parallelism and the subprocess_heavy marker (#4575)
* Document Windows CI parallelism and the subprocess_heavy marker

* Exclude subprocess_heavy from the process-free test command
2026-07-20 11:52:42 -04:00
Rach Granville
dd803a0d7f
docs: quote pip extras install examples (#4568)
* docs: quote pip extras install examples

* docs: quote remaining unquoted pip install extras

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-20 11:09:50 -04:00
Jeremiah Lowin
c8b8911226
Stop gather() from creating coroutines it may never schedule (#4559)
* 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
2026-07-20 11:01:30 -04:00
Jeremiah Lowin
c33a3c3b29
Only fail triage when a granted tool is denied, and grant get_pull_request (#4562)
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.
2026-07-20 10:51:42 -04:00
Jeremiah Lowin
b0e782a2ee
Make the unit suite fast: in-process HTTP tests, no real sleeps, parallel Windows CI (#4554) 2026-07-20 10:51:14 -04:00
Marcelo Trylesinski
7934124fb5
Make transformed tool required order deterministic (#4564)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-07-20 07:12:45 -05:00
Jeremiah Lowin
d2ac7ed3d2
Default fastmcp.Client to mode="auto"; surface extensions=/result_claims=
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.
2026-07-19 21:22:49 -04:00
Jeremiah Lowin
33ed688a8f
Bump pinned Claude models to current versions (#4561) 2026-07-19 21:09:43 -04:00
Jeremiah Lowin
2676864163
Fix AI workflow allowlists being destroyed by tokenization (#4560) 2026-07-19 20:46:29 -04:00
Jeremiah Lowin
c6e31a3be6
Rename martian workflows to marvin (#4558) 2026-07-19 20:46:02 -04:00
Jeremiah Lowin
a3163bc275
Add 'prs welcome' label to waive the PR assignment gate (#4557)
* Add 'prs welcome' label to waive the PR assignment gate

Also documents contributor accountability, maintainer edit access, and
branch targeting in CONTRIBUTING.

* Protect 'prs welcome' from prompt-injected triage labeling
2026-07-19 20:37:40 -04:00
Jeremiah Lowin
3213776b25
Run FastMCP middleware for every inbound message (#4553)
* 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
2026-07-19 20:29:08 -04:00
Jeremiah Lowin
cef327d0f2
Fix label triage applying no labels, and make blocked tool calls fail (#4555) 2026-07-19 19:24:20 -04:00
Jeremiah Lowin
1e529ee27d
Stop proxies from validating backend results or mutating shared transports (#4552) 2026-07-19 19:24:11 -04:00
Jeremiah Lowin
b9b1deacb6
Speed up the unit test suite, and fix the task-notification race it surfaced (#4550) 2026-07-19 18:52:04 -04:00
Jeremiah Lowin
eee5e91334
Fix stale MRTR/elicitation framing in client and upgrade docs (#4551) 2026-07-19 18:10:15 -04:00
Jeremiah Lowin
717f3535f6
Add guard-mode multi-round-trip tools (SEP-2322) (#4544)
* 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
2026-07-19 16:42:06 -04:00
marvin-context-protocol[bot]
0781e723c2
chore: Update SDK documentation (#4442)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-07-19 15:06:18 -04:00
dependabot[bot]
87fa361239
chore(deps): bump actions/setup-node from 6 to 7 (#4546)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 6 to 7.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-19 15:06:07 -04:00
Bill Easton
3041aa241e
Align client, Apps, and integration docs (#4261)
* docs: align client and integration docs

Generated with Codex.

* docs: align Descope local URL

Generated with Codex.

* docs: load .env explicitly in Descope setup

* docs: load .env in Scalekit setup, guard non-mapping logging extra

* docs: handle null response_type in elicitation template, qualify STDIO env allowlist by platform

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-19 14:30:51 -04:00
Bill Easton
149a7aa2ce
Align CLI, deployment, and config docs (#4259)
* docs: align CLI and deployment docs

Generated with Codex.

* docs: restore install config support, fix CIMD placeholder, add missing CLI flags

* docs: restore contrib guidance, correct --copy availability

* docs: remove dead redirect-shadowed pages

* Fix stale --path default in run command help

* docs: correct Goose flag support, fix README link to moved testing page

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-19 14:24:07 -04:00
Bill Easton
d3b7922615
Align server component docs (#4260)
* 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>
2026-07-19 14:23:36 -04:00
Jeremiah Lowin
67e8448389
[codex] Add OAuthProxy RFC 9207 issuer responses (#4438)
* 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>
2026-07-19 09:52:43 -04:00
Jeremiah Lowin
252a29e5e6
Preserve telemetry attributes when a sampler does not forward them (#4539)
* 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.
2026-07-19 09:00:04 -04:00
Alexander Savchuk
2899ffb6f3
Fix #4292: SSRF guard breaks OAuth/JWKS fetches behind a corporate HTTP proxy (#4412)
* 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>
2026-07-18 21:42:52 -04:00
Jeremiah Lowin
cee327d8f7
Restore Mintlify's fixed banner positioning (#4542) 2026-07-18 21:25:39 -04:00
Viktor Szépe
81fada4922
Fix typos (#4498)
* 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>
2026-07-18 21:18:39 -04:00
Pierre Audonnet
a57f1c8b20
Add subject field to AccessToken initialization (#4267)
* 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>
2026-07-18 21:15:13 -04:00
vijaydeepsinha
654335607c
Fix-issue-4284 : Add Auth0MCPProvider for Auth0 Auth for MCP (#4411)
* Add Auth0MCPProvider for Auth0 Auth for MCP

* Document Auth0 MCP provider integration

* Add Auth0MCPProvider scope and auth rejection tests

Cover permissions-based required_scopes enforcement and unauthenticated MCP 401 responses.

* fixed documentation

* Narrow Auth0 docs to integration guide only

* Fix Auth0 provider: use httpx2 instead of httpx

httpx is a dev-only transitive dependency in this repo; runtime installs
declare httpx2 exclusively. The module-level 'import httpx' in auth0.py
broke import on a clean install of fastmcp or fastmcp-slim[server].

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-18 21:15:02 -04:00
Jeremiah Lowin
62d32c6a90
Add 4.0.0 version badge to Path Security section (#4540) 2026-07-18 20:58:32 -04:00
Jeremiah Lowin
2ebf19e5e1
Make examples/ actually trigger the ty gate (#4541)
#4466 added examples/ to [tool.ty.src] include, but two filters still
excluded it: the ty prek hook's files: scope and the static-analysis
workflow's push path triggers. An examples-only commit or direct push
to main could skip the gate entirely.
2026-07-18 20:58:24 -04:00
Jeremiah Lowin
83702a41f8
Document icon theme support (#4537)
* Document icon theme support and add round-trip tests

MCP SDK v2 added a `theme` field to `Icon` (light/dark), letting a
server ship complementary icon variants for clients that render in
different UI themes. Document the field on the icons page and cover
it with round-trip tests through the server/client protocol.

* docs: add 4.0.0 version badge to Theme Variants section
2026-07-18 20:57:36 -04:00
Jeremiah Lowin
243f054f65
Include scopes in auth challenges (#4527) 2026-07-18 20:53:52 -04:00
Jeremiah Lowin
998b37f32b
Add server-side identity assertion (SEP-990 ID-JAG) (#4483)
* Add server-side SEP-990 identity assertion (ID-JAG)

* Test SEP-990 identity assertion token endpoint

* Format identity assertion test

* Document SEP-990 identity assertion

* Thread identity_assertion through OIDCProxy

* Harden ID-JAG: authoritative scopes and grant-type enforcement

Scopes for the issued token now derive only from the signed assertion (or server policy when it omits scopes); the client-supplied request scope may narrow but never widen them. Enforce the registered grant-type constraint the SDK check bypassed, and have proxy DCR add the jwt-bearer grant to registered clients when identity assertion is enabled.

* Harden ID-JAG: honor nbf, reject non-object payload, bound jti cache, preserve required_scopes

* Document per-process ID-JAG replay limitation and nbf check

* Harden ID-JAG round 3: resource indicator, non-object header, algorithm config

- Honor RFC 8707 resource on the jwt-bearer grant (invalid_target on
  mismatch), mirroring authorize()'s invariant incl. skip-when-unconfigured
- Reject JSON-array JOSE headers with invalid_grant instead of a 500
- Add IdentityAssertion.algorithm so ES256/PS256 issuers can be verified
  (JWTVerifier otherwise defaults to RS256)

* Bind ID-JAG exchange to the assertion's signed client_id and resource

SEP-990: the IdP signs which client and which resource the assertion was
minted for. With public proxy clients the presented client_id is
self-asserted, so the signed binding is what stops client B redeeming
client A's leaked assertion — and the signed resource claim stops an
assertion for server A being redeemed at server B behind the same IdP.

* Harden ID-JAG round 4: check bindings before jti consumption; validate temporal claims, algorithm, and discovery body

- Move the client_id/resource binding checks into the validator itself,
  before jti is recorded as consumed, so an assertion presented with the
  wrong binding is rejected without burning replay protection for whoever
  it actually belongs to
- Reject non-numeric exp/iat/nbf with invalid_grant instead of a 500
- Validate IdentityAssertion.algorithm at config time (must be an
  asymmetric JWS algorithm verifiable via JWKS)
- Reject a non-object OIDC discovery body with invalid_grant instead of a 500
- Centralize the resource-URL comparison helpers used by both the
  validator and OAuthProxy.authorize()

* Rebase onto httpx2/SDK b2 and harden ID-JAG round 5

- Migrate identity assertion + tests to httpx2 and the local httpx2_mock
  (legacy httpx is now banned; pytest-httpx no longer intercepts)
- Add is_optional to the shared httpx2_mock, mirroring pytest-httpx
- Tighten the algorithm allowlist to JWTVerifier's exact supported set
  (prefix check accepted typos like RS999 -> 500 on first exchange)
- Reject non-string jti before the cache lookup (unhashable -> 500)
- Track revocation for self-contained ID-JAG tokens: revoke_token records
  the jti and load_access_token rejects it until natural expiry
- Dedupe resource-URL helpers: proxy now imports the shared
  normalize_resource_url/server_url_has_query from identity_assertion

* Advertise 'none' token-endpoint auth method when ID-JAG is enabled without CIMD

DCR clients are public, so metadata consumers must see 'none' to use the
advertised jwt-bearer grant; previously only the CIMD path added it.

* Document 2026-07-28 protocol support as a distinct feature catalog

SEP-990 identity assertion leads: the SDK provides the wire contract and
provider hook; FastMCP provides the complete server-side implementation.
Inventories the full modern-era capability set for v4.

* Harden ID-JAG round 6: lazy re-export, dual-form audience, per-issuer algorithms, discovery backoff

- IdentityAssertion re-exported lazily from server.auth (the eager import
  bypassed the package's documented lazy-import boundary)
- Accept the ID-JAG aud both with and without base_url's trailing slash;
  metadata advertises the slashed form, so IdPs echoing it verbatim work
- algorithms={issuer: alg} per-issuer override, mirroring jwks_uris
- OIDC discovery serializes per-issuer and backs off 30s after a failure
  (discovery runs pre-signature, so garbage could amplify into HTTP floods)
2026-07-18 19:52:15 -04:00
nate nowack
f018f68bbf
Expose telemetry attributes on span start (#4487)
* Expose telemetry attributes on span start

🤖 Generated with Codex

* Expose sampling attributes on span start

🤖 Generated with Codex

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-18 19:46:19 -04:00
Jeremiah Lowin
7d76c9d055
Add examples/ to the ty static-analysis gate (#4466)
* Add examples/ to ty static-analysis gate

* Fix example type errors and stale SDK idioms for ty

* Use typing_extensions.TypedDict for the quiz tool-param type

Question is a take_quiz parameter, so FastMCP builds a Pydantic schema
for it; typing.TypedDict raises PydanticUserError on Python 3.10/3.11
(only 3.12+ accepts it). ty and 3.12 runs miss this, so it slipped in.

* Guard get_access_token() None case in huggingface_oauth example

Caught by the ty gate this PR adds: the example, merged separately,
had never been type-checked against examples/. Matches the existing
aws_oauth/keycloak_oauth pattern.

* Print actual YAML text in custom serializer example
2026-07-18 19:44:13 -04:00
Kevin J Gao
3fdeedb567
Improve DescopeProvider scope discovery and well-known URL support (#4489)
* Improve DescopeProvider scope discovery and well-known URL support

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify DescopeProvider scope and URL handling

Co-authored-by: Cursor <cursoragent@cursor.com>

* Make DescopeProvider scope discovery async and lazy

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
🤖 Generated with Claude Code

* Use generic scope in Descope tests

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
🤖 Generated with Claude Code

* Address Descope discovery edge cases

* Deduplicate Descope metadata fallback

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-07-18 16:18:45 -04:00
dependabot[bot]
c241cd4698
chore(deps): bump mcp from 1.26.0 to 1.27.2 in /examples/testing_demo in the uv group across 1 directory (#4514)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-18 15:49:30 -04:00
Jeremiah Lowin
7e077186fc
Clean up task sessions on connection exit (#4535) 2026-07-18 15:45:11 -04:00
Jeremiah Lowin
16383a64d6
Preserve component metadata in response cache (#4521) 2026-07-18 15:42:20 -04:00
Jeremiah Lowin
00cab8ba8f
Fix docs banner contrast (#4522)
* Fix docs banner contrast

* Banner: readable animated brand-rainbow in both themes
2026-07-18 15:38:03 -04:00
Jeremiah Lowin
d7eda92a2b
Fix OAuth request annotation (#4534) 2026-07-18 15:29:32 -04:00
Jeremiah Lowin
981a69d839
Handle expired OAuth client registrations (#4520) 2026-07-18 15:16:27 -04:00
Jeremiah Lowin
18b5ab5852
Migrate to MCP SDK v2.0.0b2 (httpx2) (#4503) 2026-07-18 15:12:47 -04:00
Jeremiah Lowin
66c0270bc1
Stabilize upgraded ty checks (#4526) 2026-07-17 17:46:53 -04:00
Jeremiah Lowin
bdb76ef4b2
Clean up disconnected task sessions (#4519) 2026-07-17 17:46:13 -04:00
Jeremiah Lowin
a3ecd1edb1
Clarify PR-reopen flow and fix label-race that broke auto-reopen (#4518)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-07-17 17:43:05 -04:00
Jeremiah Lowin
d779414f8a
Screen templated resource parameters for path traversal by default (#4482)
* Add ResourceSecurity screening for templated resources (defaults on)

* Add tests for resource path-security screening

* Document resource path-security; fix ty in tests

* Carry child template security policy through provider mount

Preserve a mounted template's explicit ResourceSecurity (per-param
exemptions or a deliberate opt-out) through FastMCPProviderResourceTemplate.wrap
so the parent read chokepoint honours it instead of the parent default.

* Defer mcp SDK import so fastmcp.resources loads without the [mcp] extra

* Make resource path-security docs examples self-contained and runnable

* Match exempt_params under both hyphen and underscore spellings

Template placeholders like {git-ref} extract as git_ref, so an exemption
written with the natural URI-template spelling never matched.

* Docs: describe net-depth traversal rule accurately; make example runnable

The screening only rejects .. segments that escape the starting depth
(foo/../bar passes) — saying any standalone .. is rejected overstated
the guarantee. Also define DOCS_ROOT so the example runs.
2026-07-17 17:42:48 -04:00
Jeremiah Lowin
918b85f9b2
Reject positional-only tool parameters (#4524) 2026-07-17 17:37:28 -04:00
Jeremiah Lowin
ff2fc234b2
Trace client task management requests (#4525) 2026-07-17 17:37:12 -04:00
Jeremiah Lowin
b623c23183
Serialize deep object query parameters (#4523) 2026-07-17 17:33:57 -04:00
Grégoire
977f02347b
Forward upstream instructions through create_proxy (#4512)
Co-authored-by: Mistral Vibe <vibe@mistral.ai>
2026-07-17 17:29:15 -04:00
WinkleMad
6202008cf3
Don't mutate the caller's schema in compress_schema (#4492) 2026-07-17 17:29:01 -04:00
Burt Matthews
1fca15abe6
Skip unsupported JWKS keys instead of failing the whole key set (#4515) (#4517) 2026-07-17 17:28:43 -04:00
石岳峰
291fab8789
fix(server): omit ScalarElicitationType wrapper title from elicitation schemas (#4502) 2026-07-17 17:28:30 -04:00
Jeremiah Lowin
a04f6fd911
Add telemetry off-switch and mcp.protocol.version span attribute (#4481)
* Turn OpenTelemetry instrumentation on by default with explicit off-switch

Add FASTMCP_ENABLE_TELEMETRY setting (default true) and mcp.protocol.version
span attribute for SDK parity.

* Make disabled telemetry a transparent pass-through, not a NoOpTracer

The stock NoOpTracer.start_as_current_span attaches a NonRecordingSpan, hijacking the current OTel context from any enclosing application span. When telemetry is disabled, get_tracer() now returns a non-attaching pass-through tracer so trace.get_current_span() inside handlers still resolves to the caller's span.
2026-07-17 17:02:48 -04:00
Jeremiah Lowin
266c129b62
Test lifespan fires once per process over HTTP (#4480)
* Add regression test: HTTP lifespan fires once per process across sessions

* Drop redundant enter-count assertion at teardown (CodeQL)

* Assert session-manager lifespan entry directly, not user-lifespan count
2026-07-17 17:02:26 -04:00
Jeremiah Lowin
836ceac30e
Add KeyValueResponseCacheStore for distributed client response caching (#4479)
* Add KeyValueResponseCacheStore adapter for client response cache

* Test KeyValueResponseCacheStore round-trip, isolation, and distributed sharing

* Document distributed response cache store
2026-07-17 16:41:35 -04:00
nate nowack
1d932cc778
Fix Azure scope fallback (#4469) 2026-07-09 15:29:50 -04:00
Jeremiah Lowin
9f251bad00
Forward-port Hugging Face auth provider (#4475) 2026-07-08 20:56:07 -04:00
Jeremiah Lowin
4ad78a60ef
Forward-port HTTP host guard compatibility (#4474) 2026-07-08 20:55:56 -04:00
Jeremiah Lowin
00a7745994
Docs: forward-port v3.4.4 changelog entries (#4476) 2026-07-08 20:55:43 -04:00
Jeremiah Lowin
fd5d98bd13
Test: HTTP lifespan fires once per process across sessions (#4470) 2026-07-08 20:55:26 -04:00
Jeremiah Lowin
8ba5b89918
Add server-level cache hints (SEP-2549) (#4464) 2026-07-08 09:10:41 -04:00
Jeremiah Lowin
3c43038860
Fix stale mcp.types imports in examples (#4452) 2026-07-07 08:07:07 -04:00
Jeremiah Lowin
515a2244a2
Teach fastmcp.Client the modern protocol: mode negotiation, MRTR driver, response cache (#4450) 2026-07-07 08:00:45 -04:00
Jeremiah Lowin
f30f847e1f
Merge pull request #4449 from PrefectHQ/modernize/path-security
Route skill file access through SDK path-security primitives
2026-07-07 08:00:21 -04:00
Jeremiah Lowin
f0e350942f
Merge pull request #4448 from PrefectHQ/modernize/sampling-deprecation
Deprecate ctx.sample and add clear errors for push features on 2026 connections
2026-07-07 08:00:08 -04:00
Jeremiah Lowin
7832f884c6
Merge pull request #4453 from PrefectHQ/remove/deprecated-params
Remove 3.x deprecated parameters and object-mode decorators
2026-07-07 07:59:53 -04:00
Jeremiah Lowin
3cb34034d2
Merge pull request #4451 from PrefectHQ/remove/server-method-deprecations
Remove 3.0-deprecated FastMCP server methods
2026-07-07 07:59:40 -04:00
Jeremiah Lowin
bf3a079f87
Merge pull request #4447 from PrefectHQ/remove/module-shims
Remove 3.x deprecated module shims and dead parameters
2026-07-07 07:59:16 -04:00
Jeremiah Lowin
4a8852af10
Docs: register removed deprecations in v4 change register 2026-07-07 07:53:12 -04:00
Jeremiah Lowin
7c2133a52f
Remove deprecated component-import __getattr__ shims 2026-07-07 07:53:12 -04:00
Jeremiah Lowin
805ce96689
Remove deprecated decorator_mode setting and object-mode machinery 2026-07-07 07:53:12 -04:00
Jeremiah Lowin
45475bd072
Remove deprecated exclude_args tool parameter 2026-07-07 07:53:12 -04:00
Jeremiah Lowin
da5754671b
Document as_proxy backend keyword migration 2026-07-07 07:53:11 -04:00
Jeremiah Lowin
7f032bb82e
Remove deprecated tool-level serializer parameter 2026-07-07 07:53:11 -04:00
Jeremiah Lowin
396fb876d3
Apply ruff-format: drop now-unused imports and reflow 2026-07-07 07:53:11 -04:00
Jeremiah Lowin
508a08475f
Docs: mark removed-in-4.0 deprecations in upgrade guide and change register
Annotates the v2->v3 upgrade guide's deprecated server methods as removed in
v4, and adds a Removed in 4.0 section to the change register.
2026-07-07 07:53:11 -04:00
Jeremiah Lowin
6a6fdcb2bb
Repoint tests and examples off removed deprecations
Replaces FastMCP.as_proxy() helper calls with create_proxy(), rewrites the
mount() as_proxy=/prefix= kwarg tests to plain mount() (the params are gone),
and deletes deprecation-only tests for as_proxy() and remove_tool().
2026-07-07 07:53:11 -04:00
Jeremiah Lowin
14373cc60b
Repoint examples off removed shim paths 2026-07-07 07:53:10 -04:00
Jeremiah Lowin
e5d9d1f17d
Remove deprecated FastMCP server methods for 4.0
Removes deprecations that shipped replacements in 3.0:
- FastMCP.as_proxy() classmethod -> create_proxy()
- import_server() -> mount()
- mount(prefix=) -> namespace=
- mount(as_proxy=) -> now meaningless; mounts always invoke lifespan/middleware
- add_tool_transformation() -> add_transform(ToolTransform({...}))
- remove_tool_transformation() -> pure no-op that warned callers it had no
  effect; removed entirely
- FastMCP.remove_tool() -> mcp.local_provider.remove_tool()

Also drops the now-unused URI_PATTERN/re import and FastMCPDeprecationWarning
import. The _REMOVED_KWARGS TypeError shim is retained.
2026-07-07 07:53:10 -04:00
Jeremiah Lowin
be8aee3a96
Skip live-import validation for frozen v2 doc snapshots 2026-07-07 07:53:10 -04:00
Jeremiah Lowin
ad02710e9b
Docs: register 4.0 deprecation removals in change register 2026-07-07 07:53:10 -04:00
Jeremiah Lowin
36cbef6813
Remove no-op sse_read_timeout param from StreamableHttpTransport
Tier 2 aggressive-window removal: the parameter was a deprecated no-op
on the streamable-HTTP transport (the SDK v2 client no longer supports
it). SSETransport still accepts sse_read_timeout.
2026-07-07 07:53:10 -04:00
Jeremiah Lowin
d74f7b5996
Remove deprecated PromptToolMiddleware / ResourceToolMiddleware (3.1)
Use the PromptsAsTools / ResourcesAsTools transforms instead. The
non-deprecated ToolInjectionMiddleware base class is retained.
2026-07-07 07:53:10 -04:00
Jeremiah Lowin
d1c51ea4db
Remove deprecated fastmcp.server.apps / server.app shims (3.2)
Tier 2 aggressive-window removal: these shims were deprecated in 3.2,
a shorter deprecation window than the usual policy. Canonical imports
are fastmcp.apps / fastmcp.FastMCPApp.
2026-07-07 07:53:10 -04:00
Jeremiah Lowin
9d95e34e19
Remove deprecated experimental openapi shims (2.14) 2026-07-07 07:53:10 -04:00
Jeremiah Lowin
497ed2ea00
Remove deprecated fastmcp.server.openapi shim + FastMCPOpenAPI (3.0) 2026-07-07 07:53:10 -04:00
Jeremiah Lowin
e89763d709
Remove deprecated fastmcp.server.proxy shim (3.0) 2026-07-07 07:53:09 -04:00
Jeremiah Lowin
6621024ce4
Drive the FastMCP lifespan through the SDK session manager (#4446) 2026-07-07 07:49:16 -04:00
Jeremiah Lowin
ac78e6f693
Emit one SERVER span per request and adopt spec-correct error codes (#4445) 2026-07-07 07:49:06 -04:00
Jeremiah Lowin
023a578279
Capture SharedContext for task-enabled Docket servers (#4443) 2026-07-07 07:48:49 -04:00
Jeremiah Lowin
13b9ab80ab
Use a single fastmcp import style in protocol-era tests 2026-07-06 22:06:22 -04:00
Jeremiah Lowin
77131edc00
Don't era-gate server-side sampling handlers on modern connections
The era-gate blocked every ctx.sample/sample_step on a 2026-07-28
connection, but a server-configured sampling handler answers server-side
without the client back-channel. Gate only when the request would hit the
removed client path; force the handler path (client_available=False) on
modern so "fallback" goes straight to the handler instead of a bare
client-attempt failure.
2026-07-06 21:49:18 -04:00
Jeremiah Lowin
05be554e85
Apply ruff formatting to attack corpus tests 2026-07-06 21:32:47 -04:00
Jeremiah Lowin
b023aae51a
Docs: mark sampling deprecated, update era matrix and change register 2026-07-06 21:32:17 -04:00
Jeremiah Lowin
389e3b78e7
Add path-safety attack corpus tests and document skill file confinement 2026-07-06 21:31:56 -04:00
Jeremiah Lowin
17954f569d
Deprecate ctx.sample/sample_step and era-gate sampling+elicit on modern connections 2026-07-06 21:30:03 -04:00
Jeremiah Lowin
1966e619f7
Route skill file reads through SDK safe_join for path safety 2026-07-06 21:29:22 -04:00
Jeremiah Lowin
3522a98766
Migrate to MCP Python SDK v2 (#4437) 2026-07-06 17:36:45 -04:00
140 changed files with 8475 additions and 1152 deletions

View file

@ -37,6 +37,11 @@ inputs:
required: false
default: ""
extra-allowed-tools:
description: "Additional comma-separated tools to append to allowed-tools"
required: false
default: ""
model:
description: "Model to use for Claude"
required: false
@ -88,7 +93,7 @@ runs:
track_progress: ${{ inputs.track-progress }}
prompt: ${{ inputs.prompt }}
claude_args: |
${{ (inputs.allowed-tools != '' || inputs.extra-allowed-tools != '') && format('--allowedTools {0}{1}', inputs.allowed-tools, inputs.extra-allowed-tools != '' && format(',{0}', inputs.extra-allowed-tools) || '') || '' }}
${{ (inputs.allowed-tools != '' || inputs.extra-allowed-tools != '') && format('--allowedTools ''{0}{1}''', inputs.allowed-tools, inputs.extra-allowed-tools != '' && format(',{0}', inputs.extra-allowed-tools) || '') || '' }}
${{ inputs.mcp-servers != '' && format('--mcp-config ''{0}''', inputs.mcp-servers) || '' }}
--model ${{ inputs.model }}
settings: |

View file

@ -46,6 +46,16 @@ runs:
PARALLEL_FLAGS="--numprocesses auto --maxprocesses $MAX_PROCS --dist worksteal"
fi
# pytest-timeout has no signal-based method on Windows, so it falls back
# to the thread method, which dumps stacks and os._exit()s the process.
# Under a contended runner that turns a single slow test into a dead
# xdist worker, failing whichever unrelated test that worker happened to
# be running. Give parallel Windows runs more headroom so ordinary
# scheduling jitter does not take a worker down.
if [ "$RUNNER_OS" == "Windows" ] && [ "$MAX_PROCS" != "0" ]; then
TIMEOUT=$((TIMEOUT * 4))
fi
uv run --no-sync pytest \
--inline-snapshot=disable \
--timeout=$TIMEOUT \

View file

@ -1,14 +0,0 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
labels:
- "dependencies"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
labels:
- "dependencies"

View file

@ -178,19 +178,27 @@ jobs:
run: uv publish -v dist/fastmcp-*.tar.gz dist/fastmcp-*.whl
update-published-docs:
name: Update published-docs branch
name: Open published-docs PR
runs-on: ubuntu-latest
needs: pypi-publish
if: github.event_name == 'workflow_run' && github.event.workflow_run.event == 'release' && needs['pypi-publish'].outputs.is_prerelease != 'true'
timeout-minutes: 2
timeout-minutes: 5
permissions:
contents: write
contents: read
steps:
- name: Generate Marvin App token
id: marvin-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ secrets.MARVIN_APP_ID }}
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
- uses: actions/checkout@v7
with:
fetch-depth: 0
ref: ${{ github.event.workflow_run.head_sha }}
token: ${{ steps.marvin-token.outputs.token }}
- name: Check release line
id: release_line
@ -205,6 +213,26 @@ jobs:
echo "Release commit is not on ${DEFAULT_BRANCH}; skipping published-docs update."
fi
- name: Point published-docs at published release
- name: Prepare published docs tree
if: steps.release_line.outputs.update_published_docs == 'true'
run: git push --force origin "HEAD:published-docs"
env:
RELEASE_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
git fetch origin published-docs
git switch --force-create published-docs-sync origin/published-docs
git read-tree --reset -u "$RELEASE_SHA"
test "$(git write-tree)" = "$(git rev-parse "${RELEASE_SHA}^{tree}")"
- name: Open published docs PR
if: steps.release_line.outputs.update_published_docs == 'true'
uses: peter-evans/create-pull-request@v8
with:
token: ${{ steps.marvin-token.outputs.token }}
base: published-docs
branch: marvin/publish-docs-v${{ needs.pypi-publish.outputs.version }}
commit-message: "Publish FastMCP v${{ needs.pypi-publish.outputs.version }} docs"
title: "Publish FastMCP v${{ needs.pypi-publish.outputs.version }} docs"
body: "Updates `published-docs` to the exact release tree. Merging publishes the documentation to production."
delete-branch: true
author: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"
committer: "marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>"

View file

@ -56,6 +56,8 @@ When modifying MCP functionality, changes typically need to be applied across al
**Read `CONTRIBUTING.md` before opening issues or PRs.** It describes when PRs are appropriate, what we expect from enhancement proposals, and what we'll close without review.
**Review closed contributor PRs.** When reviewing an issue, inspect every associated non-maintainer PR, including closed PRs. External PRs may be closed as part of the issue-link and assignment workflow, so closure alone is not a negative signal. Read `CONTRIBUTING.md` and the PR timeline and comments to understand its status before evaluating it.
### Git & CI
- Prek hooks are required (run automatically on commits)
@ -117,7 +119,9 @@ Set `target_commitish` to the same branch that will receive the release tag. For
**Patch releases** (3.1.1, 3.0.2) get 1-2 sentences explaining what broke and what the fix does. Keep it minimal — the auto-generated changelog has the details.
**Merge the docs changelog PR *before* cutting the release, not after.** The post-publish `update-published-docs` job force-pushes the `published-docs` branch (which gofastmcp.com serves) to the released commit for stable releases on the default branch, so the changelog entry only reaches the live site if it's already in the commit being tagged. Land the docs PR on the release target branch first, then cut the release from that branch. If you tag first and merge docs after, this release's changelog won't appear on the live site until the next default-branch stable release force-pushes `published-docs` forward. Maintenance releases from `release/3.x` or `release/2.x` publish packages and GitHub notes without repointing `published-docs`; add their changelog entries on the maintenance branch, slotted into the matching major-version section. Two hand-maintained files mirror the GitHub release and must get a new entry for every version, newest at the top (these are `.mdx` and are not covered by the prek Prettier hook, which only runs on `yaml`/`json5` — match the existing entries' style by hand):
**Publish docs through a PR.** The `published-docs` branch serves gofastmcp.com, and repository rules reject direct pushes and force-pushes to it. Stable releases from `main` automatically open a publication PR after PyPI succeeds. For prereleases and later docs follow-ups, create the same PR manually: start a temporary branch from the current `published-docs`, make a single commit whose tree exactly matches the desired commit on `main`, and use `published-docs` as the PR base. Merging publishes to production. Never push directly to `published-docs`.
**Merge the docs changelog PR *before* cutting the release, not after.** The post-publish `update-published-docs` job opens a PR that syncs `published-docs` to the released commit for stable releases on the default branch, so the changelog entry only reaches the live site if it's already in the commit being tagged. Land the docs PR on the release target branch first, then cut the release from that branch. If you tag first and merge docs after, this release's publication PR will not include the changelog; publish `main` manually through the PR flow above or wait for the next default-branch stable release. Maintenance releases from `release/3.x` or `release/2.x` publish packages and GitHub notes without repointing `published-docs`; add their changelog entries on the maintenance branch, slotted into the matching major-version section. Two hand-maintained files mirror the GitHub release and must get a new entry for every version, newest at the top (these are `.mdx` and are not covered by the prek Prettier hook, which only runs on `yaml`/`json5` — match the existing entries' style by hand):
- `docs/changelog.mdx` is the full mirror. Add an `<Update label="v<version>" description="YYYY-MM-DD">` block with: a bold linked title (`**[v<version>: <pun>](<release-url>)**`), a condensed 1-paragraph intro (one sentence for patches), the full categorized PR list reformatted from the `--generate-notes` output (`* <title> by [@user](https://github.com/user) in [#NNNN](<pull-url>)`), a `## New Contributors` list (plain `@user`, linked PR), and a `**Full Changelog**: [vA...vB](<compare-url>)` line.
- `docs/updates.mdx` is the skimmable card feed. Add an `<Update label="FastMCP <version>" description="Month DD, YYYY" tags={["Releases"]}>` wrapping a `<Card>` that links to the GitHub release, with a 1-2 sentence summary and (for point releases) a handful of emoji-bulleted highlights.

View file

@ -5,6 +5,22 @@ rss: true
tag: NEW
---
<Update label="v3.4.6" description="2026-08-05">
**[v3.4.6: Trust, but Proxy](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.6)**
FastMCP 3.4.6 backports trusted-proxy support for SSRF-protected OAuth metadata and JWKS fetches. Deployments can now route these requests through a mandated corporate proxy while preserving custom CA certificates; FastMCP refuses the fetch when no proxy is configured instead of risking an unprotected direct request.
### Fixes 🐞
* Backport #4412 to 3.x: support trusted SSRF proxies by [@jlowin](https://github.com/jlowin) in [#4755](https://github.com/PrefectHQ/fastmcp/pull/4755)
### Docs 📚
* Docs: add v3.4.6 changelog entries by [@jlowin](https://github.com/jlowin) in [#4761](https://github.com/PrefectHQ/fastmcp/pull/4761)
**Full Changelog**: [v3.4.5...v3.4.6](https://github.com/PrefectHQ/fastmcp/compare/v3.4.5...v3.4.6)
</Update>
<Update label="v4.0.0b1" description="2026-07-28">
**[v4.0.0b1: Fourgone Conclusion](https://github.com/PrefectHQ/fastmcp/releases/tag/v4.0.0b1)**

View file

@ -0,0 +1,57 @@
/* Language dropdown: injected by language-dropdown.js into the sidebar
footer, to the right of Mintlify's theme selector. Mirrors the almond
theme pill's exact metrics (lg:h-7 desktop / 2.375rem mobile, rounded-full,
border-gray-200/70, dark:border-white/[0.07]) so the two controls read as
one family. */
#language-switch {
margin-left: auto;
display: inline-flex;
align-items: center;
}
#language-switch select {
appearance: none;
-webkit-appearance: none;
background-color: transparent;
border: 1px solid rgb(229 231 235 / 0.7);
border-radius: 9999px;
color: rgb(107 114 128);
cursor: pointer;
font-size: 0.75rem;
line-height: 1rem;
height: 2.375rem;
padding: 0 1.375rem 0 0.75rem;
/* Chevron, drawn in the same gray as the label text. */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 0.5rem center;
background-size: 0.7rem;
transition: border-color 0.2s;
}
@media (min-width: 1024px) {
#language-switch select {
height: 1.75rem;
}
}
#language-switch select:hover {
color: rgb(75 85 99);
border-color: rgb(229 231 235);
}
#language-switch select:focus-visible {
outline: 2px solid rgb(45 0 247 / 0.4);
outline-offset: 1px;
}
.dark #language-switch select {
border-color: rgb(255 255 255 / 0.07);
color: rgb(156 163 175);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%239ca3af' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
}
.dark #language-switch select:hover {
color: rgb(209 213 219);
border-color: rgb(255 255 255 / 0.1);
}

View file

@ -65,7 +65,7 @@ Our release process is intentionally simple:
2. Generate release notes automatically, and curate or add additional editorial information as needed
3. GitHub releases automatically trigger PyPI deployments
Current-major releases target `main`. Maintenance releases target their release branch, such as `release/3.x` for 3.x patches and `release/2.x` for 2.x patches. Stable releases from `main` update the `published-docs` branch after PyPI publishing succeeds; maintenance releases publish packages and GitHub release notes without repointing the live docs branch.
Current-major releases target `main`. Maintenance releases target their release branch, such as `release/3.x` for 3.x patches and `release/2.x` for 2.x patches. Stable releases from `main` open a PR that syncs the release commit to `published-docs` after PyPI publishing succeeds; merging that PR publishes the live docs. Prereleases skip the automatic PR and use the same PR-based sync when their docs are ready to publish. Maintenance releases publish packages and GitHub release notes without repointing the live docs branch.
This automation lets maintainers focus on code quality rather than release mechanics.

View file

@ -209,7 +209,7 @@ transport = StreamableHttpTransport(
)
```
The `client` you pass to `FastMCP.from_openapi(client=...)` (and `OpenAPIProvider(client=...)`) is now type-hinted `httpx2.AsyncClient`. FastMCP does not gate on the type, so an existing `httpx.AsyncClient` keeps working at runtime via duck-typing this release — but switching it to `httpx2.AsyncClient` clears the type hint and is the supported path going forward. HTTP made inside your own tools is entirely yours and is unaffected either way.
The `client` you pass to `FastMCP.from_openapi(client=...)` (and `OpenAPIProvider(client=...)`) should now be an `httpx2.AsyncClient`. Existing `httpx.AsyncClient` instances remain temporarily accepted via duck typing, but emit a `FastMCPDeprecationWarning` and will be rejected in a future release. HTTP made inside your own tools is entirely yours and is unaffected.
**The subtlest break is exception handlers, and no type checker will catch it.** `httpx` very likely remains installed in your environment (the Anthropic, OpenAI, and Google SDKs all depend on it), so code that catches old-httpx exceptions around FastMCP calls still imports and still type-checks — it just never matches, because FastMCP now raises `httpx2` exceptions. The handler silently becomes dead code:

77
docs/language-dropdown.js Normal file
View file

@ -0,0 +1,77 @@
// Language dropdown: a small Python/TypeScript switcher injected into the
// sidebar footer, next to Mintlify's theme selector. Selecting the other
// language navigates to that project's docs site; selecting the current
// language is a no-op. Styling lives in css/language-dropdown.css.
(function () {
if (typeof window === "undefined") return;
var CURRENT_LANGUAGE = "python";
// TODO: fastmcp-ts has no public docs site URL discoverable in either repo
// yet. Until it exists, point at the repo README (the same cross-link the
// welcome page uses), then replace with the real docs URL.
var TYPESCRIPT_DOCS_URL = "https://github.com/PrefectHQ/fastmcp-ts";
var PYTHON_DOCS_URL = "https://gofastmcp.com";
var URLS = { python: PYTHON_DOCS_URL, typescript: TYPESCRIPT_DOCS_URL };
function findThemeSelector() {
// Mintlify's sidebar-footer DOM is not a stable public API, so probe a
// few markers (almond theme first) and give up quietly if none match.
return (
document.querySelector("[data-theme-preference-switch]") ||
document.querySelector('[role="group"][aria-label="Theme preference"]')
);
}
function buildDropdown() {
var label = document.createElement("label");
label.id = "language-switch";
var select = document.createElement("select");
select.setAttribute("aria-label", "Switch documentation language");
[
["python", "Python"],
["typescript", "TypeScript"],
].forEach(function (entry) {
var option = document.createElement("option");
option.value = entry[0];
option.textContent = entry[1];
if (entry[0] === CURRENT_LANGUAGE) option.selected = true;
select.appendChild(option);
});
select.addEventListener("change", function () {
if (select.value === CURRENT_LANGUAGE) return;
window.location.href = URLS[select.value];
});
label.appendChild(select);
return label;
}
function addDropdown() {
if (document.getElementById("language-switch")) return;
var theme = findThemeSelector();
if (!theme || !theme.parentElement) return;
// Insert after the theme pill; margin-left:auto floats it right.
theme.parentElement.insertBefore(buildDropdown(), theme.nextSibling);
}
function run() {
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", addDropdown);
} else {
addDropdown();
}
}
run();
// Mintlify re-renders the sidebar on client-side navigation; re-inject when
// the dropdown disappears.
new MutationObserver(function () {
if (!document.getElementById("language-switch")) addDropdown();
}).observe(document.body, { subtree: true, childList: true });
})();

View file

@ -22,16 +22,24 @@ The client probes `server/discover` and adopts the modern protocol when the serv
## What are the two protocol eras, and which one does my server speak?
Both. A FastMCP server serves every era from one deployment and one URL, and the SDK negotiates per connection — the client picks, not the server.
Both. A FastMCP 4 server supports the handshake revisions `2024-11-05`, `2025-03-26`, `2025-06-18`, and `2025-11-25`, plus the modern `2026-07-28` protocol. It serves all of them from one deployment and one URL, and the SDK negotiates per connection — the client picks, not the server.
The *handshake* era (`2025-11-25` and earlier) opens each connection with `initialize` and holds a session, which gives the server a back-channel it can push requests down. The *modern* era (`2026-07-28`) is sessionless: the client learns what the server offers through `server/discover`, every request stands alone, and there is no back-channel. Inside a tool, `ctx.request_context.protocol_version` tells you which era the current call arrived on; on the client, `client.protocol_version` reports it after connecting.
A protocol version establishes the wire format, while capabilities describe which optional operations a particular server provides. The capabilities returned by `server/discover` or `initialize` are therefore the authoritative way for a client to determine what is available.
## Can FastMCP 4 talk to older clients and servers?
Yes, in both directions, with no configuration. A FastMCP 4 server answers a handshake-era client and a modern one from the same process: the old client sends `initialize` and gets a session id, the modern client discovers and stays stateless.
A FastMCP 4 client is equally happy against an old server, because `mode="auto"` falls back to the handshake when discovery finds no modern peer. The client-side handlers for server-initiated capabilities are all still there too — passing `sampling_handler=` or `roots=` answers a legacy server's requests exactly as before, which is what a modern client needs in order to interoperate. See [client sampling](/clients/sampling) and [client roots](/clients/roots).
## How does FastMCP verify protocol conformance?
FastMCP runs the [official MCP conformance suite](https://github.com/modelcontextprotocol/conformance) in CI against a pinned suite release. A failing scenario for a released capability that FastMCP advertises as supported is treated as a regression.
The suite's `all` mode also exercises draft, pending, retired, and deliberately unsupported capabilities, so its raw pass count is broader than FastMCP's support contract. Known exceptions are recorded in [`expected-failures.yml`](https://github.com/PrefectHQ/fastmcp/blob/main/tests/conformance/expected-failures.yml) with their rationale, and new upstream scenarios arrive through deliberate suite-version updates rather than silently changing CI.
## When should I pin `mode="legacy"`?
Pin it when your code depends on the session the handshake creates: `client.ping()` and `transport.get_session_id()` have no modern equivalent, since a sessionless connection has neither a live back-channel to ping nor an id to hold. It is also the escape hatch when a server misbehaves under discovery or you need the classic `initialize` result object.

View file

@ -81,7 +81,7 @@ These control how the server listens when running with an HTTP transport.
## Tasks (Docket)
Task settings (the `FASTMCP_DOCKET_` variables) moved to the optional `fastmcp-tasks` package. See [server tasks](/servers/tasks) for configuration.
Task settings (the `FASTMCP_DOCKET_` and `FASTMCP_TASKS_` variables) live in the optional `fastmcp-tasks` package. See [server tasks](/servers/tasks) for configuration, including `FASTMCP_TASKS_ENCRYPTION_KEY` for [encrypting task snapshots at rest](/servers/tasks#credentials-at-rest).
## Security

View file

@ -31,6 +31,28 @@
}
]
},
{
"group": "fastmcp.server",
"pages": [
"python-sdk/fastmcp-server-caching",
"python-sdk/fastmcp-server-completions",
"python-sdk/fastmcp-server-context",
"python-sdk/fastmcp-server-dependencies",
"python-sdk/fastmcp-server-elicitation",
"python-sdk/fastmcp-server-event_store",
"python-sdk/fastmcp-server-extensions",
"python-sdk/fastmcp-server-http",
"python-sdk/fastmcp-server-lifespan",
"python-sdk/fastmcp-server-low_level",
"python-sdk/fastmcp-server-mixins",
"python-sdk/fastmcp-server-providers",
"python-sdk/fastmcp-server-server",
"python-sdk/fastmcp-server-session_scoped_event_store",
"python-sdk/fastmcp-server-sessions",
"python-sdk/fastmcp-server-telemetry",
"python-sdk/fastmcp-server-transforms"
]
},
{
"group": "fastmcp.utilities",
"pages": [
@ -79,6 +101,7 @@
"python-sdk/fastmcp-utilities-mime",
"python-sdk/fastmcp-utilities-openapi",
"python-sdk/fastmcp-utilities-pagination",
"python-sdk/fastmcp-utilities-prefab",
"python-sdk/fastmcp-utilities-skills",
"python-sdk/fastmcp-utilities-tasks",
"python-sdk/fastmcp-utilities-tests",

View file

@ -35,7 +35,7 @@ Usage::
## Classes
### `FastMCPApp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L145" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `FastMCPApp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L149" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that represents an MCP application.
@ -48,19 +48,19 @@ can find them by original name even when transforms have been applied.
**Methods:**
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L169" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L173" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: F) -> F
```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L181" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L185" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: str | None = None) -> Callable[[F], F]
```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L192" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L196" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: str | AnyFunction | None = None) -> Any
@ -83,19 +83,19 @@ Supports multiple calling patterns::
def save(name: str): ...
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L259" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L266" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ui(self, name_or_fn: F) -> F
```
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L274" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L281" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ui(self, name_or_fn: str | None = None) -> Callable[[F], F]
```
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L288" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L295" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ui(self, name_or_fn: str | AnyFunction | None = None) -> Any
@ -119,7 +119,7 @@ Supports multiple calling patterns::
def dashboard() -> Component: ...
#### `add_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L363" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `add_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L373" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_tool(self, tool: Tool | Callable[..., Any]) -> Tool
@ -130,13 +130,13 @@ Add a tool to this app programmatically.
The tool is tagged with this app's name for routing.
#### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L419" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L432" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan(self) -> AsyncIterator[None]
```
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L427" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/app.py#L440" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run(self, transport: Literal['stdio', 'http', 'sse', 'streamable-http'] | None = None, **kwargs: Any) -> None

View file

@ -15,7 +15,7 @@ UI metadata for clients that support interactive app rendering.
## Functions
### `app_config_to_meta_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L180" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `app_config_to_meta_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L181" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any]
@ -25,9 +25,32 @@ app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any]
Convert an AppConfig or dict to the wire-format dict for ``meta["ui"]``.
### `is_model_visible` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L188" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_model_visible(component: FastMCPComponent) -> bool
```
Whether a component may be shown to, or invoked by, the model.
Visibility is a declaration, and the MCP Apps spec puts the filtering on
the host — so ``tools/list`` carries app-only tools and the host keeps
them from the model. That division only works where a host stands between
the server and the model.
It does not hold for surfaces a server drives itself. A search result or
a code-mode catalog reaches the model as ordinary tool output, and a
call-tool proxy invokes on a name the model supplies; nothing downstream
can filter either. Those surfaces have to apply the declaration here.
A component with no ``visibility`` is visible: the field marks the
exception, and the spec's default is both audiences.
## Classes
### `ResourceCSP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ResourceCSP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L21" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Content Security Policy for MCP App resources.
@ -37,7 +60,7 @@ load resources from. Hosts use these declarations to build the
``Content-Security-Policy`` header for the sandboxed iframe.
### `ResourcePermissions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L56" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ResourcePermissions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L57" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Iframe sandbox permissions for MCP App resources.
@ -48,7 +71,7 @@ iframe. Hosts MAY honour these; apps should use JS feature detection
as a fallback.
### `AppConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L84" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `AppConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Configuration for MCP App tools and resources.
@ -63,7 +86,7 @@ values appear on the wire. Aliases match the MCP Apps wire format
(camelCase).
### `PrefabAppConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L124" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `PrefabAppConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
App configuration for Prefab tools with sensible defaults.
@ -83,7 +106,7 @@ Example::
**Methods:**
#### `model_post_init` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `model_post_init` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/apps/config.py#L141" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
model_post_init(self, __context: Any) -> None

View file

@ -10,7 +10,7 @@ Custom exceptions for FastMCP.
## Functions
### `to_mcp_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L122" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `to_mcp_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_error(exc: Exception) -> MCPError
@ -38,71 +38,61 @@ explicit code chosen upstream survives translation.
## Classes
### `FastMCPDeprecationWarning` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Deprecation warning for FastMCP APIs.
Subclass of DeprecationWarning so that standard warning filters
still apply, but FastMCP can selectively enable its own warnings
without affecting other libraries in the process.
### `FastMCPError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L43" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `FastMCPError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base error for FastMCP.
### `ValidationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L51" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ValidationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in validating parameters or return values.
### `ResourceError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L55" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ResourceError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L50" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in resource operations.
### `ToolError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L59" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ToolError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in tool operations.
### `PromptError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L63" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `PromptError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L58" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in prompt operations.
### `InvalidSignature` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L67" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `InvalidSignature` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L62" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Invalid signature for use with FastMCP.
### `ClientError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L71" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ClientError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L66" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in client operations.
### `NotFoundError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L75" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `NotFoundError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L70" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Object not found.
### `DisabledError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `DisabledError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L74" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Object is disabled.
### `ResourceSecurityError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L83" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ResourceSecurityError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L78" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A templated resource parameter failed path-security screening.
@ -114,13 +104,13 @@ for a resource that does not exist, and never reveals which parameter
or policy tripped.
### `AuthorizationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `AuthorizationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L89" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error when authorization check fails.
### `InsufficientScopeError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L98" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `InsufficientScopeError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L93" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Authorization failed because the token is missing required OAuth scopes.

View file

@ -32,7 +32,7 @@ Example configuration:
## Functions
### `infer_transport_type_from_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `infer_transport_type_from_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L55" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
infer_transport_type_from_url(url: str | AnyUrl) -> Literal['http', 'sse']
@ -42,7 +42,7 @@ infer_transport_type_from_url(url: str | AnyUrl) -> Literal['http', 'sse']
Infer the appropriate transport type from the given URL.
### `update_config_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L373" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `update_config_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L376" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
update_config_file(file_path: Path, server_name: str, server_config: CanonicalMCPServerTypes) -> None
@ -57,7 +57,7 @@ worry about transforming server objects here.
## Classes
### `StdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L179" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `StdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L180" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
MCP server configuration for stdio transport.
@ -67,19 +67,19 @@ This is the canonical configuration format for MCP servers using stdio transport
**Methods:**
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L212" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L213" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_transport(self) -> StdioTransport
to_transport(self) -> StdioTransport | FastMCPTransport
```
### `TransformingStdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L224" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `TransformingStdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L225" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Stdio server with tool transforms.
### `RemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L228" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `RemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L229" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
MCP server configuration for HTTP/SSE transport.
@ -89,19 +89,19 @@ This is the canonical configuration format for MCP servers using remote transpor
**Methods:**
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L264" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L265" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_transport(self) -> StreamableHttpTransport | SSETransport
to_transport(self) -> StreamableHttpTransport | SSETransport | FastMCPTransport
```
### `TransformingRemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L291" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `TransformingRemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L294" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Remote server with tool transforms.
### `MCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L302" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `MCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L305" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A configuration object for MCP Servers that conforms to the canonical MCP configuration format
@ -113,7 +113,7 @@ For an MCPConfig that is strictly canonical, see the `CanonicalMCPConfig` class.
**Methods:**
#### `wrap_servers_at_root` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L316" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `wrap_servers_at_root` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L319" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
wrap_servers_at_root(cls, values: dict[str, Any]) -> dict[str, Any]
@ -122,7 +122,7 @@ wrap_servers_at_root(cls, values: dict[str, Any]) -> dict[str, Any]
If there's no mcpServers key but there are server configs at root, wrap them.
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L329" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L332" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_server(self, name: str, server: MCPServerTypes) -> None
@ -131,7 +131,7 @@ add_server(self, name: str, server: MCPServerTypes) -> None
Add or update a server in the configuration.
#### `from_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L334" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `from_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L337" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_dict(cls, config: dict[str, Any]) -> Self
@ -140,7 +140,7 @@ from_dict(cls, config: dict[str, Any]) -> Self
Parse MCP configuration from dictionary format.
#### `to_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L338" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `to_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L341" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_dict(self) -> dict[str, Any]
@ -149,7 +149,7 @@ to_dict(self) -> dict[str, Any]
Convert MCPConfig to dictionary format, preserving all fields.
#### `write_to_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L342" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `write_to_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L345" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
write_to_file(self, file_path: Path) -> None
@ -158,7 +158,7 @@ write_to_file(self, file_path: Path) -> None
Write configuration to JSON file.
#### `from_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L348" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `from_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L351" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_file(cls, file_path: Path) -> Self
@ -167,7 +167,7 @@ from_file(cls, file_path: Path) -> Self
Load configuration from JSON file.
### `CanonicalMCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L358" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `CanonicalMCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L361" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Canonical MCP configuration format.
@ -178,7 +178,7 @@ The format is designed to be client-agnostic and extensible for future use cases
**Methods:**
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L368" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L371" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_server(self, name: str, server: CanonicalMCPServerTypes) -> None

View file

@ -0,0 +1,48 @@
---
title: caching
sidebarTitle: caching
---
# `fastmcp.server.caching`
Server-level cache hints for FastMCP (SEP-2549).
A FastMCP server opts every SDK-cacheable result it emits into client-side
caching by setting `cache_ttl` (seconds) and, optionally, `cache_scope` on the
`FastMCP` constructor. The hint is uniform by construction: one server-level
value applies to `tools/list`, `prompts/list`, `resources/list`,
`resources/templates/list`, `resources/read`, and `server/discover` alike — no
per-component surface and no aggregation.
FastMCP does not hand-set the wire fields. It passes the hint through to the SDK
low-level `Server(cache_hints=...)`, whose runner fills `ttlMs`/`cacheScope` on
every cacheable result via `apply_cache_hint`, leaving any field a handler set
explicitly untouched. Honoring is modern-only and opt-in on the client: a hinted
server is inert unless the client passes `cache=` and negotiates `2026-07-28`.
## Functions
### `build_cache_hints` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/caching.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
build_cache_hints(cache_ttl: int | None, cache_scope: CacheScope | None) -> dict[CacheableMethod, CacheHint] | None
```
Build the per-method `CacheHint` map for the SDK low-level server.
`cache_ttl` is in seconds and is converted to the wire's milliseconds. When
`cache_ttl` is `None` the server emits no hint, so its wire output is
identical to a server that never set one; a `cache_scope` given without a
`cache_ttl` is meaningless (the client gates caching on the presence of a
TTL) and is rejected rather than silently ignored.
Returns `None` when no hint is set, or a map applying the same hint to every
SDK-cacheable method otherwise.
**Raises:**
- `ValueError`: If `cache_ttl` is not positive, or if `cache_scope` is set
without `cache_ttl`.

View file

@ -0,0 +1,41 @@
---
title: completions
sidebarTitle: completions
---
# `fastmcp.server.completions`
Server-side argument completion for FastMCP.
A completion request names a reference — a specific prompt or resource
template — and the argument being completed, plus a context of the argument
values already supplied. The server answers with candidate string values.
FastMCP surfaces this as a single server-level handler registered with
``@mcp.completion``, mirroring the MCP SDK's own ``completion/complete`` shape
and FastMCP's client-side ``Client.complete()``. The handler receives the
reference, the argument, and the optional context, and returns candidates for
whichever reference/argument pair it recognizes.
## Functions
### `normalize_completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/completions.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
normalize_completion(result: CompletionValues) -> mcp_types.Completion
```
Coerce a handler's return value into a wire ``Completion``.
A returned ``str`` is rejected: it is almost always a mistake (the value
would iterate into one-character candidates), so it raises rather than
silently producing surprising output.
The MCP contract caps a completion at 100 values, so a longer result is
truncated to the first 100 with ``has_more`` set — a handler that returns
thousands of matches emits a conforming response rather than an oversized
one that strict clients reject.

View file

@ -0,0 +1,711 @@
---
title: context
sidebarTitle: context
---
# `fastmcp.server.context`
## Functions
### `set_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L97" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_transport(transport: TransportType) -> Token[TransportType | None]
```
Set the current transport type. Returns token for reset.
### `reset_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
reset_transport(token: Token[TransportType | None]) -> None
```
Reset transport to previous value.
### `set_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L134" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_context(context: Context) -> Generator[Context, None, None]
```
## Classes
### `LogData` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L110" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Data object for passing log arguments to client-side handlers.
This provides an interface to match the Python standard library logging,
for compatibility with structured logging.
### `Context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L143" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Context object providing access to MCP capabilities.
This provides a cleaner interface to MCP's RequestContext functionality.
It gets injected into tool and resource functions that request it via type hints.
To use context in a tool function, add a parameter with the Context type annotation:
```python
@server.tool
async def my_tool(x: int, ctx: Context) -> str:
# Log messages to the client
await ctx.info(f"Processing {x}")
await ctx.debug("Debug info")
await ctx.warning("Warning message")
await ctx.error("Error message")
# Report progress
await ctx.report_progress(50, 100, "Processing")
# Access resources
data = await ctx.read_resource("resource://data")
# Get request info
request_id = ctx.request_id
client_id = ctx.client_id
# Manage state across the session (persists across requests)
await ctx.set_state("key", "value")
value = await ctx.get_state("key")
# Store non-serializable values for the current request only
await ctx.set_state("client", http_client, serializable=False)
return str(x)
```
State Management:
Context provides session-scoped state that persists across requests within
the same MCP session. State is automatically keyed by session, ensuring
isolation between different clients.
State set during `on_initialize` middleware will persist to subsequent tool
calls when using the same session object (STDIO, SSE, single-server HTTP).
For distributed/serverless HTTP deployments where different machines handle
the init and tool calls, state is isolated by the mcp-session-id header.
The context parameter name can be anything as long as it's annotated with Context.
The context is optional - tools that don't need it can omit the parameter.
**Methods:**
#### `is_background_task` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L224" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_background_task(self) -> bool
```
True when this context is running in a background task (Docket worker).
When True, certain operations like elicit() will use task-aware
implementations that can pause the task and wait for client input.
#### `task_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L242" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
task_id(self) -> str | None
```
Get the background task ID if running in a background task.
Returns None if not running in a background task context.
#### `origin_request_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L250" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
origin_request_id(self) -> str | None
```
Get the request ID that originated this execution, if available.
In foreground request mode, this is the current request_id.
In background task mode, this is the request_id captured when the task
was submitted, if one was available.
#### `fastmcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L262" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
fastmcp(self) -> FastMCP
```
Get the FastMCP instance.
#### `request_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L312" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
request_context(self) -> FastMCPRequestContext | None
```
Access to the underlying request context.
Returns None when the MCP session has not been established yet.
Returns the FastMCPRequestContext wrapper once the MCP session is available.
For HTTP request access in middleware, use `get_http_request()` from fastmcp.server.dependencies,
which works whether or not the MCP session is available.
Example in middleware:
```python
async def on_request(self, context, call_next):
ctx = context.fastmcp_context
if ctx.request_context:
# MCP session available - can access session_id, request_id, etc.
session_id = ctx.session_id
else:
# MCP session not available yet - use HTTP helpers
from fastmcp.server.dependencies import get_http_request
request = get_http_request()
return await call_next(context)
```
#### `client_extension_settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L337" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
client_extension_settings(self, identifier: str) -> dict[str, Any] | None
```
This request's per-request opt-in settings for an MCP extension.
SEP-2133 extensions negotiate per request: the client repeats its
extension capabilities in each request's ``_meta`` under
``io.modelcontextprotocol/clientCapabilities`` → ``extensions`` →
``identifier``. Returns the declared settings dict (possibly empty) when
the extension was opted in for this request, or ``None`` when it was
not (or there is no active request). This bridges an extension's
``tools/call`` interceptor — which receives a FastMCP ``Context`` — to
the request's declared client capabilities.
#### `input_responses` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L378" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
input_responses(self) -> mcp_types.InputResponses | None
```
Client responses to a prior `InputRequiredResult.input_requests`.
The multi-round-trip guard channel (SEP-2322). A guard tool inspects
this to decide what to do on each round: `None` on the initial round
(nothing has been asked yet, or the client retried without responses),
so the tool returns an `InputRequiredResult` to ask; present on a later
round, so the tool reads the answers and proceeds. It is a mapping whose
keys match the `input_requests` map the tool minted; each value is the
client's result for that request (an `ElicitResult`, `CreateMessageResult`,
or `ListRootsResult`).
In a background task there is no wire request, so this falls back to the
responses the in-task guard loop delivered (see the tasks extension).
#### `request_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L399" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
request_state(self) -> str | None
```
Opaque state echoed from a prior `InputRequiredResult.request_state`.
The multi-round-trip guard channel (SEP-2322): whatever a tool put in
`InputRequiredResult.request_state` on an earlier round is handed back
here (as plaintext — the framework seals it on the wire and unseals it
before the tool runs, so tampering is rejected before this is read).
`None` on the initial round. Use it to carry a small amount of computed
state across rounds without re-deriving it.
In a background task there is no wire request, so this falls back to the
state the in-task guard loop re-injected (see the tasks extension).
#### `lifespan_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L418" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan_context(self) -> dict[str, Any]
```
Access the server's lifespan context.
Returns the context dict yielded by *this* server's lifespan function.
For a mounted child this is the child's own lifespan, not the parent's
— the MCP session always belongs to the parent, so reading from the
request context would return the parent's. We read directly from the
server's cached lifespan result instead, which is set by the
per-server ``_lifespan_manager`` regardless of mount position.
Returns an empty dict if no lifespan was configured.
Example:
```python
@server.tool
def my_tool(ctx: Context) -> str:
db = ctx.lifespan_context.get("db")
if db:
return db.query("SELECT 1")
return "No database connection"
```
#### `report_progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L453" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None
```
Report progress for the current operation.
Works in both foreground (MCP progress notifications) and background
(Docket task execution) contexts.
**Args:**
- `progress`: Current progress value e.g. 24
- `total`: Optional total value e.g. 100
- `message`: Optional status message describing current progress
#### `list_resources` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L552" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resources(self) -> list[SDKResource]
```
List all available resources from the server.
**Returns:**
- List of Resource objects available on the server
#### `list_prompts` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L563" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_prompts(self) -> list[SDKPrompt]
```
List all available prompts from the server.
**Returns:**
- List of Prompt objects available on the server
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L574" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult
```
Get a prompt by name with optional arguments.
**Args:**
- `name`: The name of the prompt to get
- `arguments`: Optional arguments to pass to the prompt
**Returns:**
- The prompt result
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L593" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_resource(self, uri: str | AnyUrl) -> ResourceResult
```
Read a resource by URI.
**Args:**
- `uri`: Resource URI to read
**Returns:**
- ResourceResult with contents
#### `log` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L609" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
log(self, message: str, level: LoggingLevel | None = None, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None
```
Send a log message to the client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
**Args:**
- `message`: Log message
- `level`: Optional log level. One of "debug", "info", "notice", "warning", "error", "critical",
"alert", or "emergency". Default is "info".
- `logger_name`: Optional logger name
- `extra`: Optional mapping for additional arguments
#### `transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L650" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
transport(self) -> TransportType | None
```
Get the current transport type.
Returns the transport type used to run this server: "stdio", "sse",
or "streamable-http". Returns None if called outside of a server context.
#### `client_supports_extension` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L658" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
client_supports_extension(self, extension_id: str) -> bool
```
Check whether the connected client supports a given MCP extension.
Inspects the ``extensions`` extra field on ``ClientCapabilities``
sent by the client during initialization.
Reads the client's advertised capabilities from the session, which is
available in request mode and in background-task mode (where the
snapshot session preserves the client's initialize params). Returns
``False`` when no session is available (e.g., a distributed worker with
no live session, or outside any context) or when the client did not
advertise the extension.
Example::
from fastmcp.apps.config import UI_EXTENSION_ID
@mcp.tool
async def my_tool(ctx: Context) -> str:
if ctx.client_supports_extension(UI_EXTENSION_ID):
return "UI-capable client"
return "text-only client"
#### `client_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L688" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
client_id(self) -> str | None
```
Get the client ID if available.
#### `request_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L696" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
request_id(self) -> str
```
Get the unique ID for this request.
Raises RuntimeError if MCP request context is not available.
#### `session_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L709" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
session_id(self) -> str
```
Get the MCP session ID for ALL transports.
Returns the session ID that can be used as a key for session-based
data storage (e.g., Redis) to share data between tool calls within
the same client session.
**Returns:**
- The session ID for StreamableHTTP transports, or a generated ID
- for other transports.
#### `session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L794" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
session(self) -> ServerSession
```
Access to the underlying session for advanced usage.
In request mode: Returns the session from the active request context.
In background task mode: Returns the session stored at Context creation.
Raises RuntimeError if no session is available.
#### `debug` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L820" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
debug(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None
```
Send a `DEBUG`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L836" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
info(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None
```
Send a `INFO`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `warning` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L852" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
warning(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None
```
Send a `WARNING`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L868" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
error(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None
```
Send a `ERROR`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `send_notification` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L884" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
send_notification(self, notification: mcp_types.ServerNotification) -> None
```
Send a notification to the client immediately.
**Args:**
- `notification`: An MCP notification instance (e.g., ToolListChangedNotification())
#### `close_sse_stream` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L904" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close_sse_stream(self) -> None
```
Close the current response stream to trigger client reconnection.
When using StreamableHTTP transport with an EventStore configured, this
method gracefully closes the HTTP connection for the current request.
The client will automatically reconnect (after `retry_interval` milliseconds)
and resume receiving events from where it left off via the EventStore.
This is useful for long-running operations to avoid load balancer timeouts.
Instead of holding a connection open for minutes, you can periodically close
and let the client reconnect.
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L958" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
elicit(self, message: str, response_type: type[T]) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation
```
The accepted elicitation will contain the response data
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L969" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
elicit(self, message: str, response_type: list[str]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation
```
When response_type is a list of strings, the accepted elicitation will
contain the selected string response
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L981" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
elicit(self, message: str, response_type: dict[str, dict[str, str]]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation
```
When response_type is a dict mapping keys to title dicts, the accepted
elicitation will contain the selected key
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L993" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
elicit(self, message: str, response_type: list[list[str]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation
```
When response_type is a list containing a list of strings (multi-select),
the accepted elicitation will contain a list of selected strings
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1005" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
elicit(self, message: str, response_type: list[dict[str, dict[str, str]]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation
```
When response_type is a list containing a dict mapping keys to title dicts
(multi-select with titles), the accepted elicitation will contain a list of
selected keys
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1017" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
elicit(self, message: str, response_type: type[T] | list[str] | dict[str, dict[str, str]] | list[list[str]] | list[dict[str, dict[str, str]]]) -> AcceptedElicitation[T] | AcceptedElicitation[dict[str, Any]] | AcceptedElicitation[str] | AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation
```
Send an elicitation request to the client and await the response.
Call this method at any time to request additional information from
the user through the client. The client must support elicitation,
or the request will error.
Note that the MCP protocol only supports simple object schemas with
primitive types. You can provide a dataclass, TypedDict, or BaseModel to
comply. If you provide a primitive type, an object schema with a single
"value" field will be generated for the MCP interaction and
automatically deconstructed into the primitive type upon response.
``response_type`` is required. Pass ``bool`` when all you need is a
confirmation; an empty schema leaves some clients rendering an empty,
non-functional form.
**Args:**
- `message`: A human-readable message explaining what information is needed
- `response_type`: The type of the response, which should be a primitive
type or dataclass or BaseModel. If it is a primitive type, an
object schema with a single "value" field will be generated.
- `response_title`: Optional label to display for the wrapped ``value``
field when ``response_type`` is a scalar, Literal, Enum, or one
of the dict/list shorthand forms. Overrides the auto-generated
"Value" label. Raises ``TypeError`` if passed with a BaseModel,
dataclass, or ``None`` response type (use ``Field(title=...)``
on the model instead).
- `response_description`: Optional description to attach to the wrapped
``value`` field. Same scope rules as ``response_title``.
#### `set_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1110" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_state(self, key: str, value: Any) -> None
```
Set a value in the state store.
By default, values are stored in the session-scoped state store and
persist across requests within the same MCP session. Values must be
JSON-serializable (dicts, lists, strings, numbers, etc.).
For non-serializable values (e.g., HTTP clients, database connections),
pass ``serializable=False``. These values are stored in a request-scoped
dict and only live for the current MCP request (tool call, resource
read, or prompt render). They will not be available in subsequent
requests.
The key is automatically prefixed with the session identifier.
#### `get_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_state(self, key: str) -> Any
```
Get a value from the state store.
Checks request-scoped state first (set with ``serializable=False``),
then falls back to the session-scoped state store.
Returns None if the key is not found.
#### `delete_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1178" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
delete_state(self, key: str) -> None
```
Delete a value from the state store.
Removes from both request-scoped and session-scoped stores.
#### `enable_components` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1199" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
enable_components(self) -> None
```
Enable components matching criteria for this session only.
Session rules override global transforms. Rules accumulate - each call
adds a new rule to the session. Later marks override earlier ones
(Visibility transform semantics).
Sends notifications to this session only: ToolListChangedNotification,
ResourceListChangedNotification, and PromptListChangedNotification.
**Args:**
- `names`: Component names or URIs to match.
- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}).
- `version`: Component version spec to match.
- `tags`: Tags to match (component must have at least one).
- `components`: Component types to match (e.g., {"tool", "prompt"}).
- `match_all`: If True, matches all components regardless of other criteria.
#### `disable_components` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1237" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
disable_components(self) -> None
```
Disable components matching criteria for this session only.
Session rules override global transforms. Rules accumulate - each call
adds a new rule to the session. Later marks override earlier ones
(Visibility transform semantics).
Sends notifications to this session only: ToolListChangedNotification,
ResourceListChangedNotification, and PromptListChangedNotification.
**Args:**
- `names`: Component names or URIs to match.
- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}).
- `version`: Component version spec to match.
- `tags`: Tags to match (component must have at least one).
- `components`: Component types to match (e.g., {"tool", "prompt"}).
- `match_all`: If True, matches all components regardless of other criteria.
#### `reset_visibility` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/context.py#L1275" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
reset_visibility(self) -> None
```
Clear all session visibility rules.
Use this to reset session visibility back to global defaults.
Sends notifications to this session only: ToolListChangedNotification,
ResourceListChangedNotification, and PromptListChangedNotification.

View file

@ -0,0 +1,614 @@
---
title: dependencies
sidebarTitle: dependencies
---
# `fastmcp.server.dependencies`
Dependency injection for FastMCP.
DI features (Depends, CurrentContext, CurrentFastMCP) work without pydocket
using the uncalled-for DI engine. The docket-specific dependencies
(``CurrentDocket``, ``CurrentWorker``) and background task execution live in the
``fastmcp-tasks`` package.
## Functions
### `bind_request_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
bind_request_context(ctx: ServerRequestContext) -> Generator[FastMCPRequestContext, None, None]
```
Bind a ``FastMCPRequestContext`` for the duration of a handler.
Constructs the wrapper from the SDK's per-request context and sets/resets
the ``fastmcp_request_ctx`` ContextVar. Every request adapter and the
initialize middleware enters this so ``Context`` and dependency helpers can
read the active request from the ContextVar.
### `extract_version_spec` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L131" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
extract_version_spec(meta: dict[str, Any] | None) -> str | None
```
Extract the FastMCP component version from a lifted ``_meta`` block.
### `set_background_context_factory` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L185" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_background_context_factory(factory: Callable[[], Awaitable[Context | None]] | None) -> None
```
Install (or clear) the background-task ``Context`` factory.
The factory returns an already-entered ``Context`` (so ``_current_context``
is set for cleanup) when called inside a worker, or ``None`` when there is
no task context. Passing ``None`` restores core's no-worker-fallback
behavior.
### `set_worker_server_resolver` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L207" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_worker_server_resolver(resolver: Callable[[], FastMCP | None] | None) -> None
```
Install (or clear) the worker-server resolver used by ``get_server()``.
### `is_docket_available` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L244" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_docket_available() -> bool
```
Check if a compatible pydocket (>= 0.19.0) is installed and importable.
Three things have to be true for fastmcp's task features to work:
1. pydocket distribution metadata is discoverable
2. its version is at least ``_MIN_DOCKET_VERSION`` (older versions are
missing symbols like ``docket.dependencies.current_execution``,
which fastmcp imports on the request hot path)
3. the package actually imports — guards against broken/partial
installs where metadata exists but ``import docket`` blows up
Any of those failing means we treat docket as unavailable and fall back
to the no-tasks code paths instead of crashing deep inside a request.
### `transform_context_annotations` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L276" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
transform_context_annotations(fn: Callable[..., Any]) -> Callable[..., Any]
```
Transform injected-by-type params into Dependency-defaulted params.
Transforms ALL params typed as Context (into ``= CurrentContext()``) and as
UserSession (into ``= CurrentSession()``) to use Docket's DI system, unless
they already have a Dependency-based default.
This unifies the legacy type annotation DI with Docket's Depends() system,
allowing both patterns to work through a single resolution path.
Note: Only POSITIONAL_OR_KEYWORD parameters are reordered (params with defaults
after those without). KEYWORD_ONLY parameters keep their position since Python
allows them to have defaults in any order.
**Args:**
- `fn`: Function to transform
**Returns:**
- Function with modified signature (same function object, updated __signature__)
### `get_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L442" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_context() -> Context
```
Get the current FastMCP Context instance directly.
### `get_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L452" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_server() -> FastMCP
```
Get the current FastMCP server instance directly.
In a background-task worker the tasks extension's resolver is consulted
first, so a mounted-child task resolves to the child server rather than the
root that started the worker (#3571).
**Returns:**
- The active FastMCP server
**Raises:**
- `RuntimeError`: If no server in context
### `get_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L480" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_session(session_id: str) -> Session
```
Resolve and validate a `Session` for an explicit `session_id`.
Pair with a `session_id: SessionId` tool argument (the agent obtains an id
from `create_session` and passes it back). For a single per-user bucket with
nothing for the agent to pass, inject `session: UserSession` instead.
State is keyed by `(principal, session_id)`: the authenticated principal is
the isolation wall and `session_id` organizes sessions within it. The id must
have been minted by `create_session` under the current principal; an id that
was never created, or created under a different principal, raises
`InvalidSession` rather than resolving to a fresh empty bucket (the specific
reason is logged at debug level, never returned to the caller).
Like `get_server()`, this resolves through the task-aware server, so it needs
no foreground context — it works from a `task=True` tool's Docket worker as
well as a normal request.
### `get_http_request` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L515" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_http_request() -> Request
```
Get the current HTTP request.
Tries MCP SDK's request_ctx first, then falls back to FastMCP's HTTP context.
### `get_http_headers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L536" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_http_headers(include_all: bool = False, include: set[str] | None = None) -> dict[str, str]
```
Extract headers from the current HTTP request if available.
Never raises an exception, even if there is no active HTTP request (in which case
an empty dict is returned).
By default, strips problematic headers like `content-length` and `authorization`
that cause issues if forwarded to downstream services. If `include_all` is True,
all headers are returned.
The `include` parameter allows specific headers to be included even if they would
normally be excluded. This is useful for proxy transports that need to forward
authorization headers to upstream MCP servers.
### `get_access_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L600" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_access_token() -> AccessToken | None
```
Get the FastMCP access token from the current context.
This function first tries to get the token from the current HTTP request's scope,
which is more reliable for long-lived connections where the SDK's auth_context_var
may become stale after token refresh. Falls back to the SDK's context var if no
request is available.
**Returns:**
- The access token if an authenticated user is available, None otherwise.
### `without_injected_parameters` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L659" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
without_injected_parameters(fn: Callable[..., Any]) -> Callable[..., Any]
```
Create a wrapper function without injected parameters.
Returns a wrapper that excludes Context and Docket dependency parameters,
making it safe to use with Pydantic TypeAdapter for schema generation and
validation. The wrapper internally handles all dependency resolution and
Context injection when called.
Handles:
- Legacy Context injection (always works)
- Depends() injection (always works - uses docket or vendored DI engine)
**Args:**
- `fn`: Original function with Context and/or dependencies
- `run_in_thread`: For sync ``fn``, whether to dispatch the call to a worker
thread after resolving dependencies. Defaults to True. Set to False
to call ``fn`` inline on the event loop thread — required for
thread-affinity libraries (e.g. Windows COM). Ignored for async fns.
**Returns:**
- Async wrapper function without injected parameters
### `resolve_dependencies` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L820" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resolve_dependencies(fn: Callable[..., Any], arguments: dict[str, Any]) -> AsyncGenerator[dict[str, Any], None]
```
Resolve dependencies for a FastMCP function.
This function:
1. Filters out any dependency parameter names from user arguments (security)
2. Resolves Depends() parameters via the DI system
The filtering prevents external callers from overriding injected parameters by
providing values for dependency parameter names. This is a security feature.
Note: Context injection is handled via transform_context_annotations() which
converts `ctx: Context` to `ctx: Context = Depends(get_context)` at registration
time, so all injection goes through the unified DI system.
**Args:**
- `fn`: The function to resolve dependencies for
- `arguments`: User arguments (may contain keys that match dependency names,
which will be filtered out)
### `CurrentContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L945" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
CurrentContext() -> Context
```
Get the current FastMCP Context instance.
This dependency provides access to the active FastMCP Context for the
current MCP operation (tool/resource/prompt call).
**Returns:**
- A dependency that resolves to the active Context instance
**Raises:**
- `RuntimeError`: If no active context found (during resolution)
### `OptionalCurrentContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L970" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
OptionalCurrentContext() -> Context | None
```
Get the current FastMCP Context, or None when no context is active.
### `CurrentFastMCP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L990" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
CurrentFastMCP() -> FastMCP
```
Get the current FastMCP server instance.
This dependency provides access to the active FastMCP server.
**Returns:**
- A dependency that resolves to the active FastMCP server
**Raises:**
- `RuntimeError`: If no server in context (during resolution)
### `CurrentRequest` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1030" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
CurrentRequest() -> Request
```
Get the current HTTP request.
This dependency provides access to the Starlette Request object for the
current HTTP request. Only available when running over HTTP transports
(SSE or Streamable HTTP).
**Returns:**
- A dependency that resolves to the active Starlette Request
**Raises:**
- `RuntimeError`: If no HTTP request in context (e.g., STDIO transport)
### `CurrentHeaders` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1071" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
CurrentHeaders() -> dict[str, str]
```
Get the current HTTP request headers.
This dependency provides access to the HTTP headers for the current request,
including the authorization header. Returns an empty dictionary when no HTTP
request is available, making it safe to use in code that might run over any
transport.
**Returns:**
- A dependency that resolves to a dictionary of header name -> value
### `CurrentAccessToken` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
CurrentAccessToken() -> AccessToken
```
Get the current access token for the authenticated user.
This dependency provides access to the AccessToken for the current
authenticated request. Raises an error if no authentication is present.
**Returns:**
- A dependency that resolves to the active AccessToken
**Raises:**
- `RuntimeError`: If no authenticated user (use get_access_token() for optional)
### `TokenClaim` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1346" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
TokenClaim(name: str) -> str
```
Get a specific claim from the access token.
This dependency extracts a single claim value from the current access token.
It's useful for getting user identifiers, roles, or other token claims
without needing the full token object.
**Args:**
- `name`: The name of the claim to extract (e.g., "oid", "sub", "email")
**Returns:**
- A dependency that resolves to the claim value as a string
**Raises:**
- `RuntimeError`: If no access token is available or claim is missing
## Classes
### `FastMCPRequestContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L55" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
FastMCP-owned wrapper around the SDK's per-request context.
The SDK v2 runner hands each handler a fresh ``ServerRequestContext`` as an
argument rather than exposing it through a ContextVar. FastMCP owns this
ContextVar (``fastmcp_request_ctx``) and each request adapter binds a
``FastMCPRequestContext`` at the top of the handler (and the initialize
middleware binds it too).
A wrapper rather than the raw context because the SDK's
``ServerRequestContext.meta`` is a bare ``RequestParamsMeta`` TypedDict that
only carries ``progress_token`` — it does not carry ``_meta.fastmcp`` or the
distributed-trace parent. Those live in the raw params dict under ``_meta``,
which this wrapper lifts once so downstream consumers have a stable surface.
### `ProgressLike` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1099" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for progress tracking interface.
Defines the common interface between InMemoryProgress (server context)
and Docket's Progress (worker context).
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1107" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
current(self) -> int | None
```
Current progress value.
#### `total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1112" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
total(self) -> int
```
Total/target progress value.
#### `message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
message(self) -> str | None
```
Current progress message.
#### `set_total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1121" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_total(self, total: int) -> None
```
Set the total/target value for progress tracking.
#### `increment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
increment(self, amount: int = 1) -> None
```
Atomically increment the current progress value.
#### `set_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1129" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_message(self, message: str | None) -> None
```
Update the progress status message.
### `InMemoryProgress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1134" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
In-memory progress tracker for immediate tool execution.
Provides the same interface as Docket's Progress but stores state in memory
instead of Redis. Useful for testing and immediate execution where
progress doesn't need to be observable across processes.
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1159" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
current(self) -> int | None
```
#### `total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1163" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
total(self) -> int
```
#### `message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1167" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
message(self) -> str | None
```
#### `set_total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1170" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_total(self, total: int) -> None
```
Set the total/target value for progress tracking.
#### `increment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1176" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
increment(self, amount: int = 1) -> None
```
Atomically increment the current progress value.
#### `set_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1185" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_message(self, message: str | None) -> None
```
Update the progress status message.
### `Progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1190" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Progress dependency that works in both server and worker contexts.
In a Docket worker, delegates to the execution's Redis-backed progress
(observable across processes). Otherwise, uses in-memory tracking.
The shared default instance acts as a stateless factory — ``__aenter__``
creates a fresh ``Progress`` per invocation so concurrent tasks never
share mutable state.
**Methods:**
#### `current` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1231" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
current(self) -> int | None
```
Current progress value.
#### `total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1237" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
total(self) -> int
```
Total/target progress value.
#### `message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1243" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
message(self) -> str | None
```
Current progress message.
#### `set_total` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1248" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_total(self, total: int) -> None
```
Set the total/target value for progress tracking.
#### `increment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1253" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
increment(self, amount: int = 1) -> None
```
Atomically increment the current progress value.
#### `set_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/dependencies.py#L1258" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_message(self, message: str | None) -> None
```
Update the progress status message.

View file

@ -0,0 +1,152 @@
---
title: elicitation
sidebarTitle: elicitation
---
# `fastmcp.server.elicitation`
## Functions
### `parse_elicit_response_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L143" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
parse_elicit_response_type(response_type: Any, response_title: str | None = None, response_description: str | None = None) -> ElicitConfig
```
Parse response_type into schema and handling configuration.
A response type is required; ``None`` raises ``TypeError``. Supports
multiple syntaxes:
- dict: `{"low": {"title": "..."}}` -> single-select titled enum
- list patterns:
- `[["a", "b"]]` -> multi-select untitled
- `[{"low": {...}}]` -> multi-select titled
- `["a", "b"]` -> single-select untitled
- `list\[X]` type annotation: multi-select with type
- Scalar types (bool, int, float, str, Literal, Enum): single value
- Other types (dataclass, BaseModel): use directly
The ``response_title`` and ``response_description`` arguments customize the
label and description of the wrapped ``value`` property for the scalar/dict/list
shorthand forms. They are only valid when FastMCP is wrapping the response
type; passing them with a full BaseModel/dataclass raises ``TypeError``,
because in those cases the user already controls field metadata via
``Field(title=..., description=...)``.
### `handle_elicit_accept` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L310" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
handle_elicit_accept(config: ElicitConfig, content: Any) -> AcceptedElicitation[Any]
```
Handle an accepted elicitation response.
**Args:**
- `config`: The elicitation configuration from parse_elicit_response_type
- `content`: The response content from the client
**Returns:**
- AcceptedElicitation with the extracted/validated data
### `get_elicitation_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L369" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_elicitation_schema(response_type: type[T]) -> dict[str, Any]
```
Get the schema for an elicitation response.
**Args:**
- `response_type`: The type of the response
### `validate_elicitation_json_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L395" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_elicitation_json_schema(schema: dict[str, Any]) -> None
```
Validate that a JSON schema follows MCP elicitation requirements.
This ensures the schema is compatible with MCP elicitation requirements:
- Must be an object schema
- Must only contain primitive field types (string, number, integer, boolean)
- Must be flat (no nested objects or arrays of objects)
- Allows const fields (for Literal types) and enum fields (for Enum types)
- Only primitive types and their nullable variants are allowed
**Args:**
- `schema`: The JSON schema to validate
**Raises:**
- `TypeError`: If the schema doesn't meet MCP elicitation requirements
## Classes
### `ElicitationJsonSchema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Custom JSON schema generator for MCP elicitation that always inlines enums.
MCP elicitation requires inline enum schemas without $ref/$defs references.
This generator ensures enums are always generated inline for compatibility.
Optionally adds enumNames for better UI display when available.
**Methods:**
#### `generate_inner` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L44" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_inner(self, schema: core_schema.CoreSchema) -> JsonSchemaValue
```
Override to prevent ref generation for enums and handle list schemas.
#### `list_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L57" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue
```
Generate schema for list types, detecting enum items for multi-select.
#### `enum_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue
```
Generate inline enum schema.
Always generates enum pattern: `{"enum": [value, ...]}`
Titled enums are handled separately via dict-based syntax in ctx.elicit().
### `AcceptedElicitation` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L105" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Result when user accepts the elicitation.
### `ScalarElicitationType` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L113" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ElicitConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/elicitation.py#L118" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Configuration for an elicitation request.
**Attributes:**
- `schema`: The JSON schema to send to the client
- `response_type`: The type to validate responses with (None for raw schemas)
- `is_raw`: True if schema was built directly (extract "value" from response)

View file

@ -0,0 +1,78 @@
---
title: event_store
sidebarTitle: event_store
---
# `fastmcp.server.event_store`
EventStore implementation backed by AsyncKeyValue.
This module provides an EventStore implementation that enables SSE polling/resumability
for Streamable HTTP transports. Events are stored using the key_value package's
AsyncKeyValue protocol, allowing users to configure any compatible backend
(in-memory, Redis, etc.) following the same pattern as ResponseCachingMiddleware.
## Classes
### `EventEntry` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/event_store.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Stored event entry.
### `StreamEventList` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/event_store.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
List of event IDs for a stream.
### `EventStore` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/event_store.py#L52" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
EventStore implementation backed by AsyncKeyValue.
Enables SSE polling/resumability by storing events that can be replayed
when clients reconnect. Works with any AsyncKeyValue backend (memory, Redis, etc.)
following the same pattern as ResponseCachingMiddleware and OAuthProxy.
**Args:**
- `storage`: AsyncKeyValue backend. Defaults to MemoryStore.
- `max_events_per_stream`: Maximum events to retain per stream. Default 100.
- `ttl`: Event TTL in seconds. Default 3600 (1 hour). Set to None for no expiration.
**Methods:**
#### `store_event` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/event_store.py#L120" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
store_event(self, stream_id: StreamId, message: JSONRPCMessage | None) -> EventId
```
Store an event and return its ID.
**Args:**
- `stream_id`: ID of the stream the event belongs to
- `message`: The JSON-RPC message to store, or None for priming events
**Returns:**
- The generated event ID for the stored event
#### `replay_events_after` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/event_store.py#L166" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
replay_events_after(self, last_event_id: EventId, send_callback: EventCallback) -> StreamId | None
```
Replay events that occurred after the specified event ID.
**Args:**
- `last_event_id`: The ID of the last event the client received
- `send_callback`: A callback function to send events to the client
**Returns:**
- The stream ID of the replayed events, or None if the event ID was not found

View file

@ -0,0 +1,194 @@
---
title: extensions
sidebarTitle: extensions
---
# `fastmcp.server.extensions`
FastMCP-native server extension API (SEP-2133).
An MCP extension is an opt-in, capability-negotiated bundle of protocol
behaviour identified by a reverse-DNS string (e.g. `io.modelcontextprotocol/tasks`).
Unlike the SDK's `mcp.server.extension.Extension`, a FastMCP `ServerExtension`
is bound to its `FastMCP` instance at registration, so its request handlers and
its `tools/call` interceptor can reach the component registry, `Context`, and
auth scope that the SDK's model withholds.
An extension contributes any subset of four things:
- **A negotiated capability.** `settings()` is spliced into
`ServerCapabilities.extensions[identifier]` (see `LowLevelServer.get_capabilities`).
- **New request methods.** `methods()` returns `MethodBinding`s, each wired onto
the low-level server via `add_request_handler` when the extension is registered.
- **A `tools/call` interceptor.** `intercept_tool_call()` is the last gate before
a tool body runs — it composes *after* the FastMCP middleware chain and *before*
component execution, so it can observe, short-circuit, or pass a call through.
- **A lifespan.** `lifespan()` is entered with the server's lifespan and exited on
shutdown — the hook the SDK's `Extension` lacks, needed to start backends/workers.
The base class follows the SDK's httpx-style shape: every contribution method has
a default, so a subclass overrides only what it needs.
## Functions
### `read_client_extension_settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L235" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_client_extension_settings(ctx: ServerRequestContext[Any, Any], identifier: str) -> dict[str, Any] | None
```
Read a client's per-request extension opt-in from the request `_meta`.
SEP-2133 extensions negotiate per request: the client repeats its extension
capabilities in each request's `_meta` under
`io.modelcontextprotocol/clientCapabilities` → `extensions` → `identifier`.
Returns the declared settings dict (possibly empty) when the extension was
opted in for this request, or `None` when it was not.
### `build_method_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L249" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
build_method_handler(binding: MethodBinding) -> ExtensionRequestHandler
```
Wrap a `MethodBinding` into a low-level request handler.
The adapter enforces `protocol_versions` gating (rejecting other versions as
`METHOD_NOT_FOUND`, since `add_request_handler` registers unconditionally)
and binds the FastMCP request context so the handler can use `get_context()`,
auth, and other request-scoped dependencies.
### `wrap_tool_call_interceptor` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L278" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
wrap_tool_call_interceptor(extension: ServerExtension, call_next: Callable[[Any], Awaitable[Any]]) -> Callable[[Any], Awaitable[Any]]
```
Fold one extension's `intercept_tool_call` around a middleware `call_next`.
The returned wrapper is a FastMCP `CallNext`: it hands the extension the
validated `tools/call` params, the FastMCP `Context`, and a zero-arg
continuation that runs the rest of the chain and, finally, the tool body.
## Classes
### `MethodBinding` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L77" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A new request method an extension serves, e.g. `tasks/get`.
`params_type` validates incoming params before `handler` runs; it should
subclass `RequestParams` so `_meta` parses uniformly. `protocol_versions`,
when set, restricts the method to those wire versions — a request at any
other version is rejected as `METHOD_NOT_FOUND`, mirroring the spec's
`(method, version)` boundary. `None` (the default) admits every version.
Extension methods are additive: `method` must not name a spec-defined
request method (`tools/call`, `completion/complete`, ...). Binding one would
silently shadow the server's own handler. Both constraints are enforced at
construction.
### `ServerExtension` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L111" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base class for an opt-in FastMCP server extension (SEP-2133).
Subclass, set `identifier`, and override the contribution methods that
apply. Every method has a default, so a minimal extension overrides only
`identifier` and one contribution. `identifier` is validated at
subclass-definition time when set as a class attribute, and again at
registration (which covers per-instance identifiers assigned in `__init__`).
Register an instance with `FastMCP.add_extension(...)`, which binds the
extension to the server so `self.server`, `intercept_tool_call`, and method
handlers can reach FastMCP-level constructs.
**Methods:**
#### `server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L149" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
server(self) -> FastMCP
```
The FastMCP server this extension is registered on.
Handlers, interceptors, and lifespan code reach the component registry,
`Context`, and auth scope through here. Raises if the extension has not
been registered with `FastMCP.add_extension()`.
#### `settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L165" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
settings(self) -> dict[str, Any]
```
Per-extension settings advertised at `capabilities.extensions[identifier]`.
An empty dict (the default) advertises the extension with no settings.
#### `methods` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L172" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
methods(self) -> Sequence[MethodBinding]
```
New request methods this extension serves (additive).
#### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L176" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan(self) -> AbstractAsyncContextManager[None]
```
A context manager entered with the server's lifespan, exited on shutdown.
Default: a no-op. Override to start and stop resources an extension owns
(a task-queue backend and worker, say). Entered once per runtime tree, at
the root — a mounted child defers to the root, as the shared Docket does.
#### `intercept_tool_call` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L185" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
intercept_tool_call(self, params: CallToolRequestParams, context: Context, call_next: ToolCallContinuation) -> ToolCallOutcome
```
Wrap `tools/call`. Default: pass through unchanged.
Runs after the FastMCP middleware chain and before the tool body, so it
is the last gate before execution. Override to observe the call, to
short-circuit (return a result without awaiting `call_next`), or to pass
it through (`return await call_next()`). `params` is the validated
`tools/call` params; `context` is the FastMCP `Context`, from which the
tool being called (`context.fastmcp.get_tool(params.name)`), auth scope,
and the server are reachable. Multiple extensions nest with the
first-registered outermost.
#### `client_settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/extensions.py#L204" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
client_settings(self, ctx: ServerRequestContext[Any, Any]) -> dict[str, Any] | None
```
This extension's per-request opt-in settings declared by the client.
Reads the request's `_meta` client-capabilities block. Returns the
declared settings dict (possibly empty) when the client opted this
extension in for the request, or `None` when it did not. Convenience for
`read_client_extension_settings(ctx, self.identifier)`.

View file

@ -0,0 +1,144 @@
---
title: http
sidebarTitle: http
---
# `fastmcp.server.http`
## Functions
### `set_http_request` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L355" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_http_request(request: Request) -> Generator[Request, None, None]
```
### `create_base_app` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L388" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_base_app(routes: list[BaseRoute], middleware: list[Middleware], debug: bool = False, lifespan: Callable | None = None) -> StarletteWithLifespan
```
Create a base Starlette app with common middleware and routes.
**Args:**
- `routes`: List of routes to include in the app
- `middleware`: List of middleware to include in the app
- `debug`: Whether to enable debug mode
- `lifespan`: Optional lifespan manager for the app
**Returns:**
- A Starlette application
### `create_sse_app` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L416" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_sse_app(server: FastMCP[LifespanResultT], message_path: str, sse_path: str, auth: AuthProvider | None = None, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan
```
Return an instance of the SSE server app.
**Args:**
- `server`: The FastMCP server instance
- `message_path`: Path for SSE messages
- `sse_path`: Path for SSE connections
- `auth`: Optional authentication provider (AuthProvider)
- `debug`: Whether to enable debug mode
- `routes`: Optional list of custom routes
- `middleware`: Optional list of middleware
Returns:
A Starlette application with RequestContextMiddleware
### `create_streamable_http_app` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L545" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_streamable_http_app(server: FastMCP[LifespanResultT], streamable_http_path: str, event_store: EventStore | None = None, retry_interval: int | None = None, auth: AuthProvider | None = None, json_response: bool = False, stateless_http: bool = False, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None, host_origin_protection: HostOriginProtection = False, allowed_hosts: Sequence[str] | None = None, allowed_origins: Sequence[str] | None = None, session_idle_timeout: float | None = None) -> StarletteWithLifespan
```
Return an instance of the StreamableHTTP server app.
**Args:**
- `server`: The FastMCP server instance
- `streamable_http_path`: Path for StreamableHTTP connections
- `event_store`: Optional event store for SSE polling/resumability
- `retry_interval`: Optional retry interval in milliseconds for SSE polling.
Controls how quickly clients should reconnect after server-initiated
disconnections. Requires event_store to be set. Defaults to SDK default.
- `auth`: Optional authentication provider (AuthProvider)
- `json_response`: Whether to use JSON response format
- `stateless_http`: Whether to use stateless mode (new transport per request)
- `debug`: Whether to enable debug mode
- `routes`: Optional list of custom routes
- `middleware`: Optional list of middleware
- `host_origin_protection`: Whether to validate Host and Origin headers
before requests reach the MCP endpoint. Defaults to False for
compatibility. "auto" protects localhost-bound servers and explicit
host/origin allowlists.
- `allowed_hosts`: Additional hostnames that may appear in the Host header.
- `allowed_origins`: Additional browser origins trusted by the request guard.
Configure CORS separately when browser JavaScript must read
cross-origin responses.
- `session_idle_timeout`: Maximum time in seconds a session may remain idle
before it is terminated. The deadline is pushed forward on every
request. When None, sessions never expire from inactivity. Not
supported in stateless mode.
**Returns:**
- A Starlette application with StreamableHTTP support
## Classes
### `FastMCPStreamableHTTPSessionManager` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L43" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Session manager that scopes resumability storage per transport session.
**Methods:**
#### `event_store` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L68" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
event_store(self) -> EventStore | None
```
#### `event_store` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
event_store(self, event_store: EventStore | None) -> None
```
### `StreamableHTTPASGIApp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L80" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
ASGI application wrapper for Streamable HTTP server transport.
### `HostOriginGuardMiddleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L227" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Validate Host and Origin headers before requests reach MCP sessions.
### `StarletteWithLifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L348" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L350" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan(self) -> Lifespan[Starlette]
```
### `RequestContextMiddleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/http.py#L363" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Middleware that stores each request in a ContextVar and sets transport type.

View file

@ -0,0 +1,101 @@
---
title: lifespan
sidebarTitle: lifespan
---
# `fastmcp.server.lifespan`
Composable lifespans for FastMCP servers.
This module provides a `@lifespan` decorator for creating composable server lifespans
that can be combined using the `|` operator.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.lifespan import lifespan
@lifespan
async def db_lifespan(server):
conn = await connect_db()
yield {"db": conn}
await conn.close()
@lifespan
async def cache_lifespan(server):
cache = await connect_cache()
yield {"cache": cache}
await cache.close()
mcp = FastMCP("server", lifespan=db_lifespan | cache_lifespan)
```
To compose with existing `@asynccontextmanager` lifespans, wrap them explicitly:
```python
from contextlib import asynccontextmanager
from fastmcp.server.lifespan import lifespan, ContextManagerLifespan
@asynccontextmanager
async def legacy_lifespan(server):
yield {"legacy": True}
@lifespan
async def new_lifespan(server):
yield {"new": True}
# Wrap the legacy lifespan explicitly
combined = ContextManagerLifespan(legacy_lifespan) | new_lifespan
```
## Functions
### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/lifespan.py#L172" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan(fn: LifespanFn) -> Lifespan
```
Decorator to create a composable lifespan.
Use this decorator on an async generator function to make it composable
with other lifespans using the `|` operator.
**Args:**
- `fn`: An async generator function that takes a FastMCP server and yields
a dict for the lifespan context.
**Returns:**
- A composable Lifespan wrapper.
## Classes
### `Lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/lifespan.py#L61" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Composable lifespan wrapper.
Wraps an async generator function and enables composition via the `|` operator.
The wrapped function should yield a dict that becomes part of the lifespan context.
### `ContextManagerLifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/lifespan.py#L110" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Lifespan wrapper for already-wrapped context manager functions.
Use this for functions already decorated with @asynccontextmanager.
### `ComposedLifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/lifespan.py#L137" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Two lifespans composed together.
Enters the left lifespan first, then the right. Exits in reverse order.
Results are shallow-merged into a single dict.

View file

@ -0,0 +1,106 @@
---
title: low_level
sidebarTitle: low_level
---
# `fastmcp.server.low_level`
## Functions
### `client_supports_extension` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/low_level.py#L111" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
client_supports_extension(session: ServerSession, extension_id: str) -> bool
```
Check whether the connected client supports a given MCP extension.
Inspects the ``extensions`` capability on ``ClientCapabilities`` sent by the
client during initialization. In v2 the client's initialize params are
reachable via ``session.client_params``.
SDK v2 declares ``extensions`` as a real field on ``ClientCapabilities``, so
a client sending ``ClientCapabilities(extensions={...})`` populates the field
directly. We read that field first and fall back to ``model_extra`` only for
legacy-serialized clients that carried ``extensions`` as an extra key.
## Classes
### `FastMCPServerMiddleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/low_level.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Root dispatch for the FastMCP middleware chain, in the SDK's middleware layer.
v2 no longer lets FastMCP subclass ``ServerSession`` (the runner constructs
it per request), so the old ``MiddlewareServerSession._received_request``
override is replaced by a ``ServerMiddleware`` — an ordinary entry in the
SDK's own middleware list. Sitting at the root of dispatch, this
is the single entry point through which *every* inbound message flows —
requests, notifications, cancellations, ``initialize``, and even malformed or
unroutable messages the SDK can still hand us. It binds the FastMCP
request-context ContextVar and re-applies the app-scoped ``SharedContext`` for
the whole chain, then runs the FastMCP ``Middleware`` chain so
``on_message`` / ``on_request`` / ``on_notification`` observe the message.
Dispatch shapes:
- Negotiation runs the *whole* FastMCP chain here: ``initialize`` dispatches
through ``on_initialize`` and ``server/discover`` through ``on_discover``.
Neither has an interior FastMCP handler adapter, and the SDK serializes both
results before returning through its middleware seam, so this root adapter
restores core results to typed models before FastMCP middleware observes them.
- The component methods (``tools/call``, ``tools/list``, ``resources/read``,
...) still run their FastMCP chain *interior*, in the handler adapter, where
``on_call_tool`` receives the typed component result and a tool exception
propagates through ``on_message``/``on_request`` exactly where the built-in
error/logging/timing middleware expect it. The root dispatch does not re-run the
chain for these — it only steps in when such a request fails *before* the
interior runs (malformed params, routing), so ``on_message`` still observes
the failure.
- Every other message — all notifications (including ``notifications/cancelled``
and ``notifications/initialized``), ``ping``, ``logging/setLevel``, and any
unroutable/non-component request — has no interior FastMCP dispatch, so the
root dispatch runs the ``"outer"`` pass (``on_message`` plus
``on_request``/``on_notification``) here, wrapping the real SDK dispatch.
This closes the long-standing gap where these messages were invisible to
FastMCP middleware.
### `LowLevelServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/low_level.py#L455" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `fastmcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/low_level.py#L507" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
fastmcp(self) -> FastMCP
```
Get the FastMCP instance.
#### `create_initialization_options` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/low_level.py#L514" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_initialization_options(self, notification_options: NotificationOptions | None = None, experimental_capabilities: dict[str, dict[str, Any]] | None = None, extensions: dict[str, dict[str, Any]] | None = None) -> InitializationOptions
```
#### `get_capabilities` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/low_level.py#L529" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_capabilities(self, notification_options: NotificationOptions | None = None, experimental_capabilities: dict[str, dict[str, Any]] | None = None, extensions: dict[str, dict[str, Any]] | None = None) -> mcp_types.ServerCapabilities
```
Override to advertise registered extensions and the MCP Apps UI extension.
``ServerCapabilities.extensions`` is a real declared field in v2, so we
update it directly. The
`FastMCP(experimental_capabilities=...)` merge also lives here rather
than in `create_initialization_options`: the modern `server/discover`
handler calls this directly, without going through
`create_initialization_options` at all, so merging there only reached
the handshake-era `initialize` response and silently dropped
constructor-configured experimental capabilities from `discover`.

View file

@ -0,0 +1,9 @@
---
title: mixins
sidebarTitle: mixins
---
# `fastmcp.server.mixins`
Server mixins for FastMCP.

View file

@ -0,0 +1,34 @@
---
title: providers
sidebarTitle: providers
---
# `fastmcp.server.providers`
Providers for dynamic MCP components.
This module provides the `Provider` abstraction for providing tools,
resources, and prompts dynamically at runtime.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.providers import Provider
from fastmcp.tools import Tool
class DatabaseProvider(Provider):
def __init__(self, db_url: str):
self.db = Database(db_url)
async def _list_tools(self) -> list[Tool]:
rows = await self.db.fetch("SELECT * FROM tools")
return [self._make_tool(row) for row in rows]
async def _get_tool(self, name: str) -> Tool | None:
row = await self.db.fetchone("SELECT * FROM tools WHERE name = ?", name)
return self._make_tool(row) if row else None
mcp = FastMCP("Server", providers=[DatabaseProvider(db_url)])
```

View file

@ -0,0 +1,891 @@
---
title: server
sidebarTitle: server
---
# `fastmcp.server.server`
FastMCP - A more ergonomic interface for MCP servers.
## Functions
### `default_lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L237" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
default_lifespan(server: FastMCP[LifespanResultT]) -> AsyncIterator[Any]
```
Default lifespan context manager that does nothing.
**Args:**
- `server`: The server instance this lifespan is managing
**Returns:**
- An empty dictionary as the lifespan result.
### `create_proxy` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2501" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_proxy(target: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | SDKServer | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy
```
Create a FastMCP proxy server for the given target.
This is the recommended way to create a proxy server. For lower-level control,
use `FastMCPProxy` or `ProxyProvider` directly from `fastmcp.server.providers.proxy`.
**Args:**
- `target`: The backend to proxy to. Can be\:
- A Client instance (connected or disconnected)
- A ClientTransport
- A FastMCP server instance
- A URL string or AnyUrl
- A Path to a server script
- An MCPConfig or dict
- `mode`: Protocol-era negotiation for auto-created proxy clients (a
non-Client target). By default (``None``) the backend MIRRORS the
front connection's negotiated era per request, so the whole chain
speaks one era end-to-end\: a modern front reaches a modern backend
(a guard tool's `InputRequiredResult` (SEP-2322) round-trips) and a
handshake front reaches a handshake backend (server-initiated
sampling / elicitation / roots push-forwarding works). Pass an
explicit mode (e.g. ``"auto"`` or a version string) to pin the
backend era regardless of the front; this overrides mirroring and is
appropriate when the backend only speaks one era. Ignored when
`target` is already a `Client` (which carries its own mode).
- `**settings`: Additional settings passed to FastMCPProxy (name, etc.)
**Returns:**
- A FastMCPProxy server that proxies to the target.
## Classes
### `StateValue` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L272" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Wrapper for stored context state values.
### `FastMCP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L278" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L507" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
name(self) -> str
```
#### `instructions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L511" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
instructions(self) -> str | None
```
#### `instructions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L515" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
instructions(self, value: str | None) -> None
```
#### `version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L519" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
version(self) -> str | None
```
#### `website_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L523" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
website_url(self) -> str | None
```
#### `icons` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L527" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
icons(self) -> list[mcp_types.Icon]
```
#### `local_provider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L534" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
local_provider(self) -> LocalProvider
```
The server's local provider, which stores directly-registered components.
Use this to remove components:
mcp.local_provider.remove_tool("my_tool")
mcp.local_provider.remove_resource("data://info")
mcp.local_provider.remove_prompt("my_prompt")
#### `add_middleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L598" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_middleware(self, middleware: Middleware) -> None
```
#### `add_extension` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L601" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_extension(self, extension: ServerExtension) -> None
```
Register a server extension (SEP-2133).
An extension contributes a negotiated capability, additive request
methods, a `tools/call` interceptor, and an optional lifespan — each
with access to FastMCP-level constructs (the component registry,
`Context`, auth scope). Its capability is advertised only while it is
registered.
The extension is bound to this server (so its handlers and interceptor
can reach it), its method bindings are wired onto the low-level server,
and it is recorded for capability advertisement, interception, and
lifespan entry. Registering two extensions with the same identifier is
an error, as is registering after the server's lifespan has started —
the extension's lifespan could no longer run, leaving it silently
half-active.
Extensions are served by the server they are registered on. A mounted
child's extensions do not propagate to the root: the root serves the
wire, so only root-registered extensions advertise capabilities and
answer methods (matching the lifespan, which also defers to the root).
Register extensions on the server you run.
#### `add_provider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L673" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_provider(self, provider: Provider) -> None
```
Add a provider for dynamic tools, resources, and prompts.
Providers are queried in registration order. The first provider to return
a non-None result wins. Static components (registered via decorators)
always take precedence over providers.
**Args:**
- `provider`: A Provider instance that will provide components dynamically.
- `namespace`: Optional namespace prefix. When set\:
- Tools become "namespace_toolname"
- Resources become "protocol\://namespace/path"
- Prompts become "namespace_promptname"
#### `get_tasks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L785" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_tasks(self) -> Sequence[FastMCPComponent]
```
Get task-eligible components with all transforms applied.
Overrides AggregateProvider.get_tasks() to apply server-level transforms
after aggregation. AggregateProvider handles provider-level namespacing.
#### `add_transform` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L814" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_transform(self, transform: Transform) -> None
```
Add a server-level transform.
Server-level transforms are applied after all providers are aggregated.
They transform tools, resources, and prompts from ALL providers.
**Args:**
- `transform`: The transform to add.
#### `list_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L834" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_tools(self) -> Sequence[Tool]
```
List all enabled tools from providers.
Overrides Provider.list_tools() to add enabled filtering, auth filtering,
and middleware execution. Returns all versions (no deduplication).
Protocol handlers deduplicate for MCP wire format.
#### `get_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L917" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None
```
Get a tool by name, filtering disabled tools.
Overrides Provider.get_tool() to filter disabled tools after all
transforms (including session-level) have been applied. This ensures
session transforms can override provider-level disables.
When the highest version is disabled and no explicit version was
requested, falls back to the next-highest enabled version.
**Args:**
- `name`: The tool name.
- `version`: Version filter (None returns highest version).
**Returns:**
- The tool if found and enabled, None otherwise.
#### `list_resources` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L971" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resources(self) -> Sequence[Resource]
```
List all enabled resources from providers.
Overrides Provider.list_resources() to add visibility filtering, auth filtering,
and middleware execution. Returns all versions (no deduplication).
Protocol handlers deduplicate for MCP wire format.
#### `get_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1056" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_resource(self, uri: str, version: VersionSpec | None = None) -> Resource | None
```
Get a resource by URI, filtering disabled resources.
Overrides Provider.get_resource() to add visibility filtering after all
transforms (including session-level) have been applied.
When the highest version is disabled and no explicit version was
requested, falls back to the next-highest enabled version.
**Args:**
- `uri`: The resource URI.
- `version`: Version filter (None returns highest version).
**Returns:**
- The resource if found and enabled, None otherwise.
#### `list_resource_templates` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resource_templates(self) -> Sequence[ResourceTemplate]
```
List all enabled resource templates from providers.
Overrides Provider.list_resource_templates() to add visibility filtering,
auth filtering, and middleware execution. Returns all versions (no deduplication).
Protocol handlers deduplicate for MCP wire format.
#### `get_resource_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1188" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_resource_template(self, uri: str, version: VersionSpec | None = None) -> ResourceTemplate | None
```
Get a resource template by URI, filtering disabled templates.
Overrides Provider.get_resource_template() to add visibility filtering after
all transforms (including session-level) have been applied.
When the highest version is disabled and no explicit version was
requested, falls back to the next-highest enabled version.
**Args:**
- `uri`: The template URI.
- `version`: Version filter (None returns highest version).
**Returns:**
- The template if found and enabled, None otherwise.
#### `list_prompts` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1242" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_prompts(self) -> Sequence[Prompt]
```
List all enabled prompts from providers.
Overrides Provider.list_prompts() to add visibility filtering, auth filtering,
and middleware execution. Returns all versions (no deduplication).
Protocol handlers deduplicate for MCP wire format.
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1314" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt(self, name: str, version: VersionSpec | None = None) -> Prompt | None
```
Get a prompt by name, filtering disabled prompts.
Overrides Provider.get_prompt() to add visibility filtering after all
transforms (including session-level) have been applied.
When the highest version is disabled and no explicit version was
requested, falls back to the next-highest enabled version.
**Args:**
- `name`: The prompt name.
- `version`: Version filter (None returns highest version).
**Returns:**
- The prompt if found and enabled, None otherwise.
#### `call_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1364" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult
```
Call a tool by name.
This is the public API for executing tools. By default, middleware is applied.
**Args:**
- `name`: The tool name
- `arguments`: Tool arguments (optional)
- `version`: Specific version to call. If None, calls highest version.
- `run_middleware`: If True (default), apply the middleware chain.
Set to False when called from middleware to avoid re-applying.
**Returns:**
- ToolResult.
A guard tool that requests client input (SEP-2322 multi-round-trip)
returns an ``InputRequiredToolResult`` (a ``ToolResult`` subclass); it
flows back through the middleware chain as an ordinary result and the
wire handler unwraps it into an ``InputRequiredResult`` on the response.
**Raises:**
- `NotFoundError`: If tool not found or disabled
- `ToolError`: If tool execution fails
- `ValidationError`: If arguments fail validation
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1557" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_resource(self, uri: str) -> ResourceResult
```
Read a resource by URI.
This is the public API for reading resources. By default, middleware is applied.
Checks concrete resources first, then templates.
**Args:**
- `uri`: The resource URI
- `version`: Specific version to read. If None, reads highest version.
- `run_middleware`: If True (default), apply the middleware chain.
Set to False when called from middleware to avoid re-applying.
**Returns:**
- ResourceResult.
**Raises:**
- `NotFoundError`: If resource not found or disabled
- `ResourceError`: If resource read fails
#### `render_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1715" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> PromptResult
```
Render a prompt by name.
This is the public API for rendering prompts. By default, middleware is applied.
Use get_prompt() to retrieve the prompt definition without rendering.
**Args:**
- `name`: The prompt name
- `arguments`: Prompt arguments (optional)
- `version`: Specific version to render. If None, renders highest version.
- `run_middleware`: If True (default), apply the middleware chain.
Set to False when called from middleware to avoid re-applying.
**Returns:**
- PromptResult.
**Raises:**
- `NotFoundError`: If prompt not found or disabled
- `PromptError`: If prompt rendering fails
#### `add_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1795" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_tool(self, tool: Tool | Callable[..., Any]) -> Tool
```
Add a tool to the server.
The tool function can optionally request a Context object by adding a parameter
with the Context type annotation. See the @tool decorator for examples.
**Args:**
- `tool`: The Tool instance or @tool-decorated function to register
**Returns:**
- The tool instance that was added to the server.
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1810" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: F) -> F
```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1831" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: str | None = None) -> Callable[[F], F]
```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1851" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool]
```
Decorator to register a tool.
Tools can optionally request a Context object by adding a parameter with the
Context type annotation. The context provides access to MCP capabilities like
logging, progress reporting, and resource access.
This decorator supports multiple calling patterns:
- @server.tool (without parentheses)
- @server.tool (with empty parentheses)
- @server.tool("custom_name") (with name as first argument)
- @server.tool(name="custom_name") (with name as keyword argument)
- server.tool(function, name="custom_name") (direct function call)
**Args:**
- `name_or_fn`: Either a function (when used as @tool), a string name, or None
- `name`: Optional name for the tool (keyword-only, alternative to name_or_fn)
- `description`: Optional description of what the tool does
- `tags`: Optional set of tags for categorizing the tool
- `output_schema`: Optional JSON schema for the tool's output
- `annotations`: Optional annotations about the tool's behavior
- `meta`: Optional meta information about the tool
**Examples:**
Register a tool with a custom name:
```python
@server.tool
def my_tool(x: int) -> str:
return str(x)
# Register a tool with a custom name
@server.tool
def my_tool(x: int) -> str:
return str(x)
@server.tool("custom_name")
def my_tool(x: int) -> str:
return str(x)
@server.tool(name="custom_name")
def my_tool(x: int) -> str:
return str(x)
# Direct function call
server.tool(my_function, name="custom_name")
```
#### `add_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1948" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_resource(self, resource: Resource | Callable[..., Any]) -> Resource | ResourceTemplate
```
Add a resource to the server.
**Args:**
- `resource`: A Resource instance or @resource-decorated function to add
**Returns:**
- The resource instance that was added to the server.
#### `add_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1961" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_template(self, template: ResourceTemplate) -> ResourceTemplate
```
Add a resource template to the server.
**Args:**
- `template`: A ResourceTemplate instance to add
**Returns:**
- The template instance that was added to the server.
#### `resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1972" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resource(self, uri: str) -> Callable[[F], F]
```
Decorator to register a function as a resource.
The function will be called when the resource is read to generate its content.
The function can return:
- str for text content
- bytes for binary content
- other types will be converted to JSON
Resources can optionally request a Context object by adding a parameter with the
Context type annotation. The context provides access to MCP capabilities like
logging, progress reporting, and session information.
If the URI contains parameters (e.g. "resource://{param}") or the function
has parameters, it will be registered as a template resource.
**Args:**
- `uri`: URI for the resource (e.g. "resource\://my-resource" or "resource\://{param}")
- `name`: Optional name for the resource
- `description`: Optional description of the resource
- `mime_type`: Optional MIME type for the resource
- `tags`: Optional set of tags for categorizing the resource
- `annotations`: Optional annotations about the resource's behavior
- `meta`: Optional meta information about the resource
**Examples:**
Register a resource with a custom name:
```python
@server.resource("resource://my-resource")
def get_data() -> str:
return "Hello, world!"
@server.resource("resource://my-resource")
async get_data() -> str:
data = await fetch_data()
return f"Hello, world! {data}"
@server.resource("resource://{city}/weather")
def get_weather(city: str) -> str:
return f"Weather for {city}"
@server.resource("resource://{city}/weather")
async def get_weather_with_context(city: str, ctx: Context) -> str:
await ctx.info(f"Fetching weather for {city}")
return f"Weather for {city}"
@server.resource("resource://{city}/weather")
async def get_weather(city: str) -> str:
data = await fetch_weather(city)
return f"Weather for {city}: {data}"
```
#### `add_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2091" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_prompt(self, prompt: Prompt | Callable[..., Any]) -> Prompt
```
Add a prompt to the server.
**Args:**
- `prompt`: A Prompt instance or @prompt-decorated function to add
**Returns:**
- The prompt instance that was added to the server.
#### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2103" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prompt(self, name_or_fn: F) -> F
```
#### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2118" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prompt(self, name_or_fn: str | None = None) -> Callable[[F], F]
```
#### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2132" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt]
```
Decorator to register a prompt.
Prompts can optionally request a Context object by adding a parameter with the
Context type annotation. The context provides access to MCP capabilities like
logging, progress reporting, and session information.
This decorator supports multiple calling patterns:
- @server.prompt (without parentheses)
- @server.prompt() (with empty parentheses)
- @server.prompt("custom_name") (with name as first argument)
- @server.prompt(name="custom_name") (with name as keyword argument)
- server.prompt(function, name="custom_name") (direct function call)
Args:
name_or_fn: Either a function (when used as @prompt), a string name, or None
name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
description: Optional description of what the prompt does
tags: Optional set of tags for categorizing the prompt
meta: Optional meta information about the prompt
Examples:
```python
@server.prompt
def analyze_table(table_name: str) -> list[Message]:
schema = read_table_schema(table_name)
return [
{
"role": "user",
"content": f"Analyze this schema:
{schema}"
}
]
@server.prompt()
async def analyze_with_context(table_name: str, ctx: Context) -> list[Message]:
await ctx.info(f"Analyzing table {table_name}")
schema = read_table_schema(table_name)
return [
{
"role": "user",
"content": f"Analyze this schema:
{schema}"
}
]
@server.prompt("custom_name")
async def analyze_file(path: str) -> list[Message]:
content = await read_file(path)
return [
{
"role": "user",
"content": {
"type": "resource",
"resource": {
"uri": f"file://{path}",
"text": content
}
}
}
]
@server.prompt(name="custom_name")
def another_prompt(data: str) -> list[Message]:
return [{"role": "user", "content": data}]
# Direct function call
server.prompt(my_function, name="custom_name")
```
#### `add_completion_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2230" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_completion_handler(self, handler: CompletionHandler) -> None
```
Register the server's argument-completion handler.
A server has a single completion handler that answers every
`completion/complete` request, switching on the reference (a prompt or
resource template) and the argument being completed. Registering it also
registers the low-level `completion/complete` handler, which is what
makes the SDK declare the completions capability — so the capability is
advertised exactly when the server can answer. Calling this again
replaces the handler.
**Args:**
- `handler`: A callable taking the reference, the
`CompletionArgument`, and the optional `CompletionContext`, and
returning candidate values (a `Completion`, a list of strings,
or None). May be sync or async.
#### `completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2251" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
completion(self, handler: CompletionHandler) -> CompletionHandler
```
#### `completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2254" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
completion(self) -> Callable[[CompletionHandler], CompletionHandler]
```
#### `completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2258" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
completion(self, handler: CompletionHandler | None = None) -> CompletionHandler | Callable[[CompletionHandler], CompletionHandler]
```
Decorator to register the server's argument-completion handler.
The handler answers `completion/complete` requests for prompt arguments
and resource-template parameters. It receives the reference being
completed, the argument (its name and the partial value typed so far),
and the context of arguments already supplied, and returns candidate
values. Return a list of strings, a `Completion` (to include pagination
hints), or None when the reference/argument is not one it handles — an
unhandled reference yields an empty completion, not an error.
Registering a handler declares the completions capability; a server with
none does not advertise it. This works identically on the handshake and
modern protocol eras.
Supports both `@mcp.completion` and `@mcp.completion()`.
Example:
```python
from fastmcp import FastMCP
from mcp_types import Completion, PromptReference
mcp = FastMCP("Completion Server")
@mcp.prompt
def poem(theme: str) -> str:
return f"Write a poem about {theme}"
@mcp.completion
def complete(ref, argument, context):
if isinstance(ref, PromptReference) and ref.name == "poem":
if argument.name == "theme":
options = ["nature", "love", "adventure"]
return [o for o in options if o.startswith(argument.value)]
return None
```
#### `mount` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2308" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
mount(self, server: FastMCP[LifespanResultT], namespace: str | None = None, tool_names: dict[str, str] | None = None) -> None
```
Mount another FastMCP server on this server with an optional namespace.
Mounting establishes a dynamic connection between servers. When a client
interacts with a mounted server's objects through the parent server, requests
are forwarded to the mounted server in real-time. This means changes to the
mounted server are immediately reflected when accessed through the parent.
When a server is mounted with a namespace:
- Tools from the mounted server are accessible with namespaced names.
Example: If server has a tool named "get_weather", it will be available as "namespace_get_weather".
- Resources are accessible with namespaced URIs.
Example: If server has a resource with URI "weather://forecast", it will be available as
"weather://namespace/forecast".
- Templates are accessible with namespaced URI templates.
Example: If server has a template with URI "weather://location/{id}", it will be available
as "weather://namespace/location/{id}".
- Prompts are accessible with namespaced names.
Example: If server has a prompt named "weather_prompt", it will be available as
"namespace_weather_prompt".
When a server is mounted without a namespace (namespace=None), its tools, resources, templates,
and prompts are accessible with their original names. Multiple servers can be mounted
without namespaces, and they will be tried in order until a match is found.
The mounted server's lifespan is executed when the parent server starts, and its
middleware chain is invoked for all operations (tool calls, resource reads, prompts).
**Args:**
- `server`: The FastMCP server to mount.
- `namespace`: Optional namespace to use for the mounted server's objects. If None,
the server's objects are accessible with their original names.
- `tool_names`: Optional mapping of original tool names to custom names. Use this
to override namespaced names. Keys are the original tool names from the
mounted server.
#### `from_openapi` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2379" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_openapi(cls, openapi_spec: dict[str, Any], client: httpx2.AsyncClient | None = None, name: str = 'OpenAPI Server', route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, validate_output: bool = True, **settings: Any) -> Self
```
Create a FastMCP server from an OpenAPI specification.
**Args:**
- `openapi_spec`: OpenAPI schema as a dictionary
- `client`: Optional httpx2 AsyncClient for making HTTP requests.
If not provided, a default client is created using the first
server URL from the OpenAPI spec with a 30-second timeout.
Legacy httpx clients are temporarily accepted with a deprecation
warning.
- `name`: Name for the MCP server
- `route_maps`: Optional list of RouteMap objects defining route mappings
- `route_map_fn`: Optional callable for advanced route type mapping
- `mcp_component_fn`: Optional callable for component customization
- `mcp_names`: Optional dictionary mapping operationId to component names
- `tags`: Optional set of tags to add to all components
- `validate_output`: If True (default), tools use the output schema
extracted from the OpenAPI spec for response validation. If
False, a permissive schema is used instead, allowing any
response structure while still returning structured JSON.
- `**settings`: Additional settings passed to FastMCP
**Returns:**
- A FastMCP server with an OpenAPIProvider attached.
#### `from_fastapi` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2432" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, httpx_client_kwargs: dict[str, Any] | None = None, tags: set[str] | None = None, **settings: Any) -> Self
```
Create a FastMCP server from a FastAPI application.
**Args:**
- `app`: FastAPI application instance
- `name`: Name for the MCP server (defaults to app.title)
- `route_maps`: Optional list of RouteMap objects defining route mappings
- `route_map_fn`: Optional callable for advanced route type mapping
- `mcp_component_fn`: Optional callable for component customization
- `mcp_names`: Optional dictionary mapping operationId to component names
- `httpx_client_kwargs`: Optional kwargs passed to httpx2.AsyncClient.
Use this to configure timeout and other client settings.
- `tags`: Optional set of tags to add to all components
- `**settings`: Additional settings passed to FastMCP
**Returns:**
- A FastMCP server with an OpenAPIProvider attached.
#### `generate_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2487" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_name(cls, name: str | None = None) -> str
```

View file

@ -0,0 +1,31 @@
---
title: session_scoped_event_store
sidebarTitle: session_scoped_event_store
---
# `fastmcp.server.session_scoped_event_store`
Lightweight session scoping for Streamable HTTP event stores.
## Classes
### `SessionScopedEventStore` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/session_scoped_event_store.py#L19" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
EventStore adapter that isolates stream IDs to one transport session.
**Methods:**
#### `store_event` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/session_scoped_event_store.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
store_event(self, stream_id: StreamId, message: JSONRPCMessage | None) -> EventId
```
#### `replay_events_after` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/session_scoped_event_store.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
replay_events_after(self, last_event_id: EventId, send_callback: EventCallback) -> StreamId | None
```

View file

@ -0,0 +1,319 @@
---
title: sessions
sidebarTitle: sessions
---
# `fastmcp.server.sessions`
Stateless session state: server-side per-user and per-session storage.
Modern (2026-07-28) MCP connections are stateless by construction — every
request builds a fresh connection whose in-memory state is discarded when the
request returns. This module gives tools two explicit ways to keep state across
calls, both backed by the server's existing state store and both isolated by the
authenticated principal rather than by any client-declared identifier.
- `Session`: async `get`/`set`/`delete`/`clear` over a single dict stored under
one key, scoped to a `(principal, session_id)` pair. This is the state-accessor
object a handler works with — the value the standalone `get_session(id)`
returns and the value injected for a `UserSession` parameter.
- `session: UserSession` (injected): a per-user bucket, dependency-injected like
`ctx: Context` and keyed by the request's authenticated principal. Requires
auth. `UserSession` is the injection annotation; the injected value is a
`Session`. It is always available under auth — no `create_session`, no
provider, no validation.
- `session_id: SessionId` (argument): a required string the agent supplies,
resolved with the standalone `await get_session(session_id)`. The id is
minted
by `create_session`; an id that was never created (or was created under a
different principal) is rejected. This validation is the whole guarantee — an
unminted id never resolves, so nothing enforces provider registration.
- `SessionProvider`: a `Provider` contributing `create_session` / `end_session`
tools. Register it with `mcp.add_provider(SessionProvider())` so a tool that
takes `session_id` has a way to mint ids; without it, no id can be created, so
those tools simply cannot resolve a session.
Isolation is the authenticated principal, not the session id. State keyed by
`(principal, session_id)` means a request under principal B can never address
principal A's keys, no matter what `session_id` it passes; the id only organizes
sessions within a principal. Without auth there is no principal wall — a session
id is a bearer capability and sessions are not a boundary between clients.
## Functions
### `current_principal` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L139" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
current_principal() -> str | None
```
The authenticated principal for the current request as a compact JSON string.
Returns the `(client_id, issuer, subject)` triple encoded as compact JSON, or
`None` on an unauthenticated request. Two users of one OAuth client are
distinct principals whenever the token verifier supplies a subject.
### `session_storage_key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
session_storage_key(principal: str | None, session_id: str) -> str
```
The single storage key holding a session's state dict.
Keyed by `(principal, session_id)`: the principal is the isolation wall, the
id organizes sessions within it. A session's whole state lives under this one
key as a dict, so one key means one store TTL per session and `end` is a
single delete.
### `session_id_parameter_names` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L343" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
session_id_parameter_names(fn: Callable[..., object]) -> tuple[str, ...]
```
Names of a function's parameters annotated with `SessionId`.
Scans resolved type hints for `Annotated[str, _SessionIdMarker()]` metadata.
Returns an empty tuple when the hints cannot be resolved (the function then
simply carries no auto-populated session-id description).
`functools.partial` is unwrapped first, since `get_type_hints` rejects a
partial object — FastMCP supports registering a partial as a tool, and its
schema is still built from the underlying function, so its `SessionId`
parameters must be detected here too. Parameters the partial has already
bound — positionally or by keyword — are dropped, matching the tool's actual
argument surface (the partial's own signature already reflects this).
### `CurrentSession` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L449" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
CurrentSession() -> Session
```
Inject the per-user `Session` for the current authenticated principal.
Rarely written explicitly — a `session: UserSession` parameter is rewritten
to this. Provided for parity with `CurrentContext()` when an explicit default
is preferred.
### `OptionalCurrentSession` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L459" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
OptionalCurrentSession() -> Session | None
```
Inject the per-user `Session`, or `None` when the request is unauthenticated.
Rarely written explicitly — a `session: UserSession | None = None` parameter
is rewritten to this. Provided for parity with `OptionalCurrentContext()`.
### `create_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L468" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_session() -> str
```
Create a new session and return its identifier.
Mints an unguessable `uuid4`, records an initial session owned by the current
principal, and returns the id as a string. Store it and pass it back as a
`session_id` argument on later calls to persist state across a session — only
an id created this way resolves. State is keyed by the authenticated
principal, so the id organizes sessions within a user; on an unauthenticated
connection the id is the only thing standing between callers, which is why it
is unguessable.
### `end_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L490" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
end_session(session_id: SessionId) -> str
```
End a session and delete all of its state.
Validates the id like any other resolution (an unknown or foreign id is
rejected), then deletes the session's key so the id no longer resolves.
## Classes
### `SessionAuthError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
An injected `session: UserSession` was requested with no authenticated principal.
Per-user session injection keys off the request's authenticated principal, so
it is only meaningful under auth. A tool that needs cross-call state without
auth should take a `session_id: SessionId` argument instead.
### `InvalidSession` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A session id did not resolve to a session created under the current principal.
Raised by `get_session(session_id)` when the id was never created, or was
created under a different principal. The public message is deliberately
generic — the specific reason (which id, which principal) is logged at debug
level, not returned to the caller, so an attacker cannot distinguish "unknown
id" from "belongs to someone else".
### `Session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L175" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Async accessors over one `(principal, session_id)` bucket of state.
A session's state is a single dict stored under one key. That dict holds user
state in a `state` sub-dict and a small creation marker alongside it, so a
created-but-empty session is still distinguishable from a missing one.
`get`/`set`/`delete` read-modify-write the sub-dict; `clear` empties the
sub-dict but keeps the session valid; `end` deletes the whole key. Writes
never impose a TTL — retention is entirely the server store's (configure it on
the store you pass to `FastMCP(session_state_store=...)`).
Concurrent writes to one session race on the read-modify-write; session state
is small and typically driven serially by one agent, so this is acceptable.
**Methods:**
#### `id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L205" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
id(self) -> str | None
```
The session's identifier, or `None` for an injected per-user session.
For a session resolved from a `session_id` argument (or minted by
`create_session`) this is that id. An injected `UserSession` has no
distinct id — its bucket is the authenticated user — so it is `None`; the
internal principal-derived key is deliberately not exposed here.
#### `get` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L254" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get(self, key: str, default: Any = None) -> Any
```
Return the value for `key`, or `default` when it is not set.
#### `set` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L259" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set(self, key: str, value: Any) -> None
```
Store `value` under `key` in this session (read-modify-write).
Preserves the creation marker: only the user-state sub-dict is touched.
#### `delete` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L270" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
delete(self, key: str) -> None
```
Remove `key` from this session, if present (preserves the marker).
#### `clear` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L281" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
clear(self) -> None
```
Empty the session's user state but keep the session valid.
The user-state sub-dict is reset to empty while the creation marker stays
in place, so a cleared session still resolves through `get_session`.
To invalidate a session entirely, use `end` (what `end_session` calls).
#### `end` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L294" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
end(self) -> None
```
Invalidate the session — delete its one key and all of its state.
After this the id no longer resolves through `get_session`. This is
what `end_session` calls; `clear` only empties state and keeps the session.
### `UserSession` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L303" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Annotation marker for the injected per-user session.
A `session: UserSession` parameter is **dependency-injected** like
`ctx: Context`: keyed by the request's authenticated principal, excluded from
the input schema, and requiring auth (it raises `SessionAuthError` with no
principal). It doubles as the injection *annotation* and the injected
type — the value a handler receives is a `UserSession`, which subclasses
`Session`, so `await session.get(...)`, `.set`, `.delete`, and `.clear` all
work exactly as on any other `Session`.
Unlike `session_id: SessionId`, the per-user bucket needs no `create_session`,
no `SessionProvider`, and no validation — it is always available under auth,
keyed directly by the caller's identity.
```python
from fastmcp.server.sessions import UserSession
@mcp.tool
async def remember(fact: str, session: UserSession) -> str:
await session.set("fact", fact)
return "noted"
```
Subclasses `Session` only so the framework's type-based injection detector can
key off it; it adds no behavior of its own.
### `SessionProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/sessions.py#L501" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Provider contributing the session lifecycle tools.
Register it whenever a tool declares a `session_id: SessionId` argument:
```python
from fastmcp.server.sessions import SessionProvider
mcp.add_provider(SessionProvider())
```
It registers two tools:
- `create_session()` mints an unguessable `uuid4`, records the session, and
returns the id.
- `end_session(session_id)` invalidates that session and deletes its state.
It owns no storage (session state lives in the server's configured
`session_state_store`) and imposes no TTL (retention is the store's). It
exists to mint and end owned session ids. Registration is not enforced: with
no provider, no id can be created, so every `get_session(...)` rejects —
a `session_id` tool without a provider simply cannot resolve a session.

View file

@ -0,0 +1,117 @@
---
title: telemetry
sidebarTitle: telemetry
---
# `fastmcp.server.telemetry`
Server-side telemetry helpers.
## Functions
### `get_auth_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L43" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_auth_span_attributes() -> dict[str, str]
```
Get auth attributes for the current request, if authenticated.
### `get_session_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L60" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_session_span_attributes() -> dict[str, str]
```
Get session attributes for the current request.
### `get_protocol_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L74" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_protocol_span_attributes() -> dict[str, str]
```
Get the negotiated MCP protocol version for the current request.
Mirrors the `mcp.protocol.version` attribute the SDK's own
`OpenTelemetryMiddleware` sets — FastMCP drops that middleware to avoid a
duplicate SERVER span, so this restores the attribute on FastMCP's span.
### `record_span_exception` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L154" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
record_span_exception(span: Span, e: Exception) -> None
```
Record an exception and error status on a span.
### `seam_span` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
seam_span(method: str, server_name: str) -> Generator[Span, None, None]
```
Open the per-request SERVER span at the FastMCP middleware seam.
The span is named after the method and carries the base MCP attributes
(`mcp.method.name`, `fastmcp.server.name`, auth/session context) so
seam-only methods (`logging/setLevel`, `tasks/*`, `ping`, `initialize`, ...)
are fully attributed even though they never reach the high-level path. It is
marked with `SEAM_SPAN_MARKER` so a later `server_span` call in the
high-level path enriches this span with component attributes instead of
opening a second one. Exceptions raised anywhere below the seam — including
rejections *before* the high-level path (auth, not-found, middleware vetoes)
that would otherwise produce no SERVER span at all — are recorded here.
In `propagation_only` mode no span is opened at all — this is the one place
that has to know the difference, because the seam is where the incoming
`_meta` parent context is applied for the whole request.
### `server_span` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L224" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
server_span(name: str, method: str, server_name: str, component_type: str, component_key: str, resource_uri: str | None = None, tool_name: str | None = None, prompt_name: str | None = None) -> Generator[Span, None, None]
```
Emit or enrich a SERVER span with standard MCP attributes and auth context.
When the current active span is the request's seam span (opened by
`FastMCPServerMiddleware` and marked with `SEAM_SPAN_MARKER`), this sets the
component attributes on that span and yields it *without* starting a second
span — so failures rejected before this point and the successful high-level
call share one richly-attributed SERVER span. Otherwise (non-seam contexts,
e.g. in-process `mcp.call_tool()` calls that bypass the dispatcher) it opens a
new SERVER span as before.
Automatically records any exception on the span and sets error status.
In `propagation_only` mode no span is opened or enriched. The seam has
normally already attached the incoming parent context for this request;
doing it again here is a no-op, and covers the in-process callers that
bypass the dispatcher and so never reach the seam at all.
### `delegate_span` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/telemetry.py#L305" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
delegate_span(name: str, provider_type: str, component_key: str, method: str | None = None) -> Generator[Span, None, None]
```
Create an INTERNAL span for provider delegation.
Used by FastMCPProvider when delegating to mounted servers.
Automatically records any exception on the span and sets error status.

View file

@ -0,0 +1,193 @@
---
title: transforms
sidebarTitle: transforms
---
# `fastmcp.server.transforms`
Transform system for component transformations.
Transforms modify components (tools, resources, prompts). List operations use a pure
function pattern where transforms receive sequences and return transformed sequences.
Get operations use a middleware pattern with `call_next` to chain lookups.
Unlike middleware (which operates on requests), transforms are observable by the
system for task registration, tag filtering, and component introspection.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.transforms import Namespace
server = FastMCP("Server")
mount = server.mount(other_server)
mount.add_transform(Namespace("api")) # Tools become api_toolname
```
## Classes
### `GetToolNext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for get_tool call_next functions.
### `GetResourceNext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L44" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for get_resource call_next functions.
### `GetResourceTemplateNext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L52" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for get_resource_template call_next functions.
### `GetPromptNext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L60" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for get_prompt call_next functions.
### `Transform` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L68" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base class for component transformations.
List operations use a pure function pattern: transforms receive sequences
and return transformed sequences. Get operations use a middleware pattern
with `call_next` to chain lookups.
**Methods:**
#### `list_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L95" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]
```
List tools with transformation applied.
**Args:**
- `tools`: Sequence of tools to transform.
**Returns:**
- Transformed sequence of tools.
#### `get_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_tool(self, name: str, call_next: GetToolNext) -> Tool | None
```
Get a tool by name.
**Args:**
- `name`: The requested tool name (may be transformed).
- `call_next`: Callable to get tool from downstream.
- `version`: Optional version filter to apply.
**Returns:**
- The tool if found, None otherwise.
#### `list_resources` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resources(self, resources: Sequence[Resource]) -> Sequence[Resource]
```
List resources with transformation applied.
**Args:**
- `resources`: Sequence of resources to transform.
**Returns:**
- Transformed sequence of resources.
#### `get_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L136" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None
```
Get a resource by URI.
**Args:**
- `uri`: The requested resource URI (may be transformed).
- `call_next`: Callable to get resource from downstream.
- `version`: Optional version filter to apply.
**Returns:**
- The resource if found, None otherwise.
#### `list_resource_templates` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L159" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resource_templates(self, templates: Sequence[ResourceTemplate]) -> Sequence[ResourceTemplate]
```
List resource templates with transformation applied.
**Args:**
- `templates`: Sequence of resource templates to transform.
**Returns:**
- Transformed sequence of resource templates.
#### `get_resource_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L172" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> ResourceTemplate | None
```
Get a resource template by URI.
**Args:**
- `uri`: The requested template URI (may be transformed).
- `call_next`: Callable to get template from downstream.
- `version`: Optional version filter to apply.
**Returns:**
- The resource template if found, None otherwise.
#### `list_prompts` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L195" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_prompts(self, prompts: Sequence[Prompt]) -> Sequence[Prompt]
```
List prompts with transformation applied.
**Args:**
- `prompts`: Sequence of prompts to transform.
**Returns:**
- Transformed sequence of prompts.
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/transforms/__init__.py#L206" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt(self, name: str, call_next: GetPromptNext) -> Prompt | None
```
Get a prompt by name.
**Args:**
- `name`: The requested prompt name (may be transformed).
- `call_next`: Callable to get prompt from downstream.
- `version`: Optional version filter to apply.
**Returns:**
- The prompt if found, None otherwise.

View file

@ -7,7 +7,7 @@ sidebarTitle: settings
## Classes
### `Settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L32" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `Settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
FastMCP settings.
@ -15,7 +15,7 @@ FastMCP settings.
**Methods:**
#### `get_setting` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L44" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `get_setting` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_setting(self, attr: str) -> Any
@ -25,7 +25,7 @@ Get a setting. If the setting contains one or more `__`, it will be
treated as a nested setting.
#### `set_setting` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L57" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `set_setting` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L59" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_setting(self, attr: str, value: Any) -> None
@ -35,7 +35,7 @@ Set a setting. If the setting contains one or more `__`, it will be
treated as a nested setting.
#### `normalize_log_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `normalize_log_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L81" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
normalize_log_level(cls, v)

View file

@ -31,7 +31,52 @@ Example usage with SDK:
## Functions
### `get_tracer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L81" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `telemetry_mode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L86" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
telemetry_mode() -> 'TelemetryMode'
```
Resolve the effective telemetry mode for the current context.
This is `fastmcp.settings.telemetry_mode`, except that an active
`suppress_fastmcp_telemetry()` block downgrades `native` to
`propagation_only`. Suppression never upgrades or overrides `off`: `off`
means FastMCP touches nothing, and a narrower request to skip FastMCP's
spans cannot re-enable the context propagation `off` deliberately omits.
### `native_spans_enabled` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L103" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
native_spans_enabled() -> bool
```
Whether FastMCP should create its own spans right now.
### `suppress_fastmcp_telemetry` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L109" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
suppress_fastmcp_telemetry() -> Iterator[None]
```
Suppress FastMCP's own spans without disabling trace propagation.
Scoped equivalent of `telemetry_mode="propagation_only"`, for callers that
embed FastMCP inside their own instrumented stack and want to own the MCP
span hierarchy for a specific block. Narrower than OpenTelemetry's global
instrumentation suppression: only FastMCP's spans are skipped, so nested
instrumentation (HTTP clients, databases) keeps emitting, and trace context
still flows through `_meta` so those spans are parented correctly.
Has no effect when `telemetry_mode` is already `off`.
### `get_tracer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L128" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_tracer(version: str | None = None) -> Tracer
@ -42,21 +87,22 @@ Get the FastMCP tracer for creating spans.
Instrumentation is on by default. FastMCP uses only the OpenTelemetry API,
so span creation is a no-op with negligible overhead unless an OpenTelemetry
SDK and exporter are configured. Set `fastmcp.settings.enable_telemetry` to
False (env `FASTMCP_ENABLE_TELEMETRY=false`) to turn instrumentation off
entirely, in which case this returns a pass-through tracer that leaves the
current OTel context untouched even when an SDK is configured.
SDK and exporter are configured. When `fastmcp.settings.telemetry_mode` is
`propagation_only` or `off` — or the caller is inside a
`suppress_fastmcp_telemetry()` block — this returns a pass-through tracer
that creates no spans and leaves the current OTel context untouched even
when an SDK is configured.
**Args:**
- `version`: Optional version string for the instrumentation
**Returns:**
- A tracer instance. Returns a non-attaching pass-through tracer if
- telemetry is disabled; span creation is otherwise a no-op unless an SDK
- is configured.
- A tracer instance. Returns a non-attaching pass-through tracer when
- FastMCP's own spans are disabled; span creation is otherwise a no-op
- unless an SDK is configured.
### `inject_trace_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `inject_trace_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L152" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
inject_trace_context(meta: dict[str, Any] | None = None) -> dict[str, Any] | None
@ -73,7 +119,7 @@ Inject current trace context into a meta dict for MCP request propagation.
- or None if no trace context to inject and meta was None
### `record_span_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L132" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `record_span_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L183" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
record_span_error(span: Span, exception: BaseException) -> None
@ -83,7 +129,7 @@ record_span_error(span: Span, exception: BaseException) -> None
Record an exception on a span and set error status.
### `restore_dropped_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L158" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `restore_dropped_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L209" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
restore_dropped_attributes(span: Span, attrs: Mapping[str, otel_types.AttributeValue]) -> None
@ -133,7 +179,7 @@ kept at call sites so it reads alongside the sibling `is_recording()`
guards already in those functions.
### `extract_trace_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L212" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `extract_trace_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L263" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
extract_trace_context(meta: dict[str, Any] | None) -> Context

View file

@ -16,7 +16,7 @@ callers.
## Functions
### `parse_docstring` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/docstring_parsing.py#L35" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `parse_docstring` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/docstring_parsing.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring
@ -32,7 +32,7 @@ docstring as the description with no parameter descriptions.
## Classes
### `ParsedDocstring` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/docstring_parsing.py#L28" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ParsedDocstring` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/docstring_parsing.py#L26" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
The extracted description and per-parameter descriptions from a docstring.

View file

@ -7,13 +7,53 @@ sidebarTitle: exceptions
## Functions
### `iter_exc` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `is_http_status_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L19" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_http_status_error(exc: BaseException) -> bool
```
Return whether an exception is an httpx2 or legacy-httpx status error.
### `get_http_status_code` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L26" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_http_status_code(exc: BaseException) -> int | None
```
Return the response status code from a recognized HTTP status error.
### `is_timeout_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_timeout_error(exc: BaseException) -> bool
```
Return whether an exception is an httpx2 or legacy-httpx timeout.
### `is_request_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_request_error(exc: BaseException) -> bool
```
Return whether an exception is an httpx2 or legacy-httpx request error.
### `iter_exc` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L48" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
iter_exc(group: BaseExceptionGroup)
```
### `get_catch_handlers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L64" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `get_catch_handlers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_catch_handlers() -> Mapping[type[BaseException] | Iterable[type[BaseException]], Callable[[BaseExceptionGroup[Any]], Any]]

View file

@ -42,7 +42,7 @@ Extract information from a FastMCP v1.x instance using a Client.
- FastMCPInfo dataclass containing the extracted information
### `inspect_fastmcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L411" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `inspect_fastmcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L413" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
inspect_fastmcp(mcp: FastMCP[Any] | SDKServer) -> FastMCPInfo
@ -61,7 +61,7 @@ and uses the appropriate extraction method.
- FastMCPInfo dataclass containing the extracted information
### `format_fastmcp_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L436" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `format_fastmcp_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L438" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
format_fastmcp_info(info: FastMCPInfo) -> bytes
@ -73,7 +73,7 @@ Format FastMCPInfo as FastMCP-specific JSON.
This includes FastMCP-specific fields like tags, enabled, annotations, etc.
### `format_mcp_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L465" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `format_mcp_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L467" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
format_mcp_info(mcp: FastMCP[Any] | SDKServer) -> bytes
@ -86,7 +86,7 @@ Uses Client to get the standard MCP protocol format with camelCase fields.
Includes version metadata at the top level.
### `format_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L500" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `format_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L502" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
format_info(mcp: FastMCP[Any] | SDKServer, format: InspectFormat | Literal['fastmcp', 'mcp'], info: FastMCPInfo | None = None) -> bytes
@ -136,7 +136,7 @@ Information about a resource template.
Information extracted from a FastMCP instance.
### `InspectFormat` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L429" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `InspectFormat` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L431" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Output format for inspect command.

View file

@ -7,7 +7,17 @@ sidebarTitle: json_schema
## Functions
### `require_discriminator_property` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L149" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `replace_refs` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L7" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
replace_refs(*args: Any, **kwargs: Any) -> Any
```
Call jsonref lazily while preserving the module's patchable boundary.
### `require_discriminator_property` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L154" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
require_discriminator_property(schema: dict[str, Any]) -> dict[str, Any]
@ -24,7 +34,7 @@ model with ``union_tag_not_found``. No-op if there is no string
``propertyName``.
### `dereference_refs` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L180" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `dereference_refs` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L185" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
dereference_refs(schema: dict[str, Any]) -> dict[str, Any]
@ -57,7 +67,7 @@ schemas from untrusted servers.
- when no longer needed
### `resolve_root_ref` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L327" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `resolve_root_ref` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L336" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resolve_root_ref(schema: dict[str, Any]) -> dict[str, Any]
@ -79,7 +89,7 @@ the referenced definition while preserving $defs for nested references.
- if no resolution is needed
### `compress_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L741" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `compress_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L750" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
compress_schema(schema: dict[str, Any], prune_params: list[str] | None = None, prune_additional_properties: bool = False, prune_titles: bool = False, dereference: bool = False) -> dict[str, Any]

View file

@ -10,7 +10,7 @@ Logging utilities for FastMCP.
## Functions
### `get_logger` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L14" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `get_logger` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_logger(name: str) -> logging.Logger
@ -26,7 +26,7 @@ Get a logger nested under FastMCP namespace.
- a configured logger instance
### `configure_logging` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `configure_logging` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
configure_logging(level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | int = 'INFO', logger: logging.Logger | None = None, enable_rich_tracebacks: bool | None = None, **rich_kwargs: Any) -> None
@ -41,7 +41,7 @@ Configure logging for FastMCP.
- `rich_kwargs`: the parameters to use for creating RichHandler
### `temporary_log_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `temporary_log_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L127" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
temporary_log_level(level: str | None, logger: logging.Logger | None = None, enable_rich_tracebacks: bool | None = None, **rich_kwargs: Any)

View file

@ -0,0 +1,61 @@
---
title: prefab
sidebarTitle: prefab
---
# `fastmcp.utilities.prefab`
Lazy helpers for FastMCP's optional Prefab UI integration.
## Functions
### `prefab_available` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/prefab.py#L12" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prefab_available() -> bool
```
Return whether Prefab UI is installed without importing it.
### `is_prefab_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/prefab.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_prefab_type(candidate: Any) -> bool
```
Return whether a type is a Prefab app or component type.
### `is_prefab_app` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/prefab.py#L51" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_prefab_app(value: Any) -> bool
```
Return whether a value is a Prefab app.
### `is_prefab_component` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/prefab.py#L60" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_prefab_component(value: Any) -> bool
```
Return whether a value is a Prefab component.
### `prefab_app_from_component` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/prefab.py#L69" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prefab_app_from_component(component: Any) -> Any
```
Wrap a Prefab component in a Prefab app.

View file

@ -315,8 +315,10 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
**`"remember"` — silent consent on return:**
Users see the consent screen on first authorization; subsequent flows from the same browser for the same `(client_id, redirect_uri)` are silently approved via a signed cookie. Cross-site navigations (detected via `Sec-Fetch-Site`) fall back to the prompt. `Sec-Fetch-Site` is a browser-level heuristic rather than a protocol guarantee: an attacker who finds a way to initiate a non-cross-site navigation (XSS on a sibling origin, a same-site redirect chain, etc.) can reach the silent-consent path. `True` does not depend on this signal. See [Confused Deputy Attacks](#confused-deputy-attacks) for the underlying attack class.
**`"external"` — delegate to upstream:**
Skip the built-in consent page; consent is collected by the upstream IdP or a custom login page referenced via `upstream_authorization_endpoint`. No security warning is logged.
**`"external"` — externally managed:**
Follows the same authorization path as `False`: FastMCP skips its consent page and associated browser-binding protections, then redirects directly to the upstream provider. The difference is logging. `False` emits a security warning, while `"external"` suppresses that warning as an explicit acknowledgment that the operator is enforcing equivalent consent and transaction-binding protections elsewhere. FastMCP does not provide or verify those external protections.
Ordinary upstream OAuth consent is generally not equivalent. It typically authorizes FastMCP's shared upstream application without identifying the downstream MCP client or binding approval to that client's transaction. Use `"external"` only when your surrounding authorization system supplies those protections.
**`False` — disable entirely:**
Authorization proceeds directly to the upstream provider without any consent UI. Logs a security warning. Only for local development or testing.
@ -336,7 +338,7 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
```
<Warning>
Disabling consent removes an important security layer. Only disable for local development or testing environments where you fully control all connecting clients.
Both `False` and `"external"` disable FastMCP's consent and browser-binding protections. `False` warns about this configuration; `"external"` suppresses the warning because it is an operator acknowledgment that equivalent protections exist elsewhere. Prefer the default `True` unless you own that external authorization flow.
</Warning>
</ParamField>

View file

@ -206,7 +206,7 @@ auth = OIDCProxy(
</ParamField>
<ParamField body="require_authorization_consent" type='bool | Literal["remember", "external"]' default="True">
Consent screen behavior for authorization requests. Accepts `True` (default; always prompt — strongest protection), `"remember"` (silent consent on return visits via signed cookie, gated by `Sec-Fetch-Site` to block AS-in-the-middle attacks), `"external"` (consent handled by upstream IdP or custom page), or `False` (disable entirely; local/testing only). See the [OAuthProxy documentation](/servers/auth/oauth-proxy) for full details on each mode and the security trade-offs.
Consent screen behavior for authorization requests. Accepts `True` (default; always prompt — strongest protection), `"remember"` (silent consent on return visits via signed cookie, gated by `Sec-Fetch-Site` to block AS-in-the-middle attacks), `"external"` (same authorization path as `False`, but the warning is suppressed because the operator asserts that equivalent protections are enforced externally), or `False` (disable entirely; local/testing only). See the [OAuthProxy documentation](/servers/auth/oauth-proxy) for full details on each mode and the security trade-offs.
</ParamField>
<ParamField body="consent_csp_policy" type="str | None" default="None">

View file

@ -80,6 +80,19 @@ This configuration creates a server that validates JWTs issued by `auth.yourcomp
The `issuer` parameter ensures tokens come from your trusted authentication system, while `audience` validation prevents tokens intended for other services from being accepted by your MCP server.
`JWTVerifier` accepts RSA (`RS*` and `PS*`), ECDSA (`ES*`), and Edwards-curve (`Ed25519` and `Ed448`) signatures from JWKS endpoints. Set `algorithm` when your issuer does not use the default `RS256`:
```python
verifier = JWTVerifier(
jwks_uri="https://auth.yourcompany.com/.well-known/jwks.json",
issuer="https://auth.yourcompany.com",
audience="mcp-production-api",
algorithm="Ed25519",
)
```
The legacy `EdDSA` identifier is also accepted for compatibility with identity providers that have not yet adopted the fully specified identifiers from RFC 9864.
### Symmetric Key Verification (HMAC)
Symmetric key verification uses a shared secret for both signing and validation, making it ideal for internal microservices and trusted environments where the same secret can be securely distributed to both token issuers and validators.
@ -121,7 +134,7 @@ The parameter is named `public_key` for backwards compatibility, but when using
### Static Public Key Verification
Static public key verification works when you have a fixed RSA or ECDSA signing key and don't need automatic key rotation. This approach is primarily useful for development environments or controlled deployments where JWKS endpoints aren't available.
Static public key verification works when you have a fixed RSA, ECDSA, or EdDSA signing key and don't need automatic key rotation. This approach is primarily useful for development environments or controlled deployments where JWKS endpoints aren't available.
```python
from fastmcp import FastMCP
@ -141,7 +154,7 @@ verifier = JWTVerifier(
mcp = FastMCP(name="Protected API", auth=verifier)
```
This configuration validates tokens using a specific RSA or ECDSA public key. The key must correspond to the private key used by your token issuer. While less flexible than JWKS endpoints, this approach can be useful in development environments or when testing with fixed keys.
This configuration validates tokens using a specific RSA, ECDSA, or EdDSA public key. The key must correspond to the private key used by your token issuer. While less flexible than JWKS endpoints, this approach can be useful in development environments or when testing with fixed keys.
## Opaque Token Verification
Many authorization servers issue opaque tokens rather than self-contained JWTs. Opaque tokens are random strings that carry no information themselves - the authorization server maintains their state and validation requires querying the server. FastMCP supports opaque token validation through OAuth 2.0 Token Introspection (RFC 7662).
@ -425,4 +438,3 @@ mcp = FastMCP(name="Production API", auth=verifier)
This keeps configuration out of your codebase while maintaining explicit setup.
This approach enables the same codebase to run across development, staging, and production environments with different authentication requirements. Development might use static tokens while production uses JWT verification, all controlled through environment configuration.

View file

@ -310,6 +310,22 @@ async def on_initialize(self, context: MiddlewareContext, call_next):
Rejection works only **before** `call_next()`. Raising `McpError` afterward logs the error without sending it — the client still receives a successful initialize response.
</Warning>
#### on_discover
Called when a modern client negotiates through `server/discover`. Core discovery responses are returned as `DiscoverResult`; extension-owned result types are returned as dictionaries and should be passed through unless the middleware handles that extension.
```python
from mcp_types import DiscoverResult
async def on_discover(self, context, call_next):
result = await call_next(context)
if not isinstance(result, DiscoverResult):
return result
return result.model_copy(update={"instructions": "Custom instructions"})
```
Fields such as `supported_versions`, `capabilities`, and cache policy should only be changed when the server's public behavior also changes.
### Raw Handler
For complete control over all messages, override `__call__` instead of individual hooks:

View file

@ -60,11 +60,9 @@ To mount a proxy inside another FastMCP server, see [Mounting External Servers](
## Connection Semantics
FastMCP proxies are lazy bridges. Creating the proxy object and starting the local server do not contact the upstream server. The upstream connection begins when an MCP client sends an `initialize` request to the proxy.
FastMCP proxies are lazy bridges. Creating the proxy object and starting the local server do not contact the upstream server. During client negotiation, the proxy makes a best-effort request for optional server metadata using the backend client's existing lifecycle and negotiation mode; an unavailable backend does not prevent the client from connecting to the proxy.
During initialization, the proxy initializes the upstream server before responding locally. If the upstream server is unavailable, the URL does not point to an MCP endpoint, or upstream authentication cannot complete, the proxy initialization fails. This keeps the local proxy's connection status aligned with the upstream server it represents.
After initialization, the proxy forwards MCP requests such as `ping`, `tools/list`, `resources/list`, `prompts/list`, tool calls, resource reads, sampling, elicitation, logging, and progress through the upstream client.
Subsequent MCP requests such as `ping`, `tools/list`, `resources/list`, `prompts/list`, tool calls, resource reads, sampling, elicitation, logging, and progress connect to the backend as needed. Component provider failures follow `provider_error_strategy`: the default `"warn"` logs and skips a failed provider, while `"raise"` reports the failure to the client.
## Transport Bridging
@ -240,6 +238,10 @@ proxy = create_proxy(
A modern client here reaches both `weather` and `calendar` on modern sessions, so a guard tool on either one round-trips end to end. An explicit `mode` pins every backend in the configuration, the same way it pins a single one.
### Request Metadata
Request `_meta` follows the same connection boundary. Progress tokens, tracing, task state, and application or vendor metadata pass through the proxy to the backend. The connection-owned keys — protocol version, client identity, and client capabilities — never copy from the frontend connection: a modern backend session stamps its own negotiated values, and a handshake-era backend receives none. This holds even when the two connections negotiate different eras, such as a modern client reaching a handshake-only backend through an explicit `mode`.
## Configuration-Based Proxies
<VersionBadge version="2.4.0" />
@ -384,6 +386,28 @@ Only reuse sessions when you know the backend is stateless (e.g. stateless HTTP)
## Advanced Usage
### Forwarding Server Metadata
Add `ProxyMetadataMiddleware` when a gateway built with `ProxyProvider` should also expose backend instructions and namespaced `_meta`:
```python
from fastmcp import FastMCP
from fastmcp.server.providers.proxy import (
ProxyClient,
ProxyMetadataMiddleware,
ProxyProvider,
)
backend = ProxyProvider(lambda: ProxyClient("http://backend:8000/mcp", mode="auto"))
gateway = FastMCP(
"Controlled Gateway",
providers=[backend],
middleware=[ProxyMetadataMiddleware(backend)],
)
```
By default the gateway keeps its own `serverInfo`; pass `identity="upstream"` to use the backend identity when available. Frontend instructions and `_meta` values win on collisions. The middleware never copies upstream protocol versions, connection metadata, capabilities, cache policy, `resultType`, or unknown top-level fields. If the backend is unavailable, the client can still connect without its optional metadata.
### FastMCPProxy Class
For explicit session control, use `FastMCPProxy` directly:

View file

@ -162,6 +162,7 @@ mcp.add_extension(TasksExtension(url="redis://localhost:6379/0", concurrency=20)
| `FASTMCP_DOCKET_URL` | `memory://` | Backend URL (`memory://` or `redis://host:port/db`) |
| `FASTMCP_DOCKET_NAME` | `fastmcp` | Queue name. Servers and workers sharing a name and URL share a queue. |
| `FASTMCP_DOCKET_CONCURRENCY` | `10` | Maximum concurrent tasks per worker. |
| `FASTMCP_TASKS_ENCRYPTION_KEY` | (unset) | Encrypts [task context snapshots at rest](#credentials-at-rest). Every server and worker sharing a queue must set the same key. |
## Backends
@ -193,6 +194,28 @@ mcp.add_extension(TasksExtension(url="redis://localhost:6379/0"))
- **Fast**: Single-digit millisecond task pickup latency
- **Scalable**: Add workers to distribute load across processes or machines
### Credentials at Rest
A background task runs long after the request that submitted it has ended, but it still needs to know who asked for the work. FastMCP captures that identity at submission time in a **task context snapshot**: the caller's access token and every inbound HTTP header, including `Authorization`. The worker restores the snapshot before the tool body runs, so `get_access_token()` and `get_http_headers()` return the submitting caller.
That snapshot lives in the backend for the task's TTL. With `memory://` it never leaves the process. With Redis or Valkey it is a stored value, and by default it is stored as plaintext JSON. A `rediss://` URL encrypts the connection, not the data the backend holds. Anyone who can read the backend can read the tokens.
Set `FASTMCP_TASKS_ENCRYPTION_KEY` to encrypt the snapshot before it is written:
```bash
export FASTMCP_TASKS_ENCRYPTION_KEY=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
```
<Warning>
Every server and worker on the same queue must set the same key. The process that restores a snapshot is rarely the one that captured it, and a worker with the wrong key cannot recover the caller.
</Warning>
With a key configured, restore **fails closed**: a worker that cannot decrypt a snapshot fails the task instead of running the tool with no identity. This matters for a tool whose behavior depends on the caller: running it as an anonymous user is worse than not running it. The failure is reported to the client as a task error, and the server log names the key mismatch.
Two consequences of failing closed are worth planning for. Tasks submitted before the key was set fail when a worker with the key picks them up, so drain the queue before you roll a key out. Rotating a key does the same to tasks in flight under the old one.
The key protects the snapshot only. Tool arguments and any answers a task gathers through [mid-task input](#gathering-input-mid-task) are still stored as plaintext, so treat the backend as sensitive regardless.
## Workers
Every FastMCP server with task-enabled tools automatically starts an **embedded worker**. You do not need to start a separate worker process for tasks to execute.

View file

@ -5,6 +5,16 @@ icon: "sparkles"
tag: NEW
---
<Update label="FastMCP 3.4.6" description="August 5, 2026" tags={["Releases"]}>
<Card
title="FastMCP v3.4.6: Trust, but Proxy"
href="https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.6"
cta="Read the release notes"
>
FastMCP 3.4.6 adds trusted-proxy support for SSRF-protected OAuth metadata and JWKS fetches on the 3.x line. Deployments can route these requests through a mandated corporate proxy while preserving custom CA certificates, and FastMCP refuses the fetch when no proxy is configured instead of risking an unprotected direct request.
</Card>
</Update>
<Update label="FastMCP 4.0.0b1" description="July 28, 2026" tags={["Releases"]}>
<Card
title="FastMCP v4.0.0b1: Fourgone Conclusion"

View file

@ -296,8 +296,10 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
**`"remember"` — silent consent on return:**
Users see the consent screen on first authorization; subsequent flows from the same browser for the same `(client_id, redirect_uri)` are silently approved via a signed cookie. Cross-site navigations (detected via `Sec-Fetch-Site`) fall back to the prompt. `Sec-Fetch-Site` is a browser-level heuristic rather than a protocol guarantee: an attacker who finds a way to initiate a non-cross-site navigation (XSS on a sibling origin, a same-site redirect chain, etc.) can reach the silent-consent path. `True` does not depend on this signal. See [Confused Deputy Attacks](#confused-deputy-attacks) for the underlying attack class.
**`"external"` — delegate to upstream:**
Skip the built-in consent page; consent is collected by the upstream IdP or a custom login page referenced via `upstream_authorization_endpoint`. No security warning is logged.
**`"external"` — externally managed:**
Follows the same authorization path as `False`: FastMCP skips its consent page and associated browser-binding protections, then redirects directly to the upstream provider. The difference is logging. `False` emits a security warning, while `"external"` suppresses that warning as an explicit acknowledgment that the operator is enforcing equivalent consent and transaction-binding protections elsewhere. FastMCP does not provide or verify those external protections.
Ordinary upstream OAuth consent is generally not equivalent. It typically authorizes FastMCP's shared upstream application without identifying the downstream MCP client or binding approval to that client's transaction. Use `"external"` only when your surrounding authorization system supplies those protections.
**`False` — disable entirely:**
Authorization proceeds directly to the upstream provider without any consent UI. Logs a security warning. Only for local development or testing.
@ -317,7 +319,7 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
```
<Warning>
Disabling consent removes an important security layer. Only disable for local development or testing environments where you fully control all connecting clients.
Both `False` and `"external"` disable FastMCP's consent and browser-binding protections. `False` warns about this configuration; `"external"` suppresses the warning because it is an operator acknowledgment that equivalent protections exist elsewhere. Prefer the default `True` unless you own that external authorization flow.
</Warning>
</ParamField>

View file

@ -199,7 +199,7 @@ auth = OIDCProxy(
</ParamField>
<ParamField body="require_authorization_consent" type='bool | Literal["remember", "external"]' default="True">
Consent screen behavior for authorization requests. Accepts `True` (default; always prompt — strongest protection), `"remember"` (silent consent on return visits via signed cookie, gated by `Sec-Fetch-Site` to block AS-in-the-middle attacks), `"external"` (consent handled by upstream IdP or custom page), or `False` (disable entirely; local/testing only). See the [OAuthProxy documentation](/v2/servers/auth/oauth-proxy) for full details on each mode and the security trade-offs.
Consent screen behavior for authorization requests. Accepts `True` (default; always prompt — strongest protection), `"remember"` (silent consent on return visits via signed cookie, gated by `Sec-Fetch-Site` to block AS-in-the-middle attacks), `"external"` (same authorization path as `False`, but the warning is suppressed because the operator asserts that equivalent protections are enforced externally), or `False` (disable entirely; local/testing only). See the [OAuthProxy documentation](/v2/servers/auth/oauth-proxy) for full details on each mode and the security trade-offs.
</ParamField>
<ParamField body="consent_csp_policy" type="str | None" default="None">

View file

@ -310,8 +310,10 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
**`"remember"` — silent consent on return:**
Users see the consent screen on first authorization; subsequent flows from the same browser for the same `(client_id, redirect_uri)` are silently approved via a signed cookie. Cross-site navigations (detected via `Sec-Fetch-Site`) fall back to the prompt. `Sec-Fetch-Site` is a browser-level heuristic rather than a protocol guarantee: an attacker who finds a way to initiate a non-cross-site navigation (XSS on a sibling origin, a same-site redirect chain, etc.) can reach the silent-consent path. `True` does not depend on this signal. See [Confused Deputy Attacks](#confused-deputy-attacks) for the underlying attack class.
**`"external"` — delegate to upstream:**
Skip the built-in consent page; consent is collected by the upstream IdP or a custom login page referenced via `upstream_authorization_endpoint`. No security warning is logged.
**`"external"` — externally managed:**
Follows the same authorization path as `False`: FastMCP skips its consent page and associated browser-binding protections, then redirects directly to the upstream provider. The difference is logging. `False` emits a security warning, while `"external"` suppresses that warning as an explicit acknowledgment that the operator is enforcing equivalent consent and transaction-binding protections elsewhere. FastMCP does not provide or verify those external protections.
Ordinary upstream OAuth consent is generally not equivalent. It typically authorizes FastMCP's shared upstream application without identifying the downstream MCP client or binding approval to that client's transaction. Use `"external"` only when your surrounding authorization system supplies those protections.
**`False` — disable entirely:**
Authorization proceeds directly to the upstream provider without any consent UI. Logs a security warning. Only for local development or testing.
@ -331,7 +333,7 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
```
<Warning>
Disabling consent removes an important security layer. Only disable for local development or testing environments where you fully control all connecting clients.
Both `False` and `"external"` disable FastMCP's consent and browser-binding protections. `False` warns about this configuration; `"external"` suppresses the warning because it is an operator acknowledgment that equivalent protections exist elsewhere. Prefer the default `True` unless you own that external authorization flow.
</Warning>
</ParamField>

View file

@ -199,7 +199,7 @@ auth = OIDCProxy(
</ParamField>
<ParamField body="require_authorization_consent" type='bool | Literal["remember", "external"]' default="True">
Consent screen behavior for authorization requests. Accepts `True` (default; always prompt — strongest protection), `"remember"` (silent consent on return visits via signed cookie, gated by `Sec-Fetch-Site` to block AS-in-the-middle attacks), `"external"` (consent handled by upstream IdP or custom page), or `False` (disable entirely; local/testing only). See the [OAuthProxy documentation](/servers/auth/oauth-proxy) for full details on each mode and the security trade-offs.
Consent screen behavior for authorization requests. Accepts `True` (default; always prompt — strongest protection), `"remember"` (silent consent on return visits via signed cookie, gated by `Sec-Fetch-Site` to block AS-in-the-middle attacks), `"external"` (same authorization path as `False`, but the warning is suppressed because the operator asserts that equivalent protections are enforced externally), or `False` (disable entirely; local/testing only). See the [OAuthProxy documentation](/servers/auth/oauth-proxy) for full details on each mode and the security trade-offs.
</ParamField>
<ParamField body="consent_csp_policy" type="str | None" default="None">

View file

@ -6,15 +6,13 @@ from importlib.metadata import PackageNotFoundError, version as _version
from typing import TYPE_CHECKING
from fastmcp import _install_hints
from fastmcp._warnings import FastMCPDeprecationWarning
from fastmcp.settings import Settings
from fastmcp.utilities.logging import configure_logging as _configure_logging
if TYPE_CHECKING:
from fastmcp.client import Client as Client
from fastmcp.apps.app import FastMCPApp as FastMCPApp
from fastmcp.exceptions import (
FastMCPDeprecationWarning as FastMCPDeprecationWarning,
)
from fastmcp.server.context import Context as Context
from fastmcp.server.server import FastMCP as FastMCP
@ -39,12 +37,7 @@ except PackageNotFoundError:
__version__ = _version("fastmcp")
if settings.deprecation_warnings:
try:
from fastmcp.exceptions import FastMCPDeprecationWarning
except ImportError:
pass
else:
warnings.simplefilter("default", FastMCPDeprecationWarning)
warnings.simplefilter("default", FastMCPDeprecationWarning)
# --- Lazy imports for performance (see #3292) ---
@ -81,10 +74,6 @@ def __getattr__(name: str) -> object:
raise ImportError(_install_hints.APP_SUPPORT) from exc
return FastMCPApp
if name == "FastMCPDeprecationWarning":
from fastmcp.exceptions import FastMCPDeprecationWarning
return FastMCPDeprecationWarning
if name == "client":
try:
return importlib.import_module("fastmcp.client")

View file

@ -33,7 +33,7 @@ import warnings
import mcp_types
from fastmcp.exceptions import FastMCPDeprecationWarning
from fastmcp._warnings import FastMCPDeprecationWarning
# Map each SDK model class to the camelCase -> snake_case field reads we bridge.
# Limited to fields FastMCP users actually read (docs boundary inventory).

View file

@ -0,0 +1,10 @@
"""Warning types that can be imported without loading FastMCP's exception stack."""
class FastMCPDeprecationWarning(DeprecationWarning):
"""Deprecation warning for FastMCP APIs.
Subclass of DeprecationWarning so that standard warning filters
still apply, but FastMCP can selectively enable its own warnings
without affecting other libraries in the process.
"""

View file

@ -97,24 +97,33 @@ def _parse_mcp_servers(
if not servers_dict:
return []
normalized = {
name: _normalize_server_entry(entry)
for name, entry in servers_dict.items()
if isinstance(entry, dict)
}
discovered: list[DiscoveredServer] = []
for name, entry in servers_dict.items():
if not isinstance(entry, dict):
continue
try:
config = MCPConfig.from_dict({"mcpServers": normalized})
except Exception as exc:
logger.warning("Could not parse MCP servers from %s: %s", config_path, exc)
return []
normalized = _normalize_server_entry(entry)
try:
config = MCPConfig.from_dict({"mcpServers": {name: normalized}})
except Exception as exc:
logger.warning(
"Could not parse MCP server %r from %s: %s",
name,
config_path,
exc,
)
continue
return [
DiscoveredServer(
name=name, source=source, config=server, config_path=config_path
discovered.append(
DiscoveredServer(
name=name,
source=source,
config=config.mcpServers[name],
config_path=config_path,
)
)
for name, server in config.mcpServers.items()
]
return discovered
def _parse_mcp_config(path: Path, source: str) -> list[DiscoveredServer]:

View file

@ -657,6 +657,11 @@ class Client(
return self._session_state.session
@property
def prior_discover(self) -> mcp_types.DiscoverResult | None:
"""The configured result to adopt when `mode` pins a modern version."""
return self._prior_discover
@property
def initialize_result(self) -> mcp_types.InitializeResult | None:
"""Get the result of the initialization request.
@ -1022,7 +1027,10 @@ class Client(
raise RuntimeError(
"Session task completed without exception but connection failed"
)
raise _connection_failure(exception) from exception
failure = _connection_failure(exception)
if failure is exception:
raise exception
raise failure from exception
self._session_state.nesting_counter += 1

View file

@ -5,6 +5,8 @@ from typing import Any
from mcp_types import INTERNAL_ERROR, INVALID_PARAMS, ErrorData
from fastmcp import _warnings
try:
from mcp import MCPError
except ImportError:
@ -30,14 +32,7 @@ except ImportError:
# see the migration notes.
McpError = MCPError
class FastMCPDeprecationWarning(DeprecationWarning):
"""Deprecation warning for FastMCP APIs.
Subclass of DeprecationWarning so that standard warning filters
still apply, but FastMCP can selectively enable its own warnings
without affecting other libraries in the process.
"""
FastMCPDeprecationWarning = _warnings.FastMCPDeprecationWarning
class FastMCPError(Exception):

View file

@ -45,6 +45,7 @@ from fastmcp import _install_hints
if TYPE_CHECKING:
from fastmcp.client.transports import (
ClientTransport,
FastMCPTransport,
SSETransport,
StdioTransport,
StreamableHttpTransport,
@ -153,7 +154,7 @@ class _TransformingMCPServerMixin(BaseModel):
return wrapped_mcp_server, transport
def to_transport(self) -> ClientTransport:
def to_transport(self) -> FastMCPTransport:
"""Get the transport for the transforming MCP server."""
try:
from fastmcp.client.transports import FastMCPTransport
@ -209,7 +210,7 @@ class StdioMCPServer(BaseModel):
model_config = ConfigDict(extra="allow") # Preserve unknown fields
def to_transport(self) -> StdioTransport:
def to_transport(self) -> StdioTransport | FastMCPTransport:
from fastmcp.client.transports import StdioTransport
return StdioTransport(
@ -261,7 +262,9 @@ class RemoteMCPServer(BaseModel):
extra="allow", arbitrary_types_allowed=True
) # Preserve unknown fields
def to_transport(self) -> StreamableHttpTransport | SSETransport:
def to_transport(
self,
) -> StreamableHttpTransport | SSETransport | FastMCPTransport:
from fastmcp.client.transports import (
SSETransport,
StreamableHttpTransport,

View file

@ -217,7 +217,10 @@ class FunctionPrompt(Prompt):
schema_str = json.dumps(param_schema, separators=(",", ":"))
# Append schema info to description
schema_note = f"Provide as a JSON string matching the following schema: {schema_str}"
schema_note = (
"Provide a value matching the following JSON schema: "
f"{schema_str}. Encode non-string values as JSON."
)
if arg_description:
arg_description = f"{arg_description}\n\n{schema_note}"
else:
@ -263,26 +266,38 @@ class FunctionPrompt(Prompt):
if param_name in sig.parameters:
param = sig.parameters[param_name]
# If parameter has no annotation or annotation is str, pass as-is
if (
param.annotation == inspect.Parameter.empty
or param.annotation is str
) or not isinstance(param_value, str):
if param.annotation == inspect.Parameter.empty or not isinstance(
param_value, str
):
converted_kwargs[param_name] = param_value
else:
# Try to convert string argument using type adapter
try:
adapter = get_cached_typeadapter(param.annotation)
# Try JSON parsing first for complex types
# Preserve the MCP wire string when validation keeps it
# as a string. Non-string results still prefer JSON
# decoding so coercible types such as bytes and Path do
# not retain JSON quote characters.
try:
python_value = adapter.validate_python(param_value)
except (ValueError, TypeError, pydantic_core.ValidationError):
converted_kwargs[param_name] = adapter.validate_json(
param_value
)
except (ValueError, TypeError, pydantic_core.ValidationError):
# Fallback to direct validation
converted_kwargs[param_name] = adapter.validate_python(
param_value
)
else:
if isinstance(python_value, str):
converted_kwargs[param_name] = python_value
else:
try:
converted_kwargs[param_name] = (
adapter.validate_json(param_value)
)
except (
ValueError,
TypeError,
pydantic_core.ValidationError,
):
converted_kwargs[param_name] = python_value
except (ValueError, TypeError, pydantic_core.ValidationError) as e:
# If conversion fails, provide informative error
raise PromptError(

View file

@ -1,17 +1,31 @@
import importlib
from typing import TYPE_CHECKING
from fastmcp import _install_hints
try:
from .context import Context
from .server import FastMCP, create_proxy
except ImportError as exc:
raise ImportError(_install_hints.SERVER_SUPPORT) from exc
if TYPE_CHECKING:
from .context import Context as Context
from .server import FastMCP as FastMCP
from .server import create_proxy as create_proxy
def __getattr__(name: str) -> object:
if name == "dependencies":
return importlib.import_module("fastmcp.server.dependencies")
if name in {"context", "dependencies"}:
return importlib.import_module(f"fastmcp.server.{name}")
if name == "Context":
try:
from .context import Context
except ImportError as exc:
raise ImportError(_install_hints.SERVER_SUPPORT) from exc
return Context
if name in {"FastMCP", "create_proxy"}:
try:
from .server import FastMCP, create_proxy
except ImportError as exc:
raise ImportError(_install_hints.SERVER_SUPPORT) from exc
return FastMCP if name == "FastMCP" else create_proxy
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

View file

@ -397,8 +397,10 @@ class OAuthProxy(OAuthProvider, ConsentMixin):
redirect_uri) in the same browser. Cross-site navigations are
still prompted to block AS-in-the-middle attacks. Lower UX
friction, but weaker protection than True.
- "external": skip the built-in consent screen; consent is handled
externally (e.g. by the upstream IdP or a custom login page).
- "external": follow the same authorization path as False, but
suppress the warning as an operator acknowledgment that equivalent
consent and transaction-binding protections are enforced externally.
FastMCP does not provide or verify those external protections.
- False: skip consent entirely. SECURITY WARNING: only set to
False for local development or testing environments.
consent_csp_policy: Content Security Policy for the consent page.

View file

@ -43,8 +43,7 @@ class AsyncOAuth2Client:
Drop-in replacement for the slice of authlib's `AsyncOAuth2Client` that
`OAuthProxy` uses. Subclasses of `OAuthProxy` that override
`_create_upstream_oauth_client` may return any object with the same
`fetch_token`/`refresh_token`/`client_secret`/`aclose` surface (including
an authlib client, if legacy httpx is installed in their environment).
`fetch_token`/`refresh_token`/`client_secret`/`aclose` surface.
"""
def __init__(

View file

@ -306,8 +306,9 @@ class OIDCProxy(OAuthProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to the upstream IdP.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
consent_csp_policy: Content Security Policy for the consent page.
If None (default), uses the built-in CSP policy with appropriate directives.

View file

@ -104,6 +104,7 @@ class Auth0Provider(OIDCProxy):
fallback_refresh_token_expiry_seconds: int | None = None,
fastmcp_access_token_expiry_seconds: int | None = None,
token_expiry_threshold_seconds: int = 0,
enable_cimd: bool = True,
) -> None:
"""Initialize Auth0 OAuth provider.
@ -134,8 +135,9 @@ class Auth0Provider(OIDCProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to Auth0.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
fallback_refresh_token_expiry_seconds: Lifetime for the FastMCP-issued
refresh token when the upstream provider omits `refresh_expires_in`
@ -148,6 +150,8 @@ class Auth0Provider(OIDCProxy):
refresh gracefully (e.g. `mcp-remote`). See `OAuthProxy` for details.
token_expiry_threshold_seconds: Number of seconds before actual expiry to
treat a token as expired, refreshing early to avoid races. Defaults to 0.
enable_cimd: Enable CIMD (Client ID Metadata Document) support for URL-based
client IDs (default True). Set to False to disable.
"""
# Parse scopes if provided as string
auth0_required_scopes = (
@ -174,6 +178,7 @@ class Auth0Provider(OIDCProxy):
fallback_refresh_token_expiry_seconds=fallback_refresh_token_expiry_seconds,
fastmcp_access_token_expiry_seconds=fastmcp_access_token_expiry_seconds,
token_expiry_threshold_seconds=token_expiry_threshold_seconds,
enable_cimd=enable_cimd,
)
logger.debug(

View file

@ -144,6 +144,7 @@ class AWSCognitoProvider(OIDCProxy):
fallback_refresh_token_expiry_seconds: int | None = None,
fastmcp_access_token_expiry_seconds: int | None = None,
token_expiry_threshold_seconds: int = 0,
enable_cimd: bool = True,
):
"""Initialize AWS Cognito OAuth provider.
@ -174,8 +175,9 @@ class AWSCognitoProvider(OIDCProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to AWS Cognito.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
fallback_refresh_token_expiry_seconds: Lifetime for the FastMCP-issued
refresh token when the upstream provider omits `refresh_expires_in`
@ -188,6 +190,8 @@ class AWSCognitoProvider(OIDCProxy):
refresh gracefully (e.g. `mcp-remote`). See `OAuthProxy` for details.
token_expiry_threshold_seconds: Number of seconds before actual expiry to
treat a token as expired, refreshing early to avoid races. Defaults to 0.
enable_cimd: Enable CIMD (Client ID Metadata Document) support for URL-based
client IDs (default True). Set to False to disable.
"""
# Parse scopes if provided as string
required_scopes_final = (
@ -223,6 +227,7 @@ class AWSCognitoProvider(OIDCProxy):
fallback_refresh_token_expiry_seconds=fallback_refresh_token_expiry_seconds,
fastmcp_access_token_expiry_seconds=fastmcp_access_token_expiry_seconds,
token_expiry_threshold_seconds=token_expiry_threshold_seconds,
enable_cimd=enable_cimd,
)
logger.debug(

View file

@ -173,8 +173,9 @@ class AzureProvider(OAuthProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to Azure.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
http_client: Optional httpx2.AsyncClient for connection pooling in JWKS fetches.
When provided, the client is reused for JWT key fetches and the caller

View file

@ -327,8 +327,9 @@ class ClerkProvider(OAuthProxy):
into a 32-byte key. If not provided, the upstream client secret will be used to
derive a 32-byte key using PBKDF2.
require_authorization_consent: Whether to require user consent before authorizing
clients (default True). When "external", the built-in consent screen is skipped
but no warning is logged, indicating that consent is handled externally by Clerk.
clients (default True). When "external", authorization follows the same direct
path as False, but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
consent_csp_policy: Custom CSP policy for the consent page.
extra_authorize_params: Additional parameters to forward to Clerk's authorization
endpoint. Example: {"prompt": "login"} to force re-authentication.

View file

@ -241,8 +241,9 @@ class DiscordProvider(OAuthProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to Discord.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
http_client: Optional httpx2.AsyncClient for connection pooling in token verification.
When provided, the client is reused across verify_token calls and the caller

View file

@ -257,8 +257,9 @@ class GitHubProvider(OAuthProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to GitHub.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
http_client: Optional httpx2.AsyncClient for connection pooling in token verification.
When provided, the client is reused across verify_token calls and the caller

View file

@ -290,8 +290,9 @@ class GoogleProvider(OAuthProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to Google.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by Google's own consent).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
extra_authorize_params: Additional parameters to forward to Google's authorization endpoint.
By default, GoogleProvider sets {"access_type": "offline", "prompt": "consent"} to ensure

View file

@ -6,7 +6,7 @@ import contextlib
import json
import time
from dataclasses import dataclass
from typing import Any, TypeAlias, cast
from typing import Any, Literal, TypeAlias, cast
import httpx2
from cryptography.hazmat.primitives import serialization
@ -29,22 +29,30 @@ JWKKeyData: TypeAlias = dict[str, str | list[str]]
SUPPORTED_JWS_HEADER_FIELDS = frozenset(JWS_HEADER_REGISTRY)
def _import_key_for_algorithm(key: str | bytes | JWKKeyData, algorithm: str):
def _key_type_for_algorithm(algorithm: str) -> Literal["oct", "RSA", "EC", "OKP"]:
if algorithm.startswith("HS"):
return jwk.import_key(key, "oct")
return "oct"
if algorithm.startswith(("RS", "PS")):
return jwk.import_key(key, "RSA")
return "RSA"
if algorithm.startswith("ES"):
return jwk.import_key(key, "EC")
return "EC"
if algorithm in {"EdDSA", "Ed25519", "Ed448"}:
return "OKP"
raise ValueError(f"Unsupported algorithm: {algorithm}.")
def _import_key_for_algorithm(key: str | bytes | JWKKeyData, algorithm: str):
return jwk.import_key(key, _key_type_for_algorithm(algorithm))
def _jwk_to_pem(key_data: JWKKeyData) -> str:
key_type = key_data.get("kty")
if key_type == "RSA":
return jwk.import_key(key_data, "RSA").as_pem().decode("utf-8")
if key_type == "EC":
return jwk.import_key(key_data, "EC").as_pem().decode("utf-8")
if key_type == "OKP":
return jwk.import_key(key_data, "OKP").as_pem().decode("utf-8")
raise ValueError(f"Unsupported JWK key type: {key_type!r}")
@ -72,6 +80,8 @@ class JWKData(TypedDict, total=False):
alg: str # Algorithm (e.g., "RS256")
n: str # Modulus (for RSA keys)
e: str # Exponent (for RSA keys)
crv: str # Curve name (for EC and OKP keys)
x: str # Public key coordinate (for EC and OKP keys)
x5c: list[str] # X.509 certificate chain (for JWKs)
x5t: str # X.509 certificate thumbprint (for JWKs)
@ -194,10 +204,11 @@ def _looks_like_pem_public_key(key: str | bytes) -> bool:
class JWTVerifier(TokenVerifier):
"""
JWT token verifier supporting both asymmetric (RSA/ECDSA) and symmetric (HMAC) algorithms.
JWT token verifier supporting asymmetric (RSA/ECDSA/EdDSA) and symmetric (HMAC) algorithms.
This verifier validates JWT tokens using various signing algorithms:
- **Asymmetric algorithms** (RS256/384/512, ES256/384/512, PS256/384/512):
- **Asymmetric algorithms** (RS256/384/512, ES256/384/512, PS256/384/512,
Ed25519, Ed448, and legacy EdDSA):
Uses public/private key pairs. Ideal for external clients and services where
only the authorization server has the private key.
- **Symmetric algorithms** (HS256/384/512): Uses a shared secret for both
@ -232,7 +243,7 @@ class JWTVerifier(TokenVerifier):
jwks_uri: URI to fetch a JSON Web Key Set; used when verifying tokens with remote JWKS.
issuer: Expected issuer claim value or list of allowed issuer values.
audience: Expected audience claim value or list of allowed audience values.
algorithm: JWT signing algorithm to accept (default: "RS256"). Supported: HS256/384/512, RS256/384/512, ES256/384/512, PS256/384/512.
algorithm: JWT signing algorithm to accept (default: "RS256"). Supported: HS256/384/512, RS256/384/512, ES256/384/512, PS256/384/512, Ed25519, Ed448, and legacy EdDSA.
required_scopes: Scopes that must be present in validated tokens.
base_url: Base URL passed to the parent TokenVerifier.
ssrf_safe: If True, JWKS fetches use SSRF protection (HTTPS-only,
@ -275,6 +286,9 @@ class JWTVerifier(TokenVerifier):
"PS256",
"PS384",
"PS512",
"EdDSA",
"Ed25519",
"Ed448",
}:
raise ValueError(f"Unsupported algorithm: {algorithm}.")
@ -347,19 +361,31 @@ class JWTVerifier(TokenVerifier):
try:
jwks_data = await self._fetch_jwks()
# Cache all usable keys. A key that cannot be converted (e.g. an
# unsupported kty like OKP/Ed25519) is skipped rather than failing
# the whole set — per RFC 7517 §5, clients should ignore JWKs they
# don't understand. Otherwise one exotic key published by the
# authorization server would reject every token, including ones
# signed by supported keys in the same set (#4515).
# Cache all usable keys. A key that cannot be converted is skipped
# rather than failing the whole set — per RFC 7517 §5, clients
# should ignore JWKs they don't understand. Otherwise one exotic
# key published by the authorization server would reject every
# token, including ones signed by supported keys in the same set
# (#4515).
self._jwks_cache = {}
skipped_kids: set[str] = set()
expected_key_type = _key_type_for_algorithm(self.algorithm)
for key_data in jwks_data.get("keys", []):
if not isinstance(key_data, dict):
self.logger.debug("Skipping non-object JWKS entry: %r", key_data)
continue
key_kid = key_data.get("kid")
if key_data.get("kty") != expected_key_type:
self.logger.debug(
"Skipping JWKS key %r: key type %r is incompatible "
"with algorithm %s",
key_kid,
key_data.get("kty"),
self.algorithm,
)
if key_kid:
skipped_kids.add(key_kid)
continue
try:
public_key = _jwk_to_pem(key_data)
except (JoseError, TypeError, KeyError, ValueError) as e:

View file

@ -141,6 +141,7 @@ class OCIProvider(OIDCProxy):
fallback_refresh_token_expiry_seconds: int | None = None,
fastmcp_access_token_expiry_seconds: int | None = None,
token_expiry_threshold_seconds: int = 0,
enable_cimd: bool = True,
) -> None:
"""Initialize OCI OIDC provider.
@ -174,6 +175,8 @@ class OCIProvider(OIDCProxy):
refresh gracefully (e.g. `mcp-remote`). See `OAuthProxy` for details.
token_expiry_threshold_seconds: Number of seconds before actual expiry to
treat a token as expired, refreshing early to avoid races. Defaults to 0.
enable_cimd: Enable CIMD (Client ID Metadata Document) support for URL-based
client IDs (default True). Set to False to disable.
"""
# Parse scopes if provided as string
oci_required_scopes = (
@ -200,6 +203,7 @@ class OCIProvider(OIDCProxy):
fallback_refresh_token_expiry_seconds=fallback_refresh_token_expiry_seconds,
fastmcp_access_token_expiry_seconds=fastmcp_access_token_expiry_seconds,
token_expiry_threshold_seconds=token_expiry_threshold_seconds,
enable_cimd=enable_cimd,
)
logger.debug(

View file

@ -213,8 +213,9 @@ class WorkOSProvider(OAuthProxy):
require_authorization_consent: Whether to require user consent before authorizing clients (default True).
When True, users see a consent screen before being redirected to WorkOS.
When False, authorization proceeds directly without user confirmation.
When "external", the built-in consent screen is skipped but no warning is
logged, indicating that consent is handled externally (e.g. by the upstream IdP).
When "external", authorization follows the same direct path as False,
but the warning is suppressed as an operator acknowledgment that
equivalent protections are enforced externally.
SECURITY WARNING: Only set to False for local development or testing environments.
extra_authorize_params: Additional parameters to forward to WorkOS's authorization endpoint.
Useful for forcing scopes like `offline_access` so WorkOS issues a refresh token,

View file

@ -10,7 +10,6 @@ from logging import Logger
from typing import Any, Literal, cast, overload
import mcp_types
from key_value.aio.errors import SerializationError
from mcp import LoggingLevel, ServerSession
from mcp.server.context import ServerRequestContext
from mcp_types import (
@ -963,9 +962,8 @@ class Context:
*,
response_title: str | None = None,
response_description: str | None = None,
) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation: ...
"""The accepted elicitation will contain the response data"""
) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation:
"""The accepted elicitation will contain the response data"""
@overload
async def elicit(
@ -975,10 +973,9 @@ class Context:
*,
response_title: str | None = None,
response_description: str | None = None,
) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation: ...
"""When response_type is a list of strings, the accepted elicitation will
contain the selected string response"""
) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation:
"""When response_type is a list of strings, the accepted elicitation will
contain the selected string response"""
@overload
async def elicit(
@ -988,10 +985,9 @@ class Context:
*,
response_title: str | None = None,
response_description: str | None = None,
) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation: ...
"""When response_type is a dict mapping keys to title dicts, the accepted
elicitation will contain the selected key"""
) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation:
"""When response_type is a dict mapping keys to title dicts, the accepted
elicitation will contain the selected key"""
@overload
async def elicit(
@ -1001,12 +997,9 @@ class Context:
*,
response_title: str | None = None,
response_description: str | None = None,
) -> (
AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation
): ...
"""When response_type is a list containing a list of strings (multi-select),
the accepted elicitation will contain a list of selected strings"""
) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation:
"""When response_type is a list containing a list of strings (multi-select),
the accepted elicitation will contain a list of selected strings"""
@overload
async def elicit(
@ -1016,13 +1009,10 @@ class Context:
*,
response_title: str | None = None,
response_description: str | None = None,
) -> (
AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation
): ...
"""When response_type is a list containing a dict mapping keys to title dicts
(multi-select with titles), the accepted elicitation will contain a list of
selected keys"""
) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation:
"""When response_type is a list containing a dict mapping keys to title dicts
(multi-select with titles), the accepted elicitation will contain a list of
selected keys"""
async def elicit(
self,
@ -1146,10 +1136,9 @@ class Context:
value=StateValue(value=value),
ttl=self._STATE_TTL_SECONDS,
)
except (ValueError, SerializationError) as e:
except ValueError as e:
# Pydantic raises PydanticSerializationError (a ValueError) and the
# key_value library raises SerializationError; both carry "serialize"
# in the message. Other ValueErrors propagate unchanged.
# message carries "serialize". Other ValueErrors propagate unchanged.
if "serialize" in str(e).lower():
raise TypeError(
f"Value for state key {key!r} is not serializable. "
@ -1158,6 +1147,19 @@ class Context:
f"request-scoped and will not persist across requests."
) from e
raise
except Exception as e:
# Import the optional storage implementation only on its error path,
# rather than adding the key_value package to every server startup.
from key_value.aio.errors import SerializationError
if not isinstance(e, SerializationError):
raise
raise TypeError(
f"Value for state key {key!r} is not serializable. "
f"Use set_state({key!r}, value, serializable=False) to store "
f"non-serializable values. Note: non-serializable state is "
f"request-scoped and will not persist across requests."
) from e
async def get_state(self, key: str) -> Any:
"""Get a value from the state store.

View file

@ -8,6 +8,7 @@ AsyncKeyValue protocol, allowing users to configure any compatible backend
from __future__ import annotations
import asyncio
from uuid import uuid4
from key_value.aio.adapters.pydantic import PydanticAdapter
@ -18,6 +19,9 @@ from mcp.server.streamable_http import EventStore as SDKEventStore
from mcp_types import JSONRPCMessage
from pydantic import TypeAdapter
from fastmcp.server.session_scoped_event_store import (
SessionScopedEventStore as SessionScopedEventStore,
)
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import FastMCPBaseModel
@ -27,6 +31,9 @@ logger = get_logger(__name__)
# TypeAdapter to validate a stored dict back into the correct member.
_jsonrpc_message_adapter: TypeAdapter[JSONRPCMessage] = TypeAdapter(JSONRPCMessage)
# Number of striped locks guarding stream event lists. See EventStore.__init__.
_LOCK_STRIPES = 64
class EventEntry(FastMCPBaseModel):
"""Stored event entry."""
@ -42,58 +49,6 @@ class StreamEventList(FastMCPBaseModel):
event_ids: list[str]
class SessionScopedEventStore(SDKEventStore):
"""EventStore adapter that isolates stream IDs to one transport session."""
def __init__(self, event_store: SDKEventStore, session_id: str):
self._event_store = event_store
self._stream_prefix = f"{len(session_id)}:{session_id}:"
def _scope_stream_id(self, stream_id: StreamId) -> StreamId:
return f"{self._stream_prefix}{stream_id}"
def _unscope_stream_id(self, stream_id: StreamId) -> StreamId | None:
if not stream_id.startswith(self._stream_prefix):
return None
return stream_id[len(self._stream_prefix) :]
async def store_event(
self, stream_id: StreamId, message: JSONRPCMessage | None
) -> EventId:
return await self._event_store.store_event(
self._scope_stream_id(stream_id), message
)
async def replay_events_after(
self,
last_event_id: EventId,
send_callback: EventCallback,
) -> StreamId | None:
replayed_events: list[EventMessage] = []
async def buffer_event(event: EventMessage) -> None:
replayed_events.append(event)
scoped_stream_id = await self._event_store.replay_events_after(
last_event_id, buffer_event
)
if scoped_stream_id is None:
return None
stream_id = self._unscope_stream_id(scoped_stream_id)
if stream_id is None:
logger.warning(
"Event ID %s does not belong to this session-scoped event store",
last_event_id,
)
return None
for event in replayed_events:
await send_callback(event)
return stream_id
class EventStore(SDKEventStore):
"""EventStore implementation backed by AsyncKeyValue.
@ -133,6 +88,20 @@ class EventStore(SDKEventStore):
self._storage: AsyncKeyValue = storage or MemoryStore()
self._max_events_per_stream = max_events_per_stream
self._ttl = ttl
# Serializes the read-modify-write of each stream's event list. A fixed
# set of striped locks rather than one lock per stream: a single store is
# shared by every session, so a store-wide lock would serialize unrelated
# streams across a Redis round-trip, while a per-stream map would grow
# with every session and need its own eviction. Two streams only contend
# when their IDs collide on the same stripe.
#
# In-process locks are enough because a stream list only ever has
# in-process writers: every transport gets its own SessionScopedEventStore
# with a random per-session prefix, so no two servers sharing one backend
# address the same stream key. Coordinating across processes would need a
# compare-and-swap or transactional update, which AsyncKeyValue does not
# expose -- it offers only get/put/delete/ttl.
self._stream_locks = tuple(asyncio.Lock() for _ in range(_LOCK_STRIPES))
# PydanticAdapter for type-safe storage (following OAuth proxy pattern)
self._event_store: PydanticAdapter[EventEntry] = PydanticAdapter[EventEntry](
@ -170,22 +139,27 @@ class EventStore(SDKEventStore):
)
await self._event_store.put(key=event_id, value=entry, ttl=self._ttl)
# Update stream's event list
stream_data = await self._stream_store.get(key=stream_id)
event_ids = stream_data.event_ids if stream_data else []
event_ids.append(event_id)
# Update stream's event list. A session stores events from more than one
# task -- the SSE writer and the message router both do -- so this
# read-modify-write has to be serialized. Interleaved, each task reads the
# same list, appends only its own ID, and the later write drops the other
# event entirely while both tasks evict the same expired IDs.
async with self._stream_locks[hash(stream_id) % _LOCK_STRIPES]:
stream_data = await self._stream_store.get(key=stream_id)
event_ids = stream_data.event_ids if stream_data else []
event_ids.append(event_id)
# Trim to max events (delete old events)
if len(event_ids) > self._max_events_per_stream:
for old_id in event_ids[: -self._max_events_per_stream]:
await self._event_store.delete(key=old_id)
event_ids = event_ids[-self._max_events_per_stream :]
# Trim to max events (delete old events)
if len(event_ids) > self._max_events_per_stream:
for old_id in event_ids[: -self._max_events_per_stream]:
await self._event_store.delete(key=old_id)
event_ids = event_ids[-self._max_events_per_stream :]
await self._stream_store.put(
key=stream_id,
value=StreamEventList(event_ids=event_ids),
ttl=self._ttl,
)
await self._stream_store.put(
key=stream_id,
value=StreamEventList(event_ids=event_ids),
ttl=self._ttl,
)
return event_id

View file

@ -27,7 +27,7 @@ from starlette.types import ASGIApp, Lifespan, Receive, Scope, Send
from fastmcp.server.auth import AuthProvider
from fastmcp.server.auth.middleware import RequireAuthMiddleware
from fastmcp.server.event_store import SessionScopedEventStore
from fastmcp.server.session_scoped_event_store import SessionScopedEventStore
from fastmcp.utilities.logging import get_logger
if TYPE_CHECKING:

View file

@ -153,10 +153,11 @@ class FastMCPServerMiddleware:
Dispatch shapes:
- ``initialize`` runs the *whole* FastMCP chain here (``on_message`` ->
``on_request`` -> ``on_initialize``) because there is no interior handler
adapter for it: the SDK builds the ``InitializeResult`` directly, so this is
the only place ``on_initialize`` can observe it or veto with ``MCPError``.
- Negotiation runs the *whole* FastMCP chain here: ``initialize`` dispatches
through ``on_initialize`` and ``server/discover`` through ``on_discover``.
Neither has an interior FastMCP handler adapter, and the SDK serializes both
results before returning through its middleware seam, so this root adapter
restores core results to typed models before FastMCP middleware observes them.
- The component methods (``tools/call``, ``tools/list``, ``resources/read``,
...) still run their FastMCP chain *interior*, in the handler adapter, where
``on_call_tool`` receives the typed component result and a tool exception
@ -192,6 +193,8 @@ class FastMCPServerMiddleware:
return await call_next(ctx)
if ctx.method == "initialize" and ctx.request_id is not None:
return await self._run_initialize_mw(fastmcp, ctx, call_next)
if ctx.method == "server/discover" and ctx.request_id is not None:
return await self._run_discover_mw(fastmcp, ctx, call_next)
if ctx.request_id is not None and ctx.method in _INTERIOR_METHODS:
return await self._dispatch_component(fastmcp, ctx, call_next)
return await self._run_outer_mw(fastmcp, ctx, call_next, _raise=None)
@ -318,6 +321,62 @@ class FastMCPServerMiddleware:
for var, token in reversed(tokens):
var.reset(token)
async def _run_discover_mw(
self,
fastmcp: FastMCP,
ctx: ServerRequestContext,
call_next: CallNext,
) -> HandlerResult:
"""Run discovery through the typed FastMCP middleware hook."""
from fastmcp.server.context import Context
from fastmcp.server.middleware.middleware import MiddlewareContext
try:
discover_message = mcp_types.DiscoverRequest.model_validate(
{"method": "server/discover", "params": ctx.params}, by_name=False
)
except ValidationError as exc:
return await self._run_outer_mw(fastmcp, ctx, call_next, _raise=exc)
async def call_original_handler(
_mw_ctx: MiddlewareContext,
) -> mcp_types.DiscoverResult | dict[str, Any]:
message = _mw_ctx.message
params = (
message.params.model_dump(by_alias=True, mode="json", exclude_none=True)
if message.params is not None
else None
)
raw = await call_next(replace(ctx, params=params))
if isinstance(raw, mcp_types.DiscoverResult):
return raw
if isinstance(raw, Mapping):
result = dict(raw)
result_type = result.get("resultType")
if (
isinstance(result_type, str)
and result_type not in mcp_types.CORE_RESULT_TYPES
):
return result
return mcp_types.DiscoverResult.model_validate(result)
raise TypeError(
"server/discover handler returned "
f"{type(raw).__name__}; expected DiscoverResult or mapping"
)
async with Context(fastmcp=fastmcp, session=ctx.session) as fastmcp_ctx:
mw_context = MiddlewareContext(
message=discover_message,
source="client",
type="request",
method="server/discover",
fastmcp_context=fastmcp_ctx,
)
return await fastmcp._run_middleware(
mw_context,
cast("FastMCPCallNext[Any, Any]", call_original_handler),
)
async def _run_initialize_mw(
self,
fastmcp: FastMCP,

View file

@ -1,6 +1,7 @@
"""A middleware for response caching."""
import hashlib
import json
from collections.abc import Sequence
from logging import Logger
from typing import Any, TypedDict
@ -354,7 +355,11 @@ class ResponseCachingMiddleware(Middleware):
cache_key: str = _get_auth_partition_key()
if cached_value := await self._list_tools_cache.get(key=cache_key):
# an empty list is a cached result, not a miss: `get` returns None when the key is
# absent, so testing truthiness would re-list on every request for any caller whose
# filtered view is empty
cached_value = await self._list_tools_cache.get(key=cache_key)
if cached_value is not None:
return cached_value
tools: Sequence[Tool] = await call_next(context)
@ -383,7 +388,9 @@ class ResponseCachingMiddleware(Middleware):
cache_key: str = _get_auth_partition_key()
if cached_value := await self._list_resources_cache.get(key=cache_key):
# an empty list is a cached result, not a miss (see on_list_tools)
cached_value = await self._list_resources_cache.get(key=cache_key)
if cached_value is not None:
return cached_value
resources: Sequence[Resource] = await call_next(context)
@ -414,7 +421,9 @@ class ResponseCachingMiddleware(Middleware):
cache_key: str = _get_auth_partition_key()
if cached_value := await self._list_prompts_cache.get(key=cache_key):
# an empty list is a cached result, not a miss (see on_list_tools)
cached_value = await self._list_prompts_cache.get(key=cache_key)
if cached_value is not None:
return cached_value
prompts: Sequence[Prompt] = await call_next(context)
@ -474,6 +483,14 @@ class ResponseCachingMiddleware(Middleware):
if not isinstance(tool_result, ToolResult):
return tool_result
# Never cache an error result. A tool that reports failure by returning
# is_error=True is describing this attempt, not a stable answer — the
# upstream 503 or bad gateway it is reporting is exactly the kind of
# thing that clears on retry. Caching it would pin the failure in place
# for the full TTL and stop the tool from ever being retried.
if tool_result.is_error:
return tool_result
cacheable_tool_result: CacheableToolResult = CacheableToolResult.wrap(
value=tool_result
)
@ -593,13 +610,19 @@ class ResponseCachingMiddleware(Middleware):
def _get_arguments_str(arguments: dict[str, Any] | None) -> str:
"""Get a string representation of the arguments."""
"""Get a canonical string representation of the arguments."""
if arguments is None:
return "null"
try:
return pydantic_core.to_json(value=arguments, fallback=str).decode()
return json.dumps(
pydantic_core.to_jsonable_python(arguments, fallback=str),
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
default=str,
)
except TypeError:
return repr(arguments)

View file

@ -170,6 +170,8 @@ class Middleware:
match context.method:
case "initialize":
handler = make_handler_wrapper(self.on_initialize, handler)
case "server/discover":
handler = make_handler_wrapper(self.on_discover, handler)
case "tools/call":
handler = make_handler_wrapper(self.on_call_tool, handler)
case "resources/read":
@ -227,6 +229,13 @@ class Middleware:
) -> mt.InitializeResult | None:
return await call_next(context)
async def on_discover(
self,
context: MiddlewareContext[mt.DiscoverRequest],
call_next: CallNext[mt.DiscoverRequest, mt.DiscoverResult | dict[str, Any]],
) -> mt.DiscoverResult | dict[str, Any]:
return await call_next(context)
async def on_call_tool(
self,
context: MiddlewareContext[mt.CallToolRequestParams],

View file

@ -11,13 +11,13 @@ import anyio
import uvicorn
from mcp.server.lowlevel.server import NotificationOptions
from mcp.server.stdio import stdio_server
from mcp.server.streamable_http import EventStore
from starlette.middleware import Middleware as ASGIMiddleware
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import BaseRoute, Route
import fastmcp
from fastmcp.server.event_store import EventStore
from fastmcp.server.http import (
HostOriginProtection,
StarletteWithLifespan,
@ -28,7 +28,6 @@ from fastmcp.server.http import (
from fastmcp.server.providers.base import Provider
from fastmcp.server.providers.fastmcp_provider import FastMCPProvider
from fastmcp.server.providers.wrapped_provider import _WrappedProvider
from fastmcp.utilities.cli import log_server_banner
from fastmcp.utilities.logging import get_logger, temporary_log_level
if TYPE_CHECKING:
@ -230,6 +229,8 @@ class TransportMixin:
# Display server banner
if show_banner:
from fastmcp.utilities.cli import log_server_banner
log_server_banner(server=self)
token = set_transport("stdio")
@ -337,6 +338,8 @@ class TransportMixin:
# Display server banner
if show_banner:
from fastmcp.utilities.cli import log_server_banner
log_server_banner(server=self)
uvicorn_config_from_user = uvicorn_config or {}

View file

@ -28,17 +28,10 @@ from mcp_types import ToolAnnotations
from fastmcp.tools.base import Tool
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.utilities.authorization import AuthCheck
from fastmcp.utilities.prefab import is_prefab_type, prefab_available
from fastmcp.utilities.tasks import TaskConfig
from fastmcp.utilities.types import AnyFunction, NotSet, NotSetT
try:
from prefab_ui.app import PrefabApp as _PrefabApp
from prefab_ui.components.base import Component as _PrefabComponent
_HAS_PREFAB = True
except ImportError:
_HAS_PREFAB = False
if TYPE_CHECKING:
from fastmcp.server.providers.local_provider import LocalProvider
@ -51,7 +44,7 @@ PREFAB_RENDERER_URI = "ui://prefab/renderer.html"
def _is_prefab_type(tp: Any) -> bool:
"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
if isinstance(tp, type) and issubclass(tp, (_PrefabApp, _PrefabComponent)):
if is_prefab_type(tp):
return True
origin = get_origin(tp)
if origin is Union or origin is types.UnionType or origin is Annotated:
@ -61,7 +54,7 @@ def _is_prefab_type(tp: Any) -> bool:
def _has_prefab_return_type(tool: Tool) -> bool:
"""Check if a FunctionTool's return type annotation is a prefab type."""
if not _HAS_PREFAB or not isinstance(tool, FunctionTool):
if not isinstance(tool, FunctionTool):
return False
rt = tool.return_type
if rt is None or rt is inspect.Parameter.empty:
@ -94,13 +87,10 @@ def _maybe_apply_prefab_ui(provider: LocalProvider, tool: Tool) -> None:
it. ``app=True``, return-type inference, and ``PrefabAppConfig`` all
funnel through the same placeholder marker.
"""
if not _HAS_PREFAB:
return
meta = tool.meta or {}
ui = meta.get("ui")
if ui is True:
if ui is True and prefab_available():
# Explicit app=True: stamp the placeholder so the synthesizer finds it.
_stamp_prefab_marker(tool)
elif ui is None and _has_prefab_return_type(tool):

View file

@ -53,7 +53,7 @@ The main server class orchestrates the stateless request building approach:
```python
class FastMCPOpenAPI(FastMCP):
def __init__(self, openapi_spec: dict, client: httpx.AsyncClient, **kwargs):
def __init__(self, openapi_spec: dict, client: httpx2.AsyncClient, **kwargs):
# 1. Parse OpenAPI spec to HTTP routes with pre-calculated schemas
self._routes = parse_openapi_to_http_routes(openapi_spec)
@ -92,7 +92,7 @@ OpenAPI Spec → HTTPRoute with Pre-calculated Fields → RequestDirector → HT
2. **RequestDirector Setup**: openapi-core Spec initialized for request building
3. **Component Creation**: Create components with RequestDirector reference
4. **Request Building**: RequestDirector builds HTTP request from flat parameters
5. **Request Execution**: Execute request with httpx client
5. **Request Execution**: Execute request with httpx2 client
6. **Response Processing**: Return structured MCP response
## Key Features
@ -263,4 +263,4 @@ logging.getLogger("fastmcp.server.openapi_new").setLevel(logging.DEBUG)
- `/utilities/openapi_new/README.md` - Utility implementation details
- `/server/openapi/README.md` - Legacy implementation reference
- `/tests/server/openapi_new/` - Comprehensive test suite
- Project documentation on OpenAPI integration patterns
- Project documentation on OpenAPI integration patterns

View file

@ -4,7 +4,7 @@ from __future__ import annotations
import json
import re
from typing import TYPE_CHECKING, Any, cast
from typing import TYPE_CHECKING, Any
import httpx2
from mcp_types import ToolAnnotations
@ -18,11 +18,7 @@ from fastmcp.resources import (
)
from fastmcp.server.dependencies import get_http_headers
from fastmcp.tools.base import Tool, ToolResult
from fastmcp.utilities.exceptions import (
HTTP_STATUS_ERRORS,
REQUEST_ERRORS,
TIMEOUT_ERRORS,
)
from fastmcp.utilities.exceptions import is_request_error, is_timeout_error
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.openapi import HTTPRoute
from fastmcp.utilities.openapi.director import RequestDirector
@ -63,6 +59,36 @@ logger = get_logger(__name__)
_DEFAULT_MIME_TYPE = "application/json"
def _raise_for_status(response: httpx2.Response) -> None:
"""Raise an OpenAPI-formatted error without relying on client exception types."""
if 200 <= response.status_code < 300:
return
error_message = f"HTTP error {response.status_code}: {response.reason_phrase}"
try:
error_data = response.json()
error_message += f" - {error_data}"
except (json.JSONDecodeError, ValueError):
if response.text:
error_message += f" - {response.text}"
raise ValueError(error_message)
async def _send_request(
client: httpx2.AsyncClient,
request: httpx2.Request,
) -> httpx2.Response:
"""Send a request while preserving transitional legacy-client errors."""
try:
return await client.send(request)
except Exception as exc:
if is_timeout_error(exc):
raise ValueError(f"HTTP request timed out ({type(exc).__name__})") from exc
if is_request_error(exc):
raise ValueError(f"Request error ({type(exc).__name__}): {exc!s}") from exc
raise
def _extract_mime_type_from_route(route: HTTPRoute) -> str:
"""Extract the primary MIME type from an HTTPRoute's response definitions.
@ -176,12 +202,8 @@ class OpenAPITool(Tool):
base_url = str(self._client.base_url) or "http://localhost"
directed_request = self._director.build(self._route, arguments, base_url)
# Rebuild through the user's client so the request object comes
# from whichever httpx library the client belongs to (a legacy
# httpx.AsyncClient cannot send an httpx2.Request). Primitive
# values (str/bytes/tuples) cross that boundary safely; client
# default headers merge in with directed headers taking priority,
# matching the previous manual merge.
# Rebuild through the configured client so its default headers are
# merged with the directed headers taking priority.
request = self._client.build_request(
method=directed_request.method,
url=str(directed_request.url.copy_with(query=None)),
@ -210,8 +232,8 @@ class OpenAPITool(Tool):
f"run - sending request; headers: {_redact_headers(request.headers)}"
)
response = await self._client.send(request)
response.raise_for_status()
response = await _send_request(self._client, request)
_raise_for_status(response)
# Try to parse as JSON first
try:
@ -238,25 +260,11 @@ class OpenAPITool(Tool):
except json.JSONDecodeError:
return ToolResult(content=response.text)
except HTTP_STATUS_ERRORS as e:
status_error = cast("httpx2.HTTPStatusError", e)
error_message = (
f"HTTP error {status_error.response.status_code}: "
f"{status_error.response.reason_phrase}"
)
try:
error_data = status_error.response.json()
error_message += f" - {error_data}"
except (json.JSONDecodeError, ValueError):
if status_error.response.text:
error_message += f" - {status_error.response.text}"
raise ValueError(error_message) from e
except httpx2.TimeoutException as exc:
raise ValueError(f"HTTP request timed out ({type(exc).__name__})") from exc
except TIMEOUT_ERRORS as e:
raise ValueError(f"HTTP request timed out ({type(e).__name__})") from e
except REQUEST_ERRORS as e:
raise ValueError(f"Request error ({type(e).__name__}): {e!s}") from e
except httpx2.RequestError as exc:
raise ValueError(f"Request error ({type(exc).__name__}): {exc!s}") from exc
class OpenAPIResource(Resource):
@ -298,8 +306,7 @@ class OpenAPIResource(Resource):
directed_request = self._director.build(
self._route, self._arguments, base_url
)
# Primitive values only: a legacy httpx.AsyncClient cannot accept
# httpx2 URL/QueryParams/Headers objects.
# Build through the configured client so its defaults are applied.
request = self._client.build_request(
method=directed_request.method,
url=str(directed_request.url.copy_with(query=None)),
@ -314,8 +321,8 @@ class OpenAPIResource(Resource):
if mcp_headers:
request.headers.update(mcp_headers)
response = await self._client.send(request)
response.raise_for_status()
response = await _send_request(self._client, request)
_raise_for_status(response)
content_type = response.headers.get("content-type", "").lower()
@ -343,25 +350,11 @@ class OpenAPIResource(Resource):
]
)
except HTTP_STATUS_ERRORS as e:
status_error = cast("httpx2.HTTPStatusError", e)
error_message = (
f"HTTP error {status_error.response.status_code}: "
f"{status_error.response.reason_phrase}"
)
try:
error_data = status_error.response.json()
error_message += f" - {error_data}"
except (json.JSONDecodeError, ValueError):
if status_error.response.text:
error_message += f" - {status_error.response.text}"
raise ValueError(error_message) from e
except httpx2.TimeoutException as exc:
raise ValueError(f"HTTP request timed out ({type(exc).__name__})") from exc
except TIMEOUT_ERRORS as e:
raise ValueError(f"HTTP request timed out ({type(e).__name__})") from e
except REQUEST_ERRORS as e:
raise ValueError(f"Request error ({type(e).__name__}): {e!s}") from e
except httpx2.RequestError as exc:
raise ValueError(f"Request error ({type(exc).__name__}): {exc!s}") from exc
def _path_argument_name(route: HTTPRoute, parameter_name: str) -> str:

View file

@ -2,6 +2,7 @@
from __future__ import annotations
import warnings
from collections import Counter
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
@ -10,6 +11,7 @@ from typing import Any, Literal, cast
import httpx2
from jsonschema_path import SchemaPath
from fastmcp._warnings import FastMCPDeprecationWarning
from fastmcp.prompts import Prompt
from fastmcp.resources import Resource, ResourceTemplate
from fastmcp.server.providers.base import Provider
@ -48,6 +50,14 @@ logger = get_logger(__name__)
DEFAULT_TIMEOUT: float = 30.0
def _is_legacy_httpx_client(client: object) -> bool:
"""Detect a legacy httpx client without importing the legacy package."""
return any(
cls.__module__.partition(".")[0] == "httpx" and cls.__name__ == "AsyncClient"
for cls in type(client).__mro__
)
class OpenAPIProvider(Provider):
"""Provider that creates MCP components from an OpenAPI specification.
@ -84,10 +94,12 @@ class OpenAPIProvider(Provider):
Args:
openapi_spec: OpenAPI schema as a dictionary
client: Optional httpx AsyncClient for making HTTP requests.
client: Optional httpx2 AsyncClient for making HTTP requests.
If not provided, a default client is created using the first
server URL from the OpenAPI spec with a 30-second timeout.
To customize timeout or other settings, pass your own client.
Legacy httpx clients are temporarily accepted with a deprecation
warning.
route_maps: Optional list of RouteMap objects defining route mappings
route_map_fn: Optional callable for advanced route type mapping
mcp_component_fn: Optional callable for component customization
@ -103,6 +115,14 @@ class OpenAPIProvider(Provider):
self._owns_client = client is None
if client is None:
client = self._create_default_client(openapi_spec)
elif _is_legacy_httpx_client(client):
warnings.warn(
"Passing an httpx.AsyncClient to OpenAPIProvider is deprecated "
"and will be removed in a future release. Pass an "
"httpx2.AsyncClient instead.",
FastMCPDeprecationWarning,
stacklevel=2,
)
self._client = client
self._mcp_component_fn = mcp_component_fn
self._validate_output = validate_output

View file

@ -10,9 +10,11 @@ from __future__ import annotations
import base64
import inspect
import time
import warnings
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import replace
from typing import TYPE_CHECKING, Any, cast
from copy import deepcopy
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, Any, Literal, cast
import anyio
import httpx2
@ -29,8 +31,10 @@ from mcp_types import (
TextResourceContents,
)
from mcp_types.version import MODERN_PROTOCOL_VERSIONS
from pydantic import ValidationError
from pydantic.networks import AnyUrl
from fastmcp._warnings import FastMCPDeprecationWarning
from fastmcp.client.client import Client, SDKServer, _connection_failure
from fastmcp.client.elicitation import ElicitResult, create_elicitation_callback
from fastmcp.client.logging import LogMessage, create_log_callback
@ -72,6 +76,7 @@ logger = get_logger(__name__)
# Type alias for client factory functions
ClientFactoryT = Callable[[], Client] | Callable[[], Awaitable[Client]]
ProxyIdentity = Literal["proxy", "upstream"]
class _ForwardingClientSession(ClientSession):
@ -105,14 +110,26 @@ PROXY_TRANSPORT_OPTIONS = TransportOptions(
#: anyio stream error directly. Every proxy entry point that opens a backend
#: connection normalizes these into an ``MCPError`` so callers see a protocol
#: error instead of a raw transport exception.
_PROXY_TRANSPORT_ERRORS: tuple[type[Exception], ...] = (
RuntimeError,
_PROXY_TRANSPORT_CAUSES: tuple[type[Exception], ...] = (
TimeoutError,
httpx2.HTTPError,
anyio.ClosedResourceError,
anyio.EndOfStream,
anyio.BrokenResourceError,
)
_PROXY_TRANSPORT_ERRORS: tuple[type[Exception], ...] = (
RuntimeError,
*_PROXY_TRANSPORT_CAUSES,
)
def _has_transport_cause(error: RuntimeError) -> bool:
cause = error.__cause__
while cause is not None:
if isinstance(cause, _PROXY_TRANSPORT_CAUSES):
return True
cause = cause.__cause__
return False
def _proxy_upstream_error(error: Exception) -> MCPError:
@ -130,6 +147,59 @@ def _proxy_upstream_error(error: Exception) -> MCPError:
)
# Request `_meta` keys that describe one negotiated MCP connection. They never
# cross the proxy: a modern backend session stamps its own negotiated values on
# every request, and a handshake-era backend must not receive them at all.
_CONNECTION_META_KEYS = frozenset(
{
mcp_types.PROTOCOL_VERSION_META_KEY,
mcp_types.CLIENT_INFO_META_KEY,
mcp_types.CLIENT_CAPABILITIES_META_KEY,
}
)
def _forwardable_request_meta(ctx: Context | None) -> dict[str, Any] | None:
"""Frontend request metadata that may cross onto the backend connection.
This is the proxy's one sanctioned read of the inbound request's `_meta`:
progress tokens, tracing, task, and application metadata pass through,
while connection-owned keys (`_CONNECTION_META_KEYS`) are dropped because
they describe the frontend connection, not the backend one.
"""
request_context = ctx.request_context if ctx is not None else None
if request_context is None or not request_context.meta:
return None
forwarded = {
key: value
for key, value in request_context.meta.items()
if key not in _CONNECTION_META_KEYS
}
return forwarded or None
def _forwardable_server_meta(meta: dict[str, Any] | None) -> dict[str, Any]:
"""Backend result metadata that may cross onto the frontend connection."""
return {
key: value
for key, value in (meta or {}).items()
if key not in _CONNECTION_META_KEYS and key != mcp_types.SERVER_INFO_META_KEY
}
def _session_request_meta(
meta: dict[str, Any] | None,
) -> mcp_types.RequestParamsMeta | None:
"""Adapt forwardable metadata for a direct backend-session call.
Direct session calls bypass the high-level client mixins, so trace context
is injected here, matching what the mixins do on the legacy client paths.
"""
return cast(
"mcp_types.RequestParamsMeta | None", inject_trace_context(meta) or None
)
async def _relay_read_resource(
client: Client, uri: str, ctx: Context | None
) -> (
@ -143,15 +213,15 @@ async def _relay_read_resource(
to forward, instead of the high-level client trying to answer it here the
proxy has no back-channel to the real user, so driving it fails outright.
The inbound request's continuation state travels down so the backend guard
sees the client's answers on its own `ctx.input_responses`. Trace context
still propagates: the SDK's JSON-RPC dispatcher injects it on every outgoing
request (SEP-414), below whichever client layer issued the call.
sees the client's answers on its own `ctx.input_responses`.
"""
meta = _forwardable_request_meta(ctx)
if client.protocol_version not in MODERN_PROTOCOL_VERSIONS:
return await client.read_resource(uri)
return await client.read_resource(uri, meta=meta)
result = await client._await_with_session_monitoring(
client.session.read_resource(
uri,
meta=_session_request_meta(meta),
input_responses=ctx.input_responses if ctx else None,
request_state=ctx.request_state if ctx else None,
allow_input_required=True,
@ -185,7 +255,16 @@ def _stash_proxy_request_context(client: Client, ctx: Context) -> None:
class ProxyInitializeMiddleware(Middleware):
"""Deprecated middleware for forwarding instructions during initialization."""
def __init__(self, proxy: FastMCPProxy) -> None:
warnings.warn(
"`ProxyInitializeMiddleware` is deprecated and will be removed in a "
"future release. `FastMCPProxy` now installs "
"`ProxyMetadataMiddleware` automatically.",
FastMCPDeprecationWarning,
stacklevel=2,
)
self.proxy = proxy
async def on_initialize(
@ -311,15 +390,11 @@ class ProxyTool(Tool):
async with client:
ctx = context or get_context()
_stash_proxy_request_context(client, ctx)
# Forward the inbound request's `_meta` block (trace context,
# version, etc.) to the backend. In SDK v2 the request context
# exposes the lifted `_meta` dict directly; task submission is a
# first-class params field rather than context state, so there
# is no separate task-metadata injection here.
req_ctx = ctx.request_context
meta: dict[str, Any] | None = (
dict(req_ctx.meta) if req_ctx is not None and req_ctx.meta else None
)
# Forward the inbound request's hop-safe `_meta` (trace
# context, progress token, etc.) to the backend. Task
# submission is a first-class params field rather than context
# state, so there is no separate task-metadata injection here.
meta = _forwardable_request_meta(ctx)
if client.protocol_version in MODERN_PROTOCOL_VERSIONS:
# Modern backend: call the session directly (not
@ -330,10 +405,7 @@ class ProxyTool(Tool):
# round. Forward the inbound request's continuation state
# down so the backend guard tool sees the client's answers
# on its own `ctx.input_responses` / `ctx.request_state`.
request_meta = cast(
"mcp_types.RequestParamsMeta | None",
inject_trace_context(meta) or None,
)
request_meta = _session_request_meta(meta)
# SEP-2243: a modern backend rejects a `tools/call` whose
# `x-mcp-header` argument is not mirrored into an `Mcp-Param-*`
# header. The SDK client emits those headers only for tools it
@ -704,6 +776,7 @@ class ProxyPrompt(Prompt):
ctx = get_context()
async with client:
_stash_proxy_request_context(client, ctx)
meta = _forwardable_request_meta(ctx)
if client.protocol_version in MODERN_PROTOCOL_VERSIONS:
# See `_relay_read_resource`: surface a backend guard's ask
# instead of trying to answer it inside the proxy.
@ -711,6 +784,7 @@ class ProxyPrompt(Prompt):
client.session.get_prompt(
backend_name,
arguments,
meta=_session_request_meta(meta),
input_responses=ctx.input_responses if ctx else None,
request_state=ctx.request_state if ctx else None,
allow_input_required=True,
@ -720,7 +794,7 @@ class ProxyPrompt(Prompt):
return InputRequiredPromptResult(raw)
result = raw
else:
result = await client.get_prompt(backend_name, arguments)
result = await client.get_prompt(backend_name, arguments, meta=meta)
# Convert GetPromptResult to PromptResult, preserving meta from result
# (not the static prompt meta which includes fastmcp tags)
# Convert PromptMessages to Messages
@ -1046,6 +1120,161 @@ class ProxyProvider(Provider):
# because client cleanup is handled per-request
@dataclass(frozen=True)
class _UpstreamServerMetadata:
instructions: str | None
server_info: mcp_types.Implementation | None
meta: dict[str, Any]
@classmethod
def from_result(
cls,
result: mcp_types.InitializeResult | mcp_types.DiscoverResult,
server_info: mcp_types.Implementation | None,
) -> _UpstreamServerMetadata:
"""Detach forwarded values from the backend session's adopted result."""
return cls(
instructions=result.instructions,
server_info=(
server_info.model_copy(deep=True) if server_info is not None else None
),
meta=deepcopy(result.meta or {}),
)
@classmethod
def from_client(cls, client: Client) -> _UpstreamServerMetadata | None:
result = client.session.initialize_result or client.session.discover_result
if result is None:
return None
return cls.from_result(result, client.session.server_info)
@classmethod
def from_discover(cls, result: mcp_types.DiscoverResult) -> _UpstreamServerMetadata:
raw_server_info = (result.meta or {}).get(mcp_types.SERVER_INFO_META_KEY)
try:
server_info = (
mcp_types.Implementation.model_validate(raw_server_info)
if raw_server_info is not None
else None
)
except ValidationError:
server_info = None
return cls.from_result(result, server_info)
class ProxyMetadataMiddleware(Middleware):
"""Forward optional server metadata from a ``ProxyProvider`` backend.
Instructions and namespaced metadata are forwarded with frontend values
taking precedence. Protocol versions, capabilities, cache policy, and result
type are never copied from the backend. ``identity`` controls whether server
identity remains the gateway's or uses the backend's when available.
"""
def __init__(
self,
provider: ProxyProvider,
*,
identity: ProxyIdentity = "proxy",
) -> None:
if identity not in ("proxy", "upstream"):
raise ValueError("identity must be 'proxy' or 'upstream'")
self.provider = provider
self.identity = identity
async def _read_connected(self, client: Client) -> _UpstreamServerMetadata | None:
"""Read metadata without changing the client's adopted negotiation state."""
if client.mode in MODERN_PROTOCOL_VERSIONS and client.prior_discover is None:
# An exact pin adopts a synthetic result without probing. Read the
# real result directly, but do not adopt it into this borrowed session.
raw = await client.session.send_discover(client.mode)
result_type = raw.get("resultType")
if (
isinstance(result_type, str)
and result_type not in mcp_types.CORE_RESULT_TYPES
):
return None
try:
result = mcp_types.DiscoverResult.model_validate(raw)
except ValidationError as error:
logger.debug("Could not read upstream server metadata: %r", error)
return None
return _UpstreamServerMetadata.from_discover(result)
return _UpstreamServerMetadata.from_client(client)
async def _read_upstream(
self, client: Client, context: Context | None
) -> _UpstreamServerMetadata | None:
if context is not None:
_stash_proxy_request_context(client, context)
try:
if client.is_connected():
return await self._read_connected(client)
async with client:
return await self._read_connected(client)
except (MCPError, *_PROXY_TRANSPORT_ERRORS) as error:
if isinstance(error, RuntimeError) and not _has_transport_cause(error):
raise
logger.debug("Could not read upstream server metadata: %r", error)
return None
def _updates(
self,
result: mcp_types.InitializeResult | mcp_types.DiscoverResult,
upstream: _UpstreamServerMetadata,
) -> dict[str, Any]:
meta = _forwardable_server_meta(upstream.meta)
meta.update(result.meta or {})
updates: dict[str, Any] = {"meta": meta or None}
if result.instructions is None and upstream.instructions is not None:
updates["instructions"] = upstream.instructions
if self.identity == "upstream" and upstream.server_info is not None:
if isinstance(result, mcp_types.InitializeResult):
updates["server_info"] = upstream.server_info
else:
meta[mcp_types.SERVER_INFO_META_KEY] = upstream.server_info.model_dump(
by_alias=True, mode="json", exclude_none=True
)
updates["meta"] = meta
return updates
async def on_initialize(
self,
context: MiddlewareContext[mcp_types.InitializeRequest],
call_next: CallNext[
mcp_types.InitializeRequest, mcp_types.InitializeResult | None
],
) -> mcp_types.InitializeResult | None:
# Factory errors must occur before the legacy response is committed.
client = await self.provider._get_client()
result = await call_next(context)
if result is None:
return None
upstream = await self._read_upstream(client, context.fastmcp_context)
if upstream is None:
return result
return result.model_copy(update=self._updates(result, upstream))
async def on_discover(
self,
context: MiddlewareContext[mcp_types.DiscoverRequest],
call_next: CallNext[
mcp_types.DiscoverRequest,
mcp_types.DiscoverResult | dict[str, Any],
],
) -> mcp_types.DiscoverResult | dict[str, Any]:
result = await call_next(context)
if not isinstance(result, mcp_types.DiscoverResult):
return result
client = await self.provider._get_client()
upstream = await self._read_upstream(client, context.fastmcp_context)
if upstream is None:
return result
return result.model_copy(update=self._updates(result, upstream))
# -----------------------------------------------------------------------------
# Factory Functions
# -----------------------------------------------------------------------------
@ -1227,6 +1456,7 @@ class FastMCPProxy(FastMCP):
*,
client_factory: ClientFactoryT,
provider_error_strategy: ProviderErrorStrategy = "warn",
identity: ProxyIdentity = "proxy",
**kwargs,
):
"""Initialize the proxy server.
@ -1241,16 +1471,18 @@ class FastMCPProxy(FastMCP):
provider_error_strategy: How provider errors should affect aggregate
operations. Defaults to ``"warn"`` for compatibility; use
``"raise"`` when the proxy should surface upstream failures.
identity: Whether clients see the proxy's server identity or the
upstream server's when available. Defaults to ``"proxy"``
for compatibility.
**kwargs: Additional settings for the FastMCP server.
"""
super().__init__(**kwargs)
self.provider_error_strategy = provider_error_strategy
self.client_factory = client_factory
provider: Provider = ProxyProvider(client_factory)
provider = ProxyProvider(client_factory)
self.add_provider(provider)
self.middleware.append(ProxyInitializeMiddleware(self))
self.middleware.append(ProxyMetadataMiddleware(provider, identity=identity))
self._setup_proxy_ping_handler()
self._setup_proxy_discover_handler()
async def _get_client(self) -> Client:
client = self.client_factory()
@ -1272,73 +1504,6 @@ class FastMCPProxy(FastMCP):
"ping", mcp_types.RequestParams, ping_remote
)
def _setup_proxy_discover_handler(self) -> None:
"""Forward the backend's instructions on the modern (`server/discover`) path.
`ProxyInitializeMiddleware` forwards upstream instructions by patching
the `InitializeResult`, but `on_initialize` only fires for the legacy
handshake. A modern client negotiates via `server/discover`, whose
default SDK handler reads `self.instructions` off the low-level server
directly, so a proxy would silently drop its upstream's instructions for
every modern client.
The SDK sanctions replacing this handler wholesale, so we delegate to
its own implementation for the rest of the result (supported versions,
capabilities, server info) and only fill in the instructions we would
otherwise lose. Resolving them here at request time, from a live
backend session keeps the proxy's lazy-connect contract intact: the
backend is contacted when a client actually asks, never at construction.
"""
build_default_result = self._mcp_server._handle_discover
async def discover_remote(
ctx: ServerRequestContext[Any, Any],
params: mcp_types.RequestParams | None,
) -> mcp_types.DiscoverResult:
result = await build_default_result(ctx, params)
# A proxy with its own instructions keeps them, matching the
# precedence `ProxyInitializeMiddleware` applies on the legacy path.
if result.instructions is not None:
return result
client = await self._get_client()
# `session.instructions` is era-neutral: it reads the backend's
# `DiscoverResult` or `InitializeResult` depending on what the
# backend negotiated, so a modern front can proxy a legacy backend.
if client.is_connected():
result.instructions = client.session.instructions
return result
# Era mirroring pins a modern backend to an exact version, and a
# pinned version adopts a synthesized `DiscoverResult` instead of
# probing the wire — so the pinned client would report no
# instructions at all. Instructions are metadata with no
# back-channel, so this read does not need the era consistency
# mirroring exists to protect; negotiate with "auto" instead, which
# probes `server/discover` and falls back to the handshake for a
# legacy-only backend.
client.mode = "auto"
try:
async with client:
result.instructions = client.session.instructions
except (MCPError, *_PROXY_TRANSPORT_ERRORS) as error:
# Instructions are optional metadata, so an unreachable backend
# must not fail negotiation itself. Failing here would surface
# as a confusing protocol error: the client's auto-negotiation
# reads any `server/discover` error as "not a modern server"
# and retries with the initialize handshake, which this
# modern-serving proxy then rejects — hiding the real cause.
# Answer without upstream instructions instead and let the
# backend failure surface on the first real operation, where
# the proxy reports it as an upstream connection error.
logger.debug(
"Could not read upstream instructions for server/discover: %r",
error,
)
return result
self._mcp_server.add_request_handler(
"server/discover", mcp_types.RequestParams, discover_remote
)
# -----------------------------------------------------------------------------
# ProxyClient and Related

View file

@ -20,9 +20,6 @@ from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast, overload
import httpx2
import mcp_types
from key_value.aio.adapters.pydantic import PydanticAdapter
from key_value.aio.protocols import AsyncKeyValue
from key_value.aio.stores.memory import MemoryStore
from mcp.server.lowlevel.server import LifespanResultT
from mcp.server.request_state import RequestStateSecurity
from mcp.shared.exceptions import MCPError
@ -91,7 +88,7 @@ from fastmcp.tools.base import Tool, ToolResult
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool_transform import ToolTransformConfig
from fastmcp.utilities.components import FastMCPComponent, _coerce_version
from fastmcp.utilities.exceptions import HTTP_STATUS_ERRORS, TIMEOUT_ERRORS
from fastmcp.utilities.exceptions import get_http_status_code, is_timeout_error
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.tasks import TaskConfig
from fastmcp.utilities.types import AnyFunction, FastMCPBaseModel, NotSet, NotSetT
@ -101,6 +98,9 @@ from fastmcp.utilities.versions import (
)
if TYPE_CHECKING:
from key_value.aio.adapters.pydantic import PydanticAdapter
from key_value.aio.protocols import AsyncKeyValue
from fastmcp.client import Client
from fastmcp.client.client import SDKServer
from fastmcp.client.transports import ClientTransport, ClientTransportT
@ -112,11 +112,6 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
# Both-library catch tuples for user-supplied code that may still raise legacy
# httpx exceptions; see fastmcp.utilities.exceptions for the defensive import.
_ACTIONABLE_HTTP_STATUS_ERRORS = HTTP_STATUS_ERRORS
_ACTIONABLE_TIMEOUT_ERRORS = TIMEOUT_ERRORS
def _version_request_meta(
version: VersionSpec | None,
@ -333,12 +328,8 @@ class FastMCP(
self._additional_http_routes: list[BaseRoute] = []
# Session-scoped state store (shared across all requests)
self._state_storage: AsyncKeyValue = session_state_store or MemoryStore()
self._state_store: PydanticAdapter[StateValue] = PydanticAdapter[StateValue](
key_value=self._state_storage,
pydantic_model=StateValue,
default_collection="fastmcp_state",
)
self._state_storage: AsyncKeyValue | None = session_state_store
self.__state_store: PydanticAdapter[StateValue] | None = None
# Create LocalProvider for local components
self._local_provider: LocalProvider = LocalProvider(
@ -496,6 +487,22 @@ class FastMCP(
def __repr__(self) -> str:
return f"{type(self).__name__}({self.name!r})"
@property
def _state_store(self) -> PydanticAdapter[StateValue]:
"""Create the session-state adapter only when state is first used."""
if self.__state_store is None:
from key_value.aio.adapters.pydantic import PydanticAdapter
from key_value.aio.stores.memory import MemoryStore
if self._state_storage is None:
self._state_storage = MemoryStore()
self.__state_store = PydanticAdapter[StateValue](
key_value=self._state_storage,
pydantic_model=StateValue,
default_collection="fastmcp_state",
)
return self.__state_store
@property
def name(self) -> str:
return self._mcp_server.name
@ -1534,15 +1541,11 @@ class FastMCP(
logger.exception(f"Error calling tool {name!r}")
# Handle actionable errors that should reach the LLM
# even when masking is enabled
if isinstance(e, _ACTIONABLE_HTTP_STATUS_ERRORS):
if (
cast("httpx2.HTTPStatusError", e).response.status_code
== 429
):
raise ToolError(
"Rate limited by upstream API, please retry later"
) from e
if isinstance(e, _ACTIONABLE_TIMEOUT_ERRORS):
if get_http_status_code(e) == 429:
raise ToolError(
"Rate limited by upstream API, please retry later"
) from e
if is_timeout_error(e):
raise ToolError(
"Upstream request timed out, please retry"
) from e
@ -1637,15 +1640,11 @@ class FastMCP(
except Exception as e:
logger.exception(f"Error reading resource {uri!r}")
# Handle actionable errors that should reach the LLM
if isinstance(e, _ACTIONABLE_HTTP_STATUS_ERRORS):
if (
cast("httpx2.HTTPStatusError", e).response.status_code
== 429
):
raise ResourceError(
"Rate limited by upstream API, please retry later"
) from e
if isinstance(e, _ACTIONABLE_TIMEOUT_ERRORS):
if get_http_status_code(e) == 429:
raise ResourceError(
"Rate limited by upstream API, please retry later"
) from e
if is_timeout_error(e):
raise ResourceError(
"Upstream request timed out, please retry"
) from e
@ -1700,15 +1699,11 @@ class FastMCP(
except Exception as e:
logger.exception(f"Error reading resource {uri!r}")
# Handle actionable errors that should reach the LLM
if isinstance(e, _ACTIONABLE_HTTP_STATUS_ERRORS):
if (
cast("httpx2.HTTPStatusError", e).response.status_code
== 429
):
raise ResourceError(
"Rate limited by upstream API, please retry later"
) from e
if isinstance(e, _ACTIONABLE_TIMEOUT_ERRORS):
if get_http_status_code(e) == 429:
raise ResourceError(
"Rate limited by upstream API, please retry later"
) from e
if is_timeout_error(e):
raise ResourceError(
"Upstream request timed out, please retry"
) from e
@ -2400,10 +2395,10 @@ class FastMCP(
Args:
openapi_spec: OpenAPI schema as a dictionary
client: Optional httpx2 AsyncClient for making HTTP requests.
An httpx (v1) AsyncClient is also accepted and works via
duck-typing. If not provided, a default client is created
using the first
If not provided, a default client is created using the first
server URL from the OpenAPI spec with a 30-second timeout.
Legacy httpx clients are temporarily accepted with a deprecation
warning.
name: Name for the MCP server
route_maps: Optional list of RouteMap objects defining route mappings
route_map_fn: Optional callable for advanced route type mapping

View file

@ -0,0 +1,68 @@
"""Lightweight session scoping for Streamable HTTP event stores."""
from __future__ import annotations
from mcp.server.streamable_http import (
EventCallback,
EventId,
EventMessage,
EventStore,
StreamId,
)
from mcp_types import JSONRPCMessage
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
class SessionScopedEventStore(EventStore):
"""EventStore adapter that isolates stream IDs to one transport session."""
def __init__(self, event_store: EventStore, session_id: str):
self._event_store = event_store
self._stream_prefix = f"{len(session_id)}:{session_id}:"
def _scope_stream_id(self, stream_id: StreamId) -> StreamId:
return f"{self._stream_prefix}{stream_id}"
def _unscope_stream_id(self, stream_id: StreamId) -> StreamId | None:
if not stream_id.startswith(self._stream_prefix):
return None
return stream_id[len(self._stream_prefix) :]
async def store_event(
self, stream_id: StreamId, message: JSONRPCMessage | None
) -> EventId:
return await self._event_store.store_event(
self._scope_stream_id(stream_id), message
)
async def replay_events_after(
self,
last_event_id: EventId,
send_callback: EventCallback,
) -> StreamId | None:
replayed_events: list[EventMessage] = []
async def buffer_event(event: EventMessage) -> None:
replayed_events.append(event)
scoped_stream_id = await self._event_store.replay_events_after(
last_event_id, buffer_event
)
if scoped_stream_id is None:
return None
stream_id = self._unscope_stream_id(scoped_stream_id)
if stream_id is None:
logger.warning(
"Event ID %s does not belong to this session-scoped event store",
last_event_id,
)
return None
for event in replayed_events:
await send_callback(event)
return stream_id

View file

@ -1,5 +1,6 @@
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import (
TYPE_CHECKING,
@ -20,12 +21,23 @@ from mcp_types import (
ToolExecution,
)
from mcp_types import Tool as MCPTool
from pydantic import BaseModel, Field, PrivateAttr, model_validator
from pydantic import (
BaseModel,
Field,
PrivateAttr,
PydanticSchemaGenerationError,
model_validator,
)
from pydantic.json_schema import SkipJsonSchema
from fastmcp.utilities.authorization import AuthCheck
from fastmcp.utilities.components import FastMCPComponent
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.prefab import (
is_prefab_app,
is_prefab_component,
prefab_app_from_component,
)
from fastmcp.utilities.tasks import TaskConfig
from fastmcp.utilities.types import (
Audio,
@ -33,16 +45,9 @@ from fastmcp.utilities.types import (
Image,
NotSet,
NotSetT,
get_cached_typeadapter,
)
try:
from prefab_ui.app import PrefabApp as _PrefabApp
from prefab_ui.components.base import Component as _PrefabComponent
_HAS_PREFAB = True
except ImportError:
_HAS_PREFAB = False
if TYPE_CHECKING:
from fastmcp.tools.function_tool import FunctionTool
from fastmcp.tools.tool_transform import ArgTransform, TransformedTool
@ -51,6 +56,8 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
_JSONABLE_ADAPTER = get_cached_typeadapter(Any)
def _default_title(name: str) -> str:
"""Derive a display title from a tool name.
@ -62,34 +69,27 @@ def _default_title(name: str) -> str:
return name.replace("_", " ").replace("-", " ").title()
def resolve_serialize_by_alias(value: Any) -> bool:
"""Resolve the effective ``by_alias`` setting for serializing *value*.
Pydantic's low-level serialization helpers (``to_json``,
``to_jsonable_python``) default ``by_alias`` to ``True``, which silently
ignores a model's ``serialize_by_alias`` config. When *value* is a Pydantic
model we consult that config instead, falling back to ``True`` to preserve
FastMCP's longstanding default of emitting aliases when no preference is
declared.
"""
if isinstance(value, type):
model = value if issubclass(value, BaseModel) else None
elif isinstance(value, BaseModel):
model = type(value)
else:
model = None
if model is None:
return True
configured = model.model_config.get("serialize_by_alias")
return True if configured is None else configured
def default_serializer(data: Any) -> str:
return pydantic_core.to_json(
data, fallback=str, by_alias=resolve_serialize_by_alias(data)
).decode()
return _JSONABLE_ADAPTER.dump_json(data, fallback=str).decode()
def _serialize_to_jsonable(data: Any, annotation: Any = Any) -> Any:
"""Serialize through Pydantic, falling back for unsupported annotations."""
if (
annotation is inspect.Signature.empty
or annotation is None
or annotation is Any
or annotation is ...
or isinstance(annotation, str)
):
adapter = _JSONABLE_ADAPTER
else:
try:
return get_cached_typeadapter(annotation).dump_python(data, mode="json")
except PydanticSchemaGenerationError:
adapter = _JSONABLE_ADAPTER
return adapter.dump_python(data, mode="json")
class ToolResult(BaseModel):
@ -128,19 +128,15 @@ class ToolResult(BaseModel):
if structured_content is not None:
# Convert Prefab types to their wire-format envelope before
# generic serialization, so the renderer gets the right shape.
if _HAS_PREFAB:
if isinstance(structured_content, _PrefabApp):
structured_content = _prefab_to_json(structured_content)
elif isinstance(structured_content, _PrefabComponent):
structured_content = _prefab_to_json(
_PrefabApp(view=structured_content)
)
if is_prefab_app(structured_content):
structured_content = _prefab_to_json(structured_content)
elif is_prefab_component(structured_content):
structured_content = _prefab_to_json(
prefab_app_from_component(structured_content)
)
try:
structured_content = pydantic_core.to_jsonable_python(
value=structured_content,
by_alias=resolve_serialize_by_alias(structured_content),
)
structured_content = _serialize_to_jsonable(structured_content)
except pydantic_core.PydanticSerializationError as e:
logger.error(
f"Could not serialize structured content. If this is unexpected, set your tool's output_schema to None to disable automatic serialization: {e}"
@ -237,6 +233,7 @@ class Tool(FastMCPComponent):
KEY_PREFIX: ClassVar[str] = "tool"
return_type: Annotated[SkipJsonSchema[Any], Field(exclude=True)] = None
parameters: Annotated[
dict[str, Any], Field(description="JSON schema for tool parameters")
]
@ -379,17 +376,16 @@ class Tool(FastMCPComponent):
if isinstance(raw_value, CallToolResult):
return ToolResult.from_mcp_result(raw_value)
if _HAS_PREFAB:
if isinstance(raw_value, _PrefabApp):
return _prefab_to_tool_result(
raw_value,
fastmcp_app_name=_get_fastmcp_app_name(self),
)
if isinstance(raw_value, _PrefabComponent):
return _prefab_to_tool_result(
_PrefabApp(view=raw_value),
fastmcp_app_name=_get_fastmcp_app_name(self),
)
if is_prefab_app(raw_value):
return _prefab_to_tool_result(
raw_value,
fastmcp_app_name=_get_fastmcp_app_name(self),
)
if is_prefab_component(raw_value):
return _prefab_to_tool_result(
prefab_app_from_component(raw_value),
fastmcp_app_name=_get_fastmcp_app_name(self),
)
content = _convert_to_content(raw_value)
@ -397,24 +393,29 @@ class Tool(FastMCPComponent):
if isinstance(raw_value, bytes):
return ToolResult(content=content)
is_content_result = isinstance(
raw_value, ContentBlock | Audio | Image | File
) or (
isinstance(raw_value, list | tuple)
and any(
isinstance(item, ContentBlock | Audio | Image | File)
for item in raw_value
)
)
# Skip structured content for ContentBlock types only if no output_schema
# (if output_schema exists, MCP SDK requires structured_content)
if self.output_schema is None and (
isinstance(raw_value, ContentBlock | Audio | Image | File)
or (
isinstance(raw_value, list | tuple)
and any(isinstance(item, ContentBlock) for item in raw_value)
)
):
if self.output_schema is None and is_content_result:
return ToolResult(content=content)
try:
structured = pydantic_core.to_jsonable_python(
raw_value, by_alias=resolve_serialize_by_alias(raw_value)
)
structured = _serialize_to_jsonable(raw_value, self.return_type)
except (pydantic_core.PydanticSerializationError, UnicodeDecodeError):
return ToolResult(content=content)
if not is_content_result:
content = _convert_to_content(structured)
if self.output_schema is None:
# No schema - only use structured_content for dicts
if isinstance(structured, dict):

View file

@ -10,14 +10,17 @@ from dataclasses import dataclass
from typing import Annotated, Any, Generic, Union, get_args, get_origin, get_type_hints
import mcp_types
from pydantic import BaseModel, PydanticSchemaGenerationError
from pydantic import PydanticSchemaGenerationError
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
from pydantic_core import core_schema
from typing_extensions import TypeAliasType
from typing_extensions import TypeVar as TypeVarExt
from fastmcp.tools.base import ToolResult, resolve_serialize_by_alias
from fastmcp.tools.base import ToolResult
from fastmcp.utilities.docstring_parsing import ParsedDocstring, parse_docstring
from fastmcp.utilities.json_schema import compress_schema
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.prefab import is_prefab_type
from fastmcp.utilities.types import (
Audio,
File,
@ -27,14 +30,6 @@ from fastmcp.utilities.types import (
replace_type,
)
try:
from prefab_ui.app import PrefabApp as _PrefabApp
from prefab_ui.components.base import Component as _PrefabComponent
_PREFAB_TYPES: tuple[type, ...] = (_PrefabApp, _PrefabComponent)
except ImportError:
_PREFAB_TYPES = ()
def _contains_bytes_type(tp: Any) -> bool:
"""Check if *tp* is or contains bytes, recursing through unions and Annotated."""
@ -48,7 +43,7 @@ def _contains_bytes_type(tp: Any) -> bool:
def _contains_prefab_type(tp: Any) -> bool:
"""Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
if isinstance(tp, type) and issubclass(tp, _PREFAB_TYPES):
if is_prefab_type(tp):
return True
origin = get_origin(tp)
if origin is Union or origin is types.UnionType or origin is Annotated:
@ -153,51 +148,30 @@ def _strip_input_required(tp: Any) -> Any:
return Union[tuple(residual)] # noqa: UP007
def _unwrap_model(tp: Any) -> type[BaseModel] | None:
"""Unwrap ``Annotated`` and return the underlying Pydantic model, if any."""
if get_origin(tp) is Annotated:
return _unwrap_model(get_args(tp)[0])
if isinstance(tp, type) and issubclass(tp, BaseModel):
return tp
return None
class _ToolOutputSchemaGenerator(GenerateJsonSchema):
"""Generate each model's schema with its configured serialization aliases.
def _resolve_output_by_alias(tp: Any) -> bool:
"""Resolve ``by_alias`` for the output schema of return type *tp*.
Unwraps ``Annotated`` and ``Optional``/``Union`` wrappers to find the
underlying Pydantic model so the generated schema honors the model's
``serialize_by_alias`` config keeping it consistent with how the runtime
result is serialized. Containers (``list[Model]`` etc.) are not unwrapped:
their schema keeps the default, matching the runtime path which only
special-cases a directly-returned model.
Known limitation: a single schema is generated with one ``by_alias`` value,
while the runtime resolves the alias mode per returned value. They cannot
diverge for a plain single-model return, but a union return can produce more
than one runtime alias mode that no single schema can describe:
- distinct models with *conflicting* ``serialize_by_alias`` (e.g. ``A | B``
where ``A`` opts out but ``B`` opts in), and
- a model arm alongside a container arm (e.g. ``Model | list[Model]``):
a directly-returned model honors its config, but a returned ``list`` is
serialized with the default alias mode, so the two variants disagree.
Pydantic's schema generator does not consult per-model ``serialize_by_alias``
and the runtime does not recurse into containers, so honoring every variant
would require per-arm schema assembly. This is an accepted edge; single-model
returns and unions whose arms all resolve to the same mode are consistent.
Pydantic's serializer consults ``serialize_by_alias`` per model, while its
JSON Schema API otherwise applies one ``by_alias`` value to the whole tree.
"""
origin = get_origin(tp)
if origin is Annotated:
return _resolve_output_by_alias(get_args(tp)[0])
if origin is Union or origin is types.UnionType:
for arg in get_args(tp):
model = _unwrap_model(arg)
if model is not None:
return resolve_serialize_by_alias(model)
return True
return resolve_serialize_by_alias(tp)
def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue:
previous_by_alias = self.by_alias
configured = schema["cls"].model_config.get("serialize_by_alias")
self.by_alias = False if configured is None else configured
try:
return super().model_schema(schema)
finally:
self.by_alias = previous_by_alias
def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue:
previous_by_alias = self.by_alias
configured = (schema.get("config") or {}).get("serialize_by_alias")
self.by_alias = False if configured is None else configured
try:
return super().dataclass_schema(schema)
finally:
self.by_alias = previous_by_alias
T = TypeVarExt("T", default=Any)
@ -405,7 +379,7 @@ class ParsedFunction:
# so we handle subclass matching explicitly here. We also need
# to handle composite types like ``Column | None`` and
# ``Annotated[PrefabApp, ...]`` by recursing into their args.
if _PREFAB_TYPES and _contains_prefab_type(output_type):
if _contains_prefab_type(output_type):
output_type = _UnserializableType
# ToolResult subclasses should suppress schema generation just
@ -450,19 +424,17 @@ class ParsedFunction:
# A guard tool's suspend signal is control flow, not
# output data (any residual bare arm is suppressed).
mcp_types.InputRequiredResult,
*_PREFAB_TYPES,
),
_UnserializableType,
),
)
try:
# Honor the model's serialize_by_alias config so the schema's
# field names match the serialized result (see base.py).
by_alias = _resolve_output_by_alias(clean_output_type)
type_adapter = get_cached_typeadapter(clean_output_type)
base_schema = type_adapter.json_schema(
mode="serialization", by_alias=by_alias
mode="serialization",
by_alias=False,
schema_generator=_ToolOutputSchemaGenerator,
)
# Generate schema for wrapped type if it's non-object
@ -474,7 +446,9 @@ class ParsedFunction:
wrapped_type = _WrappedResult[clean_output_type]
wrapped_adapter = get_cached_typeadapter(wrapped_type)
output_schema = wrapped_adapter.json_schema(
mode="serialization", by_alias=by_alias
mode="serialization",
by_alias=False,
schema_generator=_ToolOutputSchemaGenerator,
)
output_schema["x-fastmcp-wrap-result"] = True
else:

View file

@ -197,7 +197,6 @@ def _resolve_param_hints(fn: Callable[..., Any]) -> dict[str, Any]:
class FunctionTool(Tool):
fn: SkipJsonSchema[Callable[..., Any]]
return_type: Annotated[SkipJsonSchema[Any], Field(exclude=True)] = None
run_in_thread: Annotated[
bool,
Field(

View file

@ -8,7 +8,6 @@ from dataclasses import dataclass
from typing import Annotated, Any, Literal, cast
import mcp_types
import pydantic_core
from mcp_types import ToolAnnotations
from pydantic import ConfigDict
from pydantic.fields import Field
@ -19,8 +18,6 @@ from fastmcp.tools.base import (
InputRequiredToolResult,
Tool,
ToolResult,
_convert_to_content,
resolve_serialize_by_alias,
)
from fastmcp.tools.function_parsing import ParsedFunction
from fastmcp.utilities.async_utils import (
@ -394,40 +391,7 @@ class TransformedTool(Tool):
else:
return result
# Otherwise convert to content and create ToolResult with proper structured content
unstructured_result = _convert_to_content(result)
structured_output = None
# First handle structured content based on output schema, if any
if self.output_schema is not None:
if self.output_schema.get("x-fastmcp-wrap-result"):
# Schema says wrap - serialize the inner result first (so its
# serialize_by_alias config is honored) before nesting, since
# wrapping in a dict would otherwise mask the model's config.
structured_output = {
"result": pydantic_core.to_jsonable_python(
result, by_alias=resolve_serialize_by_alias(result)
)
}
else:
structured_output = result
# If no output schema, try to serialize the result. If it is a dict, use
# it as structured content. If it is not a dict, ignore it.
if structured_output is None:
try:
structured_output = pydantic_core.to_jsonable_python(
result, by_alias=resolve_serialize_by_alias(result)
)
if not isinstance(structured_output, dict):
structured_output = None
except Exception:
pass
return ToolResult(
content=unstructured_result,
structured_content=structured_output,
)
return self.convert_result(result)
finally:
_current_tool.reset(token)
@ -641,6 +605,7 @@ class TransformedTool(Tool):
transformed_tool = cls(
fn=final_fn,
return_type=parsed_fn.return_type if parsed_fn is not None else None,
forwarding_fn=forwarding_fn,
parent_tool=tool,
name=final_name,

View file

@ -14,8 +14,6 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
from griffe import Docstring, DocstringSectionKind
_PARSERS = ("google", "numpy", "sphinx")
logger = logging.getLogger("griffe")
@ -43,6 +41,10 @@ def parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring:
if not doc:
return ParsedDocstring()
# Griffe is only needed for functions that actually have docstrings. This
# keeps its parser and model graph out of ordinary server startup.
from griffe import Docstring, DocstringSectionKind
# Try each parser and use the first one that finds parameters.
for parser in _PARSERS:
docstring = Docstring(doc, lineno=1, parser=parser)

View file

@ -7,30 +7,42 @@ from mcp import MCPError
import fastmcp
# FastMCP uses httpx2 internally, but user-supplied code (tools, resources, and
# clients handed to the OpenAPI integration) may still raise exceptions from the
# legacy httpx package. These catch tuples include both families when httpx is
# installed, so user errors keep their specific handling without making httpx a
# FastMCP dependency. The two libraries' exception hierarchies match name-for-name.
try:
import httpx
HTTP_STATUS_ERRORS: tuple[type[BaseException], ...] = (
httpx2.HTTPStatusError,
httpx.HTTPStatusError,
def _is_legacy_httpx_exception(exc: BaseException, exception_type: str) -> bool:
"""Check a legacy-httpx exception without importing the legacy package."""
return any(
cls.__module__.partition(".")[0] == "httpx" and cls.__name__ == exception_type
for cls in type(exc).__mro__
)
TIMEOUT_ERRORS: tuple[type[BaseException], ...] = (
httpx2.TimeoutException,
httpx.TimeoutException,
def is_http_status_error(exc: BaseException) -> bool:
"""Return whether an exception is an httpx2 or legacy-httpx status error."""
return isinstance(exc, httpx2.HTTPStatusError) or _is_legacy_httpx_exception(
exc, "HTTPStatusError"
)
REQUEST_ERRORS: tuple[type[BaseException], ...] = (
httpx2.RequestError,
httpx.RequestError,
def get_http_status_code(exc: BaseException) -> int | None:
"""Return the response status code from a recognized HTTP status error."""
if not is_http_status_error(exc):
return None
status_code = getattr(getattr(exc, "response", None), "status_code", None)
return status_code if isinstance(status_code, int) else None
def is_timeout_error(exc: BaseException) -> bool:
"""Return whether an exception is an httpx2 or legacy-httpx timeout."""
return isinstance(exc, httpx2.TimeoutException) or _is_legacy_httpx_exception(
exc, "TimeoutException"
)
def is_request_error(exc: BaseException) -> bool:
"""Return whether an exception is an httpx2 or legacy-httpx request error."""
return isinstance(exc, httpx2.RequestError) or _is_legacy_httpx_exception(
exc, "RequestError"
)
except ImportError:
HTTP_STATUS_ERRORS = (httpx2.HTTPStatusError,)
TIMEOUT_ERRORS = (httpx2.TimeoutException,)
REQUEST_ERRORS = (httpx2.RequestError,)
def iter_exc(group: BaseExceptionGroup):

View file

@ -3,7 +3,12 @@ from __future__ import annotations
from collections import defaultdict
from typing import Any
from jsonref import JsonRefError, replace_refs
def replace_refs(*args: Any, **kwargs: Any) -> Any:
"""Call jsonref lazily while preserving the module's patchable boundary."""
from jsonref import replace_refs as _replace_refs
return _replace_refs(*args, **kwargs)
def _copy_schema(schema: dict[str, Any]) -> dict[str, Any]:
@ -221,6 +226,10 @@ def dereference_refs(schema: dict[str, Any]) -> dict[str, Any]:
if _defs_have_cycles(schema.get("$defs", {})):
return resolve_root_ref(schema)
# Most schema operations do not dereference. Keep jsonref (and its requests
# dependency tree) out of server startup until a schema actually needs it.
from jsonref import JsonRefError
try:
# Use jsonref to resolve all $ref references
# proxies=False returns plain dicts (not proxy objects)

View file

@ -1,7 +1,9 @@
"""Logging utilities for FastMCP."""
import contextlib
import importlib.util
import logging
from pathlib import Path
from typing import Any, Literal, cast
from rich.console import Console
@ -11,6 +13,17 @@ from typing_extensions import override
import fastmcp
def _get_package_path(package: str) -> str | None:
"""Return a package directory without importing the package."""
try:
spec = importlib.util.find_spec(package)
except ImportError:
return None
if spec is None or spec.origin is None:
return None
return str(Path(spec.origin).parent)
def get_logger(name: str) -> logging.Logger:
"""Get a logger nested under FastMCP namespace.
@ -83,14 +96,11 @@ def configure_logging(
# no path or level name to maximize width available for the traceback
# suppress framework frames and limit the number of frames to 3
import pydantic
try:
import mcp
except ImportError:
tracebacks_suppress = [fastmcp, pydantic]
else:
tracebacks_suppress = [fastmcp, mcp, pydantic]
tracebacks_suppress = [
package_path
for package in ("fastmcp", "mcp", "pydantic")
if (package_path := _get_package_path(package)) is not None
]
# Build traceback kwargs with defaults that can be overridden
traceback_kwargs = {

View file

@ -47,7 +47,7 @@ OpenAPI Spec → Parser → HTTPRoute with Pre-calculated Fields → RequestDire
### Request Processing
```
MCP Tool Call → RequestDirector.build() → httpx.Request → HTTP Response → Structured Output
MCP Tool Call → RequestDirector.build() → httpx2.Request → HTTP Response → Structured Output
```
1. **Tool Invocation**: FastMCP receives tool call with parameters
@ -103,14 +103,14 @@ All components use the same RequestDirector approach:
### Basic Server Setup
```python
import httpx
import httpx2
from fastmcp.server.openapi import FastMCPOpenAPI
# OpenAPI spec (can be loaded from file/URL)
openapi_spec = {...}
# Create HTTP client
async with httpx.AsyncClient() as client:
async with httpx2.AsyncClient() as client:
# Create server with stateless request building
server = FastMCPOpenAPI(
openapi_spec=openapi_spec,
@ -134,8 +134,8 @@ director = RequestDirector(spec)
# Build HTTP request
request = director.build(route, flat_arguments, base_url)
# Execute with httpx
async with httpx.AsyncClient() as client:
# Execute with httpx2
async with httpx2.AsyncClient() as client:
response = await client.send(request)
```
@ -206,6 +206,6 @@ Tests are located in `/tests/server/openapi/`:
## Dependencies
- `openapi-core` - OpenAPI specification processing and validation
- `httpx` - HTTP client library
- `httpx2` - HTTP client library
- `pydantic` - Data validation and serialization
- `urllib.parse` - URL building and manipulation
- `urllib.parse` - URL building and manipulation

View file

@ -0,0 +1,74 @@
"""Lazy helpers for FastMCP's optional Prefab UI integration."""
from __future__ import annotations
import sys
from functools import lru_cache
from importlib.util import find_spec
from typing import Any
@lru_cache(maxsize=1)
def prefab_available() -> bool:
"""Return whether Prefab UI is installed without importing it."""
return find_spec("prefab_ui") is not None
@lru_cache(maxsize=1)
def _get_prefab_types() -> tuple[type[Any], type[Any]] | None:
"""Import and return Prefab's public app and component types on demand."""
if not prefab_available():
return None
from prefab_ui.app import PrefabApp
from prefab_ui.components.base import Component
return PrefabApp, Component
def _could_be_prefab(value_or_type: Any) -> bool:
"""Cheaply reject ordinary values before importing Prefab UI."""
candidate_type = (
value_or_type if isinstance(value_or_type, type) else type(value_or_type)
)
module = getattr(candidate_type, "__module__", "")
return (
"prefab_ui" in sys.modules
or module == "prefab_ui"
or module.startswith("prefab_ui.")
)
def is_prefab_type(candidate: Any) -> bool:
"""Return whether a type is a Prefab app or component type."""
if not isinstance(candidate, type) or not _could_be_prefab(candidate):
return False
prefab_types = _get_prefab_types()
return prefab_types is not None and issubclass(candidate, prefab_types)
def is_prefab_app(value: Any) -> bool:
"""Return whether a value is a Prefab app."""
if not _could_be_prefab(value):
return False
prefab_types = _get_prefab_types()
return prefab_types is not None and isinstance(value, prefab_types[0])
def is_prefab_component(value: Any) -> bool:
"""Return whether a value is a Prefab component."""
if not _could_be_prefab(value):
return False
prefab_types = _get_prefab_types()
return prefab_types is not None and isinstance(value, prefab_types[1])
def prefab_app_from_component(component: Any) -> Any:
"""Wrap a Prefab component in a Prefab app."""
prefab_types = _get_prefab_types()
if prefab_types is None or not isinstance(component, prefab_types[1]):
raise TypeError("Expected a Prefab UI component")
return prefab_types[0](view=component)

View file

@ -205,7 +205,7 @@ async def download_skill(
# Write content
if isinstance(content, mcp_types.TextResourceContents):
file_path.write_text(content.text)
file_path.write_text(content.text, encoding="utf-8")
elif isinstance(content, mcp_types.BlobResourceContents):
file_path.write_bytes(base64.b64decode(content.blob))
else:

Some files were not shown because too many files have changed in this diff Show more