Compare commits

..

470 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
Jeremiah Lowin
1eedd1f6f1
Docs: add v3.4.2 and v3.4.3 changelog entries (#4430) 2026-07-05 19:27:01 -04:00
dependabot[bot]
3b1afe6cf1
chore(deps): bump joserfc from 1.6.7 to 1.6.8 in the uv group across 1 directory (#4429)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-05 19:16:30 -04:00
marvin-context-protocol[bot]
874425a113
chore: Update SDK documentation (#4427) 2026-07-05 19:16:03 -04:00
Jeremiah Lowin
691766b5d0
[codex] Fix OpenAPI resource template requests (#4407) 2026-07-05 19:11:03 -04:00
Jeremiah Lowin
47907e0767
Fix ty 0.0.55 diagnostics and prefab-ui protocol version drift (#4428) 2026-07-05 19:10:40 -04:00
Jeremiah Lowin
c1b0396c0a
Block IPv6 transition SSRF bypasses (#4426) 2026-07-05 17:52:57 -04:00
陈家名
522ed5bb30
fix: correct replace_type docstring parameter descriptions (#4375) 2026-07-05 17:44:28 -04:00
Jeremiah Lowin
67527c1f69
Block unsafe OAuth redirect schemes (#4419) 2026-07-05 17:16:10 -04:00
Jeremiah Lowin
57a279928d
Protect streamable HTTP from DNS rebinding (#4405) 2026-07-05 17:11:08 -04:00
Jeremiah Lowin
cccb529f50
Fix DCR redirect URI validation (#4408) 2026-07-05 17:05:13 -04:00
fengguodong
0d8844d5a7
Reject empty env var keys (#4410) 2026-06-29 09:42:06 -04:00
Jeremiah Lowin
de521e651d
Fix versioned auth middleware checks (#4401) 2026-06-28 10:43:34 -04:00
Jeremiah Lowin
feaae683a4
[codex] Fix event store replay isolation (#4402) 2026-06-27 12:49:24 -04:00
Jeremiah Lowin
5de15e0c21
Block NAT64 SSRF bypass (#4400) 2026-06-27 12:21:37 -04:00
Jeremiah Lowin
a1dd8b12e1
Fix dev apps launch escaping (#4399) 2026-06-27 12:18:36 -04:00
Jeremiah Lowin
6b2a2d507a
Clarify resource path parameter safety (#4398) 2026-06-27 12:10:37 -04:00
Jeremiah Lowin
a8bb1b08c2
Raise fastmcp.ValidationError for invalid tool arguments (#4392)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-06-27 11:14:20 -04:00
Jacky Su
0668eb7b80
Fix/cimd flow issue (#4206) 2026-06-27 10:57:58 -04:00
marvin-context-protocol[bot]
4d5627ba5d
chore: Update SDK documentation (#4360) 2026-06-27 10:36:03 -04:00
dependabot[bot]
7643480bd6
chore(deps): bump joserfc from 1.6.5 to 1.6.7 in the uv group across 1 directory (#4394)
Signed-off-by: dependabot[bot] <support@github.com>
2026-06-27 10:35:50 -04:00
Jeremiah Lowin
dc4b0e202d
fix(tools): honor serialize_by_alias in tool result serialization (#4391) 2026-06-27 10:24:39 -04:00
Jeremiah Lowin
cccff4849e
fix(deps): clear Dependabot security alerts via lockfile bumps (#4393) 2026-06-27 10:22:36 -04:00
Jeremiah Lowin
0cffe41115
fix: validate task tool arguments against declared types (#4373) 2026-06-27 10:03:59 -04:00
Jeremiah Lowin
a612846224
fix: bound default OIDC discovery timeout and expose it on provider wrappers (#4374) 2026-06-24 17:16:18 -04:00
Jeremiah Lowin
ade2b3ff46
fix: bracket IPv6 hosts in server startup log URL (#4372) 2026-06-24 17:15:40 -04:00
Jeremiah Lowin
094908042c
fix(resources): round-trip path values with reserved characters in URI templates (#4368) 2026-06-24 13:56:04 -04:00
Jeremiah Lowin
a13e48ea6f
feat(remote): add --verify flag for TLS certificate verification (#4369) 2026-06-24 12:09:22 -04:00
Bobby Davidson
7f2d034f4d
Forward IdP auth errors to MCP client instead of showing HTML error page (#4293)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-06-24 12:09:09 -04:00
Alex LaGuardia
ea63d06241
docs: add audit/event-record recipe for tool-call middleware (#4345)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:03:11 -04:00
Michael@WCD
0d5667bed2
docs: fix 5 broken internal links (auth & providers pages) (#4344)
Co-authored-by: Michael Tierney <MichaelTierney315@outlook.com>
2026-06-24 12:02:20 -04:00
Jianke LIN
ba77e4626b
fix: guard recursive refs in json_schema_to_type (#4312) 2026-06-24 11:53:36 -04:00
Perseus Computing
222742a737
fix: StatefulProxyClient.clear() no longer causes KeyError on session teardown (#4328) 2026-06-24 11:53:22 -04:00
Jeremiah Lowin
6429909f05
Switch prettier hook to rbubley/mirrors-prettier (#4366) 2026-06-24 11:52:40 -04:00
Alex LaGuardia
27a0720928
Add real Monty sandbox e2e coverage for CodeMode call_tool (#4274)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-06-24 11:52:27 -04:00
Jeremiah Lowin
47101eeccd
fix: RST docstrings in fastmcp.types render raw on gofastmcp.com (#4367)
Co-authored-by: Justin van Zyl <justin.vanzyl@xero.com>
2026-06-24 11:52:05 -04:00
Jeremiah Lowin
cf1d821129
fix(fs): isolate same-named package imports across providers (#4361) 2026-06-24 10:57:01 -04:00
Jeremiah Lowin
ddcdf64813
fix(proxy): shield stateful proxy disconnect during session teardown (#4363) 2026-06-24 10:56:40 -04:00
Jeremiah Lowin
5fa4f32cca
Dedupe discriminator-required helper across schema converters (#4362) 2026-06-24 10:54:03 -04:00
dependabot[bot]
0ca2c0d115
chore(deps): bump actions/checkout from 6 to 7 (#4343)
Signed-off-by: dependabot[bot] <support@github.com>
2026-06-24 10:39:32 -04:00
Yufeng He
9b1a1a04e0
fix: preserve required discriminator tags (#4297)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-06-24 10:36:56 -04:00
Jeremiah Lowin
d7730788fa
Recognize all GitHub issue-link forms in require-issue-link workflow (#4359) 2026-06-24 10:28:36 -04:00
Tomasz Czochański
4ce8e2a5d0
Fix: async rate limiting middleware get_client_id callbacks (#4319)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-24 10:27:30 -04:00
Greig Menzies
257fe32556
fix: caching middleware TypeError on cache miss due to mismatched call_next parameter (#4301) 2026-06-24 10:27:18 -04:00
Jeremiah Lowin
3b8538e242
Allow private JWT headers (#4290) 2026-06-06 02:23:48 +01:00
marvin-context-protocol[bot]
0445c31fef
chore: Update SDK documentation (#4223) 2026-06-06 02:23:33 +01:00
Jeremiah Lowin
9261793ae0
Docs: add v3.4.1 changelog entries (#4289) 2026-06-06 02:06:45 +01:00
Jeremiah Lowin
e1b52d00fe
Add explicit starlette>=1.0.1 floor (CVE-2026-48710) (#4286) 2026-06-05 08:42:59 -04:00
Jeremiah Lowin
e58f386bac
Log refresh-token misses in OAuthProxy instead of failing silently (#4276) 2026-06-03 11:22:35 -04:00
Jeremiah Lowin
3f09c683cc
Document --notes-start-tag requirement in release instructions (#4275) 2026-06-03 10:14:28 -04:00
Jeremiah Lowin
e124bde34e
Fix MDX syntax error in changelog (#4270) 2026-06-02 22:20:44 -04:00
Jeremiah Lowin
dae11bbc40
Backfill changelog and updates through v3.4.0 (#4269) 2026-06-02 22:15:02 -04:00
René Mulder
0f4f78c464
Fix resource templates with query params on proxied servers (#4251)
Co-authored-by: René Mulder <rene@silverflow.com>
2026-05-31 14:03:49 -04:00
Jeremiah Lowin
1a06130fcf
Fix GitHub MCP resource integration test (#4253) 2026-05-30 11:48:46 -04:00
Jeremiah Lowin
58e0f5320b
Decouple FastMCP access token lifetime from upstream expires_in (#4254) 2026-05-30 11:48:23 -04:00
Jeremiah Lowin
8e66b0a47a
Upgrade ty to 0.0.39 (#4225) 2026-05-30 11:25:05 -04:00
Jeremiah Lowin
53b20168c8
Close upstream OAuth clients (#4248) 2026-05-27 19:45:45 -04:00
Diogo Santos
989f6f8bde
docs: add tool fingerprinting recipe for stable schema hashing (#4233)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-27 10:52:14 -04:00
Jeremiah Lowin
140d96aadd
Forward proxy initialize as bridge behavior (#4228) 2026-05-27 10:41:49 -04:00
Bálint Hantos
e9848d66a3
fix: Trendshift link and badge in README.md (#4236) 2026-05-26 14:18:15 -04:00
Jeremiah Lowin
a25ca12a41
Restore Horizon docs banner (#4240) 2026-05-26 14:09:10 -04:00
Bill Easton
802ceaaa6b
Add targeted coverage tests (#4230)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-25 18:57:28 -04:00
Jeremiah Lowin
2bff3725bf
Surface proxy upstream failures (#4227) 2026-05-23 14:56:10 -04:00
Jeremiah Lowin
986353f26b
Skip published docs update for prereleases (#4224) 2026-05-23 10:45:36 -04:00
Jeremiah Lowin
59223f6e89
Allow pre-bound HTTP sockets (#4222) 2026-05-23 10:08:49 -04:00
Jeremiah Lowin
70013c5a91
Add fastmcp-remote bridge package (#4208) 2026-05-23 10:04:21 -04:00
Jeremiah Lowin
b8c9d58d61
Migrate auth JWTs to joserfc (#4221) 2026-05-23 09:29:04 -04:00
Jeremiah Lowin
9b5d402bf2
Exempt maintainers from MRE auto-close (#4220) 2026-05-23 09:02:44 -04:00
marvin-context-protocol[bot]
6acacf2191
chore: Update SDK documentation (#4155) 2026-05-23 08:54:28 -04:00
Jeremiah Lowin
292e9af087
Update published docs after PyPI release (#4211) 2026-05-23 08:53:38 -04:00
Jeremiah Lowin
44180d1e3d
Add uv dependency cooldown (#4213) 2026-05-23 08:53:20 -04:00
Jeremiah Lowin
986af54afa
Move pip upgrade recovery into a Troubleshooting section (#4219) 2026-05-22 21:13:19 -04:00
Jeremiah Lowin
7a82b57efb
Document pip upgrade recovery for the fastmcp-slim package split (#4215) 2026-05-22 20:21:28 -04:00
Jeremiah Lowin
e242abee7d
Let ToolResult return an error result via is_error (#4217) 2026-05-22 20:20:52 -04:00
Jeremiah Lowin
8382569027
Add contract gate to review-issue skill (#4214) 2026-05-22 20:08:48 -04:00
Jeremiah Lowin
0e5ec37597
Add review-issue skill for triaging gated external contributions (#4212) 2026-05-22 18:47:15 -04:00
Jeremiah Lowin
fd4d24ff62
Guard require-issue-link check job to pull_request_target events (#4209) 2026-05-22 18:43:46 -04:00
Jeremiah Lowin
b194349983
Add outbound comment guardrails (#4196) 2026-05-21 06:42:48 -04:00
Jeremiah Lowin
2ac23a4de5
Fix docs app demo iframe assets (#4194) 2026-05-20 13:18:45 -04:00
Jordan Ritter
1222e8e47a
Security: Fix 3 findings in GitHub Actions workflows (#4183)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 12:37:31 -04:00
Bill Easton
b4c35027c2
fix(ci): scope minimize-reviews concurrency by event name (#4174)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 12:23:18 -04:00
yuyua9
dbf5ee24be
fix(cli): forward stateless flag in uv run path (#4177)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 12:22:45 -04:00
rgillinlz
81a16ed27f
fix(auth): unprefix Azure scopes echoed back to MCP clients (#4130)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 12:22:24 -04:00
mohanram
0022d8518f
Add token_expiry_threshold_seconds for proactive token refresh (#4142)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 10:47:26 -04:00
Bill Easton
9d384ffa7f
feat(code-mode): default sandbox limits and per-execution tool-call cap (#4170)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 10:47:12 -04:00
Bill Easton
bdbef49383
fix(code-mode): cancel Monty sandbox future on task cancellation (#4169) 2026-05-20 10:36:31 -04:00
Shigechika AIKAWA
2a262438fa
fix(auth): add /.well-known/openid-configuration alias for OAuth server metadata (#4167)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:36:01 -04:00
Bill Easton
1c4069efa3
fix(proxy): restore _current_server in _restore_request_context (#4168) 2026-05-20 10:34:00 -04:00
Tiago Surjus Kaneta
b0fb2c3ae6
Add valid_scopes and extra_authorize_params to WorkOSProvider (#4135) 2026-05-20 10:31:48 -04:00
dependabot[bot]
7cfcaf22b8
chore(deps-dev): bump pydantic-monty from 0.0.16 to 0.0.17 (#4023)
Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com>
Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
Signed-off-by: dependabot[bot] <support@github.com>
2026-05-20 10:31:27 -04:00
yuyua9
834f96d462
fix(schema): preserve root metadata on fallback (#4178) 2026-05-20 09:46:56 -04:00
Pragnyan Ramtha
5c2627cb15
fix(config): read MCP config files as UTF-8 (#4164)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 09:43:27 -04:00
Bill Easton
2d61d8a46b
fix: add OTEL spans to sampling step and tool execution (#4059)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 09:38:58 -04:00
Bill Easton
01b971d80d
fix: preserve annotations, meta, title, icons when creating resources from templates (#4061)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 09:38:19 -04:00
dependabot[bot]
d6984f4719
chore(deps): bump the uv group across 2 directories with 1 update (#4113)
Signed-off-by: dependabot[bot] <support@github.com>
2026-05-20 09:37:51 -04:00
itaru2622
7fddab52a9
feat: new options --host and --no-log-panel | --log-panel to cli dev apps (#4123) 2026-05-20 09:37:32 -04:00
Bill Easton
344a4f81b5
fix(auth): disambiguate auth-denied vs missing component messages (#4165) 2026-05-20 09:36:27 -04:00
Bill Easton
11951585c0
fix(tests): hoist azure-identity import out of the OBO test timeout window (#4176) 2026-05-20 09:35:56 -04:00
Bill Easton
24b594b1e3
fix: VersionSpec eq matching normalizes versions and selects deterministically (#4058)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 09:35:25 -04:00
Bill Easton
d3ff774c78
ci: require external PRs to link a tracked issue (#4173)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-20 08:43:52 -04:00
Jeremiah Lowin
d8dcc273ca
Decouple component imports from server (#4150) 2026-05-15 11:49:08 -04:00
Jeremiah Lowin
255e3e4910
fix(docs): use valid FA icon on client-only package page (#4139) 2026-05-14 22:14:38 -04:00
marvin-context-protocol[bot]
73df4dcaee
chore: Update SDK documentation (#4096) 2026-05-14 22:06:38 -04:00
Jeremiah Lowin
ee48a0fd6e
Refine fastmcp-slim packaging (#4125)
* Refine fastmcp-slim packaging

* Format install hints
2026-05-12 07:11:57 -07:00
Jeremiah Lowin
bb4894d215
Add fastmcp-slim for client-only installs (#4122)
* Add fastmcp-client workspace package

* Fix client package static checks

* Document client-only package

* Harden fastmcp-client package split

* Preserve forwarded headers in full package

* Switch to fastmcp-slim package

* Fix fastmcp-slim release edges

* Match pydantic-style slim layout

* Polish fastmcp-slim packaging
2026-05-11 17:13:21 -04:00
Sarthak Bhardwaj
8209093871
fix(http): terminate active streamable-HTTP transports before lifespan shutdown (#4118) 2026-05-10 10:58:13 -04:00
Kiran Thakkar
cf59a4511f
Fix OCI Provider issue in 3.x version. Add OCI auth provider example … (#4116)
* Fix OCI Provider issue in 3.x version. Add OCI auth provider example and test

* Fix OCI Provider issue in 3.x version. Add OCI auth provider example and test. Fixed a couple of minor issues in README.

* Rerun CI
2026-05-10 10:08:00 -04:00
Craig Ringer
89b99ecfb9
fix(proxy): fall back to live identifier for backend_* span attributes (#4109)
🤖 Generated with Claude Code (Opus 4.7) on behalf of @ringerc

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 10:07:57 -04:00
itaru2622
310314cf14
fix: cli option --no-banner is NOT passed to cli but server-spec in-correctly when cli --reload option is specified. (#4083) 2026-05-09 14:57:42 -04:00
sergeykad
28722f846a
fix: drop exc_info for expected tool failures, remove unreachable ValidationError (#4029) 2026-05-09 14:56:17 -04:00
Owen Taylor
567b832bca
fix: Don't completely hide plain mcp.tool app-only tools (#4112) 2026-05-09 14:55:20 -04:00
Shaik Mohammed Kaif
6b6db33c4a
#4084 [Issues] Windows startup crash due to UnicodeDecodeError when l… (#4092)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-07 15:30:56 -04:00
Jeremiah Lowin
3d476ca01e
fix: don't cache import map in dev apps bundle (#4106) 2026-05-07 11:46:13 -04:00
Sarthak Bhardwaj
aaff9243a3
fix(auth): silence authlib.jose DeprecationWarning at JWT import (#4100)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-07 11:27:08 -04:00
Sarthak Bhardwaj
b8597f941d
fix(tool_transform): hoist $defs to schema root when ArgTransform introduces them (#4101) 2026-05-07 11:10:52 -04:00
Jeremiah Lowin
4719f3055a
Make Docket reentrant; mounted servers enter their own lifespan (#4095) 2026-05-04 17:36:50 -04:00
Taylor Wilsdon
61e56c683e
enh: Add public API for updating OAuthProxy scopes after initialization (#4091) 2026-05-04 15:49:12 -04:00
marvin-context-protocol[bot]
074189265d
chore: Update SDK documentation (#3988)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-05-04 15:34:27 -04:00
Chris Guidry
a037bd8cc7
Bump pydocket to 0.20.0 (#4031)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 15:34:06 -04:00
cuyua9
0b59af9489
Fix sampling from background tasks (#4068)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-04 12:52:35 -04:00
Ashwin Madavan
44d3f8d858
fix(ping): exit ping loop cleanly when session stream is closed (#4087) 2026-05-04 12:50:39 -04:00
Mukunda Rao Katta
20359de953
Fix #4056: keep blank query values, add token bucket regression test (#4069)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-04 12:44:38 -04:00
Mukunda Rao Katta
1cfd30840d
fix(openapi): keep blank values in parse_qs (refs #4056) (#4076)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-04 12:44:06 -04:00
Daniel Tsiang
73b7f2e44d
Add log_level parameter to FastMCP errors (#4036)
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-05-04 12:38:16 -04:00
Jeremiah Lowin
51e339d8ed
docs: fix broken links in Pydantic AI guide (#4094) 2026-05-04 12:35:35 -04:00
chaoliang yan
2ffe68cfa1
fix: preserve tool decorator metadata (#4072)
Generated with Codex.

Co-authored-by: lawrence3699 <lawrence3699@users.noreply.github.com>
2026-05-04 12:22:31 -04:00
Mukunda Rao Katta
f5dea2a17c
docs(integrations): add Pydantic AI FastMCP toolset guide (#4070)
* docs(integrations): add Pydantic AI FastMCP toolset guide

* docs(integrations): add Pydantic AI to AI SDKs nav
2026-05-04 12:22:17 -04:00
Jeremiah Lowin
d0315974fa
Add UTM tracking to Horizon links (#4064) 2026-04-26 08:38:05 -04:00
Jeremiah Lowin
b96ce24e35
Refresh landing page copy (#4047) 2026-04-25 22:06:30 -04:00
Jeremiah Lowin
6f3ea0b929
Refresh landing page copy (#4043) 2026-04-25 14:46:48 -04:00
Jeremiah Lowin
a010927ea5
Add experimental_capabilities kwarg to FastMCP constructor (#4042)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-25 12:24:54 -04:00
Jeremiah Lowin
0fe01372f0
Partition ResponseCachingMiddleware cache by access token (#4041)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-25 12:09:11 -04:00
Mukunda Rao Katta
c740b6d70a
docs: add best practices for custom telemetry spans (#4001) 2026-04-25 11:43:31 -04:00
Bill Easton
4be46c6fa6
Add a sandboxed-agents deployment guide (#4027)
* Add sandboxed agents deployment guide

* Tighten sandboxed agents guide

* Refine sandboxed agents docs flow

---------

Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-04-25 11:40:56 -04:00
Zach Leventer
07c34acb12
Add missing return type annotation to __getattr__ (#4026) 2026-04-25 11:35:27 -04:00
Adam Azzam
e95efce988
Add UTM params to Horizon docs links (#4018)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 16:47:55 -04:00
Jeremiah Lowin
74efa32edf
Add run_in_thread opt-out for sync tools with thread affinity (#4010)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-22 10:31:44 -04:00
Jeremiah Lowin
485747353e
fix: cancel orphaned session_task when Client._disconnect times out (#4011)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-22 10:17:00 -04:00
Jeremiah Lowin
008f91d84b
fix: narrow _token_validator with isinstance for ty in AzureProvider.from_b2c (#4007)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-22 09:30:37 -04:00
Carlos Rian
eebdc8c031
feat: add AzureB2CProvider for Azure AD B2C user flows (#3995) 2026-04-22 09:24:09 -04:00
Jeremiah Lowin
2d6143c6d8
fix: honor upstream refresh token expiry in OAuthProxy (#3990) 2026-04-20 14:03:57 -04:00
dependabot[bot]
db6bc3e94c
chore(deps-dev): bump pydantic-monty from 0.0.14 to 0.0.16 (#3984)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-04-20 13:26:23 -04:00
marvin-context-protocol[bot]
34f6e68826
chore: Update SDK documentation (#3969)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-04-20 13:00:37 -04:00
chaoliang yan
5009d64465
fix: handle circular JSON Pointer $ref in dereference_refs (#3896)
Co-authored-by: lawrence3699 <lawrence3699@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-04-20 13:00:18 -04:00
Jeremiah Lowin
a075b14432
Be constructively skeptical of bot reviews on own PRs (#3971) 2026-04-18 17:22:54 -04:00
Jeremiah Lowin
801385df44
fix: bound _refresh_locks with LRU eviction to prevent memory leak (#3968) 2026-04-18 11:07:38 -04:00
Jeremiah Lowin
64fbc52e1d
fix: skip stdio subprocess test on Windows CI (#3966)
Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com>
2026-04-18 10:30:03 -04:00
dependabot[bot]
c759890d9e
chore(deps-dev): bump pydantic-monty from 0.0.11 to 0.0.12 (#3940)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jeremiah Lowin <153965+jlowin@users.noreply.github.com>
2026-04-17 21:06:00 -04:00
marvin-context-protocol[bot]
b4c4cfd3d5
chore: Update SDK documentation (#3917)
Co-authored-by: marvin-context-protocol[bot] <225465937+marvin-context-protocol[bot]@users.noreply.github.com>
2026-04-17 18:29:09 -04:00
Jeremiah Lowin
37a46231fd
Bump deps with open dependabot alerts (#3965) 2026-04-17 18:04:22 -04:00
Jeremiah Lowin
97bff96ef1
Revert "Forward backend capabilities in ProxyProvider (#3956)" (#3964)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-17 17:51:27 -04:00
Jeremiah Lowin
1e67c53a17
Reject dot-segments in redirect URI allowlist matching (#3963) 2026-04-17 17:49:25 -04:00
Gnani Rahul
ff8aa484ff
docs: standardize ToolAnnotations examples (#3952) 2026-04-17 16:42:57 -04:00
Jeremiah Lowin
e1ea695d68
Restructure docs navigation (#3951)
Co-authored-by: Jeremiah Lowin <jlowin@users.noreply.github.com>
Co-authored-by: Marvin Context Protocol <41898282+Marvin Context Protocol@users.noreply.github.com>
2026-04-17 16:42:39 -04:00
Jeremiah Lowin
789a298650
Graceful fallback for unsupported regex patterns in json_schema_to_type (#3959)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-17 16:42:10 -04:00
Jeremiah Lowin
7fb037f20c
Harden OAuth Proxy silent consent against AS-in-the-middle (#3960) 2026-04-17 16:39:50 -04:00
Jeremiah Lowin
eb1426251c
Allow upstream client_id to be used directly without DCR (#3957)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-17 15:22:44 -04:00
Jeremiah Lowin
98f69bdba0
Forward backend capabilities in ProxyProvider (#3956)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-17 15:22:08 -04:00
Jeremiah Lowin
e3f845f558
Improve real-world schema crash test: failure dump, cluster analysis, TypeErrors baseline ratchet (#3958)
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-17 15:08:48 -04:00
Chris Guidry
34313ea112
Restore task snapshot via a worker-level dependency (#3945)
* Restore task snapshot via a worker-level dependency

`get_access_token()` returned `None` inside background tasks whenever
`FASTMCP_DOCKET_URL` pointed at a `redis+cluster://` URL. The write side
was fine — it went through `docket.redis()`, which is cluster-aware —
but fastmcp kept a parallel sync Redis client just to read the snapshot
back, and `Redis.from_url()` rejects the cluster scheme.

Docket 0.19.1 ships worker-level dependencies that resolve per task in
the same asyncio.Task as user code, so ContextVars propagate cleanly.
That lets us load the snapshot once via `restore_task_snapshot` and
drop the sync Redis path entirely. Sync helpers like
`get_access_token()` and `get_http_request()` now just read a
ContextVar; Docket is the sole Redis consumer.

Closes #3897

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Revert TaskKey stub to a plain return

NotImplementedError would fire at module import if anything evaluated
the default; a no-op stub keeps the module usable without the
fastmcp[tasks] extra, which is what we want.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 08:24:42 -04:00
Jeremiah Lowin
ac1416bd2e
fix tests that relied on task=True returning error results (#3954) 2026-04-17 07:48:46 -04:00
Bill Easton
39b421a464
OTEL: Instrument all MCP list operations and enrich delegate spans (#3890)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 18:45:50 -04:00
Bill Easton
5593cf3e11
fix: FileSystemProvider reload race condition (#3938)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 18:45:11 -04:00
Gnani Rahul
012f674ee4
Fix raise_on_error handling for tool tasks (#3946) 2026-04-16 18:37:52 -04:00
Bill Easton
7dd573980a
fix: OpenAPI request director sends multipart and form-urlencoded as JSON (#3932)
* fix: OpenAPI request director content-type dispatch and cookie params

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Stringify multipart form values and cookie params for httpx

httpx rejects non-string scalars in files= and cookies=.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add tests for non-string multipart values and cookie stringification

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Consolidate to single httpx.Request construction point

Eliminate early returns by using variables for files/data kwargs.
All httpx body kwargs accept None, so we set exactly one and
pass all to a single Request() call.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Use _query_scalar_to_str for multipart booleans, add tuple passthrough test

Reuse existing boolean serialization (true/false not True/False) for
multipart form fields. Add test for file-like tuple passthrough.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Normalize media type for dispatch, use OpenAPI serialization for cookies

- Strip content-type parameters (e.g. "; charset=utf-8") and lowercase
  before matching, so variants like "Multipart/Form-Data" match correctly
- Use _query_scalar_to_str for cookie values (true/false not True/False)
- Add boolean cookie test

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Preserve media-type parameters in Content-Type header

Use raw_content_type (with charset etc.) for the outgoing header,
normalized form only for dispatch matching.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Pass bytes/file-like values directly in multipart, add charset preservation test

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:28:55 -04:00
Bill Easton
970b92bb16
fix: allow hyphens in resource template parameter names (#3929)
* fix: allow hyphens in resource template parameter names

Normalize hyphens to underscores at the regex group level in build_regex()
and at the param extraction level in from_function(). No API changes —
build_regex still returns Pattern | None, match_uri_template still returns
the same dict shape.

Closes #3921

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Guard against query params clobbering path params

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add tests for wildcard hyphens, expand, and query clobber guard

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ruff format fix

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add collision detection for hyphen/underscore param name normalization

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:28:51 -04:00
Bill Easton
7184a4ca21
OTEL: Fix attribute compliance with MCP semantic conventions (#3889)
* OTEL: Fix attribute compliance and improve telemetry helpers

Attribute compliance:
- Remove rpc.system/service/method (MCP is not traditional RPC)
- Add gen_ai.tool.name on tools/call spans
- Add gen_ai.prompt.name on prompts/get spans
- Fix session_id check (truthy -> is not None)

Telemetry helper improvements:
- Add is_recording() guards to skip work on non-recording spans
- Add error.type attribute with __qualname__ on error spans
- Use isinstance check for ToolError to set "tool_error" error type
- Include exception message in span status description
- Add tool_name/prompt_name params to server_span and client_span

Client call_tool enrichment:
- Reflect tool-level errors (result.isError) on client span status
  so callers see ERROR even though the MCP protocol call succeeded

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: remove resource URI from span names to avoid high-cardinality

Per MCP semantic conventions, resource URIs SHOULD NOT be included in
span names by default since they can be unbounded (especially with
templates like users://{id}/profile). The URI remains available via
the mcp.resource.uri attribute.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add missing gen_ai/mcp attributes to proxy and delegate spans

- Proxy tool spans: add gen_ai.tool.name
- Proxy prompt spans: add gen_ai.prompt.name
- All delegate spans: add mcp.method.name
- Docs: remove rpc.* references, update span names and attributes table

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Hoist ToolError imports to module level, add rpc.* migration note

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:28:47 -04:00
Jeremiah Lowin
e4bb6666ab
Add default prefill to FormInput.collect_input (#3937) 2026-04-14 13:23:36 -04:00
Jeremiah Lowin
8c020adfc6
fix: narrow OpenAI audio format dict to Literal for ty (#3936) 2026-04-14 13:09:54 -04:00
Bill Easton
8d1b28958f
fix: prevent schema mutation in _prune_param and _convert_nullable_field (#3927)
🤖 Generated with Claude Code

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 12:10:27 -04:00
Bill Easton
4ea102b433
fix: ProxyTool crashes on non-TextContent error responses (#3926)
* fix: handle non-TextContent error responses in ProxyTool

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Avoid serializing binary content into ToolError messages

Use type name instead of str(content) to prevent dumping
large base64 payloads into error messages.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ruff format fix

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 12:10:23 -04:00
Bill Easton
757678bc7e
fix: reject self-mount to prevent infinite recursion (#3925)
* fix: server safety guards for self-mount, duplicate middleware, mount arg order

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Remove duplicate middleware and mount arg order checks

These are runtime type checking, not bugs — a type checker catches them.
Keep only the self-mount guard which is a semantic check.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 12:10:19 -04:00
Bill Easton
55f3cade10
Improve Claude workflow prompts based on output audit (#3934)
* Improve Claude workflow prompts based on 60-day output audit

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Encourage tl;dr-first structure and collapsible details across workflows

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Add quality gates, evidence standards, and calibration examples to workflows

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 11:06:12 -05:00
1369 changed files with 126009 additions and 52143 deletions

View file

@ -0,0 +1,168 @@
---
name: review-issue
description: Review an incoming external issue (and any gated-closed PR behind it) and decide whether to assign the contributor or decline. Use when the maintainer says "look at this issue", "review issue #N", "should we take this", or asks whether to assign someone. Assigning the author auto-reopens their PR for normal review. This is the entry point for incoming-issue triage — distinct from review-pr, which responds to bot reviews on your own open PR.
---
# Triaging contributions under the issue-link gate
FastMCP auto-closes external PRs unless the author is **assigned to a referenced issue**
(see [require-issue-link.yml](../../../.github/workflows/require-issue-link.yml)). The practical
effect: contributors open an issue, open a PR, get auto-closed, and ask to be assigned. The
maintainer almost never sees the PR directly — **the issue is the decision point**, and
**assigning the author is the single action that reopens their PR** and sends it into review.
This skill turns "look at this issue" into one of two outcomes:
- **Assign** — the issue is valid, we want it fixed, an external PR is appropriate, and a sound
PR already exists → assign the author (auto-reopens the PR) and queue it for code review.
- **Decline** — leave the issue/PR closed and explain why on the issue.
Be opinionated about declining. The gate moved spam from junk PRs to junk issues; this skill is
worthless if it just rubber-stamps assignment. Assignment is a commitment to review and likely
merge, not a courtesy.
## How the gate works (the part that matters here)
- External PR is closed unless its body has `Fixes/Closes/Resolves #N` **and** the author is
assigned to issue `#N`.
- **Assigning the author to the issue auto-reopens their closed PR** and re-runs the check —
this is the lever you pull. `gh issue edit N --add-assignee <login>`. The assignment fires a
`require-issue-link` run; expect it to pass. If it fails, the gate itself misbehaved (not the
PR) — investigate the run, don't re-assign.
- Maintainer-authored PRs are exempt. A `trusted-contributor` label exempts a contributor up
front. Reopening the PR or removing the `missing-issue-link` label applies a sticky
`bypass-issue-check`.
- Sibling bots have usually already run on the issue: `marvin-triage-issue` (investigates +
recommends), `marvin-dedupe-issues` / `auto-close-duplicates` (dupes), `auto-close-needs-mre`
(missing MRE). Read their comments before re-deriving anything.
## Step 1 — Orient
Read the issue, its bot triage, and any PR behind it. Run these together:
```bash
gh issue view N --repo PrefectHQ/fastmcp \
--json number,title,state,author,body,labels,assignees,comments
# Find PRs the author opened that reference this issue (they're likely CLOSED):
gh pr list --repo PrefectHQ/fastmcp --state all --search "author:<login> #N in:body" \
--json number,title,state,url,labels
```
If a PR exists, pull its metadata and any review-bot comments (CodeRabbit, Codex). Treat the bot
comments as leads, not conclusions — they often don't run on closed PRs at all, and even when
they do you still owe the PR your own read:
```bash
gh pr view <pr> --repo PrefectHQ/fastmcp --json number,title,body,labels,files,additions,deletions
gh pr view <pr> --repo PrefectHQ/fastmcp --comments
```
## Step 2 — Classify the issue (is it valid AND a real bug?)
- Is there a real, reproducible problem? For bugs, demand an MRE that shows FastMCP misbehaving
— not user config error, not a question, not an upstream-SDK issue.
- Is it a duplicate or already fixed on `main`? Check the dedupe bot's comment and recent commits.
- If the issue itself is weak, **stop here and decline** — don't evaluate the PR. A good PR
attached to a bad issue is still declined.
**A reproducible MRE is not the same as a bug.** This is the trap that produces wrong verdicts:
an MRE can demonstrate real, observable behavior that is nonetheless *not a bug*, because it
violates no contract the framework intends to hold. The decisive question is not "does this
reproduce?" but "does the demonstrated behavior violate the intended contract for this API?" A
shared-mutable-state MRE only matters if callers are *supposed* to mutate that state; an
ordering/timing MRE only matters if the framework promises an order; a "wrong" value only matters
relative to what the API guarantees. An MRE that has to reach past the supported surface to
trigger the behavior (mutating a field meant to be set only at construction, depending on an
internal that isn't part of the public contract) is showing you a property, not a defect.
You usually cannot read the intended contract off the code — the code shows what it *does*, not
what it *promises*. **The maintainer is often the only authoritative source for the contract, so
stopping to ask is legitimate and expected here.** Ask "is X a supported pattern / does this API
promise Y?" before sinking time into investigating a fix. If the behavior is in-contract correct,
decline — no matter how cleanly the PR fixes it, and no matter how real the MRE looks.
## Step 3 — Investigate the PR (mandatory; do NOT skip if a PR exists)
The most common failure of this skill is judging a PR from the diff hunk and the PR description
alone. That is a cursory review and it produces wrong verdicts — a redundant-looking conditional
can be a real bug fix; a tidy-looking diff can patch the wrong layer. **You cannot assess a PR
without reading the code it changes in context.** Reading `gh pr diff` is necessary but never
sufficient.
Do all of this before forming any opinion on quality:
1. **Read the diff in full**, then **open every file it touches in the repo** (`Read`, not just
the patch). The hunk shows *what changed*; the file shows *what it changed into*.
2. **Trace the functions and values the change depends on.** Grep for the called functions,
the fields being set, and the defaults. If the PR overrides or replaces a value, find what
produced the original value and what consumes it downstream.
3. **Establish the actual root cause from the issue's MRE**, then check whether the change fixes
*that* — at the layer where the bug originates, not a compensating patch elsewhere.
4. **Check consistency with adjacent code.** Does the new value/behavior match how nearby code
already handles the same case? An inconsistency is a real finding; a match is evidence the fix
is correct.
5. **Run or read the tests** the PR adds/changes — do they actually exercise the bug, and would
they fail without the fix?
Write down, for yourself, a one-line answer to: *what was broken, where, and does this change fix
it there?* If you can't answer from evidence you've actually read, you haven't investigated yet.
Then separate findings by severity: a **cosmetic** nit (style, a redundant-but-harmless line) is a
review comment, not a blocker. A **substantive** defect (wrong layer, breaks an adjacent path,
doesn't actually fix the MRE) changes the verdict. Don't let a cosmetic nit read as a reason to
decline, and don't let a clean style read as evidence of correctness.
## Step 4 — Decide if an external PR is appropriate (CONTRIBUTING.md)
This is the gate CONTRIBUTING.md actually enforces. Map the change to a category:
- **Simple, well-scoped bug fix** → external PR welcome. Assignable.
- **Docs / typo / example fix** → welcome. Assignable.
- **Auth provider** → assignable (auth is the one integration exception).
- **Enhancement / feature** → needs a maintainer-approved design proposal *in the issue first*.
Do **not** assign just because code exists. If the proposal is sound, the path is "approve the
approach in the issue, then assign" — not "assign because they were fast."
- **Third-party integration** (middleware, provider adapters, non-auth) → decline; belongs in a
separate package.
- **Sweeping / multi-subsystem change with no prior discussion** → decline.
Combine the category with the Step 3 investigation: does it fix the cause or paper over a symptom?
Does it read like unedited LLM output (verbose body, speculative/shotgun changes)? CONTRIBUTING.md
says we close those — a closed PR that reads that way is staying closed.
## Step 5 — Recommend, then act
Present a short verdict to the maintainer before mutating anything: **assign** or **decline**,
one or two sentences of reasoning, and the exact command you'll run. Wait for confirmation on
borderline calls; for clear-cut ones you may proceed and report.
**Assign** (valid issue + appropriate external contribution + sound PR exists):
```bash
gh issue edit N --repo PrefectHQ/fastmcp --add-assignee <login>
```
That reopens the PR automatically. Then hand off to code review — invoke the `code-review` /
`review-pr` skills on the reopened PR. Assignment is not approval; the code still gets the normal
pass.
If a PR's head branch was deleted, assignment can't reopen it — the workflow comments asking the
author to open a fresh PR. Don't try to force it.
**Decline** (invalid issue, wrong contribution type, or low-quality PR): leave it closed and
comment on the **issue** explaining the decision, pointing to the relevant CONTRIBUTING.md
section. Per repo rules, use `--body-file`, never inline `--body`, for any comment that could
contain `$`, backticks, or code:
```bash
gh issue comment N --repo PrefectHQ/fastmcp --body-file /tmp/triage-reply.md
```
Keep the reply short and point to the relevant CONTRIBUTING.md section. (If a `github-reply`
skill is available for maintainer voice/tone, use it — but it isn't required.)
## What this skill does NOT do
- It doesn't bypass the gate via `trusted-contributor` / `bypass-issue-check` — that's a
deliberate maintainer escalation, not a triage outcome.
- It doesn't merge. Assignment → reopen → review → (maybe) merge are distinct steps.
- It doesn't re-run the first-pass triage the bots already did; read their output instead.

View file

@ -94,6 +94,12 @@ After evaluating comments:
Codex sometimes re-posts old comments that reference code you've already fixed (they appear on the old commit's diff). These are stale — verify the fix is in the latest commit and reply noting the fix is already in place.
## Labels — never apply or invent them
**Do not apply labels to PRs or issues programmatically, and never create new ones.** Issues and PRs in this repo are auto-labeled by a bot based on title, body, and code changes — there's no fixed canonical list to match against, and GitHub's "add labels" API auto-creates any label name that doesn't already exist, so a typo or guessed name silently pollutes the repo's label list with a stray, uncolored duplicate. There is no MCP tool to delete a label, so a mistaken creation can only be cleaned up by hand in repo settings.
Don't call out a "suggested" or "appropriate" label in the PR body either — the bot doesn't read it, and it just adds noise.
## When a PR is ready
A PR is ready for human review when:

View file

@ -37,10 +37,15 @@ 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
default: "claude-opus-4-6"
default: "claude-opus-4-8"
allowed-bots:
description: "Allowed bot usernames, or '*' for all bots"
@ -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

@ -19,7 +19,7 @@ runs:
MAX_PROCS="2"
EXTRA_FLAGS=""
elif [ "${{ inputs.test-type }}" == "client_process" ]; then
MARKER="client_process"
MARKER="client_process or subprocess_heavy"
TIMEOUT="5"
MAX_PROCS="0"
EXTRA_FLAGS="-x"
@ -29,17 +29,33 @@ runs:
MAX_PROCS="0"
EXTRA_FLAGS="-x"
else
MARKER="not integration and not client_process and not conformance"
MARKER="not integration and not client_process and not subprocess_heavy and not conformance"
TIMEOUT="5"
MAX_PROCS="4"
EXTRA_FLAGS=""
fi
# Windows previously ran serially: parallel workers crashed intermittently
# when many tests spawned stdio subprocesses (#2715, reverted in #2726).
# Most of those tests now run in-memory, but tests that spawn a fresh
# interpreter importing all of FastMCP still crash xdist workers on the
# 2-core Windows runners. They carry the subprocess_heavy marker and run
# in the serial client_process step instead.
PARALLEL_FLAGS=""
if [ "$MAX_PROCS" != "0" ] && [ "${{ runner.os }}" != "Windows" ]; then
if [ "$MAX_PROCS" != "0" ]; then
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"

80
.github/scripts/triage-label.sh vendored Executable file
View file

@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Locked-down label helper for the Marvin triage workflow.
#
# Marvin runs on untrusted issue/PR bodies from non-write users, so it must
# NOT be handed raw `gh api` (that would expose every endpoint the app token
# can reach). This helper is the ONLY GitHub write it is allowed to perform:
# it adds or removes repository labels on the one issue/PR being triaged.
#
# The target repo and number come from the environment set by the workflow —
# never from the model — and the operation is fixed to the additive labels
# endpoint (POST/DELETE /repos/{repo}/issues/{n}/labels), which works for both
# issues and PRs and cannot clobber labels applied by other workflows.
set -euo pipefail
repo="${TRIAGE_REPO:?TRIAGE_REPO not set}"
number="${TRIAGE_NUMBER:?TRIAGE_NUMBER not set}"
if [[ ! "$number" =~ ^[0-9]+$ ]]; then
echo "TRIAGE_NUMBER must be numeric, got: $number" >&2
exit 1
fi
op="${1:-}"
shift || true
case "$op" in
add) method=POST ;;
remove) method=DELETE ;;
*)
echo "usage: triage-label.sh <add|remove> <label>..." >&2
exit 1
;;
esac
if [[ "$#" -eq 0 ]]; then
echo "no labels given" >&2
exit 1
fi
# Reject anything that isn't a plausible label name. Notably blocks '/' so a
# crafted value can't turn the DELETE path into a different endpoint.
label_re="^[A-Za-z0-9 ._'-]+$"
for label in "$@"; do
if [[ ! "$label" =~ $label_re ]]; then
echo "refusing suspicious label name: $label" >&2
exit 1
fi
done
# Never let triage add or remove the Require Issue Link control labels. Those
# govern PR enforcement (bypass-issue-check / trusted-contributor are sticky
# exemptions, "prs welcome" waives the assignment requirement) and reopening
# (missing-issue-link is how closed PRs are found), so a prompt-injected triage
# run must not be able to grant an exemption or break recovery. Enforced here —
# in code — not merely in the prompt.
#
# Exact match against array entries, not a substring scan of a joined string:
# label names may contain spaces ("prs welcome"), which in a space-delimited
# string would also make bare "prs" and "welcome" match.
protected=(missing-issue-link bypass-issue-check trusted-contributor "prs welcome")
for label in "$@"; do
lower="${label,,}"
for p in "${protected[@]}"; do
if [[ "$lower" == "$p" ]]; then
echo "refusing to touch protected control label: $label" >&2
exit 1
fi
done
done
if [[ "$method" == POST ]]; then
args=()
for label in "$@"; do
args+=(-f "labels[]=$label")
done
gh api --method POST "/repos/${repo}/issues/${number}/labels" "${args[@]}"
else
for label in "$@"; do
gh api --method DELETE "/repos/${repo}/issues/${number}/labels/${label}"
done
fi

View file

@ -16,7 +16,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Generate Marvin App token
id: marvin-token

View file

@ -16,7 +16,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Generate Marvin App token
id: marvin-token

View file

@ -25,7 +25,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Install UV
uses: astral-sh/setup-uv@v7
@ -51,6 +51,9 @@ jobs:
- name: Run Claude for Issue Comment
uses: ./.github/actions/run-claude
env:
COMMENT_BODY: ${{ github.event.comment.body }}
ISSUE_TITLE: ${{ github.event.issue.title }}
with:
claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github-token: ${{ steps.marvin-token.outputs.token }}
@ -61,13 +64,13 @@ jobs:
<context>
Repository: ${{ github.repository }}
Issue Number: #${{ github.event.issue.number }}
Issue Title: ${{ github.event.issue.title }}
Issue Title: ${{ env.ISSUE_TITLE }}
Issue Author: ${{ github.event.issue.user.login }}
Comment Author: ${{ github.event.comment.user.login }}
</context>
<user_request>
${{ github.event.comment.body }}
${{ env.COMMENT_BODY }}
</user_request>
<task>
@ -75,9 +78,7 @@ jobs:
</task>
<constraints>
You CAN: Read/analyze code, modify files, write code, run tests, execute commands
You CAN: Commit code, push changes, create branches, create pull requests
You CAN: Read/analyze code, modify files, write code, run tests, execute commands, commit code, push changes, create branches, create pull requests
</constraints>
<allowed_tools>
@ -107,20 +108,30 @@ jobs:
<common_tasks>
- Answer questions about the codebase
- Help debug reported problems (make changes locally to test, cannot push)
- Help debug reported problems
- Suggest solutions or workarounds
- Provide code examples
- Help clarify requirements
- Link to relevant documentation or code
- Create branches, commit changes, and open PRs when asked
</common_tasks>
<response_guidelines>
- Be concise and actionable
- If the request is unclear, ask clarifying questions
- If the request requires actions you cannot perform (like pushing changes), explain what you can and cannot do
- When making code changes, explain that they are local only and cannot be pushed
- Lead with a tl;dr — the bottom line in 1-3 sentences, always visible. The reader should be able to act without expanding anything.
- Push supporting detail (code analysis, verification output, related items) into collapsible `<details>` blocks. These are appendices, not the main message.
- Short responses (a few sentences) don't need collapsible sections at all.
- Be concise and actionable.
- If the request is unclear, ask clarifying questions.
- Report findings and recommendations — not your process. Do not include task checklists or "steps I took" narration.
- Every claim needs evidence: cite file paths, line numbers, or command output. Never say "the code does X" without pointing to where.
- If you're uncertain, say so. "I couldn't confirm this" is better than a speculative answer.
</response_guidelines>
<github_safety>
- Do not write `fixes #N`, `closes #N`, or `resolves #N` in comments — these can accidentally close issues.
- When referencing issues, use plain `#N` or link syntax without action keywords.
</github_safety>
<response_footer>
Always end your comment with a new line, three dashes, and the footer message:
<exact_content>

View file

@ -24,7 +24,7 @@ jobs:
steps:
- name: Checkout PR head branch
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
# do not set to pull_request.head.ref, claude will pull the branch if needed
fetch-depth: 0
@ -72,6 +72,8 @@ jobs:
PR_REVIEW_HEAD_SHA: ${{ steps.pr-info.outputs.head_sha }}
PR_REVIEW_COMMENTS_DIR: /tmp/pr-review-comments
PR_REVIEW_HELPERS_DIR: ${{ github.workspace }}/.github/scripts/pr-review
COMMENT_BODY: ${{ github.event.comment.body }}
PR_TITLE: ${{ github.event.issue.title }}
with:
claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github-token: ${{ steps.marvin-token.outputs.token }}
@ -82,7 +84,7 @@ jobs:
<context>
Repository: ${{ github.repository }}
PR Number: #${{ steps.pr-info.outputs.pr_number }}
PR Title: ${{ github.event.issue.title }}
PR Title: ${{ env.PR_TITLE }}
PR Author: ${{ github.event.issue.user.login }}
Comment Author: ${{ github.event.comment.user.login }}
@ -90,7 +92,7 @@ jobs:
</context>
<user_request>
${{ github.event.comment.body }}
${{ env.COMMENT_BODY }}
</user_request>
<task>
@ -98,12 +100,10 @@ jobs:
</task>
<constraints>
This workflow allows read, write, and execute capabilities but cannot push changes.
You CAN: Read/analyze code, modify files, write code, run tests, execute commands, resolve review threads, commit and push changes to the PR branch, checkout branches
You CANNOT: Create new branches unrelated to this PR, create new pull requests
You CAN: Read/analyze code, modify files, write code, run tests, execute commands, resolve review threads
You CANNOT: Commit code, push changes, create branches, checkout branches, create pull requests
**Important**: You cannot push changes to the repository - you can only make changes locally and provide feedback or recommendations.
When making changes, commit and push to the PR's head branch so the author gets the fix directly.
</constraints>
<allowed_tools>
@ -132,10 +132,10 @@ jobs:
</investigation_approach>
<common_tasks>
- Address review feedback and fix issues (make changes locally, cannot push)
- Address review feedback and fix issues (commit and push to the PR branch)
- Answer questions about the changes
- Make additional code changes (local only)
- Resolve review threads after addressing feedback (if changes are made separately)
- Make code changes and push them
- Resolve review threads after addressing feedback
- Perform PR reviews when asked (use the PR review process below)
</common_tasks>
@ -224,6 +224,25 @@ jobs:
6. Breaking changes to public APIs without migration path
7. Missing or incorrect test coverage for critical paths
</review_criteria>
<review_calibration>
**What NOT to flag** — do not comment on:
- Issues in unchanged code (only review the diff)
- Input already validated or sanitized at a different layer
- Theoretical performance concerns without evidence that N is large
- Style or formatting not in the project's linting rules
- Missing tests for trivial or generated code
- Pre-existing patterns the PR is following consistently
**Calibration examples**:
- Unguarded return from a lookup (e.g., `tool = registry.get(name)` used without None check) → FLAG if the diff introduces the unguarded usage
- Same pattern, but the function's return type is `Tool` (not `Optional[Tool]`) → DO NOT FLAG, the type system guarantees non-None
- String interpolation in a query with user input → FLAG
- String interpolation in a query with a hardcoded enum value → DO NOT FLAG
- O(n²) loop → FLAG only if there's evidence N can be large (e.g., user-controlled list). If N is bounded by design (e.g., number of MCP tools), do not flag.
When in doubt, do not flag. A false positive wastes a reviewer's time and erodes trust in every future review comment.
</review_calibration>
</pr_review_guidance>
<review_thread_tools>
@ -244,14 +263,18 @@ jobs:
- `THREAD_ID` is the GraphQL node ID from the review threads output (e.g., `PRRT_kwDOABC123`)
- The comment is optional - use it to explain what you did
Note: Since you cannot push changes, you can resolve threads to acknowledge feedback, but actual fixes would need to be applied separately.
Note: You can resolve threads after pushing fixes, or resolve them to acknowledge feedback that will be addressed separately.
</review_thread_tools>
<response_guidelines>
- Be concise and actionable
- If the request is unclear, ask clarifying questions
- If the request requires actions you cannot perform (like pushing changes), explain what you can and cannot do
- When making code changes, explain that they are local only and cannot be pushed
- Lead with a tl;dr — the bottom line in 1-3 sentences, always visible. The reader should be able to act without expanding anything.
- Push supporting detail (code analysis, verification output, related items) into collapsible `<details>` blocks. These are appendices, not the main message.
- Short responses (a few sentences) don't need collapsible sections at all.
- Be concise and actionable.
- If the request is unclear, ask clarifying questions.
- When making code changes, commit and push them to the PR branch so the author gets the fix directly.
- Every claim needs evidence: cite file paths, line numbers, or command output. Never say "the code does X" without pointing to where.
- If you're uncertain, say so. "I couldn't confirm this" is better than a speculative answer.
**When performing a PR review**: Your substantive feedback belongs in the PR review submission
(via pr-review.sh), not in the comment response. The comment should only report:
@ -263,6 +286,11 @@ jobs:
Keep the comment short, e.g., "I've submitted my review requesting changes. See the review for details."
</response_guidelines>
<github_safety>
- Do not write `fixes #N`, `closes #N`, or `resolves #N` in comments — these can accidentally close issues.
- When referencing issues, use plain `#N` or link syntax without action keywords.
</github_safety>
<response_footer>
Always end your comment with a new line, three dashes, and the footer message:
<exact_content>

View file

@ -19,9 +19,16 @@ jobs:
issues: write
id-token: write
# TEMPORARY PIN — see the matching note in marvin-label-triage.yml.
# Claude Code 2.1.216 broke every Bash call under the action's subprocess
# isolation, which this workflow needs for all of its `gh` searching.
# https://github.com/anthropics/claude-code/issues/79997
env:
PINNED_CLAUDE_CODE_VERSION: "2.1.215"
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
- name: Generate Marvin App token
id: marvin-token
@ -37,23 +44,38 @@ jobs:
PROMPT<<PROMPT_END
Find up to 3 likely duplicate issues for GitHub issue ${{ github.repository }}/issues/${{ github.event.issue.number || inputs.issue_number }}.
Follow these steps precisely:
# Core Principle
Silence is better than noise. A false positive wastes a human's time and erodes trust in every future report. Most runs should end with no comment — that means the system is working.
# Steps
1. Check if the GitHub issue (a) is closed, (b) does not need to be deduped (eg. because it is broad product feedback without a specific solution, or positive feedback), or (c) already has a duplicates comment that you made earlier. If so, do not proceed.
2. View the GitHub issue and produce a summary of the issue
2. View the GitHub issue and produce a summary of the issue.
3. Then, launch 3 parallel agents using the Task tool to search GitHub for duplicates of this issue, using diverse keywords and search approaches, using the summary from step 2
3. Launch 3 parallel agents using the Task tool to search GitHub for duplicates, using diverse keywords and search approaches, using the summary from step 2.
4. Next, consider the results from steps 2 and 3 and filter out false positives that are likely not actually duplicates of the original issue. Be conservative — only flag issues that describe the same underlying problem, not issues that merely share keywords or involve the same subsystem. If there are no duplicates remaining, do not proceed.
4. Filter aggressively for false positives. The bar for "duplicate" is high:
5. Finally, comment back on the issue with a list of up to three duplicate issues (or zero, if there are no likely duplicates). If there are no duplicates, DO NOT COMMENT. Just exit. Do NOT add any labels — labeling is handled by a later workflow step.
A duplicate means the SAME bug or the SAME feature request. Apply this test to every candidate:
- **Same fix test**: Could the candidate be closed by the exact same code change? If not, not a duplicate.
- **Same symptom test**: Does the user experience the exact same broken behavior? "Both involve middleware" is not duplication. "Both get TypeError on line 42 of proxy.py when calling mount()" is duplication.
- **Same request test** (for features): Are they asking for the same specific capability? "Both want better auth" is not duplication. "Both request OAuth PKCE flow for CLI login" is duplication.
Notes for your agents:
Candidates found by only one search agent deserve extra scrutiny — a single keyword match is often a false positive.
When in doubt, do not flag. A missed duplicate is harmless; a false positive wastes the reporter's time.
If there are no duplicates remaining, do not proceed — just exit.
5. **Quality gate**: Before commenting, re-read each candidate as a skeptical reviewer. For each one, ask: "Would a maintainer who knows this codebase agree this is a duplicate, or would they dismiss it?" If you'd need to hedge with "might" or "possibly," drop it.
6. Comment back on the issue with your findings (or exit silently if none remain). Do NOT add any labels — labeling is handled by a later workflow step.
# Notes for your agents
- Use `gh` to interact with GitHub, rather than web fetch
- Do not use other tools, beyond `gh` and Task (eg. don't use other MCP servers, file edit, etc.)
- Make a todo list first
- Do not use other tools beyond `gh` and Task (no MCP servers, file edit, etc.)
- Never include this issue as a duplicate of itself
- When searching, read the FULL body of candidate issues — titles alone are not enough to judge duplication
For your comment, follow this format precisely (example with 3 suspected duplicates):
@ -76,19 +98,27 @@ jobs:
- name: Clean up stale Claude locks
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
- name: Install pinned Claude Code
id: pin-claude
run: |
curl -fsSL https://claude.ai/install.sh | bash -s -- "$PINNED_CLAUDE_CODE_VERSION"
echo "path=$HOME/.local/bin/claude" >> "$GITHUB_OUTPUT"
"$HOME/.local/bin/claude" --version
- name: Run Marvin dedupe command
uses: anthropics/claude-code-action@v1
with:
path_to_claude_code_executable: ${{ steps.pin-claude.outputs.path }}
github_token: ${{ steps.marvin-token.outputs.token }}
bot_name: "Marvin Context Protocol"
prompt: ${{ steps.dedupe-prompt.outputs.PROMPT }}
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY_FOR_CI }}
allowed_non_write_users: "*"
claude_args: |
--allowedTools Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh api:*),Bash(gh issue comment:*),Task
--allowedTools "Bash(gh issue view:*)","Bash(gh search:*)","Bash(gh issue list:*)","Bash(gh api:*)","Bash(gh issue comment:*)",Task
settings: |
{
"model": "claude-sonnet-4-6",
"model": "claude-sonnet-5",
"env": {
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}"
}

View file

@ -27,9 +27,25 @@ jobs:
issues: write
pull-requests: write
# TEMPORARY PIN — remove once upstream ships a fix.
#
# Claude Code 2.1.216 regressed the sandbox that claude-code-action wraps
# every Bash call in when `allowed_non_write_users` is set: the mountpoint
# walk fails closed, so every command — down to `true` — dies with
# `bwrap: Can't create file at /home/.mcp.json: Permission denied`.
# Marvin still reads the issue and picks correct labels, then cannot run
# the helper that applies them, so triage silently applied zero labels
# from 2026-07-20 onward while every run reported success.
#
# 2.1.215 is the last release without the regression.
# https://github.com/anthropics/claude-code/issues/79997
# https://github.com/anthropics/claude-code-action/issues/1547
env:
PINNED_CLAUDE_CODE_VERSION: "2.1.215"
steps:
- name: Checkout base repository
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
repository: ${{ github.repository }}
ref: ${{ github.event.repository.default_branch }}
@ -49,7 +65,16 @@ jobs:
PROMPT<<PROMPT_END
You're an issue triage assistant for FastMCP, a Python framework for building Model Context Protocol servers and clients. Your task is to analyze issues/PRs and apply appropriate labels.
IMPORTANT: Your primary action should be to apply labels using mcp__github__update_issue. DO NOT post comments EXCEPT when applying the too-long label (see below).
IMPORTANT: Your primary action should be to apply labels using the locked-down helper `.github/scripts/triage-label.sh`. DO NOT post comments EXCEPT when applying the too-long label (see below).
CRITICAL — LABEL MECHANICS:
- Apply labels ONLY through the helper, which adds or removes repository labels on THIS issue/PR. It already knows the target repo and number (from the workflow environment) — you never pass them:
add: `bash .github/scripts/triage-label.sh add "label1" "label2"`
remove: `bash .github/scripts/triage-label.sh remove "label1"`
- The helper uses the additive REST labels endpoint, so it works for both issues and PRs and never clobbers labels applied by other workflows — notably the Require Issue Link workflow's `missing-issue-link` control label, which must survive or an auto-closed PR won't reopen when its author is assigned.
- The helper is your ONLY GitHub write access. Do NOT use raw `gh api`, `gh issue edit`, `gh pr edit`, or any other mutation — they are not available to you.
- Only apply labels that exist in the repository (from `gh label list` in step 1). Never invent labels.
- Use `remove` only to correct a label you believe is wrong, and never remove the control labels `missing-issue-link`, `bypass-issue-check`, or `trusted-contributor`.
Issue/PR Information:
- REPO: ${{ github.repository }}
@ -97,7 +122,7 @@ jobs:
STATUS (apply if applicable):
- needs more info: Issue lacks reproduction steps, error messages, or clear description
- invalid: Spam, completely off-topic, or nonsensical (often LLM-generated)
- too-long: Apply when an issue or PR doesn't conform to CONTRIBUTING.md. Issues should be a short problem description, an MRE, and expected vs. actual behavior — not a design document. PRs should have a focused description of the change — not a report. We don't need proposed solutions or design alternatives (the issue should describe the problem and let maintainers architect the fix), summaries of what tests cover, explanations of code we can read ourselves, or speculative root-cause analysis. Common LLM failure modes to watch for: verbose "diagnostic" writeups, large proposed patches in issue bodies, multi-section reports restating what's visible in the diff, numbered lists of possible approaches or solutions, "suggested" schemas/shapes/APIs, generic analysis that doesn't reference specific code, and "Notes" sections. But these are heuristics, not rules — a complex PR may legitimately need more context, and a brief submission can still be low-quality. Judge by whether the content helps a reviewer or just adds noise. When applying, do not apply other triage labels. The author needs to condense before triage is worthwhile.
- too-long: Apply when an issue or PR doesn't conform to CONTRIBUTING.md. Issues should be a short problem description, an MRE, and expected vs. actual behavior — not a design document. PRs should have a focused description of the change — not a report. We don't need proposed solutions or design alternatives (the issue should describe the problem and let maintainers architect the fix), summaries of what tests cover, explanations of code we can read ourselves, or speculative root-cause analysis. Common LLM failure modes to watch for: verbose "diagnostic" writeups, large proposed patches in issue bodies, multi-section reports restating what's visible in the diff, numbered lists of possible approaches or solutions, "suggested" schemas/shapes/APIs, generic analysis that doesn't reference specific code, and "Notes" sections. But these are heuristics, not rules — a complex PR may legitimately need more context, and a brief submission can still be low-quality. Judge by whether the content helps a reviewer or just adds noise. When applying too-long, still apply the core category and area labels — too-long is a format signal, not a replacement for categorization. Issues still need to be findable by category.
WHEN APPLYING too-long: After labeling, post a brief comment using mcp__github__add_issue_comment:
"Thanks for the report. This issue goes beyond what our contributor guidelines ask for — we just need a short problem description and an MRE. Please see our [contributing guidelines](https://github.com/PrefectHQ/fastmcp/blob/main/CONTRIBUTING.md) and condense this issue. We'll triage it once it's trimmed down."
@ -110,23 +135,22 @@ jobs:
- auth: Authentication is the main concern (Bearer, JWT, OAuth, WorkOS)
- openapi: OpenAPI integration/parsing is the primary topic
- http: HTTP transport or networking is the main issue
- contrib: Specifically about community contributions in src/contrib/
- contrib: Specifically about community contributions in fastmcp_slim/fastmcp/contrib/
- tests: Issues primarily about testing infrastructure, CI/CD workflows, or test coverage
- security: Apply ONLY when the issue/PR addresses an exploitable vulnerability or hardens against one. Examples: SSRF, LFI, path traversal, injection, auth bypass allowing unauthorized access, scope escalation, open redirects. Do NOT apply for ordinary auth bugs (wrong scopes returned, token refresh logic, OAuth flow correctness) unless an attacker could exploit the bug to bypass access controls or escalate privileges. The key question: "Could a malicious actor exploit this?" If the answer is just "it breaks for legitimate users," that's a bug, not a security issue.
IMPORTANT LABELING RULES:
- Be selective - only apply labels that are clearly relevant
- Don't apply area labels just because a file in that area is mentioned
- The issue must be PRIMARILY about that area to get the label
- When in doubt, don't apply the label
- Apply 2-5 labels total typically (category + maybe priority + maybe 1-2 areas)
LABELING PRINCIPLES:
- Precision over recall: a missing label is a minor inconvenience; a wrong label sends the wrong people to the wrong issue. When in doubt, don't apply.
- Don't apply area labels just because a file in that area is mentioned — the issue must be PRIMARILY about that area.
- Apply 2-5 labels total typically (category + maybe priority + maybe 1-2 areas).
- For ambiguous cases (bug vs enhancement, which area label), prefer the more conservative choice or omit the uncertain label entirely.
META LABELS (rarely needed for issues):
- dependencies: Only for dependabot PRs or issues specifically about package updates
- DON'T MERGE: Only if PR author explicitly states it's not ready
4. Apply selected labels:
Use mcp__github__update_issue to apply your selected labels
Add them with `bash .github/scripts/triage-label.sh add "label1" "label2"`.
DO NOT post any comments unless applying too-long (see above)
PROMPT_END
EOF
@ -134,9 +158,21 @@ jobs:
- name: Clean up stale Claude locks
run: rm -rf ~/.claude/.locks ~/.local/state/claude/locks || true
# Mirrors how the action installs Claude Code itself, minus the version
# it hardcodes. Passing path_to_claude_code_executable makes the action
# skip its own install and use this build.
- name: Install pinned Claude Code
id: pin-claude
run: |
curl -fsSL https://claude.ai/install.sh | bash -s -- "$PINNED_CLAUDE_CODE_VERSION"
echo "path=$HOME/.local/bin/claude" >> "$GITHUB_OUTPUT"
"$HOME/.local/bin/claude" --version
- name: Run Marvin for Issue Triage
id: marvin
uses: anthropics/claude-code-action@v1
with:
path_to_claude_code_executable: ${{ steps.pin-claude.outputs.path }}
github_token: ${{ steps.marvin-token.outputs.token }}
bot_name: "Marvin Context Protocol"
prompt: ${{ steps.triage-prompt.outputs.PROMPT }}
@ -144,11 +180,114 @@ jobs:
allowed_non_write_users: "*"
allowed_bots: "marvin-context-protocol"
claude_args: |
--allowedTools Bash(gh label list),mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__update_issue,mcp__github__add_issue_comment,mcp__github__get_pull_request_files
--allowedTools "Bash(gh label list:*)","Bash(bash .github/scripts/triage-label.sh:*)",mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__add_issue_comment,mcp__github__get_pull_request,mcp__github__get_pull_request_files
settings: |
{
"model": "claude-sonnet-4-6",
"model": "claude-sonnet-5",
"env": {
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}"
"GH_TOKEN": "${{ steps.marvin-token.outputs.token }}",
"TRIAGE_REPO": "${{ github.repository }}",
"TRIAGE_NUMBER": "${{ github.event.issue.number || github.event.pull_request.number || inputs.issue_number }}"
}
}
# Triage is fire-and-forget: nobody watches a green run, so a broken
# allowlist has to fail the job or it goes unnoticed indefinitely — a
# mangled pattern silently produced zero labels across a dozen PRs
# because the run still reported success.
#
# Only denials of commands we MEANT to grant indicate that breakage. An
# agent reaching for something never on the allowlist (falling back to
# `gh issue view` when the API is down, say) is behaving normally, and
# failing on that would cry wolf during every GitHub incident.
- name: Fail if Marvin could not run its tools
if: always() && steps.marvin.conclusion != 'skipped'
env:
EXECUTION_FILE: ${{ steps.marvin.outputs.execution_file }}
run: |
file="${EXECUTION_FILE:-}"
if [[ -z "$file" || ! -s "$file" ]]; then
file="${RUNNER_TEMP}/claude-execution-output.json"
fi
# A missing or empty log means we cannot tell a clean run from a
# blocked one, which is the exact failure this step exists to catch.
if [[ ! -s "$file" ]]; then
echo "::error::No Marvin execution log found; cannot verify tool permissions."
exit 1
fi
# The persisted log carries a `permission_denials` array on each
# `type: result` entry; the `permission_denials_count` scalar only
# appears in the action's condensed stdout summary, never on disk.
# Anchor to result entries rather than recursing with `..`, which
# descends into each denial's `tool_input` and double-counts any
# denied command that happens to mention the field name.
if ! summary=$(jq -sr '
[ .[] | if type == "array" then .[] else . end ]
| map(select(type == "object" and .type == "result"))
| map(.permission_denials // []) | flatten
| map(.tool_input.command // "")
| { total: length,
granted: map(select(
startswith("gh label list")
or startswith("bash .github/scripts/triage-label.sh")
))
}
| "\(.total)\t\(.granted | length)\t\(.granted | join(" | "))"
' "$file"); then
echo "::error::Could not parse Marvin execution log ($file)."
exit 1
fi
IFS=$'\t' read -r total granted commands <<<"$summary"
echo "Denied tool calls: $total (of which allowlisted: $granted)"
if [[ "$granted" -gt 0 ]]; then
echo "::error::Marvin was denied $granted call(s) to tools this workflow grants, so it could not apply labels: ${commands}. The --allowedTools value is not reaching the permission matcher intact — claude_args is lexed with shell-quote, so any Bash(...) pattern containing a space must be quoted or it is split into fragments."
exit 1
fi
if [[ "$total" -gt 0 ]]; then
echo "::notice::Marvin was denied $total call(s), none of them to tools this workflow grants. That is expected when it probes for a tool we deliberately withhold; the allowlist is intact."
fi
# A granted tool can also fail *after* the permission check, which the
# denial count above cannot see. Claude Code 2.1.216 did exactly that:
# the sandbox refused to build and every Bash call — including the
# labeling helper — exited 1 with `bwrap: ...`, while the run stayed
# green. Correlate results back to their Bash tool_use rather than
# grepping the whole log, so an issue body quoting a sandbox error
# cannot fail an otherwise healthy run.
if ! sandbox=$(jq -sr '
[ .[] | if type == "array" then .[] else . end ]
| map(select(type == "object" and (.type == "assistant" or .type == "user")))
| map(.message.content // []) | flatten
| map(select(type == "object"))
| . as $blocks
| ( $blocks
| map(select(.type == "tool_use" and .name == "Bash"))
| map(.id) ) as $bash
| $blocks
| map(select(.type == "tool_result" and (.tool_use_id as $i | $bash | index($i))))
| map(.content | tostring)
| map(select(test("bwrap:|Failed to (start|create) sandbox")))
| "\(length)\t\(.[0] // "" | gsub("[\t\n]"; " ") | .[0:200])"
' "$file"); then
echo "::error::Could not scan Marvin execution log for sandbox failures ($file)."
exit 1
fi
IFS=$'\t' read -r sandbox_failures sandbox_sample <<<"$sandbox"
if [[ "$sandbox_failures" -gt 0 ]]; then
echo "::error::Marvin's Bash tool failed $sandbox_failures time(s) inside the action's subprocess sandbox, so it could not apply labels: ${sandbox_sample}. This is an environment failure, not a prompt or allowlist problem — check whether the pinned Claude Code version (${PINNED_CLAUDE_CODE_VERSION}) still avoids the upstream sandbox regression."
exit 1
fi
- name: Upload Marvin execution log
if: always() && steps.marvin.conclusion != 'skipped'
uses: actions/upload-artifact@v7
with:
name: marvin-triage-execution-log
path: |
${{ steps.marvin.outputs.execution_file }}
${{ runner.temp }}/claude-execution-output.json
if-no-files-found: ignore
retention-days: 14

View file

@ -11,7 +11,7 @@ concurrency:
cancel-in-progress: true
jobs:
martian-test-failure:
marvin-test-failure:
# Only run if the test workflow failed
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
runs-on: ubuntu-latest
@ -23,7 +23,7 @@ jobs:
actions: read # Required for Claude to read CI results
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
fetch-depth: 1
@ -35,7 +35,7 @@ jobs:
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
- name: Set up Python 3.10
uses: actions/setup-python@v6
uses: actions/setup-python@v7
with:
python-version: "3.10"
@ -60,6 +60,17 @@ jobs:
2. Identify the root cause of the failure(s)
3. Suggest a clear, actionable solution to fix the failure(s)
# Response Proportionality
Match your response length to the complexity of the failure. Not every failure needs a full investigation:
**Trivial failures** (formatting, linting) — post a short, direct comment. No collapsible sections, no root-cause deep-dive. Example:
> CI failed: `ruff format` reformatted 2 files. Run `uv run ruff format .` locally and push.
**Pre-existing flaky tests** unrelated to the PR — say so briefly. Don't write a full analysis of a test the PR didn't touch. Example:
> CI failed due to a pre-existing flaky test (`test_name`) unrelated to this PR's changes. Safe to re-run.
**Real failures caused by the PR** — these deserve the full analysis format below. Spend your effort here.
# Getting Started
1. Call the generate_agents_md tool to get a high-level summary of the project
2. Get the pull request associated with this workflow run from the GitHub repository: ${{ github.repository }}
@ -75,60 +86,61 @@ jobs:
5. Search the codebase for relevant files, tests, and implementations
# Your Response
Post a comment on the pull request with your analysis. Your comment should include:
Post a comment on the pull request with your analysis.
## Test Failure Analysis
Lead with a tl;dr — 1-2 sentences that tell the developer what broke and what to do about it. This should be visible without expanding anything.
**Summary**: A brief 1-2 sentence summary of what failed.
Push supporting detail into collapsible `<details>` blocks. The reader should be able to act on your comment without expanding a single one. Think of details blocks as appendices — there if someone wants to dig deeper, not required for the main message.
**Root Cause**: A clear explanation of why the tests failed, based on your analysis of the logs and code.
For real (non-trivial) failures, use this structure:
**Suggested Solution**: Specific, actionable steps to fix the failure(s). Include:
- Which files need to be modified
- What changes are needed
- Why these changes will fix the issue
**tl;dr**: What failed and what to do (1-2 sentences, always visible)
**Root Cause**: Why it failed (a short paragraph, always visible)
**Fix**: Specific files and changes needed (always visible)
<details>
<summary>Detailed Analysis</summary>
Include here:
- Relevant log excerpts showing the failure
- Code snippets that are causing the issue
- Any related issues or PRs that might be relevant
<summary>Log excerpts</summary>
Relevant failure output
</details>
<details>
<summary>Related Files</summary>
List files that are relevant to the failure with brief explanations of their relevance.
<summary>Related files</summary>
Files relevant to the failure
</details>
# Important Guidelines
- Be concise and actionable - developers want to quickly understand and fix the issue. Provide
additional context, references, etc in collapsible details blocks to ensure that the comment you're adding
is short and easy to read but additional information is a click away.
- Focus on facts from the logs and code, not speculation
- If you can't determine the root cause, say so clearly
- If your only suggestion is a bad suggestion (disable the test, change the timeout, etc), indicate that you've run out of ideas and
that they probably don't want to do that.
- Provide specific file names, line numbers, and code references when possible
- You can run make commands (e.g., `make lint`, `make typecheck`, `make sync`) to build, test, or lint the code
- You can also run git commands (e.g., `git status`, `git log`, `git diff`) to inspect the repository
- You can use WebSearch and WebFetch to research errors, stack traces, or related issues
- For bash commands, you are limited to make and git commands only
# Quality Standards
- Every claim needs evidence: file paths, line numbers, log excerpts. Never say "the test fails" without citing which test and what the error was.
- Focus on facts from the logs and code, not speculation. If you can't determine the root cause, say so clearly — "I don't know" is better than a wrong diagnosis.
- If your only suggestion is a bad one (disable the test, increase the timeout, etc.), say so honestly rather than dressing it up.
- Do not paste raw CLI output (e.g., prek progress bars, pytest collection output) into the comment body. Quote only the relevant failure lines.
- Always include specific file names, tool names, and test names in your summary. Never leave a sentence with a blank where a name should be.
# CRITICAL: ANGRY USERS
**IMPORTANT**: If the user is angry with you, the triage bot, don't respond. Just exit immediately without further action.
If at any point in the conversation the user has asked you to stop replying to the thread, just exit immediately.
# Self-Review Before Posting
Before posting your comment, re-read it as the PR author would. Ask:
- Can I act on this without expanding any `<details>` block?
- Does every claim cite a specific file, line, or log excerpt?
- Am I telling them something they can't already see in the CI logs, or just restating them?
If your comment doesn't add value beyond what the logs already show, don't post it.
# STOP SIGNALS
If anyone on the PR has asked the bot to stop — e.g., "stop", "go away", "don't comment", "no more bot comments" — exit immediately without further action. This includes past comments in the thread, not just the most recent one.
If you are posting the same suggestion as you have previously made, do not post the suggestion again.
# IMPORTANT: EDIT YOUR COMMENT
Do not post a new comment every time you triage a failing workflow. If a previous comment has been posted by you (marvin)
in a previous triage, edit that comment do not add a new comment for each failure. Be sure to include a note that you've edited
your comment to reflect the latest analysis. Don't worry about keeping the old content around, there's comment history for
your comment to reflect the latest analysis. Don't worry about keeping the old content around, there's comment history for
that.
# Available Tools
- You can run make commands (e.g., `make lint`, `make typecheck`, `make sync`) to build, test, or lint the code
- You can also run git commands (e.g., `git status`, `git log`, `git diff`) to inspect the repository
- You can use WebSearch and WebFetch to research errors, stack traces, or related issues
- For bash commands, you are limited to make and git commands only
# Problems Encountered
If you encounter any problems during your analysis (e.g., unable to fetch logs, tools not working), document them clearly so the team knows what limitations you faced.
PROMPT_END
@ -181,5 +193,5 @@ jobs:
prompt: ${{ steps.analysis-prompt.outputs.PROMPT }}
claude_args: |
--allowed-tools mcp__repository-summary,mcp__code-search,mcp__github-research,WebSearch,WebFetch,Bash(make:*,git:*)
--allowed-tools mcp__repository-summary,mcp__code-search,mcp__github-research,WebSearch,WebFetch,"Bash(make:*)","Bash(git:*)"
--mcp-config /tmp/mcp-config/mcp-servers.json

View file

@ -26,7 +26,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
uses: actions/checkout@v7
with:
repository: ${{ github.repository }}
ref: ${{ github.event.repository.default_branch }}
@ -46,6 +46,9 @@ jobs:
- name: Run Claude for Triage
uses: ./.github/actions/run-claude
env:
ISSUE_BODY: ${{ github.event.issue.body }}
ISSUE_TITLE: ${{ github.event.issue.title }}
with:
claude-oauth-token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github-token: ${{ steps.marvin-token.outputs.token }}
@ -54,12 +57,12 @@ jobs:
<context>
Repository: ${{ github.repository }}
Issue Number: #${{ github.event.issue.number }}
Issue Title: ${{ github.event.issue.title }}
Issue Title: ${{ env.ISSUE_TITLE }}
Issue Author: ${{ github.event.issue.user.login }}
</context>
<issue_body>
${{ github.event.issue.body }}
${{ env.ISSUE_BODY }}
</issue_body>
<task>
@ -119,8 +122,26 @@ jobs:
2. Layout a single high-quality and actionable recommendation for how to address the issue based on your knowledge of the project, codebase, and issue
3. Provide a high quality and detailed plan that a junior developer could follow to implement the recommendation
4. Use execution to verify findings when appropriate (check `<allowed_tools>` section for available commands)
Report findings and recommendations — not your process. Do not include task checklists, progress tracking, or "steps I took" narration (e.g., `- [x] Read source code`). The reader cares about what you found, not how you found it.
</response_goals>
<evidence_standards>
Every claim in your response must be grounded in evidence you can cite:
- **Code references**: Always include file path and line number (e.g., `fastmcp_slim/fastmcp/client/client.py:142`). Never say "the client code does X" without pointing to where.
- **Bug confirmation**: If you say a bug is real, show the specific code path that produces it. If you ran a test, include the command and output.
- **Related items**: When citing a related issue or PR, explain specifically why it's related — not just that it exists.
- **Confidence**: If you're uncertain about a finding, say so. "I don't know" or "I couldn't confirm this" is better than a speculative diagnosis. Only report findings you would confidently defend.
</evidence_standards>
<quality_gate>
Before posting, re-read your response as a maintainer would:
- Does the tl;dr give the full picture without expanding anything?
- Does every claim cite a specific file, line, or test result?
- Is this telling the maintainer something they couldn't find in 5 minutes of reading the issue and grepping the code?
If your response doesn't add meaningful value beyond restating the issue, it's okay to post a short "confirmed, straightforward fix in [file]:[line]" response instead of a full analysis.
</quality_gate>
<response_sections>
Populate the following sections in your response:
Recommendation (or "No recommendation" with reason)
@ -133,12 +154,17 @@ jobs:
You may not be able to do all of these things, sometimes you may find that all you can do is provide in-depth context of the issue and related items. That's perfectly acceptable and expected. Your performance is judged by how accurate your findings are, do the investigation required to have high confidence in your findings and recommendations. "I don't know" or "I'm unable to recommend a course of action" is better than a bad or wrong answer.
When formulating your response, you will never "bury the lede", you will always provide a clear and concise tl;dr as the first thing in your response. As your response grows in length you can organize the more detailed parts of your response collapsible sections using <details> and <summary> tags. You shouldn't put everything in collapsible sections, especially if the response is short. Use your discretion to determine when to use collapsible sections to avoid overwhelming the reader with too much detail -- think of them like an appendix that can be expanded if the reader is interested.
Structure: Lead with a tl;dr (1-3 sentences, always visible) that gives the reader the bottom line — what this issue is, whether it's valid, and what to do about it. The reader should be able to act on your comment without expanding anything.
Push everything else into collapsible `<details>` blocks: findings, verification output, action plans, related items, related files. These are appendices — valuable for someone who wants to dig deeper, but not required for the main message. The only things that should be visible without clicking are the tl;dr and the recommendation. Short responses (a few sentences) don't need collapsible sections at all.
</response_sections>
<response_examples>
# Example output for "Recommendation" part of the response
PR #654 already implements the requested feature but is incomplete. The Pull Request is not in a mergeable state yet, the remaining work should be completed: 1) update the Calculator.divide method to utilize the new DivisionByZeroError or the safe_divide function, and 2) update the tests to ensure that the Calculator.divide method raises the new DivisionByZeroError when the divisor is 0.
# Example: the tl;dr and recommendation are always visible, everything else is collapsed
**tl;dr**: Confirmed bug — `Calculator.divide` raises `ValueError` instead of `DivisionByZeroError`. PR #654 partially addresses this but is incomplete.
**Recommendation**: Complete PR #654: update `Calculator.divide` to raise `DivisionByZeroError` and update the test assertions to match.
<details>
<summary>Findings</summary>
@ -147,7 +173,7 @@ jobs:
<details>
<summary>Verification</summary>
I ran the existing tests (if execution commands are available in `<allowed_tools>`) and confirmed the current behavior:
```bash
$ pytest test_calculator.py::test_divide_by_zero
FAILED - raises ValueError instead of DivisionByZeroError
@ -156,36 +182,25 @@ jobs:
</details>
<details>
<summary>Detailed Action Plan</summary>
<summary>Action Plan</summary>
...a detailed plan that a junior developer could follow to implement the recommendation...
</details>
# Example Output for "Related Items" part of the response
<details>
<summary>Related Issues and Pull Requests</summary>
| Repository | Issue or PR | Relevance |
| --- | --- | --- |
| PrefectHQ/fastmcp | [Add matrix operations support](https://github.com/PrefectHQ/fastmcp/pull/680) | This pull request directly addresses the feature request for adding matrix operations to the calculator. |
| PrefectHQ/fastmcp | [Add matrix operations support](https://github.com/PrefectHQ/fastmcp/issues/681) | This issue directly addresses the feature request for adding matrix operations to the calculator. |
| Issue or PR | Relevance |
| --- | --- |
| [Add matrix operations support](https://github.com/PrefectHQ/fastmcp/pull/680) | Directly addresses the feature request |
</details>
<details>
<summary>Related Files</summary>
| Repository | File | Relevance | Sections |
| --- | --- | --- | --- |
| modelcontextprotocol/python-sdk | [test_calculator.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/test_calculator.py) | This file contains the test cases for the Calculator class, including a test that specifically asserts a ValueError is raised for division by zero, confirming the current intended behavior. | [25-27](https://github.com/modelcontextprotocol/python-sdk/blob/main/test_calculator.py#L25-L27) |
| modelcontextprotocol/python-sdk | [calculator.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/calculator.py) | This file contains the implementation of the Calculator class, specifically the `divide` method which raises the ValueError when dividing by zero, matching the bug report. | [29-32](https://github.com/modelcontextprotocol/python-sdk/blob/main/calculator.py#L29-L32) |
</details>
<details>
<summary>Related Webpages</summary>
| Name | URL | Relevance |
| --- | --- | --- |
| Handling Division by Zero Best Practices | https://my-blog-about-division-by-zero.com/handling+division+by+zero+in+calculator | This webpage provides general best practices for handling division by zero in calculator applications and in Python, which is directly relevant to the issue and potential solutions. |
| File | Relevance |
| --- | --- |
| [calculator.py L29-32](https://github.com/modelcontextprotocol/python-sdk/blob/main/calculator.py#L29-L32) | The `divide` method that raises ValueError |
| [test_calculator.py L25-27](https://github.com/modelcontextprotocol/python-sdk/blob/main/test_calculator.py#L25-L27) | Test asserting ValueError (needs updating) |
</details>
</response_examples>
@ -202,4 +217,5 @@ jobs:
<github_formatting>
When writing GitHub comments, wrap branch names, tags, or other @-references in backticks (e.g., `@main`, `@v1.0`) to avoid accidentally pinging users. Do not add backticks around terms that are already inside backticks or code blocks.
Do not write `fixes #N`, `closes #N`, or `resolves #N` in comments — these can accidentally close issues. Use plain `#N` references instead.
</github_formatting>

View file

@ -14,8 +14,12 @@ on:
issue_comment:
types: [created]
# Scope the group by event name so that the sibling events fired by a single
# review action (pull_request_review + pull_request_review_comment, same instant)
# don't cancel each other. Same-PR runs of the *same* event still supersede
# cleanly, and the last one always completes.
concurrency:
group: minimize-reviews-${{ github.event.pull_request.number || github.event.issue.number }}
group: minimize-reviews-${{ github.event.pull_request.number || github.event.issue.number }}-${{ github.event_name }}
cancel-in-progress: true
permissions:

View file

@ -0,0 +1,87 @@
name: Publish fastmcp-remote to PyPI
on:
workflow_run:
workflows: ["Publish fastmcp-slim to PyPI"]
types: [completed]
workflow_dispatch:
permissions:
contents: read
id-token: write
jobs:
pypi-publish:
name: Upload fastmcp-remote to PyPI
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Build fastmcp-remote
run: uv build --package fastmcp-remote
- name: Verify matching fastmcp-slim is published
run: |
SLIM_VERSION=$(python - <<'PY'
import email.parser
import re
import zipfile
from pathlib import Path
wheel = next(Path("dist").glob("fastmcp_remote-*.whl"))
metadata_name = next(
name for name in zipfile.ZipFile(wheel).namelist()
if name.endswith(".dist-info/METADATA")
)
metadata = email.parser.Parser().parsestr(
zipfile.ZipFile(wheel).read(metadata_name).decode()
)
for value in metadata.get_all("Requires-Dist", []):
requirement, _, marker = value.partition(";")
if marker.strip():
continue
match = re.fullmatch(
r"fastmcp-slim(?:\[[^\]]+\])?==([^;\s]+)",
requirement.strip(),
)
if match:
print(match.group(1))
break
else:
raise RuntimeError("Could not find the base fastmcp-slim dependency")
PY
)
for attempt in {1..12}; do
if python - "$SLIM_VERSION" <<'PY'
import json
import sys
import urllib.request
version = sys.argv[1]
url = f"https://pypi.org/pypi/fastmcp-slim/{version}/json"
with urllib.request.urlopen(url, timeout=30) as response:
json.load(response)
PY
then
exit 0
fi
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
sleep 10
done
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI; refusing to publish fastmcp-remote." >&2
exit 1
- name: Publish fastmcp-remote to PyPI
run: uv publish -v dist/fastmcp_remote-*.tar.gz dist/fastmcp_remote-*.whl

View file

@ -0,0 +1,30 @@
name: Publish fastmcp-slim to PyPI
on:
release:
types: [published]
workflow_dispatch:
permissions:
contents: read
id-token: write
jobs:
pypi-publish:
name: Upload fastmcp-slim to PyPI
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Build fastmcp-slim
run: uv build --package fastmcp-slim
- name: Publish fastmcp-slim to PyPI
run: uv publish -v dist/fastmcp_slim-*.tar.gz dist/fastmcp_slim-*.whl

View file

@ -0,0 +1,104 @@
name: Publish fastmcp-tasks to PyPI
on:
workflow_run:
workflows: ["Publish fastmcp-slim to PyPI"]
types: [completed]
workflow_dispatch:
permissions:
contents: read
id-token: write
jobs:
pypi-publish:
name: Upload fastmcp-tasks to PyPI
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
# Maintenance branches predate the standalone fastmcp-tasks package and
# resolve the `tasks` extra through fastmcp-slim instead. This workflow
# runs from the default branch for every fastmcp-slim release, including
# those tags, so detect the package rather than assume it is there.
- name: Check whether this ref builds fastmcp-tasks
id: package_present
run: |
if [ -d fastmcp_tasks ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "This ref has no fastmcp_tasks package; nothing to publish."
fi
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Build fastmcp-tasks
if: steps.package_present.outputs.present == 'true'
run: uv build --package fastmcp-tasks
- name: Verify matching fastmcp-slim is published
if: steps.package_present.outputs.present == 'true'
run: |
SLIM_VERSION=$(python - <<'PY'
import email.parser
import re
import zipfile
from pathlib import Path
wheel = next(Path("dist").glob("fastmcp_tasks-*.whl"))
metadata_name = next(
name for name in zipfile.ZipFile(wheel).namelist()
if name.endswith(".dist-info/METADATA")
)
metadata = email.parser.Parser().parsestr(
zipfile.ZipFile(wheel).read(metadata_name).decode()
)
for value in metadata.get_all("Requires-Dist", []):
requirement, _, marker = value.partition(";")
if marker.strip():
continue
match = re.fullmatch(
r"fastmcp-slim(?:\[[^\]]+\])?==([^;\s]+)",
requirement.strip(),
)
if match:
print(match.group(1))
break
else:
raise RuntimeError("Could not find the base fastmcp-slim dependency")
PY
)
for attempt in {1..12}; do
if python - "$SLIM_VERSION" <<'PY'
import json
import sys
import urllib.request
version = sys.argv[1]
url = f"https://pypi.org/pypi/fastmcp-slim/{version}/json"
with urllib.request.urlopen(url, timeout=30) as response:
json.load(response)
PY
then
exit 0
fi
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
sleep 10
done
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI; refusing to publish fastmcp-tasks." >&2
exit 1
- name: Publish fastmcp-tasks to PyPI
if: steps.package_present.outputs.present == 'true'
run: uv publish -v dist/fastmcp_tasks-*.tar.gz dist/fastmcp_tasks-*.whl

238
.github/workflows/publish-fastmcp.yml vendored Normal file
View file

@ -0,0 +1,238 @@
name: Publish fastmcp to PyPI
on:
workflow_run:
workflows: ["Publish fastmcp-slim to PyPI"]
types: [completed]
workflow_dispatch:
permissions:
contents: read
id-token: write
jobs:
pypi-publish:
name: Upload fastmcp to PyPI
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'release')
outputs:
is_prerelease: ${{ steps.package_version.outputs.is_prerelease }}
version: ${{ steps.package_version.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@v7
with:
fetch-depth: 0
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Build fastmcp
run: uv build --package fastmcp
- name: Read built package version
id: package_version
run: |
python - <<'PY' >> "$GITHUB_OUTPUT"
import email.parser
import re
import zipfile
from pathlib import Path
wheel = next(Path("dist").glob("fastmcp-*.whl"))
metadata_name = next(
name for name in zipfile.ZipFile(wheel).namelist()
if name.endswith(".dist-info/METADATA")
)
metadata = email.parser.Parser().parsestr(
zipfile.ZipFile(wheel).read(metadata_name).decode()
)
version = metadata["Version"]
public_version = version.partition("+")[0]
is_prerelease = bool(
re.search(
r"(?i)(?:^|[0-9.])(?:a|b|c|rc|alpha|beta|pre|preview|dev)[0-9]*",
public_version,
)
)
print(f"version={version}")
print(f"is_prerelease={str(is_prerelease).lower()}")
PY
- name: Verify matching fastmcp-slim is published
run: |
SLIM_VERSION=$(python - <<'PY'
import email.parser
import re
import zipfile
from pathlib import Path
wheel = next(Path("dist").glob("fastmcp-*.whl"))
metadata_name = next(
name for name in zipfile.ZipFile(wheel).namelist()
if name.endswith(".dist-info/METADATA")
)
metadata = email.parser.Parser().parsestr(
zipfile.ZipFile(wheel).read(metadata_name).decode()
)
for value in metadata.get_all("Requires-Dist", []):
requirement, _, marker = value.partition(";")
if marker.strip():
continue
match = re.fullmatch(
r"fastmcp-slim(?:\[[^\]]+\])?==([^;\s]+)",
requirement.strip(),
)
if match:
print(match.group(1))
break
else:
raise RuntimeError("Could not find the base fastmcp-slim dependency")
PY
)
for attempt in {1..12}; do
if python - "$SLIM_VERSION" <<'PY'
import json
import sys
import urllib.request
version = sys.argv[1]
url = f"https://pypi.org/pypi/fastmcp-slim/{version}/json"
with urllib.request.urlopen(url, timeout=30) as response:
json.load(response)
PY
then
exit 0
fi
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
sleep 10
done
echo "fastmcp-slim ${SLIM_VERSION} is not available on PyPI; refusing to publish fastmcp." >&2
exit 1
- name: Verify matching fastmcp-tasks is published
run: |
TASKS_VERSION=$(python - <<'PY'
import email.parser
import re
import zipfile
from pathlib import Path
wheel = next(Path("dist").glob("fastmcp-*.whl"))
metadata_name = next(
name for name in zipfile.ZipFile(wheel).namelist()
if name.endswith(".dist-info/METADATA")
)
metadata = email.parser.Parser().parsestr(
zipfile.ZipFile(wheel).read(metadata_name).decode()
)
# fastmcp-tasks is pinned via the optional `tasks` extra, so its
# Requires-Dist entry carries an `extra == "tasks"` marker — unlike the
# base slim dependency, do not skip marked entries here.
#
# Print nothing when there is no such pin. Release lines that resolve
# the `tasks` extra through fastmcp-slim instead of a standalone
# fastmcp-tasks package have nothing here to verify.
for value in metadata.get_all("Requires-Dist", []):
requirement, _, _marker = value.partition(";")
match = re.fullmatch(r"fastmcp-tasks==([^;\s]+)", requirement.strip())
if match:
print(match.group(1))
break
PY
)
if [ -z "$TASKS_VERSION" ]; then
echo "This build does not pin fastmcp-tasks; the [tasks] extra cannot be uninstallable, so there is nothing to verify."
exit 0
fi
for attempt in {1..12}; do
if python - "$TASKS_VERSION" <<'PY'
import json
import sys
import urllib.request
version = sys.argv[1]
url = f"https://pypi.org/pypi/fastmcp-tasks/{version}/json"
with urllib.request.urlopen(url, timeout=30) as response:
json.load(response)
PY
then
exit 0
fi
echo "fastmcp-tasks ${TASKS_VERSION} is not available on PyPI yet; retrying (${attempt}/12)."
sleep 10
done
echo "fastmcp-tasks ${TASKS_VERSION} is not available on PyPI; refusing to publish fastmcp (the [tasks] extra would be uninstallable)." >&2
exit 1
- name: Publish fastmcp to PyPI
run: uv publish -v dist/fastmcp-*.tar.gz dist/fastmcp-*.whl
update-published-docs:
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: 5
permissions:
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
env:
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
run: |
git fetch origin "${DEFAULT_BRANCH}:refs/remotes/origin/${DEFAULT_BRANCH}"
if git merge-base --is-ancestor HEAD "refs/remotes/origin/${DEFAULT_BRANCH}"; then
echo "update_published_docs=true" >> "$GITHUB_OUTPUT"
else
echo "update_published_docs=false" >> "$GITHUB_OUTPUT"
echo "Release commit is not on ${DEFAULT_BRANCH}; skipping published-docs update."
fi
- name: Prepare published docs tree
if: steps.release_line.outputs.update_published_docs == 'true'
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

@ -1,26 +0,0 @@
name: Publish FastMCP to PyPI
on:
release:
types: [published]
workflow_dispatch:
jobs:
pypi-publish:
name: Upload to PyPI
runs-on: ubuntu-latest
permissions:
id-token: write # For PyPI's trusted publishing
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: "Install uv"
uses: astral-sh/setup-uv@v7
- name: Build
run: uv build
- name: Publish to PyPi
run: uv publish -v dist/*

613
.github/workflows/require-issue-link.yml vendored Normal file
View file

@ -0,0 +1,613 @@
# Require external PRs to reference an issue with an auto-close keyword
# (e.g. "Fixes #123") AND have the PR author assigned to that issue —
# unless the referenced issue is labeled "prs welcome", which waives the
# assignment requirement for everyone (the link itself is still required,
# since that's how the check finds the issue to read the label from).
# Otherwise the PR is labeled "missing-issue-link", commented on, and
# closed. CONTRIBUTING.md requires external contributors to be assigned to
# an issue before opening a PR; this enforces that.
#
# Adapted from langchain-ai/langchain's require_issue_link.yml. Differences:
# - Self-contained: it does NOT depend on a separate labeler workflow
# applying an "external" label first, so it can run on `opened`.
# - "External" is determined authoritatively, in-script, from the PR
# author's repo collaborator permission level — NOT from the event
# payload's author_association. author_association reports MEMBER only
# for *public* org members; a maintainer whose org membership is
# private appears as CONTRIBUTOR/NONE, so gating on it would wrongly
# enforce against private-member maintainers. getCollaboratorPermission
# reflects effective write access regardless of membership visibility.
# - The enforcement path is a single github-script step (the upstream
# version is split across four, forcing the label/comment/reopen helpers
# to be duplicated per scope).
# - Issue assignment events are handled in this same workflow so assigning
# the linked issue reopens previously closed PRs automatically.
#
# Maintainer override: reopen the PR, or remove the "missing-issue-link"
# label — either applies a sticky "bypass-issue-check" label and reopens.
name: Require Issue Link
on:
pull_request_target:
# SECURITY: pull_request_target runs with repo write scope against the
# BASE repo. NEVER check out or execute PR-head code here — it would run
# with these permissions. This workflow only reads the PR payload and
# calls the API; it never checks anything out.
# ready_for_review matters because the job skips drafts: without it a
# draft opened with no issue link would never be checked when it later
# becomes reviewable.
types: [opened, edited, reopened, ready_for_review, labeled, unlabeled]
issues:
# Assignment is what makes a previously closed "not assigned" PR compliant,
# so it needs a separate event path that finds and reopens matching PRs.
types: [assigned]
# Dry run: when 'false' the check still runs and logs its verdict but makes
# NO mutations at all (no label, comment, close, reopen, or failure). Flip
# to 'true' to enforce.
env:
ENFORCE_ISSUE_LINK: "true"
permissions:
contents: read
jobs:
check-issue-link:
# Cheap pre-filters only. Maintainer detection is deliberately NOT done
# here: the job-level `if` can't call the API, and author_association is
# unreliable for private org members (see file header). The job runs,
# then the script resolves the author's real permission and exits early
# for maintainers.
#
# Gate: only run on pull_request_target events. The workflow also listens
# to `issues.assigned` (handled by reopen-on-assignment below), and without
# this guard the job would also fire there — `github.event.pull_request` is
# null on an issues event, so `...draft == false` coerces to true and the
# script then dereferences a missing PR and crashes. Beyond the event type,
# skip drafts, bots, and already-bypassed/trusted PRs, and allow the primary
# actions plus the one maintainer-override action we care about (removing
# the missing-issue-link label).
if: >-
github.event_name == 'pull_request_target' &&
github.event.pull_request.draft == false &&
!endsWith(github.actor, '[bot]') &&
!contains(github.event.pull_request.labels.*.name, 'trusted-contributor') &&
!contains(github.event.pull_request.labels.*.name, 'bypass-issue-check') &&
(
(github.event.action != 'labeled' && github.event.action != 'unlabeled') ||
(github.event.action == 'unlabeled' && github.event.label.name == 'missing-issue-link')
)
runs-on: ubuntu-latest
timeout-minutes: 10
concurrency:
group: require-issue-link-${{ github.event.pull_request.number }}
cancel-in-progress: false
permissions:
issues: write
pull-requests: write
steps:
- name: Enforce issue link
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const { owner, repo } = context.repo;
const pr = context.payload.pull_request;
const prNumber = pr.number;
const action = context.payload.action;
const enforce = process.env.ENFORCE_ISSUE_LINK === 'true';
const LABEL = 'missing-issue-link';
const MARKER = '<!-- require-issue-link -->';
// Issue-level label that waives the assignment requirement.
const OPEN_LABEL = 'prs welcome';
// Dry-run guard: every mutating call goes through this so that
// ENFORCE_ISSUE_LINK=false means strictly read-only.
async function mutate(description, fn) {
if (!enforce) {
console.log(`[dry-run] would ${description}`);
return;
}
await fn();
}
// Authoritative maintainer check. Uses collaborator permission,
// not org membership or author_association:
// - GITHUB_TOKEN is an app token and is never an org member,
// so the org-membership endpoint always 403s.
// - author_association reports MEMBER only for *public* org
// members; a private-member maintainer shows as
// CONTRIBUTOR/NONE. Permission level is visibility-
// independent and reflects effective access.
// 404 (not a collaborator) → not a maintainer. Other errors
// (rate limit, 5xx) MUST throw: silently treating them as
// "not a maintainer" could wrongly close a maintainer's PR.
// A throw aborts the script before any close/label call, so the
// job fails red and the PR is left untouched — the safe direction.
async function hasWriteAccess(username) {
if (!username) throw new Error('No username — cannot check permissions');
try {
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
owner, repo, username,
});
const ok = ['admin', 'maintain', 'write'].includes(data.permission);
console.log(`${username}: ${data.permission} — ${ok ? 'maintainer' : 'not a maintainer'}`);
return ok;
} catch (e) {
if (e.status === 404) {
console.log(`${username} is not a collaborator — not a maintainer`);
return false;
}
throw new Error(
`Permission check failed for ${username} (HTTP ${e.status ?? 'unknown'}): ${e.message}`,
);
}
}
async function addLabel() {
await mutate(`label PR #${prNumber} "${LABEL}"`, async () => {
try {
await github.rest.issues.getLabel({ owner, repo, name: LABEL });
} catch (e) {
if (e.status !== 404) throw e;
try {
await github.rest.issues.createLabel({ owner, repo, name: LABEL, color: 'b76e79' });
} catch (createErr) {
// 422 = created by a concurrent run between GET and POST.
if (createErr.status !== 422) throw createErr;
}
}
await github.rest.issues.addLabels({
owner, repo, issue_number: prNumber, labels: [LABEL],
});
});
}
async function minimizeStaleComment() {
try {
const comments = await github.paginate(
github.rest.issues.listComments,
{ owner, repo, issue_number: prNumber, per_page: 100 },
);
const stale = comments.find(c => c.body && c.body.includes(MARKER));
if (!stale) return;
await mutate(`minimize stale comment ${stale.id}`, () => github.graphql(`
mutation($id: ID!) {
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
minimizedComment { isMinimized }
}
}
`, { id: stale.node_id }));
} catch (e) {
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
}
}
// Shared "this PR passes" cleanup: drop the label, reopen, and
// retire any stale enforcement comment.
//
// For the normal pass paths we only reopen if THIS workflow had
// closed the PR — inferred from the label still being on the
// payload. The maintainer-override paths pass forceReopen: the
// `unlabeled` event payload no longer carries the just-removed
// label, so the heuristic can't see it; without forcing, the
// advertised "remove the label to bypass" gesture would leave
// the PR closed.
async function clearEnforcement(forceReopen = false) {
await mutate(`remove "${LABEL}" from PR #${prNumber}`, async () => {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: prNumber, name: LABEL,
});
} catch (e) {
if (e.status !== 404) throw e;
}
});
const hadLabel = pr.labels.map(l => l.name).includes(LABEL);
if (pr.state === 'closed' && (forceReopen || hadLabel)) {
await mutate(`reopen PR #${prNumber}`, async () => {
await github.rest.pulls.update({
owner, repo, pull_number: prNumber, state: 'open',
});
});
}
await minimizeStaleComment();
}
async function applyBypass(reason) {
console.log(reason);
await clearEnforcement(true);
await mutate(`add sticky "bypass-issue-check" to PR #${prNumber}`, async () => {
try {
await github.rest.issues.getLabel({ owner, repo, name: 'bypass-issue-check' });
} catch (e) {
if (e.status !== 404) throw e;
try {
await github.rest.issues.createLabel({
owner, repo, name: 'bypass-issue-check', color: '0e8a16',
});
} catch (createErr) {
if (createErr.status !== 422) throw createErr;
}
}
await github.rest.issues.addLabels({
owner, repo, issue_number: prNumber, labels: ['bypass-issue-check'],
});
});
}
// ── Maintainer-authored PRs are exempt entirely ────────────────
if (await hasWriteAccess(pr.user.login)) {
console.log(`PR author ${pr.user.login} has write access — exempt`);
await clearEnforcement();
return;
}
const sender = context.payload.sender?.login;
// ── Maintainer override: removed the "missing-issue-link" label ─
if (action === 'unlabeled') {
if (await hasWriteAccess(sender)) {
await applyBypass(`Maintainer ${sender} removed ${LABEL} from PR #${prNumber} — bypassing`);
return;
}
// Only triage/admin can manage labels, so a non-write actor
// reaching here is rare (triage role). Fall through to the
// normal check, which recomputes link + assignment and
// re-enforces with the correct message if still failing.
console.log(`Non-maintainer ${sender} removed ${LABEL} — re-checking`);
}
// ── Maintainer override: reopened a PR we had closed ───────────
if (
action === 'reopened' &&
pr.labels.map(l => l.name).includes(LABEL) &&
(await hasWriteAccess(sender))
) {
await applyBypass(`Maintainer ${sender} reopened PR #${prNumber} — bypassing`);
return;
}
// ── Race guard: re-read live labels ────────────────────────────
const { data: liveLabels } = await github.rest.issues.listLabelsOnIssue({
owner, repo, issue_number: prNumber,
});
const liveNames = liveLabels.map(l => l.name);
if (liveNames.includes('trusted-contributor') || liveNames.includes('bypass-issue-check')) {
console.log('PR carries trusted-contributor or bypass-issue-check — clearing any prior enforcement');
await clearEnforcement();
return;
}
// ── The actual check: an auto-close keyword + issue number ─────
const body = pr.body || '';
// Match GitHub's auto-close keywords against any reference form
// that GitHub itself honors: bare `#123`, the `owner/repo#123`
// shorthand, and the full issue URL. Scope the qualified forms to
// THIS repo — GitHub only auto-closes same-repo issues, so a
// cross-repo reference must not be resolved against our numbering.
const repoRef = `${owner}/${repo}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = new RegExp(
'(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s*:?\\s*' +
`(?:${repoRef}#|#|https?://github\\.com/${repoRef}/issues/)(\\d+)`,
'gi',
);
const matches = [...body.matchAll(pattern)];
if (matches.length === 0) {
console.log('No issue link found in PR body');
await enforceFailure('no-link');
return;
}
// The author must be assigned to at least one linked issue.
// CONTRIBUTING.md requires external contributors to be assigned
// before opening a PR (so maintainers can deconflict / steer
// approach first).
//
// Exception: an issue labeled OPEN_LABEL waives that requirement
// for everyone. It's how maintainers advertise "the reporter
// isn't implementing this, we'd take a PR from anyone" without
// having to assign a specific person up front. Unlike the
// PR-level `trusted-contributor` / `bypass-issue-check` escapes,
// this one lives on the *issue* and is set ahead of time.
const MAX_ISSUES = 5;
const allNumbers = [...new Set(matches.map(m => parseInt(m[1], 10)))];
const numbers = allNumbers.slice(0, MAX_ISSUES);
if (allNumbers.length > MAX_ISSUES) {
core.warning(`PR references ${allNumbers.length} issues — checking only the first ${MAX_ISSUES}`);
}
const prAuthor = pr.user.login.toLowerCase();
let sawRealIssue = false;
let assignedToAny = false;
for (const num of numbers) {
let issue;
try {
({ data: issue } = await github.rest.issues.get({
owner, repo, issue_number: num,
}));
} catch (e) {
if (e.status === 404) {
console.log(`#${num} does not exist — ignoring`);
continue;
}
// Same safe-direction rule as hasWriteAccess: a transient
// error must not be read as "not assigned" and close the PR.
throw new Error(`Cannot fetch issue #${num} (HTTP ${e.status ?? 'unknown'}): ${e.message}`);
}
sawRealIssue = true;
// GitHub returns labels as objects here, but the REST schema
// permits bare strings — normalize both rather than assume.
const labelNames = (issue.labels || [])
.map(l => (typeof l === 'string' ? l : l && l.name))
.filter(Boolean)
.map(n => n.toLowerCase());
if (labelNames.includes(OPEN_LABEL)) {
console.log(`#${num} is labeled "${OPEN_LABEL}" — assignment not required`);
assignedToAny = true;
break;
}
const assignees = (issue.assignees || []).map(a => a.login.toLowerCase());
if (assignees.includes(prAuthor)) {
console.log(`PR author ${pr.user.login} is assigned to #${num}`);
assignedToAny = true;
break;
}
console.log(`PR author ${pr.user.login} is NOT assigned to #${num} (assignees: ${assignees.join(', ') || 'none'})`);
}
if (!sawRealIssue) {
console.log('Referenced issue(s) do not exist');
await enforceFailure('no-link');
return;
}
if (!assignedToAny) {
await enforceFailure('not-assigned');
return;
}
console.log('Linked and assigned — clearing any prior enforcement');
await clearEnforcement();
// ── Label, comment, close, and fail ────────────────────────────
// `kind`: 'no-link' (no valid issue reference) or 'not-assigned'
// (referenced an issue, but the author isn't assigned to it).
async function enforceFailure(kind) {
await addLabel();
const reason = kind === 'no-link'
? "it doesn't reference a tracked issue assigned to you"
: "you aren't assigned to the issue it references";
const steps = kind === 'no-link'
? [
`1. Find or [open an issue](https://github.com/${owner}/${repo}/issues/new/choose) describing the change — if you open it, you have first claim on it.`,
"2. Add `Fixes #<issue>`, `Closes #<issue>`, or `Resolves #<issue>` to **this** PR's description — edit it in place, don't open a new PR.",
]
: [
"1. If you opened the linked issue, a maintainer will assign you when they pick it up and this PR reopens automatically. If someone else opened it, the PR reopens only if a maintainer chooses to assign it to you — please don't comment to ask.",
];
const commentBody = [
MARKER,
"**Don't open a new pull request — this one reopens on its own.** It's closed for " +
`now because ${reason}, but the moment that's fixed it reopens automatically. Keep this ` +
'PR and edit it; opening a fresh duplicate just starts you over and creates more to triage.',
'',
`Per [CONTRIBUTING.md](https://github.com/${owner}/${repo}/blob/main/CONTRIBUTING.md), an external PR must reference an issue that's assigned to its author. To get there:`,
'',
...steps,
'',
"Once you're assigned and the link is present, this PR reopens automatically — no further action needed.",
'',
`*Maintainers: reopen this PR or remove the \`${LABEL}\` label to bypass this check.*`,
].join('\n');
const comments = await github.paginate(
github.rest.issues.listComments,
{ owner, repo, issue_number: prNumber, per_page: 100 },
);
const existing = comments.find(c => c.body && c.body.includes(MARKER));
if (!existing) {
await mutate(`comment on PR #${prNumber}`, () => github.rest.issues.createComment({
owner, repo, issue_number: prNumber, body: commentBody,
}));
} else if (existing.body !== commentBody) {
await mutate(`update comment ${existing.id}`, () => github.rest.issues.updateComment({
owner, repo, comment_id: existing.id, body: commentBody,
}));
} else {
console.log('Requirement comment already present — skipping');
}
if (pr.state === 'open') {
await mutate(`close PR #${prNumber}`, () => github.rest.pulls.update({
owner, repo, pull_number: prNumber, state: 'closed',
}));
}
if (enforce) {
core.setFailed(
kind === 'no-link'
? 'PR must reference a tracked issue using an auto-close keyword (e.g. "Fixes #123").'
: 'PR author must be assigned to the referenced issue.',
);
}
}
reopen-on-assignment:
if: github.event_name == 'issues' && github.event.action == 'assigned' && !github.event.issue.pull_request
runs-on: ubuntu-latest
timeout-minutes: 10
concurrency:
group: reopen-on-assignment-${{ github.event.issue.number }}-${{ github.event.assignee.login }}
cancel-in-progress: false
permissions:
actions: write
issues: write
pull-requests: write
steps:
- name: Reopen linked PRs
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const { owner, repo } = context.repo;
const issueNumber = context.payload.issue.number;
const assignee = context.payload.assignee.login;
const enforce = process.env.ENFORCE_ISSUE_LINK === 'true';
const LABEL = 'missing-issue-link';
const MARKER = '<!-- require-issue-link -->';
// Match GitHub's auto-close keywords against any reference form
// that GitHub itself honors: bare `#123`, the `owner/repo#123`
// shorthand, and the full issue URL. Scope the qualified forms to
// THIS repo — GitHub only auto-closes same-repo issues, so a
// cross-repo reference must not be resolved against our numbering.
const repoRef = `${owner}/${repo}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const pattern = new RegExp(
'(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s*:?\\s*' +
`(?:${repoRef}#|#|https?://github\\.com/${repoRef}/issues/)(\\d+)`,
'gi',
);
async function mutate(description, fn) {
if (!enforce) {
console.log(`[dry-run] would ${description}`);
return;
}
await fn();
}
console.log(`Issue #${issueNumber} assigned to ${assignee} — searching for closed PRs to reopen`);
const q = [
'is:pr',
'is:closed',
`author:${assignee}`,
`label:${LABEL}`,
`repo:${owner}/${repo}`,
].join(' ');
let search;
try {
({ data: search } = await github.rest.search.issuesAndPullRequests({
q,
per_page: 30,
}));
} catch (e) {
throw new Error(
`Failed to search closed PRs for ${assignee} after assigning #${issueNumber} ` +
`(HTTP ${e.status ?? 'unknown'}): ${e.message}`,
);
}
if (search.total_count === 0) {
console.log('No matching closed PRs found');
return;
}
console.log(`Found ${search.total_count} candidate PR(s)`);
for (const item of search.items) {
const prNumber = item.number;
let issue;
try {
({ data: issue } = await github.rest.issues.get({
owner, repo, issue_number: prNumber,
}));
} catch (e) {
throw new Error(`Cannot fetch PR #${prNumber} issue data (HTTP ${e.status ?? 'unknown'}): ${e.message}`);
}
const labels = (issue.labels || []).map(label => label.name);
if (labels.includes('bypass-issue-check')) {
console.log(`PR #${prNumber} already has bypass-issue-check — skipping`);
continue;
}
const body = issue.body || '';
const referencedIssues = [...body.matchAll(pattern)].map(match => parseInt(match[1], 10));
if (!referencedIssues.includes(issueNumber)) {
console.log(`PR #${prNumber} does not reference #${issueNumber} — skipping`);
continue;
}
try {
await mutate(`reopen PR #${prNumber}`, () => github.rest.pulls.update({
owner, repo, pull_number: prNumber, state: 'open',
}));
} catch (e) {
if (e.status === 422) {
core.warning(`Cannot reopen PR #${prNumber}: the head branch was likely deleted`);
await mutate(`comment on unreopenable PR #${prNumber}`, () => github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body:
`You have been assigned to #${issueNumber}, but this PR could not be ` +
'reopened because the head branch has been deleted. Please open a new PR ' +
'referencing the issue.',
}));
continue;
}
throw e;
}
await mutate(`remove "${LABEL}" from PR #${prNumber}`, async () => {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: prNumber, name: LABEL,
});
} catch (e) {
if (e.status !== 404) throw e;
}
});
try {
const comments = await github.paginate(
github.rest.issues.listComments,
{ owner, repo, issue_number: prNumber, per_page: 100 },
);
const stale = comments.find(comment => comment.body && comment.body.includes(MARKER));
if (stale) {
await mutate(`minimize stale comment ${stale.id}`, () => github.graphql(`
mutation($id: ID!) {
minimizeComment(input: {subjectId: $id, classifier: OUTDATED}) {
minimizedComment { isMinimized }
}
}
`, { id: stale.node_id }));
}
} catch (e) {
core.warning(`Could not minimize stale comment on PR #${prNumber}: ${e.message}`);
}
try {
const { data: pr } = await github.rest.pulls.get({
owner, repo, pull_number: prNumber,
});
const { data: runs } = await github.rest.actions.listWorkflowRuns({
owner,
repo,
workflow_id: 'require-issue-link.yml',
head_sha: pr.head.sha,
status: 'failure',
per_page: 1,
});
if (runs.workflow_runs.length === 0) {
console.log(`No failed require-issue-link runs found for PR #${prNumber}`);
continue;
}
await mutate(`re-run failed require-issue-link run for PR #${prNumber}`, () =>
github.rest.actions.reRunWorkflowFailedJobs({
owner, repo, run_id: runs.workflow_runs[0].id,
}),
);
} catch (e) {
core.warning(`Could not re-run require-issue-link for PR #${prNumber}: ${e.message}`);
}
}

View file

@ -4,21 +4,21 @@ on:
push:
branches: ["main"]
paths:
- "src/fastmcp/utilities/json_schema_type.py"
- "src/fastmcp/utilities/json_schema.py"
- "src/fastmcp/utilities/openapi/**"
- "src/fastmcp/server/providers/openapi/**"
- "src/fastmcp/client/mixins/tools.py"
- "fastmcp_slim/fastmcp/utilities/json_schema_type.py"
- "fastmcp_slim/fastmcp/utilities/json_schema.py"
- "fastmcp_slim/fastmcp/utilities/openapi/**"
- "fastmcp_slim/fastmcp/server/providers/openapi/**"
- "fastmcp_slim/fastmcp/client/mixins/tools.py"
- "tests/utilities/json_schema_type/test_real_world_schemas.py"
- ".github/workflows/run-schema-crash-test.yml"
pull_request:
paths:
- "src/fastmcp/utilities/json_schema_type.py"
- "src/fastmcp/utilities/json_schema.py"
- "src/fastmcp/utilities/openapi/**"
- "src/fastmcp/server/providers/openapi/**"
- "src/fastmcp/client/mixins/tools.py"
- "fastmcp_slim/fastmcp/utilities/json_schema_type.py"
- "fastmcp_slim/fastmcp/utilities/json_schema.py"
- "fastmcp_slim/fastmcp/utilities/openapi/**"
- "fastmcp_slim/fastmcp/server/providers/openapi/**"
- "fastmcp_slim/fastmcp/client/mixins/tools.py"
- "tests/utilities/json_schema_type/test_real_world_schemas.py"
- ".github/workflows/run-schema-crash-test.yml"
@ -34,7 +34,7 @@ jobs:
timeout-minutes: 45
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Install uv
uses: astral-sh/setup-uv@v7

View file

@ -7,10 +7,12 @@ on:
push:
branches: ["main"]
paths:
- "src/**"
- "fastmcp_slim/**"
- "fastmcp_remote/**"
- "tests/**"
- "uv.lock"
- "examples/**"
- "pyproject.toml"
- "uv.lock"
- ".github/workflows/**"
# run on all pull requests because these checks are required and will block merges otherwise
@ -27,7 +29,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv
uses: ./.github/actions/setup-uv

View file

@ -7,10 +7,11 @@ on:
push:
branches: ["main"]
paths:
- "src/**"
- "fastmcp_slim/**"
- "fastmcp_remote/**"
- "tests/**"
- "uv.lock"
- "pyproject.toml"
- "uv.lock"
- ".github/workflows/**"
# run on all pull requests because these checks are required and will block merges otherwise
@ -36,7 +37,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv
uses: ./.github/actions/setup-uv
@ -47,7 +48,7 @@ jobs:
- name: Run unit tests
uses: ./.github/actions/run-pytest
- name: Run client process tests
- name: Run serial subprocess tests
uses: ./.github/actions/run-pytest
with:
test-type: client_process
@ -58,7 +59,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv (lowest-direct)
uses: ./.github/actions/setup-uv
@ -68,7 +69,7 @@ jobs:
- name: Run unit tests
uses: ./.github/actions/run-pytest
- name: Run client process tests
- name: Run serial subprocess tests
uses: ./.github/actions/run-pytest
with:
test-type: client_process
@ -79,7 +80,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv
uses: ./.github/actions/setup-uv
@ -87,7 +88,7 @@ jobs:
resolution: locked
- name: Setup Node.js
uses: actions/setup-node@v6
uses: actions/setup-node@v7
with:
node-version: "22"
@ -102,7 +103,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv
uses: ./.github/actions/setup-uv
@ -117,3 +118,150 @@ jobs:
FASTMCP_GITHUB_TOKEN: ${{ secrets.FASTMCP_GITHUB_TOKEN }}
FASTMCP_TEST_AUTH_GITHUB_CLIENT_ID: ${{ secrets.FASTMCP_TEST_AUTH_GITHUB_CLIENT_ID }}
FASTMCP_TEST_AUTH_GITHUB_CLIENT_SECRET: ${{ secrets.FASTMCP_TEST_AUTH_GITHUB_CLIENT_SECRET }}
package_install_smoke:
name: "Package install smoke"
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- name: Setup uv
uses: ./.github/actions/setup-uv
with:
resolution: locked
- name: Build package wheels
run: uv build --all-packages --wheel --out-dir /tmp/fastmcp-dist
- name: Install bare slim wheel
run: |
uv venv /tmp/fastmcp-slim-bare-smoke
SLIM_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_slim-*.whl)
uv pip install --python /tmp/fastmcp-slim-bare-smoke/bin/python "$SLIM_WHEEL"
/tmp/fastmcp-slim-bare-smoke/bin/python - <<'PY'
from importlib.metadata import entry_points
import fastmcp
import fastmcp.settings
assert any(ep.name == "fastmcp" for ep in entry_points(group="console_scripts"))
try:
from fastmcp.cli import app
except ImportError as exc:
assert "FastMCP CLI support is not installed" in str(exc)
else:
raise AssertionError(f"bare fastmcp-slim unexpectedly imported CLI app {app!r}")
try:
fastmcp.FastMCP
except ImportError as exc:
assert "fastmcp-slim[server]" in str(exc)
else:
raise AssertionError("bare fastmcp-slim unexpectedly imported FastMCP")
PY
- name: Install client slim wheel
run: |
uv venv /tmp/fastmcp-slim-client-smoke
SLIM_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_slim-*.whl)
uv pip install --python /tmp/fastmcp-slim-client-smoke/bin/python "${SLIM_WHEEL}[client]"
/tmp/fastmcp-slim-client-smoke/bin/python - <<'PY'
from importlib.metadata import entry_points
from fastmcp import Client
from fastmcp.client.transports import StdioTransport, StreamableHttpTransport
from fastmcp.mcp_config import MCPConfig
assert any(ep.name == "fastmcp" for ep in entry_points(group="console_scripts"))
try:
from fastmcp.cli import app
except ImportError as exc:
assert "FastMCP CLI support is not installed" in str(exc)
else:
raise AssertionError(f"client-only slim unexpectedly imported CLI app {app!r}")
assert Client("https://example.com/mcp")
assert StreamableHttpTransport("https://example.com/mcp")
assert StdioTransport(command="uvx", args=["demo"])
assert MCPConfig.from_dict({"mcpServers": {"demo": {"url": "https://example.com/mcp"}}})
try:
from fastmcp import FastMCP
except ImportError as exc:
assert "fastmcp-slim[server]" in str(exc)
else:
raise AssertionError(f"client-only slim unexpectedly imported {FastMCP!r}")
PY
- name: Install server slim wheel
run: |
uv venv /tmp/fastmcp-slim-server-smoke
SLIM_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_slim-*.whl)
uv pip install --python /tmp/fastmcp-slim-server-smoke/bin/python "${SLIM_WHEEL}[server]"
/tmp/fastmcp-slim-server-smoke/bin/python - <<'PY'
from importlib.metadata import entry_points
from fastmcp import FastMCP
from fastmcp.cli import app
assert any(
ep.name == "fastmcp" and ep.value == "fastmcp.cli:app"
for ep in entry_points(group="console_scripts")
)
mcp = FastMCP("smoke")
assert app is not None
assert mcp.name == "smoke"
PY
- name: Install full package from matching local wheels
run: |
uv venv /tmp/fastmcp-full-smoke
FULL_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp-*.whl)
uv pip install --python /tmp/fastmcp-full-smoke/bin/python --prerelease=allow --find-links /tmp/fastmcp-dist "$FULL_WHEEL"
/tmp/fastmcp-full-smoke/bin/python - <<'PY'
from importlib.metadata import entry_points
from importlib.metadata import requires
from fastmcp import Client, FastMCP
from fastmcp.client.client import CallToolResult
from fastmcp.exceptions import ToolError
fastmcp_reqs = requires("fastmcp") or []
assert any("fastmcp-slim[client,server]" in req for req in fastmcp_reqs)
assert not any("fastmcp-slim[full" in req for req in fastmcp_reqs)
assert any(
ep.name == "fastmcp" and ep.value == "fastmcp.cli:app"
for ep in entry_points(group="console_scripts")
)
assert Client("https://example.com/mcp")
assert FastMCP("smoke").name == "smoke"
assert CallToolResult is not None
assert ToolError is not None
PY
- name: Install fastmcp-remote from matching local wheels
run: |
uv venv /tmp/fastmcp-remote-smoke
REMOTE_WHEEL=$(ls /tmp/fastmcp-dist/fastmcp_remote-*.whl)
uv pip install --python /tmp/fastmcp-remote-smoke/bin/python --prerelease=allow --find-links /tmp/fastmcp-dist "$REMOTE_WHEEL"
/tmp/fastmcp-remote-smoke/bin/python - <<'PY'
from importlib.metadata import entry_points
from importlib.metadata import requires
from fastmcp_remote.cli import build_parser
remote_reqs = requires("fastmcp-remote") or []
assert any("fastmcp-slim[client,server]" in req for req in remote_reqs)
assert any(
ep.name == "fastmcp-remote" and ep.value == "fastmcp_remote.cli:main"
for ep in entry_points(group="console_scripts")
)
assert build_parser().prog == "fastmcp-remote"
PY

View file

@ -7,10 +7,10 @@ on:
push:
branches: ["main"]
paths:
- "src/**"
- "fastmcp_slim/**"
- "tests/**"
- "uv.lock"
- "pyproject.toml"
- "uv.lock"
- ".github/workflows/**"
schedule:
@ -30,7 +30,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv (upgrade)
uses: ./.github/actions/setup-uv
@ -56,7 +56,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv (upgrade)
uses: ./.github/actions/setup-uv
@ -67,7 +67,7 @@ jobs:
- name: Run unit tests
uses: ./.github/actions/run-pytest
- name: Run client process tests
- name: Run serial subprocess tests
uses: ./.github/actions/run-pytest
with:
test-type: client_process
@ -78,7 +78,7 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v6
- uses: actions/checkout@v7
- name: Setup uv (upgrade)
uses: ./.github/actions/setup-uv

View file

@ -7,8 +7,8 @@ on:
push:
branches: ["main"]
paths:
- "src/fastmcp/utilities/mcp_server_config/**"
- "!src/fastmcp/utilities/mcp_server_config/v1/schema.json"
- "fastmcp_slim/fastmcp/utilities/mcp_server_config/**"
- "!fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/schema.json"
workflow_dispatch:
permissions:
@ -28,7 +28,7 @@ jobs:
app-id: ${{ secrets.MARVIN_APP_ID }}
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
token: ${{ steps.marvin-token.outputs.token }}
@ -47,7 +47,7 @@ jobs:
from fastmcp.utilities.mcp_server_config import generate_schema
generate_schema('docs/public/schemas/fastmcp.json/latest.json')
generate_schema('docs/public/schemas/fastmcp.json/v1.json')
generate_schema('src/fastmcp/utilities/mcp_server_config/v1/schema.json')
generate_schema('fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/schema.json')
"
- name: Create Pull Request
@ -59,7 +59,7 @@ jobs:
body: |
This PR updates the fastmcp.json schema files to match the current source code.
The schema is automatically generated from `src/fastmcp/utilities/mcp_server_config/` to ensure consistency.
The schema is automatically generated from `fastmcp_slim/fastmcp/utilities/mcp_server_config/` to ensure consistency.
**Note:** This PR is fully automated and will update itself with any subsequent changes to the schema, or close automatically if the schema becomes up-to-date through other means.

View file

@ -7,7 +7,7 @@ on:
push:
branches: ["main"]
paths:
- "src/**"
- "fastmcp_slim/**"
- "pyproject.toml"
workflow_dispatch:
@ -28,7 +28,7 @@ jobs:
app-id: ${{ secrets.MARVIN_APP_ID }}
private-key: ${{ secrets.MARVIN_APP_PRIVATE_KEY }}
- uses: actions/checkout@v6
- uses: actions/checkout@v7
with:
token: ${{ steps.marvin-token.outputs.token }}

View file

@ -6,8 +6,8 @@ repos:
hooks:
- id: validate-pyproject
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.1.0
- repo: https://github.com/rbubley/mirrors-prettier
rev: v3.8.4
hooks:
- id: prettier
types_or: [yaml, json5]
@ -29,7 +29,7 @@ repos:
entry: uv run --isolated ty check
language: system
types: [python]
files: ^src/|^tests/
files: ^fastmcp_slim/|^tests/|^examples/
pass_filenames: false
require_serial: true

View file

@ -27,7 +27,7 @@ uv run prek run --all-files # Ruff + Prettier + ty
| Path | Purpose |
| ----------------- | -------------------------------------- |
| `src/fastmcp/` | Library source code |
| `fastmcp_slim/fastmcp/` | Library source code |
| `├─server/` | Server implementation |
| `│ ├─auth/` | Authentication providers |
| `│ └─middleware/` | Error handling, logging, rate limiting |
@ -50,23 +50,38 @@ When modifying MCP functionality, changes typically need to be applied across al
- **Resource Templates** (`src/resources/`)
- **Prompts** (`src/prompts/`)
**Before writing cross-component logic (dedupe, grouping, lookups, identity checks), read `FastMCPComponent` in `src/fastmcp/utilities/components.py`.** The base class defines the shared surface — `name`, `version`, `tags`, `meta`, and critically the `key` property which is the canonical MCP identity (encodes type, identifier, and version). Prefer `item.key` over ad-hoc `name or uri or uri_template` fallbacks; overrides in `Resource` and `ResourceTemplate` already handle URI-based identity, and `.key` includes the version suffix so variants of the same component don't falsely collide.
**Before writing cross-component logic (dedupe, grouping, lookups, identity checks), read `FastMCPComponent` in `fastmcp_slim/fastmcp/utilities/components.py`.** The base class defines the shared surface — `name`, `version`, `tags`, `meta`, and critically the `key` property which is the canonical MCP identity (encodes type, identifier, and version). Prefer `item.key` over ad-hoc `name or uri or uri_template` fallbacks; overrides in `Resource` and `ResourceTemplate` already handle URI-based identity, and `.key` includes the version suffix so variants of the same component don't falsely collide.
## Development Rules
**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)
- Never amend commits to fix prek failures
- Apply PR labels: bugs/breaking/enhancements/features
- Never apply labels manually or invent new ones — issues and PRs are auto-labeled by a bot based on title/body/code changes. Don't note a "suggested" or "appropriate" label anywhere in the PR body either. See the review-pr skill.
- Improvements = enhancements (not features) unless specified
- **NEVER** force-push on collaborative repos
- **ALWAYS** run prek before PRs
- **NEVER** create a release, comment on an issue, or open a PR unless specifically instructed to do so.
- **NEVER** merge a PR marked as do-not-merge or draft. Check title, body, AND labels for `[DNM]`, `DNM`, `DO NOT MERGE`, `DON'T MERGE`, `DONT MERGE`, `do-not-merge`, `dont-merge`, `[DRAFT]`, or `DRAFT` (case-insensitive, any variation — some authors use `[DRAFT]` in the title even when `isDraft` is false). Authors use these as hard stops — respect them even if CI is green and review looks clean. When triaging a batch of PRs, filter these out up front AND re-check each one's labels immediately before merging, since labels can change mid-session.
- **ALWAYS** read review-bot comments before approving a PR. CodeRabbit and chatgpt-codex-connector (Codex) leave substantive review comments on most PRs in this repo — these bots have read the diff and often flag real issues that aren't in the PR description. Use `gh pr view <num> --comments` and read the bot feedback as part of review. Unlike proposed solutions from issue reporters, review-bot feedback should be evaluated on its merits, not discounted.
- **Be constructively skeptical of bot review comments on your own PRs.** CodeRabbit, Codex, and claude[bot] run a fresh review pass on every push, which means a PR with active churn can accumulate bot comments in a stream that never really ends — each fix surfaces a new edge case the next pass can flag. Most of the early feedback is real and worth acting on; diminishing returns set in fast. Evaluate each comment on its merits, the same way you would a human reviewer: is this a real bug users will hit, or a hypothetical that requires an adversarial setup? Does the fix introduce more complexity than the problem? Has the bot missed context that's obvious to a human reader (a `*,` keyword-only marker, a design decision documented elsewhere, something already resolved on a later commit)? When a comment is pedantic, a false positive, or flagging something already fixed, reply on the thread explaining the reasoning and move on — don't keep iterating just because more comments arrive. If you find yourself three rounds deep and the feedback is shifting toward "what if someone does X" hypotheticals, you're past the point where each fix is improving the PR. Stop, document the contract as-is, and ship.
- **Resolve a review thread when you fix it; reply when you're declining it.** A fix explains itself through the commit, so resolving is enough — and it leaves unresolved threads meaning unfinished business, which is the signal worth having. A decline needs a one-line reason in a reply, because resolving collapses the thread and a hidden objection is worse than a visible one. Doing both is noise. Get thread ids from the GraphQL `reviewThreads` field, then resolve:
```bash
gh api graphql -f query='query($n:Int!){repository(owner:"PrefectHQ",name:"fastmcp"){pullRequest(number:$n){reviewThreads(first:50){nodes{id isResolved path}}}}}' -F n=<pr-number>
gh api graphql -f query='mutation($id:ID!){resolveReviewThread(input:{threadId:$id}){thread{isResolved}}}' -F id=PRRT_...
```
### Outbound Comments and Shell Interpolation
- Never pass GitHub, Linear, or Slack comment bodies inline through shell arguments when the body contains `$`, `${...}`, backticks, `$(...)`, environment-variable examples, secrets, or config interpolation examples.
- Use a body file or structured API payload for outbound comments, then inspect the exact outgoing text before posting. Prefer `gh ... --body-file /path/to/comment.md` over `--body "..."`.
- When explaining environment interpolation, use placeholders and fenced code blocks. Never include raw `.env` contents in outbound comments.
### Releases
@ -77,10 +92,12 @@ Only cut releases when the maintainer explicitly asks. Tags follow `v<version>`
Write the maintainer-approved handwritten notes to a temporary file, then create the release. `--generate-notes` appends the auto-generated changelog after the handwritten content.
```bash
gh release create v3.2.0 --target main --title "v3.2.0: Theme Here" --generate-notes --notes-file /tmp/release-notes.md
gh release create v4.0.0 --target main --title "v4.0.0: Theme Here" --generate-notes --notes-start-tag v3.4.4 --notes-file /tmp/release-notes.md
```
Most releases target `main`, but maintenance or backport releases may target a different branch (e.g., `release/2.x`). Confirm the target with the maintainer if there's any ambiguity.
**Always pass `--notes-start-tag <last-stable-tag>`.** Without it, `--generate-notes` picks the most recent prior tag as the changelog start point — and if a prerelease exists (e.g. `v3.4.0b1`), it starts from *that*, silently truncating the PR list to only the commits since the beta. Pin it to the last stable release (e.g. `v3.3.1` when cutting `v3.4.0`). Verify after: the compare link at the bottom of the generated notes should read `v<last-stable>...v<new>`.
Use the branch that owns the release line as the target: current-major releases target `main`, 3.x maintenance releases target `release/3.x`, and 2.x maintenance releases target `release/2.x`. Confirm the target with the maintainer if there's any ambiguity. For example, cut a 3.4.4 maintenance release with `--target release/3.x`, not `main`.
The handwritten notes are prepended above the auto-generated changelog and are the part that matters. Do not include a title in the notes body — the release title (`v{version}: {pun}`) already serves as the heading. Work with the maintainer to draft the notes — propose a draft, get feedback, iterate. Do not publish without the maintainer's sign-off.
@ -96,10 +113,21 @@ gh api -X POST repos/PrefectHQ/fastmcp/releases/generate-notes \
--jq '.body'
```
Set `target_commitish` to the same branch that will receive the release tag. For maintenance releases, use the maintenance branch (for example, `release/3.x`) so the preview matches the release notes GitHub will generate.
**Point releases** (3.0, 3.1, 3.2) get narrative prose: open with the theme of the release, then walk through headline features conceptually — what they enable, why they matter, how they fit together. Write it the way a blog post reads, not a changelog. Multiple paragraphs, code examples where they clarify.
**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.
**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.
Because the docs land *before* the tag exists, derive the entry from the maintainer-approved handwritten notes (intro/summary) and the `--generate-notes` API *preview* (the PR-list body — see the generate-notes API call above, which returns the exact changelog without cutting anything). Scripting the link reformatting is reliable for long PR lists. The release-URL, tag, and compare links follow the known pattern (`/releases/tag/v<version>`, `compare/v<last-stable>...v<version>`) and will 404 only during the short window between merging the docs PR and cutting the release minutes later — they resolve before the release workflow completes. For this reason, create and merge the docs PR *immediately* before cutting the release — treat the two as one tight back-to-back sequence, not independent steps — so the links are valid by the time the release publishes rather than dangling for any longer than necessary.
### Commit Messages and Agent Attribution
- **Agents NOT acting on behalf of @jlowin MUST identify themselves** (e.g., "🤖 Generated with Claude Code" in commits/PRs)
@ -135,6 +163,7 @@ gh api -X POST repos/PrefectHQ/fastmcp/releases/generate-notes \
### Module Exports
- **Do not create overeager `__init__.py` files.** Package initializers should not import heavy submodules, provider stacks, optional integrations, or modules that can point back into the package. Overeager re-exports make the framework sprawl and create circular imports that only appear in fresh interpreters or clean installs.
- **Be intentional about re-exports** - don't blindly re-export everything to parent namespaces
- Core types that define a module's purpose should be exported (e.g., `Middleware` from `fastmcp.server.middleware`)
- Specialized features can live in submodules (e.g., `fastmcp.server.middleware.dynamic`)
@ -146,9 +175,9 @@ gh api -X POST repos/PrefectHQ/fastmcp/releases/generate-notes \
- Uses Mintlify framework
- Files must be in docs.json to be included
- Do not manually modify `docs/python-sdk/**` — these files are auto-generated from source code by a bot and maintained via a long-lived PR. Do not include changes to these files in contributor PRs.
- Do not manually modify `docs/public/schemas/**` or `src/fastmcp/utilities/mcp_server_config/v1/schema.json` — these are auto-generated and maintained via a long-lived PR.
- Do not manually modify `docs/public/schemas/**` or `fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/schema.json` — these are auto-generated and maintained via a long-lived PR.
- **Core Principle:** A feature doesn't exist unless it is documented!
- When adding or modifying settings in `src/fastmcp/settings.py`, update `docs/more/settings.mdx` to match.
- When adding or modifying settings in `fastmcp_slim/fastmcp/settings.py`, update `docs/more/settings.mdx` to match.
### Documentation Guidelines
@ -159,6 +188,20 @@ gh api -X POST repos/PrefectHQ/fastmcp/releases/generate-notes \
- **Style:** Prose over code comments for important information
- **Docstrings:** FastMCP docstrings are automatically compiled into MDX documents. Use markdown (single backticks, fenced code blocks), not RST (no double backticks). Bare `{}` in examples will be interpreted as JSX — wrap in backticks instead.
## Code Review Rules
### Framework regressions and root causes
- Review changes carefully for regressions in supported framework behavior, including interactions beyond the immediate diff. Trace relevant callers, shared abstractions, protocol and public API contracts, and all affected MCP component types. Determine whether a change fixes the causal code path or merely compensates for the symptom; side channels and special cases that leave the root cause intact should be treated as suspect.
### Comprehensive first pass
- Review the entire pull request diff against the merge base, not only the latest commits. Inspect every changed file and the relevant surrounding code, collect all independent, substantiated consequential findings before submitting the review, and report the complete set in one review whenever possible. Do not stop after finding the first few issues or defer other already-visible findings to later review cycles.
### Prior discussion and proportionality
- When prior review threads and author or maintainer replies are available, read them before commenting. Evaluate responses on their merits and do not repeat a resolved or convincingly rebutted finding without new evidence. Avoid fixating on speculative edge cases: report an edge case only when it is reachable under supported usage or a credible threat model and has meaningful impact; otherwise omit it or clearly treat it as non-blocking.
## Critical Patterns
- Never use bare `except` - be specific with exception types

View file

@ -2,6 +2,8 @@
FastMCP is an actively maintained, high-traffic project. We welcome contributions — but the most impactful way to contribute might not be what you expect.
Participation is governed by our [Code of Conduct](CODE_OF_CONDUCT.md), and contributions are licensed under [Apache 2.0](LICENSE).
## The best contribution is a great issue
FastMCP is an opinionated framework, and its maintainers use AI-assisted tooling that is deeply tuned to those opinions — the design philosophy, the API patterns, the way the framework is meant to evolve. A well-written issue with a clear problem description is often more valuable than a pull request, because it lets maintainers produce a solution that isn't just correct, but consistent with how the framework wants to work. That matters more than speed, though it's faster too.
@ -18,9 +20,17 @@ That's it. No need to diagnose root causes, propose API designs, or suggest impl
We encourage you to use LLMs to help identify bugs, write MREs, and prepare contributions. But if you do, your LLM must take into account the conventions and contributing guidelines of this repo — including how we want issues formatted and when it's appropriate to open a PR. Generic LLM output that ignores these guidelines tells us the contribution wasn't made thoughtfully, and we will close it. A good AI-assisted contribution is indistinguishable from a good human one. A bad one is obvious.
If you're driving an agent: do **not** have it post comments asking to be assigned to an issue or announcing that it intends to work on one. Those comments are ignored. If the agent intends to contribute, open a PR instead — it will be gated on assignment (see below). Comment on an issue only to propose a genuinely novel, differentiated solution, never to claim a task that's already described.
## When to open a pull request
An open issue is not an invitation to submit a PR. Issues track problems; whether and how to solve them is a separate decision. If you want to work on something, propose your approach in the issue first — especially for anything beyond a trivial fix.
An open issue is not an invitation to submit a PR, and it is not a queue you join by commenting. Issues track problems; who implements them and how is a separate decision maintainers make, and whoever opened the issue has first claim on it.
**Don't post drive-by comments claiming an issue** — "can I work on this?", "please assign me", "I'll take this." They don't affect who gets assigned, they're the most common form of noise we get, and automated versions are ignored. Whoever opens the issue has first claim on it; if that's you, a maintainer will assign you. If you want to implement something someone else reported, just open a PR — you don't need permission to try, and competing PRs are fine — but it's reviewed only if a maintainer assigns you to the issue, which usually won't happen if the reporter intends to handle it. The one comment worth posting is a genuinely different approach worth discussing; a substantive design proposal is welcome, a bare claim on the task is not.
**Issues labeled `prs welcome` skip the assignment gate.** When we apply that label, we're saying the reporter isn't implementing it and we'd take a PR from anyone. Open one directly — no assignment needed, and it won't be auto-closed. Still reference the issue (`Fixes #123`), since that's how the check knows which issue to look at.
**What assignment means.** Being assigned is a commitment on both sides: we'll review your work seriously, and you'll see it through. That means responding to review feedback yourself and being able to explain any part of your change and why you made it that way. Use whatever tooling you like to get there — but if you can't answer a question about your own diff, we'll unassign the issue so someone else can pick it up.
**Bug fixes** — PRs are welcome for simple, well-scoped bug fixes where the problem and solution are both straightforward. "The function raises `TypeError` when passed `None` because of a missing guard" is a good candidate. If the fix requires design decisions or touches multiple subsystems, open an issue with a design proposal instead.
@ -34,7 +44,10 @@ An open issue is not an invitation to submit a PR. Issues track problems; whethe
If you do open a PR:
- **Reference an issue.** Every PR should address a tracked issue. If there isn't one, open an issue first. This isn't a permission step — you don't need to wait for a response. But the issue gives us context on the problem, and if a maintainer is already working on it, we can let you know before you invest time in code.
- **Reference an issue you're assigned to.** Every PR must reference a tracked issue using an auto-close keyword (`Fixes #123`, `Closes #123`, or `Resolves #123`), and the referenced issue must be assigned to you — unless it's labeled `prs welcome`, which waives the assignment requirement. If there isn't an issue, open one. This lets us deconflict effort and steer the approach before you invest time in code. External PRs that don't meet these conditions are automatically labeled `missing-issue-link` and closed; they reopen automatically once the link is present and you're assigned.
- **Leave "Allow edits by maintainers" enabled.** We frequently take a PR the last few steps ourselves rather than block on another round trip — tightening a test, adjusting naming, rebasing. It's enabled by default on PRs from personal forks; leave it that way. GitHub doesn't allow it at all for forks owned by an organization, so if you're contributing from one, expect us to land the final changes separately.
- **Target the right branch.** Open against `main` unless you're fixing something specific to a maintenance line, in which case target that branch directly (`release/3.x`, `release/2.x`).
- **If your PR was auto-closed, don't open a new one.** Edit the *existing* PR to add the issue link, get assigned to that issue, and it reopens on its own — the branch and history are preserved. A duplicate PR just starts you over and adds to the triage pile.
- **Keep it focused.** One logical change per PR. Don't bundle unrelated fixes or refactors.
- **Match existing patterns.** Follow the code style, type annotation conventions, and test patterns you see in the codebase. Run `uv run prek run --all-files` before submitting.
- **Write tests.** Bug fixes should include a test that fails without the fix. Enhancements should include tests for the new behavior.

View file

@ -17,15 +17,16 @@
[![Docs](https://img.shields.io/badge/docs-gofastmcp.com-blue)](https://gofastmcp.com)
[![Discord](https://img.shields.io/badge/community-discord-5865F2?logo=discord&logoColor=white)](https://discord.gg/uu8dJCgttd)
[![PyPI - Version](https://img.shields.io/pypi/v/fastmcp.svg)](https://pypi.org/project/fastmcp)
[![TypeScript](https://img.shields.io/npm/v/%40prefecthq%2Ffastmcp-ts?label=typescript&color=3178c6)](https://github.com/PrefectHQ/fastmcp-ts)
[![Tests](https://github.com/PrefectHQ/fastmcp/actions/workflows/run-tests.yml/badge.svg)](https://github.com/PrefectHQ/fastmcp/actions/workflows/run-tests.yml)
[![License](https://img.shields.io/github/license/PrefectHQ/fastmcp.svg)](https://github.com/PrefectHQ/fastmcp/blob/main/LICENSE)
<a href="https://trendshift.io/repositories/13266" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13266" alt="prefecthq%2Ffastmcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/21461" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21461" alt="prefecthq%2Ffastmcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</div>
---
The [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) connects LLMs to tools and data. FastMCP gives you everything you need to go from prototype to production:
The [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) connects LLMs to tools and data. FastMCP is a full MCP application framework for servers, clients, and interactive apps. A server starts with ordinary Python:
```python
from fastmcp import FastMCP
@ -77,22 +78,35 @@ FastMCP has three pillars:
**[Servers](https://gofastmcp.com/servers/server)** wrap your Python functions into MCP-compliant tools, resources, and prompts. **[Clients](https://gofastmcp.com/clients/client)** connect to any server with full protocol support. And **[Apps](https://gofastmcp.com/apps/overview)** give your tools interactive UIs rendered directly in the conversation.
Ready to build? Start with the [installation guide](https://gofastmcp.com/getting-started/installation) or jump straight to the [quickstart](https://gofastmcp.com/getting-started/quickstart). When you're ready to deploy, [Prefect Horizon](https://www.prefect.io/horizon) offers free hosting for FastMCP users.
**Building in TypeScript?** [FastMCP for TypeScript](https://github.com/PrefectHQ/fastmcp-ts) is the official counterpart, built and maintained by the same team. Same pillars, same ideas, `npm install @prefecthq/fastmcp-ts`.
Ready to build? Start with the [installation guide](https://gofastmcp.com/getting-started/installation) or jump straight to the [quickstart](https://gofastmcp.com/getting-started/quickstart).
## Scale MCP with Horizon
FastMCP handles the MCP application layer. **[Prefect Horizon](https://www.prefect.io/horizon?utm_source=github&utm_medium=readme&utm_campaign=readme_horizon&utm_content=readme_body)** is the enterprise MCP gateway for scaling servers and tools across teams, with centralized governance over how they are deployed, discovered, secured, and used.
FastMCP and Horizon are built by the same team at [Prefect](https://www.prefect.io/).
Deploy FastMCP servers from GitHub with branch previews and instant rollback. Create a private registry of every MCP your company uses. Secure access with SSO and tool-level RBAC. Get audit logs, observability, and governance across your MCP stack. Remix approved tools into purpose-built endpoints for teams and agents.
Start with FastMCP. [Scale with Horizon →](https://www.prefect.io/horizon?utm_source=github&utm_medium=readme&utm_campaign=readme_horizon&utm_content=readme_cta)
## Installation
We recommend installing FastMCP with [uv](https://docs.astral.sh/uv/):
We recommend adding FastMCP to your project with [uv](https://docs.astral.sh/uv/):
```bash
uv pip install fastmcp
uv add fastmcp
```
For full installation instructions, including verification and upgrading, see the [**Installation Guide**](https://gofastmcp.com/getting-started/installation).
**Upgrading?** We have guides for:
- [Upgrading from FastMCP v2](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-2)
- [Upgrading from the MCP Python SDK](https://gofastmcp.com/getting-started/upgrading/from-mcp-sdk)
- [Upgrading from the low-level SDK](https://gofastmcp.com/getting-started/upgrading/from-low-level-sdk)
- [Upgrading from FastMCP 3](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-3)
- [Upgrading from FastMCP 2](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-2)
- [Upgrading from MCP SDK v1](https://gofastmcp.com/getting-started/upgrading/from-mcp-sdk-v1) or [v2](https://gofastmcp.com/getting-started/upgrading/from-mcp-sdk-v2)
- [Upgrading from the low-level SDK v1](https://gofastmcp.com/getting-started/upgrading/from-low-level-sdk-v1) or [v2](https://gofastmcp.com/getting-started/upgrading/from-low-level-sdk-v2)
## 📚 Documentation

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,153 @@
---
title: Background Tasks (SEP-2663)
---
**Status: Shipped (#4602, #4603).** This page is the approved design for rebuilding FastMCP's background-task support on the `io.modelcontextprotocol/tasks` extension. It supersedes the earlier "delete the task machinery" direction recorded during the SDK v2 migration. The [Feature Program](feature-program.md#background-tasks-sep-2663) carries the one-line status; user-facing usage is documented at [Background Tasks](https://gofastmcp.com/servers/tasks) and [Background Tasks (client)](https://gofastmcp.com/clients/tasks).
## TL;DR
Background tasks live on. The MCP spec moved them out of core and into a **Final, merged** extension — `io.modelcontextprotocol/tasks` (SEP-2663) — that keeps the polling model FastMCP already implements. **No SDK, in any language, ships a runtime for it yet.** FastMCP owns the only production-shaped execution engine (Docket/Redis) built for a near-identical protocol.
The plan: **rebuild task support on SEP-2663 as `fastmcp-tasks`, an in-repo optional package**, gated by `task=True` exactly as MCP Apps is gated by `app=True`. Remove the SEP-1686 *wire layer*; keep and re-home the *execution engine*. Along the way, introduce a **FastMCP-native server extension API** so tasks (and later Apps) plug in through one documented mechanism instead of bespoke surgery on core.
Net effect: a server that already uses `@mcp.tool(task=True)` needs **no code change**, and FastMCP plausibly becomes the first runtime implementation of the tasks extension anywhere.
## Background: where tasks stand today
FastMCP 3 shipped background tasks against **SEP-1686**, the task protocol that briefly lived in the core MCP spec. The implementation is ~4,000 lines across server, client, CLI, and an SDK shim, split into two very different halves:
- **A wire layer** — capability advertisement, the `tasks/get|result|list|cancel` handlers, a `CreateTaskResult` on augmented `tools/call`, and a Redis-backed *push* relay that lets a worker reach a client to deliver notifications and elicitation requests.
- **An execution engine** — [Docket](https://github.com/chrisguidry/docket) (queue, worker, result store, TTL, `memory://` or `redis://` backends) plus FastMCP-built durability: auth-scoped compound keys that isolate task access by caller, request-context snapshot/restore across worker processes, argument-coercion parity with the sync path, and the `fastmcp tasks worker` CLI.
The SDK v2 migration removed SEP-1686 from the core spec. The v4 design notes, until now, recorded the consequence as "delete the task machinery; users who need tasks stay on FastMCP 3." That was the right call **given the information at the time** — the assumption was that the successor protocol either didn't exist or wasn't implementable. Both halves of that assumption turned out to be wrong.
## What changed upstream: SEP-2663
Tasks were reworked, not removed. **SEP-2663 ("Tasks Extension") is Final and was merged upstream on 2026-05-15**, superseding SEP-1686. It defines the `io.modelcontextprotocol/tasks` extension, a capability-negotiated feature layered on the SEP-2133 extensions mechanism. It keeps SEP-1686's polling core and tightens it.
**The wire shape:**
1. Client advertises the tasks capability (per-request, in `_meta`). This is *consent* — "I can handle a task result" — not a request to run one.
2. Client issues a normal `tools/call`. **The server decides** whether to run it as a task.
3. If tasked, the server returns a `CreateTaskResult` (a claimed result shape carrying `resultType: "task"`) with a **server-generated** `taskId`.
4. Client polls `tasks/get` until the status is terminal; the result is **inlined** into that response.
5. In-task input (elicit/sample/roots requested *during* execution) is **poll-based**: status flips to `input_required`, outstanding requests appear in an `inputRequests` map, and the client answers via `tasks/update`.
6. `tasks/cancel` is cooperative. Optional push exists (`notifications/tasks` over `subscriptions/listen`) but servers need not send it.
**Delta from SEP-1686** — and the striking thing is that most of it is *deletion*, because the spec moved toward what FastMCP already built:
| Dimension | SEP-1686 (old) | SEP-2663 (new) | FastMCP today |
| --- | --- | --- | --- |
| Task-id generation | Client-generated | **Server**-generated | Already server-generated |
| `tasks/list` | Present | **Removed** (enumeration risk) | Already a stub returning `[]` |
| Result retrieval | Separate `tasks/result` | **Inlined** into `tasks/get` | Merge two handlers into one |
| `tasks/delete` | Present | **Removed** (rely on TTL) | TTL is Docket-native |
| Creation race | `notifications/tasks/created` | **Durable-creation MUST** | One read-your-writes check away |
| In-task input | Push relay + `_meta` tagging | **Poll**: `input_required` + `tasks/update` | Replaces the hairiest module |
| Statuses | 7 (incl. `submitted`, `unknown`) | 5 | Shrinks a mapping table |
| Augmentable requests | Any | **`tools/call` only** | Tools-only surface (see scope) |
| LB routing | Unspecified | `Mcp-Name: <taskId>` header | Moot with shared Redis |
**Critically: no runtime exists.** The `ext-tasks` repo is schema + prose only. The TypeScript and Python SDKs carry the wire types and conformance fixtures — no client/server implementation. The field is open.
## The decision
**Build it.** Two facts flip the earlier "delete and wait" call:
1. **The spec is what FastMCP already implements**, minus a push relay it can now shed. The rebuild is dominated by deletion and a thin new wire adapter, not a from-scratch effort.
2. **FastMCP is uniquely positioned.** SEP-2663 *assumes* a durable server-side store, server-minted high-entropy ids, eventual-consistency-aware creation, and multi-node routing — precisely what Docket/Redis provides. No other framework has this built.
Maintaining the SEP-1686 machinery through the migration is dead weight (it's the sole reason for the `_sdk_patches.py` shim, the `TaskNotificationHandler`, and a cluster of protocol-era xfails). Rebuilding on SEP-2663 clears that debt *and* produces a flagship v4 capability with a zero-code-change migration story.
## Architecture
### Engine and wire split
The existing code already separates cleanly along this line; the rebuild makes the boundary a package boundary.
- **Removed:** the SEP-1686 wire layer — capability advertisement, the four CRUD handlers, and (the big win) the entire Redis push relay (`server/tasks/elicitation.py`, `notifications.py`), which existed only because SEP-1686 had no poll-based in-task input channel. SEP-2663's `input_required`/`tasks/update` replaces it; the request/response store survives, the push envelope does not.
- **Kept and re-homed:** the Docket execution engine, the auth-scoped key encoding (this is our *authorization* layer for `tasks/get`/`update`/`cancel` — stronger than the spec's "taskIds may be bearer tokens"), context snapshot/restore, argument coercion, and the worker CLI. All of it is wire-agnostic.
- **New:** a thin SEP-2663 wire adapter — capability, the `tasks/get`/`update`/`cancel` methods, and a `tools/call` interceptor that decides-and-tasks.
### Packaging
`fastmcp-tasks` becomes an in-repo `uv` workspace member on the `fastmcp_remote` template (own `pyproject.toml`, lockstep-versioned, re-exported through the `fastmcp` metapackage). The DX parallel with MCP Apps is exact:
| Concern | MCP Apps | Background tasks |
| --- | --- | --- |
| Authoring flag (core) | `@mcp.tool(app=True)` | `@mcp.tool(task=True)` |
| Optional package | `prefab-ui` | `fastmcp-tasks` |
| Extra | `fastmcp[apps]` | `fastmcp[tasks]` |
| Missing-package behavior | Loud install hint | Loud install hint at server build |
**Core keeps only the declaration:** `task=True` / `TaskConfig` is metadata on a component, with no engine import. Everything else — engine and wire adapter — lives in the `fastmcp-tasks` package. The existing `[tasks]` extra re-points from the SEP-1686 machinery to `fastmcp-tasks`, so `pip install fastmcp[tasks]` and `task=True` keep working with modern wire underneath.
Activation stays **implicit-but-loud** (the existing `require_docket()` pattern, not silent degradation): `task=True` anywhere triggers a lazy import of `fastmcp-tasks` at build time; a missing install raises immediately. A tool the author marked as a task silently running inline would be a correctness bug, not a graceful fallback.
### The extension API
MCP extensions (SEP-2133) are a **genuinely new abstraction in SDK v2** — they did not exist in v1. So MCP Apps hand-rolling its integration wasn't a wrong choice; it predates the tool. Today FastMCP's **server** bypasses the SDK's `Extension` class entirely (it hand-splices the `ui` capability onto the low-level server and walks tool metadata directly), while the **client** forwards `ClientExtension` natively. Every new protocol extension currently means bespoke core surgery.
Tasks is the forcing function to fix that. The design adds a single registration point:
```python test="skip"
from fastmcp import FastMCP
from fastmcp_tasks import TasksExtension
mcp = FastMCP("Server")
mcp.add_extension(TasksExtension(url="redis://...")) # required to enable tasks
@mcp.tool(task=True) # intent: this tool CAN run as a task
async def crunch(dataset: str) -> str:
...
```
`add_extension` is **required** for `task=True` to work — it is not autodetected from the presence of `task=True` flags. This is deliberate. The extension needs configuration that has to live somewhere (backend URL, worker concurrency, TTL defaults), and `add_extension(TasksExtension(...))` is its natural home; autodetection would only scatter that config into settings/env and hide the moment of enablement. Requiring it also keeps capability advertisement honest — the server advertises the `tasks` capability iff the extension is registered — and removes the worst footgun, a tool silently running on an in-memory backend in production because nobody configured Redis. The two concerns stay cleanly separated: `task=True` is per-component intent ("this tool *can* be a task"); `add_extension` is server-wide enablement and config ("this server *runs* tasks, here's how"). Using `task=True` with no extension registered is a loud build-time error.
The extension API contributes a negotiated capability, additive request methods, and a `tools/call` interceptor — with access to FastMCP-level constructs the SDK's `Extension` withholds (the component registry, `Context`, auth scope). It is **designed against tasks** because tasks exercises the full surface (capability + methods + interception + client claims + notifications), where Apps exercises only a subset. Apps migrates onto the extension API as a fast-follow, deleting the hand-rolled splices and confirming the design generalizes.
**Extension vs. middleware** — the discriminator, so we do not over-apply this: an extension is a *negotiated contract change the client must understand*; middleware is *unilateral server behavior the client never sees*. PII detection, auth, rate limiting → [middleware](https://gofastmcp.com/servers/middleware). Tasks, Apps → extensions. Litmus test: delete the capability advertisement — if nothing about the client's behavior changes, it was middleware.
### Client experience
SEP-2663 removed the client-side "make this a task" flag — the server decides. That maps onto FastMCP's existing two-tier client surface, the **friendly** `call_tool` vs the **low-level** `call_tool_mcp`, so there is almost no new API:
- **`call_tool(name, args)` (friendly)** — advertises the capability and, if the server tasks the call, **transparently drives the poll loop** and returns the finished result. Whether the server tasked it is invisible. The machinery already exists: the migration wired claim-resolution through `call_tool_mcp`'s `allow_claimed` path, so a returned `CreateTaskResult` is finished into an ordinary `CallToolResult`. In-task `input_required` routes through the client's **existing elicitation handler**, answered via `tasks/update` — so background elicitation looks identical to foreground elicitation, with zero new client API.
- **`call_tool_mcp(...)` (low-level)** — hands back the raw `CreateTaskResult` claimed shape for callers managing the task themselves.
- **A "return quickly" flag on the friendly interface** yields the `Task` handle (`.status()`, `.wait()`, `.cancel()`, awaitable) without blocking — the escape hatch for progress and cancellation.
Server-side, `TaskConfig` modes translate directly: `required` → always task (`-32003` for non-declaring clients), `optional` → task iff the client declared, `forbidden` → never.
## Sequencing
1. **Design + unit-test the extension API** against tasks' full surface (capability, methods, interception, client claims/notifications) — as its own testable layer, proven in isolation with a trivial in-test extension before any tasks logic lands on it.
2. **Build `fastmcp-tasks`** — extract the engine from the removed SEP-1686 layer, write the SEP-2663 adapter, port the client half.
3. **Migrate MCP Apps onto the extension API** — fast-follow, off the critical path, with Apps' existing green tests as the regression net.
Tasks leads because only it exercises the full API surface; leading with the Apps subset would design us into a corner. Apps becomes the second consumer that confirms generality.
## Scope for v1 (non-goals)
- **Polling only.** The optional `notifications/tasks` push and `subscriptions/listen` integration are deferred to a later `fastmcp-tasks` version. This lets the second Redis notification queue die rather than be ported.
- **`tools/call` only — do not lead the spec.** SEP-2663 augments `tools/call` only. FastMCP 3 offered `task=True` on prompts and resources *ahead* of the SDK under SEP-1686, and that was a mistake: it produced wire-inexpressible capability, a permanent xfail cluster, and the sdk-feedback #3 gap. The rebuild does **not** repeat it — `task=` is a tools-only surface, and the generic prompt/resource task spine is dropped rather than carried. If the spec extends augmentation later, the surface grows with it.
- **Ship experimental.** The `ext-tasks` schema is labeled experimental with no releases; `fastmcp-tasks` ships labeled experimental initially and revs on its own cadence when the schema moves.
## Risks
| Risk | Mitigation |
| --- | --- |
| **Spec churn** (extension is experimental) | Thin wire adapter over a wire-agnostic engine; ship experimental; SEP itself is Final, so the polling model is stable even if field names move. |
| **Era gating** — SDK strips `capabilities.extensions` at pre-2026 negotiated versions (sdk-feedback #2) | Advertisement effectively requires the 2026-07-28 era. FastMCP 3 covers legacy tasks. **#2 now gates a flagship feature → escalate upstream.** |
| **Co-developing a new abstraction + greenfield feature** | Build and unit-test the extension API in isolation first (step 1) before tasks logic lands on it. |
| **Naming confusion**`[tasks]` extra re-points under the same name | Deliberate changelog note; user code and the extra name are unchanged, only the wire modernizes. |
## Design decisions (resolved)
These were the open forks; the maintainer has settled them. Recorded here so the direction is unambiguous going into implementation.
1. **Wire adapter location — in the `fastmcp-tasks` package.** The engine *and* the SEP-2663 wire adapter live in the package; core carries only the `task=True` declaration. This isolates the experimental schema's churn from core, at the cost of diverging from the Apps precedent (where the `ui` wire glue lives in core today — Apps will converge onto this model when it migrates to the extension API).
2. **Extension API shape — a FastMCP-native `mcp.add_extension()`, required to enable tasks.** Chosen over a thin pass-through to the SDK's `MCPServer(extensions=...)` because the FastMCP-native API can hand extensions the `Context`, component registry, and auth scope the SDK's `Extension` withholds. `add_extension` is **required** for `task=True` (not autodetected) — it is the single home for backend config and the honest source of capability advertisement. See [The extension API](#the-extension-api).
3. **Client default — transparent completion on the friendly interface.** `call_tool` drives the poll loop and returns the finished result; `call_tool_mcp` exposes the raw `CreateTaskResult`; a "return quickly" flag yields the `Task` handle. See [Client experience](#client-experience).
4. **Experimental labeling — yes.** `fastmcp-tasks` ships labeled experimental for at least one minor cycle, tracking the experimental `ext-tasks` schema.
5. **Resource/prompt spine — dropped; tools-only.** The rebuild does not lead the SDK on augmentable request types, correcting the SEP-1686-era mistake. See [Scope for v1](#scope-for-v1-non-goals).

View file

@ -0,0 +1,595 @@
---
title: Change Register
---
This is the complete register of user-facing changes from the MCP Python SDK v2 migration ([PR #4437](https://github.com/PrefectHQ/fastmcp/pull/4437)), organized by subsystem. It doubles as a review lens: take one subsystem, read its claimed changes, and verify each against the diff.
Each entry is tagged **Absorbed** (public surface unchanged), **Bridged** (shim keeps old code working, usually warning), **Breaking** (user code must change), or **Deprecated** (works, warns, slated for removal). See the [overview](index.md) for what each disposition means.
**Empirical validation (WS2 upgrade reality-check).** The register's compatibility claims are verified, not predicted. Running unchanged 3.x-era code against this branch, all 11 upgrade scenarios pass or warn — the only failures were the two predicted breaks, user `mcp.types` imports and positional `McpError(ErrorData(...))` construction — and the first of those went away when the stable SDK restored `mcp.types` (below). Cross-version wire interop between a 3.4.3 peer and this branch is bidirectionally clean across 9 operations (3.4.3 client ↔ v4 server and v4 client ↔ 3.4.3 server over HTTP). All 29 `_ALIASES` bridge entries warn correctly with actionable messages.
## Environment
### Dependency floors: pydantic >= 2.12, Starlette >= 1.0 — Breaking (environment)
The SDK v2 raises FastMCP's dependency floors. Projects pinning an older pydantic (e.g. `2.11.*`) hit an unsatisfiable-resolution error at install time and must bump their pin; unpinned projects get pydantic upgraded silently. The server extra floors Starlette at `>=1.0.1` — modern FastAPI (0.11x+) already runs Starlette 1.x, so coexistence is clean (verified with FastAPI 0.138.2); only very old FastAPI pinned below Starlette 1.0 conflicts. Both are documented in the [upgrade guide's Environment requirements](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-3#environment-requirements).
*Verify:* `fastmcp_slim/pyproject.toml` (`pydantic[email]>=2.12.0` core, `starlette>=1.0.1` server extra); WS2 environment-upgrade scenario.
## Types and imports
The SDK v2 moved protocol types into a standalone `mcp_types` package — still importable as `mcp.types` — and renamed every model field from camelCase to snake_case in Python. The wire format is unchanged: the models keep their camelCase aliases and the SDK serializes with `by_alias=True`, so this renames the attributes code reads, not the JSON on the connection. This is the single largest source of user-facing change, and FastMCP absorbs nearly all of it.
### `mcp.types` split into `mcp_types` — Breaking (by omission)
<Note>
Superseded by the stable SDK — see "`mcp.types` restored as a permanent alias" below. The betas this section was written against had no `mcp.types`; `2.0.0` brought it back, so the break never reached a release.
</Note>
The `mcp.types` module no longer exists. Any `from mcp.types import X` or `import mcp.types` in user code raises `ImportError`. This is the one import change users cannot avoid.
*Verify:* `fastmcp_slim/fastmcp/types.py`, and grep the diff for the doc migration `from mcp.types import``from fastmcp.types import` (30 sites).
### `mcp.types` restored as a permanent alias — Absorbed (stable-SDK change)
The SDK betas removed `mcp.types` outright, which made user imports the one unavoidable break in the migration. SDK `2.0.0` reintroduced it as a permanent alias for `mcp_types`: a wildcard mirror where every name is the *same object* (`mcp.types.Tool is mcp_types.Tool`), with matching `__all__` and the same snake_case fields. It is not a v1 restoration — only the import path came back. So `from mcp.types import X` keeps working, and the break is gone.
This leaves the two spellings pointing at one package, and FastMCP uses each in a different place on purpose:
- **User-facing docs and examples use `mcp.types`.** Anyone installing `fastmcp` gets the full SDK (`fastmcp``fastmcp-slim[client,server]``[mcp]``mcp`), so the aliased path always resolves and is the spelling the SDK prefers. It also means a user's own dependency list needs only `mcp`, without naming `mcp-types` to satisfy a linter.
- **FastMCP's own source uses `mcp_types`.** `mcp.types` is a submodule of `mcp`, so importing it requires the whole SDK. `mcp-types` is a *core* `fastmcp-slim` dependency while `mcp` sits behind the `[mcp]` extra, and a bare `fastmcp-slim` install must import without the SDK present — a guarantee `test_bare_slim_import_needs_only_mcp_types` pins. Reaching for `mcp.types` in core modules (`exceptions.py`, `_compat.py`, `tools/`, `resources/`) would pull the full SDK into the slim floor and break it.
The rule of thumb: import `mcp_types` in library code, write `mcp.types` in anything a user copies. Both resolve to the same objects, so neither choice constrains the other.
*Verify:* `.venv/.../mcp/types/__init__.py` (the wildcard mirror), `fastmcp_slim/pyproject.toml` (`mcp-types` core vs `mcp` in the `[mcp]` extra), `tests/client/test_slim_package_boundaries.py::test_bare_slim_import_needs_only_mcp_types`, and `tests/test_upgrade_from_v3.py::TestRemovedSurfacesFailLoudly::test_mcp_types_import_path_restored_by_stable_sdk`.
### `fastmcp.types` is the stable home — Bridged
<Note>
Superseded before release — see "`fastmcp.types` trimmed to FastMCP-unique types only" below. This section documents the re-export set as it existed mid-migration; none of it ever shipped.
</Note>
FastMCP re-exports the protocol types users are most likely to touch from `fastmcp.types`, sourced from `mcp_types` (the `mcp` root package lacks most of them):
```python test="skip"
from fastmcp.types import TextContent, Tool, ToolAnnotations, ErrorData
```
The re-export set is deliberately limited to names that trace to a documented user import: `TextContent`, `ImageContent`, `AudioContent`, `EmbeddedResource`, `ResourceLink`, `ContentBlock`, `Tool`, `Resource`, `ResourceTemplate`, `Prompt`, `PromptMessage`, `CallToolResult`, `GetPromptResult`, `ReadResourceResult`, `TextResourceContents`, `BlobResourceContents`, `SamplingMessage`, `CreateMessageResult`, `SamplingCapability`, `Root`, `ErrorData`, `Completion`, `Annotations`, `ToolAnnotations`, `Icon`, `ToolResultContent`, plus the pre-existing `Textarea`. Notification and request wrapper types (e.g. `ToolListChangedNotification`) are not re-exported — import those from `mcp_types` directly.
*Verify:* `fastmcp_slim/fastmcp/types.py` `__all__`.
### `fastmcp.types` trimmed to FastMCP-unique types only — Absorbed (post-review cleanup)
The re-export set above never shipped in a release, so it was cut before 4.0 rather than deprecated. `fastmcp.types` now holds only types FastMCP defines itself — `Textarea` — and every bare `mcp_types` mirror (`TextContent`, `Tool`, `ToolAnnotations`, `ErrorData`, and the rest of the 29-name list) is gone. Code that imported those from `fastmcp.types` now imports them from `mcp_types` directly:
```python
from mcp_types import TextContent, Tool, ToolAnnotations, ErrorData
```
Because `fastmcp.types.__all__` was `["Textarea"]` as of the last stable release (v3.4.4) and the mirrors were added only in this unreleased migration work, removing them breaks no released user — there is no bridge or deprecation warning to write.
*Verify:* `fastmcp_slim/fastmcp/types.py` `__all__` (back down to `["Textarea"]`).
### camelCase field reads are bridged — Bridged (deprecated)
Objects FastMCP hands back — results of `client.list_tools()`, `client.call_tool_mcp()`, `client.read_resource()`, and the parameter objects passed to sampling and elicitation handlers — are SDK v2 objects with snake_case fields. A compatibility bridge installed at import time routes the old camelCase names to their snake_case fields, warning once per read:
```python
from fastmcp import Client
async def read_schema():
async with Client("my_mcp_server.py") as client:
tools = await client.list_tools()
return tools[0].inputSchema # works, warns; prefer .input_schema
```
The bridged fields are exactly those users read, data-driven from an `_ALIASES` table: `inputSchema`/`outputSchema` (Tool); `readOnlyHint`/`destructiveHint`/`idempotentHint`/`openWorldHint` (ToolAnnotations); `mimeType` (Resource, ResourceTemplate, TextResourceContents, BlobResourceContents, ImageContent, AudioContent) and `uriTemplate` (ResourceTemplate); `isError`/`structuredContent` (CallToolResult); `hasMore` (Completion); `serverInfo`/`protocolVersion` (InitializeResult); `nextCursor`/`resourceTemplates` (List\*Result); `systemPrompt`/`maxTokens`/`stopSequences`/`modelPreferences`/`toolChoice` (CreateMessageRequestParams); `requestedSchema` (ElicitRequestFormParams). WS2 verified all 29 alias entries warn correctly with actionable messages.
*Verify:* `fastmcp_slim/fastmcp/_compat.py` (the `_ALIASES` table and `install()`).
### The bridge is a genuine runtime toggle — Absorbed (post-review fix)
The bridge properties install unconditionally, and each getter reads the live `mcp_camelcase_compat` setting on every access: warn-and-return when enabled, raise `AttributeError` when disabled. An earlier version installed the bridge once at import, so flipping the setting afterward did nothing — commit `d9659453` fixed this so the toggle works at runtime:
```python
import fastmcp
fastmcp.settings.mcp_camelcase_compat = False # now takes effect immediately
```
The setting is documented in [Settings](https://gofastmcp.com/more/settings) as `FASTMCP_MCP_CAMELCASE_COMPAT`.
*Verify:* `fastmcp_slim/fastmcp/settings.py` (setting), `fastmcp_slim/fastmcp/_compat.py` (per-read gate), commit `d9659453`.
### `mcp-types` is now a core slim dependency — Absorbed (post-review fix)
Bare `import fastmcp` loads `mcp_types` via `_sdk_patches` and `_compat`, so a bare `fastmcp-slim` install (without the `[mcp]` extra) hit `ModuleNotFoundError`. Because `mcp-types` only pulls `pydantic` and `typing-extensions` (already core), it was promoted to a core dependency while the full `mcp` SDK stays in the `[mcp]` extra.
*Verify:* `fastmcp_slim/pyproject.toml` (`mcp-types==2.0.0b1` in core dependencies), commit `e16ffad4`.
### `McpError` is an alias; construction changed — Bridged (catch) / Breaking (construct)
`fastmcp.exceptions.McpError` is a plain alias of the SDK's `MCPError` — a plain alias, not a subclass, so `except McpError` still catches SDK-raised errors and `err.error.code` still reads:
```python
from fastmcp.exceptions import McpError
try:
...
except McpError as err:
print(err.error.code) # unchanged
```
Construction is the one unavoidable behavior break. The v1 pattern of wrapping an `ErrorData` positionally raises `TypeError` under v2; construct with keywords instead:
```python
from fastmcp.exceptions import McpError
# Before (raises TypeError under SDK v2):
# raise McpError(ErrorData(code=-32000, message="Client not supported"))
raise McpError(code=-32000, message="Client not supported")
```
*Verify:* `fastmcp_slim/fastmcp/exceptions.py` (`McpError = MCPError`).
## Server core
The SDK v2 rewrote the server request-handling model. FastMCP's handler layer is the most heavily rewritten part of the migration, but the public server API is unchanged.
### Handler adapters — Absorbed
Handlers are now registered by method string via `add_request_handler(method, params_type, handler)`, take a uniform `(ctx, params)` signature, and return the **bare** result model (no `ServerResult` wrapper). FastMCP's `_setup_handlers` builds one thin adapter per method (`tools/list`, `tools/call`, `resources/read`, `prompts/get`, `logging/setLevel`, …) that binds the request context, adapts params to the existing handler body, and returns the bare result. The v1 decorator overrides and `_wrap_list_handler` are deleted.
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (462 lines changed), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py`.
### FastMCP-owned request context — Absorbed
The SDK's `request_ctx` ContextVar is gone; the SDK passes context to handlers as an argument only. FastMCP owns its own `fastmcp_request_ctx` ContextVar, set at the top of every adapter. It stores a FastMCP-owned `FastMCPRequestContext` wrapper rather than the raw SDK context, because the raw `ServerRequestContext.meta` is a bare `TypedDict` carrying only `progress_token` — the full `_meta` block (which holds `_meta.fastmcp.version` and the distributed-trace parent) has to be lifted out of the raw params dict. `Context.request_context` and its consumers (`report_progress`, `session_id`, telemetry trace extraction, `get_http_request`) all read through the wrapper.
*Verify:* `fastmcp_slim/fastmcp/server/dependencies.py`, `server/context.py`, `server/telemetry.py`.
### `ServerMiddleware` bridge for `initialize` — Absorbed
Server-side middleware is a new first-class SDK concept: `Server.middleware` is a list of `ServerMiddleware` composed around every request and notification, including `initialize`. FastMCP no longer subclasses `ServerSession` (the runner constructs it), so the old `MiddlewareServerSession._received_request` override is gone. A `FastMCPServerMiddleware` is appended to the SDK's middleware list (preserving the SDK's own OpenTelemetry middleware) and intercepts `initialize` to run FastMCP's middleware chain. The v2 interface is cleaner — `call_next(ctx)` returns the serialized result directly, so the old `capturing_respond` machinery is deleted.
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (`FastMCPServerMiddleware`).
### Middleware observes every inbound message — New (coverage)
FastMCP's `Middleware` chain used to begin *inside* the per-method handlers, so `on_message`/`on_request`/`on_notification` only fired for messages that reached a tool/resource/prompt handler. Notifications, cancellations, and malformed or unroutable requests were invisible to middleware. `FastMCPServerMiddleware` — FastMCP's entry in the SDK's own middleware list — is now the dispatch root: it runs the `on_message`/`on_request`/`on_notification` pass for every message the interior handlers do not dispatch (all notifications including `notifications/cancelled`, `ping`, `logging/setLevel`, unknown methods, and component requests that fail validation before the handler runs). The component methods keep their interior dispatch unchanged, so `on_call_tool` and friends still receive the typed component result and a tool exception still propagates through `on_message`/`on_request` exactly where the built-in error/logging/timing middleware expect it — each hook fires exactly once per message. Multi-round (SEP-2322) calls compose cleanly with this: each round is a complete request→response cycle through the full chain, and an asking round's `call_next` returns the ask as an ordinary `InputRequiredToolResult` value (see the MRTR entry below). All thirteen built-in middleware pass their suites unmodified. See [What middleware sees](https://gofastmcp.com/servers/middleware#what-middleware-sees).
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (`FastMCPServerMiddleware` root dispatch, `_INTERIOR_METHODS`), `fastmcp_slim/fastmcp/server/middleware/middleware.py` (`MiddlewarePhase`, `mark_interior_dispatched`), `fastmcp_slim/fastmcp/server/server.py` (`_dispatch_component_middleware`), `tests/server/middleware/test_message_visibility.py`.
### Per-session state re-homed to the connection — Absorbed
Because `ServerSession` is now per-request, per-session state can no longer live on the session object. The minimum logging level is re-homed to a FastMCP-side map keyed by session id (via `connection.session_id`), and `client_supports_extension` becomes a free function reading `session.client_params.capabilities`.
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py`, `server/context.py` (`_log_to_server_and_client`).
### `extensions` capability read from the real field — Absorbed (post-review fix)
SDK v2 declares `extensions` as a real field on `ClientCapabilities`, so a client sending `ClientCapabilities(extensions={...})` populates the field, not `model_extra`. `client_supports_extension` now reads `caps.extensions` first and falls back to `model_extra` only for legacy-serialized clients.
*Verify:* commit `96ca0092`, `server/low_level.py` / `server/context.py`.
### Task protocol and the `_sdk_patches` shim — Absorbed (with an upstream gap)
The SEP-1686 task CRUD protocol (`tasks/get`, `tasks/result`, `tasks/list`, `tasks/cancel`) is entirely FastMCP-owned — the SDK ships no task store. Task detection moves to a params field: `params.task is not None` on `CallToolRequestParams`, with `ttl` from `params.task.ttl`. The four task handlers port to `add_request_handler`.
The SDK has a real gap here (see [Known Gaps](known-gaps.md) and sdk-feedback #1): it ships the task result types but omits them from the method registries, so a background-task `tools/call` returning a `CreateTaskResult` fails validation. FastMCP installs a registry-widening shim in `_sdk_patches.py` that adds `CreateTaskResult` to the `tools/call` result union and registers the `tasks/*` rows. It is a temporary patch with a self-documented removal trigger.
Resources and prompts have **no `task` field** on their params in b1, so task-augmented resource reads and prompt gets are not wire-expressible — a documented capability regression, tracked by xfails, not a bug FastMCP fixes.
This section records the migration's *handling* of the SEP-1686 wire layer as it stood at merge. That layer is not the end state: it is slated for removal and rebuild on the `io.modelcontextprotocol/tasks` extension (SEP-2663) as the `fastmcp-tasks` package. See [Background Tasks (SEP-2663)](background-tasks.md) for the forward plan; the `_sdk_patches.py` shim and the `server/tasks/*` wire handlers described here go away with it, while the Docket execution engine moves into `fastmcp-tasks`.
*Verify:* `fastmcp_slim/fastmcp/_sdk_patches.py`, `server/tasks/*`.
### Single SERVER span per request — Absorbed (post-migration fix)
SDK v2 seeds an `OpenTelemetryMiddleware` into every lowlevel `Server`, so each inbound request already emits a SERVER span. FastMCP emits its own richer SERVER span per request (with `fastmcp.*` and auth/session attributes), so a server with an OTel exporter installed would export **two** SERVER spans per request under different attribute conventions. `LowLevelServer.__init__` now drops the SDK's seeded `OpenTelemetryMiddleware` (matched by type, not position, leaving any other seeded middleware intact) and keeps FastMCP's spans. Inbound W3C trace-context extraction is unaffected — FastMCP's telemetry reads `traceparent` from `_meta` itself, so distributed traces still link client to server. Client-side is not double-counted: the SDK's `ClientSession` emits a low-level `MCP send <method>` CLIENT span that nests *under* FastMCP's high-level client span, a legitimate parent/child hierarchy rather than a duplicate.
*Verify:* `fastmcp_slim/fastmcp/server/low_level.py` (the `OpenTelemetryMiddleware` filter); `tests/server/telemetry/test_server_tracing.py::TestSingleServerSpan`.
### Telemetry on by default, with a three-way mode setting — Absorbed
FastMCP's OpenTelemetry instrumentation is on by default. Because FastMCP uses only the OpenTelemetry API, span creation is a no-op with negligible overhead (the API's `NonRecordingSpan`) unless the user configures an SDK and exporter — so being always-on costs nothing until you opt into collection. `FASTMCP_TELEMETRY_MODE` (`fastmcp.settings.telemetry_mode`, default `native`) controls how much is active: `native` emits spans and propagates trace context; `propagation_only` emits no FastMCP spans but still extracts the incoming `_meta` context and attaches it, so downstream spans are parented to the calling trace; `off` is a full pass-through that touches neither spans nor context. The setting governs FastMCP's own spans (all SERVER spans, plus FastMCP's high-level CLIENT span); the SDK's low-level `mcp-python-sdk` `MCP send <method>` CLIENT spans are governed by the user's OpenTelemetry SDK, not this setting. `suppress_fastmcp_telemetry()` applies `propagation_only` semantics to a single block for library authors who own the MCP hierarchy for one operation rather than process-wide; it cannot override `off`. FastMCP's SERVER span now also carries `mcp.protocol.version` — the attribute the dropped SDK `OpenTelemetryMiddleware` set — restoring parity with the SDK's semantic conventions.
`propagation_only` is applied at the seam span, which is where the incoming `_meta` parent context is established for the whole request; suppressing only the deeper `server_span` would leave the per-request SERVER span intact and defeat the mode.
*Verify:* `fastmcp_slim/fastmcp/settings.py` (`telemetry_mode`); `fastmcp_slim/fastmcp/telemetry.py` (`telemetry_mode`, `get_tracer`, `suppress_fastmcp_telemetry`); `fastmcp_slim/fastmcp/server/telemetry.py` (`_propagation_only_span`, `seam_span`, `get_protocol_span_attributes`); `tests/server/telemetry/test_server_tracing.py::TestTelemetryEnabledByDefault`, `::TestProtocolVersionAttribute`; `tests/telemetry/test_interop.py`.
### Spec-correct error codes via a central translator — Breaking (wire error code)
Resource-not-found responses from the core `resources/read` handler previously used `-32002`. SEP-2164 (and the SDK's own mcpserver, which maps `ResourceNotFoundError``INVALID_PARAMS`) makes this `-32602`. The per-adapter `MCPError(code=..., ...)` literals in `server/mixins/mcp_operations.py` are replaced by a single `fastmcp.exceptions.to_mcp_error()` translator that maps FastMCP's public exceptions to the `mcp_types` code constants (`NotFoundError`/`DisabledError`/`ValidationError``INVALID_PARAMS`, else `INTERNAL_ERROR`). Clients that string-matched on the old `-32002` for resource-not-found must switch to `-32602`; the human-readable message ("Resource not found: ...") is unchanged. The opt-in `ErrorHandlingMiddleware`, which has its own documented per-method-prefix code mapping, is intentionally left as-is.
*Verify:* `fastmcp_slim/fastmcp/exceptions.py` (`to_mcp_error`); `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py`; `tests/test_exceptions.py`.
### `Cachable*` response-cache models renamed to `Cacheable*` — Breaking (rename) <!-- codespell:ignore -->
The response-caching middleware's Pydantic wrapper models — used to serialize cached tool, resource, and prompt results for `ResponseCachingMiddleware` — carried a spelling typo. `CachableToolResult`, `CachableResourceContent`, `CachableResourceResult`, `CachableMessage`, and `CachablePromptResult` are renamed to `CacheableToolResult`, `CacheableResourceContent`, `CacheableResourceResult`, `CacheableMessage`, and `CacheablePromptResult`. None of these classes are re-exported from `fastmcp` or any package `__init__.py`, so the realistic blast radius is limited to code that imported the old names directly from `fastmcp.server.middleware.caching`:
```python
# Before (now raises ImportError):
# from fastmcp.server.middleware.caching import CachableToolResult
# After
from fastmcp.server.middleware.caching import CacheableToolResult
```
There is deliberately no compatibility alias for the old spelling.
*Verify:* `fastmcp_slim/fastmcp/server/middleware/caching.py`.
### Server-side argument completion — New (opt-in feature)
A FastMCP server can now answer `completion/complete` requests, suggesting values for prompt arguments and resource-template parameters as a user types. Previously a FastMCP *client* could call `complete()` but a FastMCP *server* had no way to respond — the method was unregistered, so it returned `-32601` (method-not-found) on both eras. The new `@mcp.completion` decorator registers a single server-level handler that receives the reference (a `PromptReference` or `ResourceTemplateReference`), the `CompletionArgument` being completed, and the optional `CompletionContext` of already-supplied argument values, and returns candidates — a list of strings, a `Completion` (to carry the `total`/`has_more` pagination hints), or `None`/empty for a reference it does not recognize (which yields an empty completion, not an error).
```python
from fastmcp import FastMCP
from mcp_types import PromptReference
mcp = FastMCP("Completion Server")
@mcp.prompt
def write_poem(theme: str) -> str:
return f"Write a poem about {theme}"
@mcp.completion
def complete(ref, argument, context):
if isinstance(ref, PromptReference) and argument.name == "theme":
options = ["nature", "love", "adventure"]
return [o for o in options if o.startswith(argument.value)]
return None
```
The completions capability is declared exactly when a handler exists: `add_completion_handler` registers the low-level `completion/complete` handler, and the SDK derives the capability from that handler's presence — a server with no completion handler does not advertise it. FastMCP does not hand-set the capability. The single-handler shape mirrors the SDK's own `completion/complete` surface and FastMCP's existing client-side `Client.complete()`, and it slots into the `@mcp.tool`/`@mcp.prompt`/`@mcp.resource` decorator lineup as another server-level `@mcp.<verb>` registration rather than inventing a per-argument sub-decorator idiom. It works identically on the handshake and modern (`2026-07-28`) eras, since `completion/complete` is a request/response method that flows on every era. The authoring types — `PromptReference`, `ResourceTemplateReference`, `CompletionArgument`, `CompletionContext`, and `Completion` — are imported from `mcp_types`, not `fastmcp.types`.
*Verify:* `fastmcp_slim/fastmcp/server/completions.py` (handler type + `normalize_completion`), `fastmcp_slim/fastmcp/server/server.py` (`completion` decorator, `add_completion_handler`), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_complete`), `tests/server/test_completions.py`, `docs/servers/completions.mdx`.
## Client
The `fastmcp.Client` public API is largely preserved. The client stays a wrapper around `mcp.ClientSession`; the first-class `mcp.client.Client` is deliberately not adopted. Two client-surface changes are called out below: the connection `mode` default flips to `"auto"`, and `extensions=` / `result_claims=` are newly surfaced.
### Connection `mode` defaults to `"auto"` — Breaking (behavior)
`Client(mode=...)` now defaults to `"auto"` instead of `"legacy"`. The client probes `server/discover` and adopts the modern (`2026-07-28`) era when the server responds, denylist-falling-back to the initialize handshake for any server that is not positive evidence of a modern peer. Against a FastMCP server (which serves both eras), an ordinary `Client(url)` now negotiates the modern era by default, where the legacy-only Context push features are unavailable per the per-feature era matrix (see the *Protocol eras* section below) — server-initiated sampling/elicitation/roots, `ping`, session ids, and FastMCP task submission all require the legacy era. The one-line revert is `Client(..., mode="legacy")`, which restores byte-identical pre-v4 negotiation.
The SSE transport is legacy-only (it cannot carry the sessionless modern era), so a client connecting over SSE negotiates the legacy handshake even under `mode="auto"` — expressed by a `ClientTransport.legacy_only` flag set on `SSETransport`. `MCPConfigTransport` reports `legacy_only` as a property: a multi-server config is legacy-only (each backend is mounted behind a legacy-era proxy), while a single-server config mirrors its one backend transport's era so a modern Streamable HTTP backend stays modern-capable. Two internal library clients that are inherently handshake-based are pinned to legacy so the flip does not break them: the `ProxyClient` backend (which forwards the initialize handshake and server-initiated features) defaults to `mode="legacy"`, and the `inspect` utility (which reads the full `server_info` only the handshake carries) connects legacy.
```python
from fastmcp import Client
client = Client("https://example.com/mcp") # now negotiates "auto"
client = Client("https://example.com/mcp", mode="legacy") # opt back into the handshake
```
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (`mode` default, `_negotiate` `legacy_only` shortcut), `fastmcp_slim/fastmcp/client/transports/{base,sse,config}.py` (`legacy_only`), `fastmcp_slim/fastmcp/server/providers/proxy.py` (`ProxyClient` legacy default), `fastmcp_slim/fastmcp/mcp_config.py` and `fastmcp_slim/fastmcp/utilities/inspect.py` (legacy inner clients), `tests/client/client/test_mode_negotiation.py` (default, clean discover-rejection fallback, legacy-only transport), `tests/test_mcp_config.py` (single- vs multi-server `legacy_only`), `docs/clients/client.mdx`.
### `extensions=` / `result_claims=` surfaced — New (opt-in feature)
`fastmcp.Client` now accepts `extensions=` (a sequence of SEP-2133 `ClientExtension` instances) and `result_claims=` (extra `ResultClaim`s keyed by an advertised extension's identifier). Each extension's capability advertisement, result claims, and notification bindings are folded into the underlying `ClientSession` on every transport. User-supplied notification bindings **compose** with FastMCP's internal task-status binding rather than clobbering it: the task binding always leads, and a user extension that binds the same method surfaces a clear duplicate-method error at connect time rather than silently winning. Result claims are wired end-to-end: `call_tool()` / `call_tool_mcp()` pass `allow_claimed=True` and resolve a claimed result through the owning claim's resolver (`ClaimContext`), so a server-emitted claimed shape is finished into an ordinary `CallToolResult` instead of raising `UnexpectedClaimedResult`. Claimed shapes are modern-only, so they are inert on a legacy connection.
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (`_build_extension_kwargs`, `_resolve_claimed_result`, `new()`), `fastmcp_slim/fastmcp/client/mixins/tools.py` (`call_tool_mcp` claim resolution), `fastmcp_slim/fastmcp/client/transports/base.py` (`SessionKwargs.extensions`/`result_claims`), `tests/client/test_client_extensions.py` (fold, composition, live both-bindings-fire, end-to-end claim resolution).
### Protocol helpers delegated to the SDK — Absorbed (internal)
`fastmcp.Client` carried forked copies of three SDK helpers — `_fold_extensions` (with its `_FoldedExtensions` dataclass), `_evicting_message_handler`, and `_synthesize_discover` — written when the SDK had not yet stabilized them. It now imports the SDK's implementations directly. The forks had already drifted: FastMCP's `_fold_extensions` was missing the SEP-2133 `validate_extension_identifier` check, so a non-reverse-DNS extension identifier that the SDK rejects was silently accepted. Adopting the SDK's version closes that gap. No public surface moves; the SDK returns `None` rather than empty collections for the folded claims and bindings, absorbed at the two call sites in `_build_extension_kwargs`.
Full composition — `fastmcp.Client` holding an `mcp.Client` and delegating the connection lifecycle to it — remains blocked upstream. `mcp.Client._build_session` hardcodes `ClientSession(...)` with no override hook, but FastMCP's `TransportOptions.session_class` is load-bearing: `ProxyClient` supplies a `_ForwardingClientSession` that skips output-schema validation so a backend's schema bug surfaces at the end client rather than as a proxy error. Separately, `mcp.Client.__aenter__` raises on reentry, while FastMCP's refcounted reentrant context manager is depended on by proxy session reuse. Both would need an upstream `session_factory=` hook (the same shape as the `notification_bindings=` ask that unblocked extension composition) before the lifecycle itself can be delegated.
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (imports from `mcp.client.client`; no local helper definitions), `fastmcp_slim/fastmcp/client/transports/base.py` (`TransportOptions.session_class`), `fastmcp_slim/fastmcp/server/providers/proxy.py` (`_ForwardingClientSession`, `PROXY_TRANSPORT_OPTIONS`).
### Transports yield 2-tuples — Absorbed
All SDK transports (`streamable_http_client`, `sse_client`, `stdio_client`) now yield a 2-tuple `(read, write)` instead of exposing a third `get_session_id` element. HTTP configuration flows through a caller-supplied `http_client=`. Only the tuple unpack changed on the FastMCP side.
*Verify:* `fastmcp_slim/fastmcp/client/transports/http.py`, `transports/sse.py`, `transports/stdio.py`.
### Float timeouts; `timedelta` still accepted — Absorbed
The SDK session and call timeouts are now plain floats. FastMCP's public `Client(timeout=...)` still accepts a `timedelta`, a plain float, or an int, normalizing through the existing `normalize_timeout_to_seconds` at the `SessionKwargs` chokepoint:
```python
from datetime import timedelta
from fastmcp import Client
client = Client("my_mcp_server.py", timeout=timedelta(seconds=30)) # still works
client = Client("my_mcp_server.py", timeout=30.0) # also works
```
*Verify:* `fastmcp_slim/fastmcp/client/transports/base.py` (`SessionKwargs.read_timeout_seconds: float | None`), `client/client.py`.
### Connection settings passed to `connect_session` — Breaking (custom transports)
`ClientTransport.connect_session` takes a new keyword-only `transport_options: TransportOptions | None`, describing how the connecting client wants its session built: which `ClientSession` class to instantiate, and whether to forward the caller's authorization header upstream. Proxies use it to relay backend results without enforcing their output schema (see [Proxy Servers](https://gofastmcp.com/servers/providers/proxy#tool-results-are-relayed-not-inspected)).
These settings previously lived on the transport instance, so a transport shared between clients leaked one client's configuration into another — including credential forwarding, which `create_proxy(some_client)` would silently enable on the caller's own client. They now travel with the client that wants them, and `forward_incoming_headers` is no longer a settable transport attribute.
A client only passes the argument when it wants non-default settings, so an ordinary `Client` is unaffected and transports that don't accept it keep working. A custom `ClientTransport` used as a *proxy backend* must accept and honor it:
```python
import contextlib
from fastmcp.client.transports.base import ClientTransport, TransportOptions
class MyTransport(ClientTransport):
@contextlib.asynccontextmanager
async def connect_session(self, *, transport_options=None, **session_kwargs):
options = transport_options or TransportOptions()
async with options.session_class(read, write, **session_kwargs) as session:
yield session
```
A transport that wraps others must pass it along; `MCPConfigTransport` forwards it to both its single-server delegate and its composite server.
*Verify:* `fastmcp_slim/fastmcp/client/transports/base.py` (`TransportOptions`), the four built-in transports, `transports/config.py`, and `tests/server/providers/proxy/test_proxy_server.py`.
### `get_session_id` via header sniff — Bridged
The SDK dropped `get_session_id` from the streamable-HTTP transport with no replacement (the SDK source has an author TODO acknowledging it breaks the Transport protocol). FastMCP reconstructs it by registering an httpx2 response event hook on the client it owns, capturing the `mcp-session-id` response header (httpx2 preserves httpx's `event_hooks` API). The removal trigger is the upstream TODO.
*Verify:* `fastmcp_slim/fastmcp/client/transports/http.py` (`_capture_session_id`, `get_session_id`).
### Pagination via `params=` — Absorbed
The SDK's `cursor=` kwarg on `list_*` is gone; pagination now flows through `params=PaginatedRequestParams(cursor=...)`. FastMCP's public `cursor=` on the `list_*_mcp` methods is preserved and translated internally.
*Verify:* `fastmcp_slim/fastmcp/client/mixins/{tools,resources,prompts}.py`.
### OAuth `callback_handler` returns `AuthorizationCodeResult` — Breaking (advanced)
The one OAuth break: a custom `callback_handler` must return an `AuthorizationCodeResult` (fields `code`, `state`, `iss`) instead of the old `tuple[str, str | None]`. Everything else in the OAuth surface — `OAuthClientProvider` kwargs, `TokenStorage`, `async_auth_flow` — is unchanged.
*Verify:* `fastmcp_slim/fastmcp/client/auth/oauth.py`.
### Notification dispatch unwrapped — Absorbed
The client's notification handling was reworked for the v2 message model. Custom server-to-client notifications (like SEP-1686 `notifications/tasks/status`) are no longer tee'd to a user `message_handler` — the SDK routes them only through `NotificationBinding` (see sdk-feedback #8). FastMCP registers a binding so task-status updates reach the Task registry.
*Verify:* `fastmcp_slim/fastmcp/client/messages.py`, `client/tasks.py`.
### `SDKServer` alias — Absorbed (post-review rename)
The in-memory transport resolves the low-level server per server type. The alias for the SDK's own `MCPServer` was renamed from the misleading `FastMCP1Server` / `FastMCP1x` to `SDKServer`, since it names the SDK v2 server, not a FastMCP 1.x object.
*Verify:* commit `5c3b82e4`; `client/client.py`, `client/transports/memory.py`, `server/providers/proxy.py`, `cli/run.py`.
### Proxy request-context stash — Absorbed (post-review fix)
Proxy forwarding handlers stash the request context so a backend that issues a server-initiated request (list_roots/sampling/elicitation) can relay it back to the proxy's own client. This stash was initially applied only on the tool path; commit `1ac166bd` extended it to proxied resources, templates, and prompts.
*Verify:* commit `1ac166bd`, `server/providers/proxy.py`.
### Shared response cache via `KeyValueResponseCacheStore` — New
The SDK's client response cache (SEP-2549) reads and writes through a pluggable `ResponseCacheStore`; the default is a per-client in-memory LRU. FastMCP adds `KeyValueResponseCacheStore`, an adapter over the same `AsyncKeyValue` key-value abstraction the event store and OAuth proxy already use, so a fleet of clients (e.g. proxy replicas) can share one Redis-backed response cache. Pass it via `CacheConfig(store=...)`; a custom store requires an explicit `partition` (SDK) and `target_id` (FastMCP). Results serialize through a type-tagged envelope validated against an allowlist of cacheable result models — an unknown tag is a cache miss, never an import-by-name — and each adapter owns its own collection so `clear()` never touches another tenant.
```python
from fastmcp.client.caching import KeyValueResponseCacheStore
from mcp.client.caching import CacheConfig
from key_value.aio.stores.redis import RedisStore
store = KeyValueResponseCacheStore(storage=RedisStore(url="redis://localhost"))
config = CacheConfig(store=store, partition="tenant-a", target_id="weather-api")
```
*Verify:* `fastmcp_slim/fastmcp/client/caching.py`, `tests/client/client/test_kv_response_cache.py`.
### Machine-to-machine client auth — New (feature)
`fastmcp.client.auth` gains two browser-free auth providers for the OAuth 2.0 `client_credentials` grant, closing the most common client-auth gap (previously only interactive `OAuth` and static `BearerAuth` were available). `ClientCredentialsOAuthProvider(client_id=..., client_secret=...)` authenticates with a client ID and secret; `PrivateKeyJWTOAuthProvider(client_id=..., assertion_provider=...)` uses an RFC 7523 `private_key_jwt` assertion (workload identity federation or a locally signed JWT via the re-exported `SignedJWTParameters` / `static_assertion_provider` helpers). Both are thin wrappers over the SDK's `mcp.client.auth.extensions.client_credentials` providers and implement `httpx2.Auth`, so they slot into the same `Client(auth=...)` path as every other provider. Like interactive `OAuth`, they take the MCP server URL (the token endpoint is discovered from OAuth metadata) and bind to it lazily — omit `mcp_url` and the transport supplies it. In-memory token storage is the default with no warning, since a lost M2M token is re-acquired in one non-interactive request.
```python
from fastmcp import Client
from fastmcp.client.auth import ClientCredentialsOAuthProvider
auth = ClientCredentialsOAuthProvider(client_id="id", client_secret="secret")
async with Client("https://example.com/mcp", auth=auth) as client:
await client.list_tools()
```
*Verify:* `fastmcp_slim/fastmcp/client/auth/client_credentials.py`, `fastmcp_slim/fastmcp/client/transports/{http,sse}.py`, `tests/client/auth/test_client_credentials.py`.
## HTTP
The maintainer asked whether FastMCP can now delete its custom HTTP app and let the SDK's `Server.streamable_http_app()` handle everything. The answer for this PR is **no** — every override earns its keep. Convergence is a v4 project gated on three upstream additions (see [Feature Program](feature-program.md)).
### Kept overrides — Absorbed
Four overrides survive, each for a concrete reason:
1. **Event-store session scoping.** The SDK hands every per-session transport the *same* `event_store` object, one stream-ID keyspace shared across sessions. FastMCP's `FastMCPStreamableHTTPSessionManager` returns a fresh `SessionScopedEventStore(shared, session_id=…)` per session, so resumability events don't leak across sessions.
2. **Lifespan reconciliation.** The SDK builder enters the bare lowlevel `Server.lifespan` (which yields `{}`). FastMCP drives its own `_lifespan_manager` — ref-counted for mounts, Ctrl-C-shielded, docket-aware. The SDK path silently skips all of it, so FastMCP sets the server lifespan to delegate to `_lifespan_manager` and lets the manager enter it once.
3. **Graceful transport termination.** FastMCP's lifespan `finally` drains the manager's server instances via `transport.terminate()` before task-group cancel, fixing the Uvicorn "returned without completing response" edge (#3025). The SDK just cancels.
4. **User ASGI middleware hook.** The SDK builder hardcodes an empty middleware list and only appends auth. FastMCP's `http_app(middleware=...)` and `RequestContextMiddleware` have nowhere to go in the SDK path.
*Verify:* `fastmcp_slim/fastmcp/server/http.py`, `server/event_store.py`, `server/mixins/lifespan.py`.
### DNS-rebinding ownership — Absorbed (security)
FastMCP owns DNS-rebinding protection through its `HostOriginGuardMiddleware`, which is more expressive than the SDK's and is the documented surface. To avoid two allowlists double-blocking with confusing errors from two layers, FastMCP **always** disables the SDK's layer by passing `TransportSecuritySettings(enable_dns_rebinding_protection=False)` to the manager — both when FastMCP's protection is on (so they don't double-block) and when it's off (so the SDK's default-on flip can't silently re-enable it).
*Verify:* `fastmcp_slim/fastmcp/server/http.py` (`enable_dns_rebinding_protection=False`, `HostOriginGuardMiddleware`).
### httpx2 replaces httpx — Breaking (custom client/factory, typing) / Absorbed (everything else)
SDK v2.0.0b2 replaces `httpx` + `httpx-sse` with [httpx2](https://pypi.org/project/httpx2/) (`>=2.5.0`), a next-generation httpx fork with built-in SSE. httpx2 is a near drop-in fork: the public API (`AsyncClient`, `Auth`, `Request`, `Response`, `Timeout`, `MockTransport`, exception hierarchy, `event_hooks`) matches httpx name-for-name. The SDK duck-types the client you hand it — `streamable_http_client(http_client=...)` and `sse_client(httpx_client_factory=...)` are type-hinted `httpx2.AsyncClient` with no `isinstance` gate — but the objects that cross into the SDK must be httpx2.
FastMCP now uses **httpx2 exclusively** and no longer depends on `httpx`. Every FastMCP-owned HTTP path moves to httpx2: the client transports (`client/transports/{base,http,sse}.py`), client auth (`client/auth/{oauth,bearer}.py``BearerAuth`/`OAuth` subclass `httpx2.Auth`), the client-side exception-group handler (`utilities/exceptions.py`), the proxy's upstream client (`server/providers/proxy.py`), the `MCPConfig` client-auth field (`mcp_config.py`), **and** all the server-side code that the earlier migration pass had left on httpx — the ~15 server auth providers' upstream IdP calls, the OpenAPI provider, `from_openapi`/`from_fastapi`, `version_check`, `resources/types.py`, the SSRF download guard, and the `apps_dev` CLI. `httpx` is dropped from the `mcp` extra entirely (it may still arrive transitively via other libraries, but FastMCP never imports it). The ~170 `httpx_mock` calls across the security-critical server-auth test files are ported to a local httpx2-backed `httpx_mock` fixture (`tests/utilities/httpx2_mock.py`) that preserves the `add_response`/`add_exception`/`get_request(s)` API verbatim, so `pytest-httpx` is dropped too.
User-visible deltas:
- **Custom client factory / client.** `StreamableHttpTransport(httpx_client_factory=...)`, `SSETransport(httpx_client_factory=...)`, and `OAuth(httpx_client_factory=...)` factories must now return `httpx2.AsyncClient`; a custom `httpx.Auth` passed as `Client(auth=...)` should become `httpx2.Auth`. httpx2 is a drop-in fork, so the change is an import swap (`import httpx``import httpx2`). This is a typing break; at runtime a duck-compatible httpx client still satisfies the SDK, but mixing `httpx.Timeout`/`httpx.Auth` with an httpx2 client is unsupported.
- **OpenAPI client.** `FastMCP.from_openapi(client=...)` and `OpenAPIProvider(client=...)` are now type-hinted `httpx2.AsyncClient`. There is no `isinstance` gate, so an existing `httpx.AsyncClient` still works at runtime via duck-typing this release; the typing nudges you to httpx2.
- **TLS trust store.** httpx2 verifies TLS against the OS trust store via `truststore` (honoring `SSL_CERT_FILE`/`SSL_CERT_DIR` first) instead of the bundled certifi CA set. This now applies to **all** FastMCP HTTP, including server-auth upstream IdP calls — not just the client path. Corporate-CA and certifi-pinned setups may see different trust behavior.
- **Logger renames.** FastMCP HTTP now logs under `httpx2` and `httpcore2.*` (was `httpx`/`httpcore.*`). Anyone filtering FastMCP HTTP logs by logger name must update the names.
The session-id header hook (below) works unchanged: httpx2 keeps httpx's `event_hooks` API. FastMCP's tool/resource/prompt handlers still map upstream 429/timeout errors to actionable `ToolError`/`ResourceError`; because a user's own tool may raise from either library, `server/server.py` catches both `httpx2` and (if installed) legacy `httpx` `HTTPStatusError`/`TimeoutException` via a defensive `try: import httpx` shim.
*Verify:* `fastmcp_slim/pyproject.toml` (`mcp` extra lists only `httpx2`); no FastMCP source imports `httpx` except the documented defensive shim in `server/server.py`.
## Protocol eras
The SDK v2 serves multiple protocol eras from one server, and FastMCP formally embraces this.
### Dual-era serving — Absorbed (supersedes "latest only")
A single FastMCP server now handles clients across the protocol transition: the session-based handshake eras (through 2025-11-25) and the sessionless `2026-07-28` era (capability discovery via `server/discover`) simultaneously. This supersedes FastMCP's earlier "latest protocol only" stance.
### Per-feature era matrix — Breaking (feature availability by era)
The push-style Context features that require the server to call back into the client are unavailable on the sessionless `2026-07-28` era, because that era removes server-initiated requests (SEP-2577). The request/response features flow on every era.
| Context feature | Session-based eras | `2026-07-28` (sessionless) |
| --- | --- | --- |
| `ctx.info` / logging notifications | Supported | Supported |
| Tools, resources, prompts, completions | Supported | Supported |
| `ctx.elicit` (imperative) | Supported | Not on the back-channel — use [elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol) |
| `ctx.sample` / `ctx.sample_step` | Not in the API | Not in the API — call an LLM server-side |
| `ctx.list_roots` | Not in the API | Not in the API — take paths as arguments, or use the [guard pattern](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol) |
| `client.set_logging_level()` | Supported | Raises — `logging/setLevel` is absent from the era's registry |
| Background tasks (`task=True`) | Runs synchronously — never tasked | Supported via the tasks extension |
Tools that rely on `ctx.elicit` continue to work against clients on the session-based eras; on the modern era, elicitation is reachable through the multi-round "guard" pattern instead (a tool returns an `InputRequiredResult`; see the New entry below). Sampling and roots have no era row to speak of — they left the server API entirely (see the Removed entry below).
Ordinary `ctx.info` usage emits an SDK-level `MCPDeprecationWarning` ("The logging capability is deprecated as of 2026-07-28 (SEP-2577)"). That warning comes from the SDK, not FastMCP, and is benign — logging *notifications* ride the request's own stream and work on every era, including the modern one. The upgrade guide calls it out explicitly.
Wire interop across the transition is verified: a 3.4.3 client against a v4 server and a v4 client against a 3.4.3 server are bidirectionally clean across 9 operations over HTTP (WS2).
*Verify:* `docs/getting-started/upgrading/from-fastmcp-3.mdx` (the published matrix and SDK-warning note), `tests/server/test_protocol_eras.py`.
### Server-initiated sampling and roots removed from the server API — Breaking
FastMCP 4 is a modern MCP toolkit, so the capabilities the modern protocol removed are not in its server-authoring API. `Context.sample()`, `Context.sample_step()`, and `Context.list_roots()` are gone, along with the whole `fastmcp/server/sampling/` package (`SamplingTool`, `SampleStep`, `SamplingResult`, the tool loop, structured-result sampling) and the server-side handler arguments `FastMCP(sampling_handler=..., sampling_handler_behavior=...)`. These were previously deprecated-and-era-gated; they are now absent. Calling them raises `AttributeError`; the constructor kwargs raise a `TypeError` naming SEP-2577 and the migration.
The motivating failure is that the gate had become the default experience. `Client` now defaults to `mode="auto"`, which negotiates `2026-07-28` against a FastMCP server, so an unmodified `ctx.sample()` server failed on an ordinary client connection. Four shipped examples (`examples/sampling/`) were broken by that flip; they are deleted rather than ported, and remain available on `release/3.x`.
Server-initiated sampling and roots are *requests* — the server sends one and blocks for the answer — which needs a back-channel the sessionless protocol does not have. What the protocol removed is the *pushing*, not the asking: both capabilities remain reachable through the guard pattern, where a tool returns an `InputRequiredResult` whose `input_requests` map carries a `CreateMessageRequest` or a `ListRootsRequest`, the client answers it, and the tool re-runs and reads `ctx.input_responses`. `Client._drive_input_required()` dispatches those to the same `sampling_handler` / `roots` handler a handshake-era server would have pushed to, and `tests/conformance/server.py` exercises both routes. For roots that guard round is the recommended modern path. For generation it is available but usually the wrong tool — each round is a full request-response cycle, so an agentic loop exhausts the round-trip budget — and the recommended migration stays a direct LLM call from the server.
**What is deliberately kept.** Client-side `Client(sampling_handler=..., roots=...)` and the provider handlers (anthropic/openai/google_genai) stay: a FastMCP client must still answer a legacy server's requests, and removing them would break interop with older servers. `docs/clients/sampling.mdx` and `docs/clients/roots.mdx` stay as real documentation. Logging is untouched — `ctx.log`/`info`/`debug`/`warning`/`error` are notifications that ride the request's own stream and work on every era.
**Proxy relay.** `ProxyClient`'s default `roots` and `sampling_handler` are client-side handlers that relay a handshake-era backend's requests to the proxy's own front client. They are kept, because a proxy is a client to its backend and falls squarely under the interop guarantee above. They no longer route through the removed `Context` methods: both now call the SDK session directly (`ctx.session.list_roots()` / `ctx.session.create_message()`), an internal path with no public authoring surface. The relay is reachable only when both legs speak the handshake era.
*Verify:* `fastmcp_slim/fastmcp/server/context.py` (no `sample`/`sample_step`/`list_roots`), `fastmcp_slim/fastmcp/server/server.py` (`_REMOVED_KWARGS`), `fastmcp_slim/fastmcp/server/providers/proxy.py` (`default_proxy_roots_handler`, `default_proxy_sampling_handler`), `docs/servers/sampling.mdx` (rewritten in place as the explainer), `tests/server/test_protocol_eras.py` (`test_removed_server_initiated_methods_are_absent`), `tests/server/providers/proxy/test_proxy_client.py` (relay still green).
### `client.set_logging_level()` era-gated — Breaking (modern era)
`logging/setLevel` asks a server to remember a level for the rest of the session, and it is absent from the `2026-07-28` method registry because that era has no session to remember it in. It previously surfaced the SDK's opaque "Method not found". `Client.set_logging_level()` now raises a `RuntimeError` naming the era and pointing at level-filtering in the client's `log_handler`; it is unchanged on handshake-era connections. It is never a silent no-op.
*Verify:* `fastmcp_slim/fastmcp/client/client.py` (`set_logging_level`), `tests/server/test_protocol_eras.py` (`test_set_logging_level_is_era_gated_on_modern`).
### Push-feature degradation quality — Resolved (was sdk-feedback #10)
On a `2026-07-28` connection `ctx.elicit` used to surface a bare "Method not found", because it attaches a `related_request_id` and reaches client dispatch before failing. FastMCP now era-gates `ctx.elicit` to raise a clear, era-aware `ToolError` before the wire ("elicitation via server-initiated requests is unavailable on 2026-07-28 connections."). The strict xfail that captured #10 is flipped to a passing test. The sampling half of #10 is moot: `ctx.sample` no longer exists.
*Verify:* `tests/server/test_protocol_eras.py` (`test_elicit_degradation_message_is_clear_on_modern`, now a real test), `server/context.py` (era gate).
### Server-level cache hints (SEP-2549) — New (opt-in feature)
A FastMCP server can emit SEP-2549 freshness hints so a caching client (`fastmcp.Client(cache=...)`) may reuse a response without a wire round-trip. Two constructor params carry it: `FastMCP(cache_ttl=300, cache_scope="public")`, where `cache_ttl` is in seconds and `cache_scope` is `"public"` or `"private"` (default `"private"` when a TTL is set). The hint is uniform by construction — one server-level value applies to every SDK-cacheable method (`tools/list`, `prompts/list`, `resources/list`, `resources/templates/list`, `resources/read`, and `server/discover`) with 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. `cache_ttl` must be positive, and a `cache_scope` without a `cache_ttl` is rejected at construction (a scope alone does not enable caching, since the client gates on the TTL's presence). Absent both params, no hint is emitted. Honoring is modern-only (the SDK client reads hints only at `2026-07-28`) and opt-in on the client, so a hinted server is inert unless the client passes `cache=`.
*Verify:* `fastmcp_slim/fastmcp/server/caching.py` (`build_cache_hints`), `fastmcp_slim/fastmcp/server/server.py` (constructor params passed to `LowLevelServer(cache_hints=...)`), `tests/server/test_cache_hints.py` (unit validation + end-to-end interop with `fastmcp.Client(cache=True)`).
### Elicitation on the modern protocol (SEP-2322), guard form — New (opt-in feature)
A tool can gather client input across rounds on a `2026-07-28` call by returning an `InputRequiredResult` (see [Elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)). Each round is a complete request→response cycle: the tool re-runs per round and reads the client's answers off two new `Context` properties, `ctx.input_responses` (`None` on the first round) and `ctx.request_state` (the echoed opaque state) — thin passthroughs matching the SDK's mcpserver semantics. This is the modern-era elicitation path the earlier per-feature matrix flagged as "MRTR rewrite pending"; it mirrors the SDK's base guard model exactly (tool re-runs, checks whether answers are present, returns to ask for more), with no FastMCP-invented resolver or annotation layer. For authoring these requests, `InputRequiredResult`, `ElicitRequest`, and `ElicitRequestFormParams` import from `mcp_types`. The `request_state` channel is sealed by the framework, not the author: FastMCP installs the SDK's `RequestStateBoundary` middleware on its low-level server, which seals every outgoing `request_state` and unseals and verifies every inbound echo before a tool runs — so a tool only ever sees plaintext and a tampered, expired, or foreign token is rejected with a frozen wire error. `FastMCP(request_state_security=RequestStateSecurity(keys=[...]))` supplies shared keys for multi-replica deployments; omitted, each process seals under an ephemeral key (correct single-process). Returning this result on a handshake-era (≤ 2025-11-25) connection raises a clear era error naming the mismatch rather than failing as a generic invalid result. The client half (`fastmcp.Client` at `mode="auto"`) drives the loop through its existing elicitation/sampling/roots handlers, capped by `input_required_max_rounds`.
*Verify:* `fastmcp_slim/fastmcp/server/context.py` (`input_responses`/`request_state` properties), `fastmcp_slim/fastmcp/server/low_level.py` (`RequestStateBoundary` install), `fastmcp_slim/fastmcp/server/server.py` (`request_state_security` param), `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_call_tool` input-required passthrough + era gate), `fastmcp_slim/fastmcp/tools/base.py` (`InputRequiredToolResult`), `tests/server/test_mrtr_guards.py`.
### Proxy era mirroring — New (behavior)
A proxy is a server on its front and a client on its back, and the two eras have mutually exclusive interaction models on a single session: the handshake era pushes server-initiated requests (sampling/elicitation/roots) that the proxy forwards to its client, while the modern era forbids those and round-trips a guard tool's `InputRequiredResult` as a result instead. A proxy created from a non-Client target with no explicit `mode` now MIRRORS the front connection's negotiated era onto its backend session per request, so the whole chain speaks one era end-to-end — a modern client reaches a modern backend (guard round-trips work), a handshake client reaches a handshake backend (push-forwarding works), and the same proxy serves both without a backend session ever crossing eras. Because the default factory builds a fresh backend client per request and derives its `mode` from the front era at call time, only the metadata-only component caches are shared across eras. An explicit `create_proxy(target, mode=...)` still pins the backend era regardless of the front, overriding mirroring for a backend that only speaks one era; the resulting cross-era feature mismatches surface through the existing era gates. `ProxyInitializeMiddleware` no longer force-calls the handshake-only `client.initialize()` when the backend negotiated the modern era, so an explicit modern pin behind a handshake front no longer crashes on connect. The mirrored era carries through a multi-server `MCPConfig` target as well: that form mounts one proxy per configured server onto a composite router, and `TransportOptions.backend_mode` hands the era down to those mounted legs so every real backend negotiates it, not just the router in front of them. That router is also now 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.
*Verify:* `fastmcp_slim/fastmcp/server/providers/proxy.py` (`_mirror_front_era_mode`, the `_create_client_factory` non-Client branch, the era guard in `ProxyInitializeMiddleware.on_initialize`), `fastmcp_slim/fastmcp/client/transports/base.py` (`TransportOptions.backend_mode`), `fastmcp_slim/fastmcp/client/transports/config.py` (`MCPConfigTransport.connect_session` / `_create_proxy`), `fastmcp_slim/fastmcp/server/server.py` (`create_proxy` docstring), `tests/server/test_mrtr_guards.py` (`TestProxyEraMirroring`, `TestMultiServerConfigEraMirroring`).
### Resource and prompt errors survive the modern era — Absorbed (defect fix)
`_on_call_tool` returns a `ResourceError`-equivalent as an error result, but `_on_read_resource` and `_on_get_prompt` caught only `DisabledError`/`NotFoundError`, so a `ResourceError`, `PromptError`, or an argument-conversion failure on a resource template escaped as a raw handler exception. On the handshake eras that reached the wire as `str(exc)`, which is survivable; on `2026-07-28` the runner masks anything that is not an `MCPError` or `ValidationError` as a generic `"Internal server error"`, so a legitimate client-input error became indistinguishable from a server bug. Both handlers now translate a `FastMCPError` through `to_mcp_error` the way tools already do. Masking is unchanged — `mask_error_details` is still applied inside `read_resource`/`render_prompt`, so these paths leak no more than tools do.
*Verify:* `fastmcp_slim/fastmcp/server/mixins/mcp_operations.py` (`_on_read_resource`, `_on_get_prompt`), `tests/server/test_protocol_eras.py`.
### Proxies forward upstream instructions on the modern era — Absorbed (defect fix)
`ProxyInitializeMiddleware` forwards an upstream server's `instructions` by patching the `InitializeResult`, but `on_initialize` only fires for the handshake era. A modern client negotiates via `server/discover`, which the SDK builds from the low-level server's own `instructions`, so a proxy silently dropped its upstream's instructions for every modern client. `FastMCPProxy` now registers a `server/discover` handler (the same `add_request_handler` hook it already uses for `ping`, and a replacement the SDK explicitly sanctions) that delegates to the SDK's own implementation and fills in only the instructions that would otherwise be lost. The proxy's lazy-connect contract is unchanged: the backend is contacted when a client asks, never at construction. Because era mirroring pins a modern backend to an exact version — and a pinned version adopts a synthesized `DiscoverResult` rather than probing the wire — this read negotiates with `mode="auto"`; instructions are metadata with no back-channel, so they do not need the era consistency mirroring exists to protect.
*Verify:* `fastmcp_slim/fastmcp/server/providers/proxy.py` (`FastMCPProxy._setup_proxy_discover_handler`), `tests/server/providers/proxy/test_proxy_server.py` (`TestProxyModernEraInstructions`).
### Proxy list methods raise `MCPError` on backend failure — Breaking (in-process error type)
`ProxyProvider`'s four `_list_*` methods caught only `MCPError`, so a failed backend connection escaped as the `RuntimeError` the client wraps it in (or a raw `httpx2.ConnectError`). On the handshake eras that reached the wire as `str(exc)` and named the real failure; on `2026-07-28` it was masked as `"Internal server error"`, leaving a modern client unable to tell a dead backend from a server bug. The list methods now normalize transport failures through `_proxy_upstream_error`, matching `ProxyInitializeMiddleware.on_initialize`. Code calling a proxy's `list_tools()` (and friends) in-process must now catch `MCPError` rather than `RuntimeError`; the over-the-wire error type is unchanged.
*Verify:* `fastmcp_slim/fastmcp/server/providers/proxy.py` (`_PROXY_TRANSPORT_ERRORS` and the four `_list_*` methods), `tests/server/providers/proxy/test_proxy_server.py` (`TestProxyProviderTransportErrors`).
### The xfail register — Known gap
Roughly forty `xfail` markers across the test tree (concentrated in `tests/server/tasks/`, `tests/client/tasks/`, and `test_protocol_eras.py`) are the built-in beta tracker: each names the SDK gap it waits on. They are enumerated and mapped to sdk-feedback findings on the [Known Gaps](known-gaps.md) page.
## Security
FastMCP retains hardening that is not yet upstream and does not remove it during the migration.
### Retained OAuth / DCR hardening — Absorbed
FastMCP keeps its own DCR redirect-URI hardening (PRs #4419, #4408) regardless of the SDK's validation, which still accepts unsafe `javascript:`/`data:` redirect schemes at the model level (sdk-feedback #4). The streamable-HTTP DNS-rebinding protection above is a second retained security surface.
*Verify:* recent commits `67527c1f` (block unsafe OAuth redirect schemes), `57a27992` (DNS rebinding), `cccb529f` (DCR redirect URI validation) on `main`.
### Identity assertion (SEP-990 ID-JAG) — Added (beta)
`OAuthProxy` (and `OIDCProxy`, which inherits it) accepts an optional `identity_assertion=IdentityAssertion(trusted_issuers=[...])`. When configured, the token endpoint accepts the RFC 7523 `urn:ietf:params:oauth:grant-type:jwt-bearer` grant carrying an enterprise IdP-issued ID-JAG, validates it (signature against the trusted issuer's JWKS, `iss`/`aud`/`exp`, `typ` of `oauth-id-jag+jwt`, mandatory `sub`, signed `client_id`/`resource` binding, and `jti` replay rejection), and mints a short-lived FastMCP access token carrying the asserted subject with no refresh token. Authorization server metadata advertises the `jwt-bearer` grant type and the `urn:ietf:params:oauth:grant-profile:id-jag` profile when enabled. This is server-side only; the client-side wrapper ships separately. See [Identity Assertion](https://gofastmcp.com/servers/auth/oauth-proxy#identity-assertion-sep-990).
*Verify:* `fastmcp_slim/fastmcp/server/auth/identity_assertion.py`, the `exchange_identity_assertion` and `get_routes` changes in `fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py`, and the jwt-bearer dispatch in `fastmcp_slim/fastmcp/server/auth/auth.py` (`TokenHandler._maybe_handle_id_jag`).
### Templated resource parameters are path-screened by default — Breaking (behavior)
Every templated resource now has its extracted parameter values screened for path-traversal (`..` segments), absolute paths, and null bytes **before the handler runs** — on by default, at the server's read chokepoint, covering local and provider-sourced (mounted/proxied) templates alike. Previously these payloads reached handlers raw; a template whose parameter flowed into a filesystem path or upstream URL was exposed unless the author added their own check. A rejected read now surfaces a non-leaky "resource not found" error (`-32602`) and a debug log.
The check is component-based, matching the SDK's `contains_path_traversal`: only a standalone `..` segment is traversal, so values that merely contain dots (`HEAD~3..HEAD`, `file.tar.gz`) and dotfiles (`.env`) still pass. This can break a template that legitimately accepts `..`-bearing or absolute values — exempt the parameter with `ResourceSecurity(exempt_params={...})`, disable per-component with `security=None`, or set a server-wide default with `FastMCP(resource_security=...)`. See [Resources → Path Security](https://gofastmcp.com/servers/resources#path-security).
*Verify:* `fastmcp_slim/fastmcp/resources/security.py` (`ResourceSecurity`), the screening block in `FastMCP.read_resource` (`fastmcp_slim/fastmcp/server/server.py`), and `tests/resources/test_resource_security.py`.
## Removed in 4.0
Deprecations that warned in 3.x are removed in 4.0. Each entry below is a hard removal — the old surface raises `TypeError` / `AttributeError` rather than warning, unless noted otherwise.
### Module and class shims
- **`fastmcp.server.proxy`** (deprecated 3.0) — Breaking. Import proxy classes (`FastMCPProxy`, `ProxyClient`, etc.) from `fastmcp.server.providers.proxy` instead.
- **`fastmcp.server.openapi`** and its submodules (`server`, `components`, `routing`), including the **`FastMCPOpenAPI`** class (deprecated 3.0) — Breaking. Use `FastMCP` with an `OpenAPIProvider` from `fastmcp.server.providers.openapi` instead.
- **`fastmcp.experimental.server.openapi`** and **`fastmcp.experimental.utilities.openapi`** shims (deprecated 2.14) — Breaking. Import from `fastmcp.server.providers.openapi` and `fastmcp.utilities.openapi` respectively.
- **`fastmcp.server.apps`** and **`fastmcp.server.app`** shims (deprecated 3.2) — Breaking. Import from `fastmcp.apps` (e.g. `AppConfig`) or `fastmcp` (`FastMCPApp`) instead.
- **`PromptToolMiddleware`** and **`ResourceToolMiddleware`** (deprecated 3.1) — Breaking. Use the `PromptsAsTools` / `ResourcesAsTools` transforms from `fastmcp.server.transforms` instead. The non-deprecated `ToolInjectionMiddleware` base class is retained.
- **`StreamableHttpTransport(sse_read_timeout=...)`** (deprecated no-op) — Breaking. The parameter had no effect under the SDK v2 client; configure timeouts via `read_timeout_seconds` in `session_kwargs` or on the httpx2 client via `httpx_client_factory`. `SSETransport` still accepts `sse_read_timeout`.
### `FastMCP` server methods and `mount()` kwargs
The following `FastMCP` methods and parameters, deprecated since 3.0, are removed:
- `FastMCP.as_proxy(...)``create_proxy(...)` (`from fastmcp.server import create_proxy`)
- `FastMCP.import_server(sub)``mount(sub)`
- `mount(prefix=...)``mount(namespace=...)`
- `mount(as_proxy=...)` — removed; mounts always invoke the child's lifespan and middleware, so the flag was already meaningless. To proxy a server, wrap it with `create_proxy()` before mounting.
- `FastMCP.add_tool_transformation(name, config)``add_transform(ToolTransform({name: config}))`
- `FastMCP.remove_tool_transformation(name)` — removed; it was a no-op that only warned (transforms are immutable once added). Use `server.disable(keys=[...])` to hide tools.
- `FastMCP.remove_tool(name)``mcp.local_provider.remove_tool(name)`
The `_REMOVED_KWARGS` constructor shim (which raises helpful `TypeError`s for kwargs removed in 3.0) is retained through 4.0.
### Tool and component parameters
- **Tool-level `serializer` parameter** — removed from `@tool` / `mcp.tool()`, `Tool.from_function`, `Tool.from_tool`, `TransformedTool.from_tool`, the OpenAPI `OpenAPITool`, and the `mcp_mixin` tool decorator. Return a `ToolResult` from your tool for full control over serialization instead (see [Custom Serialization](https://gofastmcp.com/servers/tools#custom-serialization)). The server-level `tool_serializer` constructor kwarg was already removed in 3.0.
- **Tool `exclude_args` parameter** — removed from the tool decorator and its plumbing (`ParsedFunction.from_function`, `Tool.from_function`, `mcp.tool()`). Use dependency injection with `Depends()` to hide parameters from the tool schema instead.
- **`decorator_mode` setting** (`FASTMCP_DECORATOR_MODE`) and its `"object"` mode — removed. Decorators always return the original function with metadata attached; the object-returning machinery is gone. Access component objects through the server (e.g. `await mcp.get_tool("name")`) rather than the decorated function.
- **Component-import compatibility shims** — Breaking. `fastmcp.tools.tool`, `fastmcp.resources.resource`, and `fastmcp.prompts.prompt` no longer exist as modules. Two separate mechanisms kept them alive and both are now gone: the `__getattr__` shims that re-exported `FunctionTool` / `ParsedFunction` / `tool`, `FunctionResource` / `resource`, and `FunctionPrompt` / `prompt`; and the `sys.modules` aliases that pointed each old module name at its renamed `base.py`. Import the component types from the package itself — `from fastmcp.tools import Tool, ToolResult` — and the function-backed classes from their canonical modules (`fastmcp.tools.function_tool`, `fastmcp.resources.function_resource`, `fastmcp.prompts.function_prompt`).
- **`fastmcp.experimental.sampling`** and **`fastmcp.experimental.sampling.handlers`** (2.x-era re-export shims) — Breaking. These aliased the client-side sampling handlers without warning. Import from `fastmcp.client.sampling.handlers.openai` instead. Note this is unrelated to the SEP-2577 removal of *server-initiated* sampling: a FastMCP client still answers a legacy-era server's sampling requests, so `Client(sampling_handler=...)` and the Anthropic / OpenAI / Google GenAI handlers under `fastmcp.client.sampling.handlers` remain fully supported.
- **`fastmcp.server.auth.authorization`** (3.0-era re-export shim) — Breaking. The module was a pass-through sitting between the `fastmcp.server.auth` package and the real implementation in `fastmcp.utilities.authorization`, and FastMCP's own middleware and local-provider decorators imported through it. Everything internal now imports from `fastmcp.utilities.authorization` directly. The documented public path is unchanged: `from fastmcp.server.auth import require_scopes, require_roles, restrict_tag, run_auth_checks, AuthCheck, AuthContext`. Two names the old module also exported — `run_auth_checks_with_shortfall` and `scope_requirements` — are *not* re-exported from `fastmcp.server.auth` and must be imported from `fastmcp.utilities.authorization`. They are middleware plumbing with no documented user-facing use, so they were deliberately not widened onto the auth package's surface; the upgrade guide names the utilities path for them explicitly.
- **`SkillsProvider`** (3.0-era rename alias) — Breaking. Use `SkillsDirectoryProvider` from `fastmcp.server.providers.skills`. The alias was also re-exported from `fastmcp.server.providers`; both are gone.
- **`ctx.elicit()` without `response_type`** (deprecated 3.2, warned through 3.4.4) — Breaking. The parameter is now required, and passing `None` explicitly raises `TypeError`. The empty-object schema it produced was ambiguous under the MCP spec and left some clients (e.g. VS Code) rendering an empty, non-functional form. Pass a type describing the data you expect back; `bool` covers confirmations. This is the server-authoring API only — the *client* elicitation handler still receives `response_type=None` for URL requests and for empty schemas sent by other servers, which is unchanged.
*Verify:* deletions of `fastmcp_slim/fastmcp/server/proxy.py`, `fastmcp_slim/fastmcp/server/openapi/`, `fastmcp_slim/fastmcp/experimental/server/openapi/`, `fastmcp_slim/fastmcp/experimental/utilities/openapi/`, `fastmcp_slim/fastmcp/server/apps.py`, `fastmcp_slim/fastmcp/server/app.py`; the removed classes in `fastmcp_slim/fastmcp/server/middleware/tool_injection.py`; the removed parameter in `fastmcp_slim/fastmcp/client/transports/http.py`; `fastmcp_slim/fastmcp/server/server.py`; `fastmcp_slim/fastmcp/tools/base.py`, `tools/function_tool.py`, `tools/tool_transform.py`, `tools/function_parsing.py`; `fastmcp_slim/fastmcp/settings.py`, `resources/function_resource.py`, `prompts/function_prompt.py`, and the local-provider decorators; `resources/base.py`, `prompts/base.py`.

View file

@ -0,0 +1,140 @@
---
title: Feature Program
---
The migration is the foundation. The forward v4 program is a sequence of post-merge PRs that build on it. Several have now merged. Each feature below carries an explicit status:
- **Shipped** — merged to `main`, with the PR cited.
- **Designed** — the approach is settled and an API sketch exists; implementation has not started.
- **Planned** — the shape is agreed but design details remain open.
- **Not started** — identified as v4 scope, not yet designed.
Code blocks marked as sketches show the *intended* API and do not resolve against the current tree.
## Sampling removal
**Status: Shipped in 4.0.**
Sampling was the push-shaped API where a server borrows the client's model mid-call (`ctx.sample`, `ctx.sample_step`). The `2026-07-28` era removes server-initiated requests, so it cannot work on modern connections, and `Client`'s flip to `mode="auto"` made a modern connection the default — the era gate had become the default experience rather than an edge case. Background-task sampling was dead under v2 in any event: a worker's back-channel is gone once the submitting request returns, and no relay was ever built (sdk-feedback #9).
Deprecation and era-gating shipped in #4448. The removal completes the plan: `ctx.sample`, `ctx.sample_step`, `ctx.list_roots`, `server/sampling/` (including `SamplingTool` and structured-result sampling), `FastMCP(sampling_handler=..., sampling_handler_behavior=...)`, and `examples/sampling/` are all gone. The server-authoring API is now the modern protocol's API, with nothing in it that only works against old clients.
The migration story is honest: there is **no drop-in**. The guidance is architectural — call an LLM from your server directly, with your own API key, rather than borrowing the client's model. For roots, take paths as tool arguments or ask through the guard pattern, whose `input_requests` map still carries a `ListRootsRequest`.
The client-side provider handlers (Anthropic, OpenAI, Google GenAI) and `Client(sampling_handler=..., roots=...)` are **retained**: a FastMCP client still has to answer a legacy server's requests, and MRTR needs them from the client side. What is removed is the server-side push emitter. `ProxyClient`'s default relay handlers are retained for the same interop reason and now call the SDK session directly.
## MRTR elicitation
**Status: Guard form shipped (4.0). Declarative `Resolve` layer designed.**
Elicitation survives the modern era through multi-round-trip (MRTR). The 2026 wire envelope carries elicitation as a multi-round input-request: a tool returns an `InputRequiredResult` and re-runs per round, each round a complete request→response cycle. Imperative `ctx.elicit` relies on the session back-channel, which is gone on `2026-07-28` foreground calls; on the modern era, elicitation is reachable through MRTR instead.
The **guard form** of this is shipped in 4.0 (see [Elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)): a tool returns an `InputRequiredResult` and reads the client's answers off `ctx.input_responses` / `ctx.request_state`, re-running each round. It mirrors the SDK's base guard model exactly — no FastMCP-invented DX, the framework owns `request_state` sealing, and returning this result on a handshake-era connection produces a clear era error.
What remains is the declarative `Resolve(...)` layer that sits *on top of* that shipped primitive. It is designed, not built: a new `fastmcp.elicitation` module — `Resolve`, `Elicit`, and `ElicitationResult` — thin wrappers over the SDK's resolver, wired into FastMCP's own tool layer (FastMCP tools do not inherit the SDK's auto-resolver wiring). It would detect `Annotated[_, Resolve(...)]` parameters, build resolver plans, and return the SDK's `InputRequiredResult` instead of the tool body on the first round.
Imperative `ctx.elicit` is **not** re-plumbed to survive the modern era. It works on the legacy eras through the session back-channel, and on `2026-07-28` foreground calls it is era-gated to raise a clear error (shipped in #4448) pointing at the guard form. The earlier plan to keep imperative `ctx.elicit` alive on modern connections through a background-task relay is dead twice over: the guard model shipped in its place, and the 2025 task machinery the relay depended on is slated for removal (see [Known Gaps](known-gaps.md#the-xfail-register)).
The intended declarative DX (sketch — the module does not exist yet):
```python test="skip"
from typing import Annotated
from pydantic import BaseModel
from fastmcp import FastMCP, Context
from fastmcp.elicitation import Resolve, Elicit, ElicitationResult
mcp = FastMCP("shipping")
class Address(BaseModel):
street: str
city: str
zip: str
async def ask_address(ctx: Context) -> Elicit[Address]:
return Elicit("Where should we ship this order?", Address)
@mcp.tool
async def create_shipment(
order_id: str,
address: Annotated[Address, Resolve(ask_address)], # unwrapped; decline -> ToolError
) -> str:
return f"Shipping {order_id} to {address.city}"
@mcp.tool
async def maybe_ship(
order_id: str,
address: Annotated[ElicitationResult[Address], Resolve(ask_address)], # full outcome
) -> str:
if address.action != "accept":
return "cancelled"
return f"Shipping {order_id} to {address.data.city}"
```
The FastMCP client already dispatches input-requests through its elicitation callback; the remaining declarative work confirms the FastMCP client drives the input-required driver the way the SDK's own client does.
The divergence between elicitation and sampling on 2026 comes down to one fact: the SDK built the server-side emitter for elicitation (`Elicit`/`Resolve`) and not for sampling. The wire carries all three input-request types and the client dispatches all three; only elicitation can produce one server-side. That is why elicitation survives 4.0 via MRTR and push-sampling does not.
## Middleware root dispatch
**Status: Shipped (#4553).**
The migration already routed `initialize` interception through the SDK's `ServerMiddleware` list via `FastMCPServerMiddleware`. #4553 made that entry the root of middleware dispatch: FastMCP's method-agnostic hooks (`on_message`, `on_request`, `on_notification`) now fire for every inbound message — client cancellations, progress notifications, and requests that fail routing or validation — not only the ones that reach a component handler. The component methods keep running their own chain interior, and a method set plus a dispatch flag keep the two passes disjoint so each hook fires exactly once per message.
## First-class 2026 client
**Status: Partly shipped (#4572, #4574); full composition blocked upstream.**
`fastmcp.Client` now defaults to `mode="auto"` (#4572): it probes `server/discover`, falls back to the classic handshake, and answers multi-round-trip `input_required` requests through its existing handlers. The same PR surfaced `extensions=` and `result_claims=` (SEP-2133). The client also dropped its forked protocol helpers — extension folding, the evicting message handler, discover synthesis — in favor of the SDK's own (#4574).
The decision here was **compose, not wrap** (D16): rebuild `fastmcp.Client` on the SDK's high-level `mcp.Client` rather than wrapping `mcp.ClientSession`. The parts that compose cleanly have shipped. The rest is **blocked upstream on two counts**. First, `mcp.Client` constructs its `ClientSession` at a single hardcoded site with no injection hook, while FastMCP's `session_class` is load-bearing (`ProxyClient` substitutes a session that skips result validation so a backend's schema violation surfaces at the end client rather than becoming a proxy error) — a `session_factory=` hook on `mcp.Client`, the same shape as the `notification_bindings=` parameter added earlier, would solve this. Second, `mcp.Client.__aenter__` refuses reentry, but FastMCP's client is deliberately reentrant (its refcounted context manager exists to fix a proxy session-reuse deadlock), so the rebuild also needs the SDK client to tolerate reentrant entry. Both must land upstream before the full rebuild is possible; `session_factory=` alone is necessary but not sufficient.
This workstream also owns the server-side statelessness design holes — `ctx.session_id` / `set_state` round-tripping and stateful-proxy affinity — since they turn on the same "what is a session without a session?" question. See [Statelessness on 2026-07-28](known-gaps.md#statelessness-on-2026-07-28) for the full accounting.
## Subscriptions, cache hints, extensions, OTel
**Status: Mixed — cache hints and OTel shipped; subscriptions not started.**
A cluster of protocol features tracked for v4. Their statuses have diverged:
- **Cache hints — shipped (#4464).** Server-level authoring (`FastMCP(cache_ttl=..., cache_scope=...)`, SEP-2549) stamps every cacheable result, and the FastMCP client honors hints with an opt-in response cache.
- **OpenTelemetry — shipped (#4481).** Spans are on by default (a no-op without an exporter), with SDK-aligned attributes and a `FASTMCP_TELEMETRY_MODE` setting (`native` / `propagation_only` / `off`).
- **Extensions — client side shipped (#4572).** `Client(extensions=..., result_claims=...)` advertises opt-in client extensions (SEP-2133). The server side is a Designed workstream in its own right (see [FastMCP-native extension API](#fastmcp-native-extension-api)). The cross-era reconciliation of the `extensions` / MCP Apps capability advertisement is still open (the capability is stripped at pre-2026 negotiated versions — sdk-feedback #2).
- **Subscriptions — not started.** A `subscriptions/listen` surface backed by a subscription bus.
## FastMCP-native extension API
**Status: Shipped (#4602).**
MCP extensions (SEP-2133) are optional, capability-negotiated protocol features identified by a reverse-DNS string — `io.modelcontextprotocol/ui` (MCP Apps), `io.modelcontextprotocol/tasks` (SEP-2663). They are a genuinely new abstraction in SDK v2; they did not exist in v1. The SDK exposes them through an `Extension` server class that contributes a capability, additive request methods, and a `tools/call` interceptor, plus a symmetric `ClientExtension` with result claims and notification bindings.
FastMCP already forwards `ClientExtension` natively (`Client(extensions=...)`, #4572). The **server** side does not use the SDK's `Extension` class at all: MCP Apps predates the abstraction, so FastMCP hand-splices the `ui` capability into `get_capabilities()` on the low-level server and walks tool metadata directly. That worked for one extension, but every new protocol extension currently means bespoke surgery on core.
The Designed work is a FastMCP-native server extension API — a single registration point (`mcp.add_extension(...)`) that contributes a negotiated capability, request methods, and a `tools/call` interceptor, with access to FastMCP-level constructs the SDK's `Extension` withholds (the component registry, `Context`, auth scope). It is designed against the SEP-2663 tasks extension because tasks exercises the full surface — capability *and* methods *and* interception *and* client claims/notifications — where MCP Apps exercises only a subset. Tasks is the pathfinder; MCP Apps migrates onto the extension API as a fast-follow, deleting the hand-rolled splices, and confirms the design generalizes. The discriminator that keeps the extension API distinct from [middleware](https://gofastmcp.com/servers/middleware): an extension is a *negotiated contract change* the client must understand, where middleware is unilateral server behavior the client never sees. Delete a capability advertisement and nothing about the client changes — that is middleware, not an extension.
## Background tasks (SEP-2663)
**Status: Shipped (#4603).**
Background tasks return to the modern era as `fastmcp-tasks`, an in-repo optional package rebuilt on the `io.modelcontextprotocol/tasks` extension (SEP-2663, Final, merged upstream 2026-05-15). SEP-2663 supersedes SEP-1686 but keeps its polling core: a client that advertises the tasks capability issues an augmented `tools/call`; the server decides whether to run it as a task and returns a `CreateTaskResult` carrying a server-generated task id; the client polls `tasks/get` until terminal and reads the result inlined there. FastMCP's existing SEP-1686 wire layer is removed while the Docket/Redis execution engine underneath moves into `fastmcp-tasks` intact — the spec moved toward what FastMCP already built, so the rebuild is mostly deletion plus a thin wire adapter. `task=True` stays the authoring surface (gated by the `fastmcp[tasks]` extra and an explicit `mcp.add_extension(TasksExtension(...))`, the first consumer of the [extension API](#fastmcp-native-extension-api) above), so a server that already uses tasks needs no code change. Scope for v1 is polling-only and `tools/call`-only.
The full design — wire delta, the engine/wire split, packaging, client experience, sequencing, risks, and the five resolved decisions — is on the dedicated [Background Tasks (SEP-2663)](background-tasks.md) page.
## SDK delegation, round two
**Status: Planned (gated on upstream).**
The real HTTP simplification is a v4 project, not this PR. FastMCP can collapse its `create_streamable_http_app` onto the SDK's `Server.streamable_http_app()` once upstream adds three things:
1. per-session event-store scoping,
2. a user-middleware injection hook,
3. a lifespan hook.
The payoff is not only less code — FastMCP would also inherit the SDK's session-owner credential enforcement, a security gain it lacks today. These are the three upstream feature requests to file (alongside the advisory dossier described in [Known Gaps](known-gaps.md)). Until they land, the four HTTP overrides in the [Change Register](change-register.md#http) stay.
One latent capability worth surfacing on FastMCP's side: `session_idle_timeout` is accepted by the manager but never set by `create_streamable_http_app` — a one-line plumb if FastMCP wants to expose it.

View file

@ -0,0 +1,49 @@
---
title: v4.0 Development Notes
---
This directory is the working map of FastMCP v4.0: the complete register of user-facing changes from the MCP Python SDK v2 migration ([PR #4437](https://github.com/PrefectHQ/fastmcp/pull/4437)), plus the forward v4 feature program. It plays three roles at once.
1. **A change register.** Every user-visible change from the migration, organized by subsystem, with a note on how FastMCP handles it (absorbed, bridged, breaking, or deprecated) and where to find it in the diff. This is the [Change Register](change-register.md).
2. **A feature program.** The forward v4 work — sampling removal, multi-round-trip elicitation, the first-class 2026 client, a FastMCP-native extension API, the SEP-2663 background-tasks rebuild, and the SDK-delegation round-two convergence — now a mix of shipped, designed, and pending. Multi-round-trip guard tools (#4544), the client's `mode="auto"` default with a partial SDK-composition (#4572/#4574, full composition blocked upstream), the extension API (#4602), and background tasks on SEP-2663 (#4603) have shipped; sampling removal and SDK delegation remain ahead. Each carries an explicit status in the [Feature Program](feature-program.md). The shipped side — what a v4 deployment provides on the modern protocol today, including the complete server-side SEP-990 identity assertion implementation — is cataloged in [2026-07-28 Protocol Support](protocol-2026.md).
3. **A review lens.** Because the migration PR is too large to review line by line, the change register is organized so a reviewer can take one subsystem, read its claimed changes, and verify each against the diff. The [Known Gaps](known-gaps.md) page collects the deliberate xfails and the upstream dependencies that gate the follow-up work.
## Why v4 exists
FastMCP v4.0 is an engine swap. Three forces drive the major version:
**The MCP Python SDK v2 rebuild.** The SDK v2 makes two sweeping changes to the protocol layer: it splits the protocol types out of `mcp.types` into a standalone `mcp_types` package, and it renames every protocol field from camelCase to snake_case (`inputSchema``input_schema`, `mimeType``mime_type`, `isError``is_error`). It also rewrites the server request-handling model — handlers are now registered by method string and return bare result models, there is no `request_ctx` ContextVar, and server-side middleware is a first-class SDK concept. FastMCP absorbs almost all of this so that a typical server needs zero code changes.
**Protocol version 2026-07-28.** The SDK v2 serves multiple protocol eras from one server. Alongside the session-based handshake eras, it introduces the sessionless `2026-07-28` era, which discovers capabilities through `server/discover` and removes server-initiated requests (SEP-2577). This formally supersedes FastMCP's earlier "latest protocol only" stance: a single server now works with clients across the protocol transition.
**Sampling and roots removed from the server API.** The `2026-07-28` era removes the server's ability to push a request back to the client mid-call, which takes `ctx.sample`, `ctx.sample_step`, and `ctx.list_roots` off the table. Rather than leave them half-working against old clients only, 4.0 removes them from the server API entirely — a real architectural shift for servers that borrowed the client's model, and one that justifies the major bump. Client-side handlers stay, because a modern client still has to answer a legacy server.
## Release strategy
The migration merges to `main` and development continues there with subsequent PRs. Releases follow the SDK's own beta timeline:
- **`main` carries the beta pins.** While the SDK is on `mcp==2.0.0b1` / `mcp-types==2.0.0b1`, `main` cuts **pre-releases** (`4.0.0b1`, `4.0.0b2`, …). No stable PyPI release goes out until `mcp 2.0.0` reaches GA — at which point the pins swap to the stable SDK and `4.0.0` ships. The pin-swap is a tracked checklist item on the [Known Gaps](known-gaps.md) page.
- **`release/3.x` is the maintenance line.** A `release/3.x` branch is cut from pre-merge `main`. It stays on the SDK v1 line, receives upstream security patches, and serves users who cannot move to the SDK v2 beta yet.
### Release codenames
Following the pun-title convention (`v<version>: <pun>`), the v4 line runs a single "four" motif across the whole cycle, holding the headline name for the stable release the way v3 did ("Three at Last" for `3.0.0`, stage puns for its betas):
| Release | Codename | The nod |
| --- | --- | --- |
| `4.0.0a1` (alpha) | **Fourst Contact** | _first contact_ — the first, cautious look at the new engine |
| `4.0.0a2` (alpha) | **Back and Fourth** | _back and forth_ — the second pass, where background tasks and stateless state land |
| `4.0.0b1` (beta) | **Fourgone Conclusion** | _foregone conclusion_ — once the MCP SDK went v2, v4 was inevitable |
| `4.0.0b2` (beta) | **Fourmidable** | _formidable_ — held in reserve for a second beta if one is needed |
| `4.0.0` (stable) | **Fast Fourward** | _fast forward_ — full speed onto the new foundation |
## How to read the register
Each subsystem section in the [Change Register](change-register.md) tags its changes with one of four dispositions:
- **Absorbed** — the SDK changed underneath, but FastMCP's public surface is identical. Nothing for users to do.
- **Bridged** — a compatibility shim keeps old code working, usually with a `FastMCPDeprecationWarning`. Users should migrate but are not forced to.
- **Breaking** — user code must change. These are the headline migration items.
- **Deprecated** — still works, warns now, slated for removal in a later release.
The user-facing summary of the migration lives in the published [Upgrading from FastMCP 3](https://gofastmcp.com/getting-started/upgrading/from-fastmcp-3) guide. These development notes are the exhaustive version behind it.

View file

@ -0,0 +1,85 @@
---
title: Known Gaps and Upstream Dependencies
---
The migration ships with a set of deliberate gaps: temporary shims, xfailed tests, and pins that depend on the MCP Python SDK v2 reaching GA. Each is tracked here with its removal trigger. This page is the checklist for the beta-to-stable transition and the advisory relationship with the SDK team.
## The xfail register
Roughly forty `xfail` markers across the test tree name the SDK gaps and removed protocol surfaces they wait on. Re-running the suite against a new SDK beta surfaces which have closed (a strict xfail that starts passing fails the suite, prompting removal of the marker). They cluster in three areas — but the largest cluster is no longer a set of gaps to close.
**Task suite (`tests/server/tasks/`, `tests/client/tasks/`) — SEP-1686 wire layer being removed; engine rebuilt on SEP-2663.** The large majority. These cover the 2025 task protocol (SEP-1686), which left the core MCP spec and was reworked into the `io.modelcontextprotocol/tasks` extension (SEP-2663). FastMCP's SEP-1686 *wire* machinery (capability advertisement, the `tasks/get|result|list|cancel` handlers, the push notification/elicitation relay) is slated for removal, so the wire-protocol xfails disappear with the code they cover — they are not waiting on an SDK fix. The Docket/Redis *execution engine* underneath is not discarded: it is extracted into the planned `fastmcp-tasks` package and re-adapted to the SEP-2663 polling shape (see [Background Tasks (SEP-2663)](background-tasks.md)). The two SDK gaps these were originally filed against — **sdk-feedback #1** (SEP-1686 task result types omitted from the method registries) and **sdk-feedback #3** (no `task` field on `ReadResourceRequestParams` / `GetPromptRequestParams`) — are moot: they patched the SEP-1686 wire shape, which SEP-2663 replaces with a `CreateTaskResult` claimed on `tools/call`. The gap that matters for the rebuild is **sdk-feedback #2** (extensions capability stripped at pre-2026 negotiated versions) — it now gates a flagship feature and is escalated accordingly.
**Protocol eras (`tests/server/test_protocol_eras.py`).** One remaining strict xfail, and it too is task-related: the v2 SDK high-level client exposes no `task=` parameter on `call_tool`, so a SEP-1686 task-augmented `tools/call` cannot be submitted through it. It resolves with the SEP-1686 wire-layer removal above; the SEP-2663 rebuild submits tasks by advertising the extension capability and claiming a `CreateTaskResult`, not through a `task=` params field. The earlier strict xfail for the `ctx.elicit` / `ctx.sample` "Method not found" degradation (sdk-feedback #10) is **gone** — the era-gating shipped in #4448 flipped it to a passing test.
**MCP Apps (`tests/test_apps.py`).** Two xfails tied to **sdk-feedback #2** — the `extensions` capability is stripped by the pre-2026 version sieve, so the UI extension can't be advertised to legacy-era clients.
## Shims and their removal triggers
Every shim in the migration is temporary and carries a documented removal trigger.
| Shim | Location | Removal trigger |
| --- | --- | --- |
| `_sdk_patches.py` — task registry widening | `fastmcp_slim/fastmcp/_sdk_patches.py` | Removed with FastMCP's SEP-1686 wire machinery (`server/tasks/`), which is slated for removal now that the 2025 task protocol left the spec. The SEP-2663 rebuild does not need it — `CreateTaskResult` is claimed on `tools/call` through the extensions mechanism, which the SDK registries already admit. |
| `_compat.py` — camelCase field bridge | `fastmcp_slim/fastmcp/_compat.py` | User-migration aid; removed in a future release after users migrate reads to snake_case. Users can preview removal with `mcp_camelcase_compat = False`. |
| `FastMCPRequestContext` ContextVar | `fastmcp_slim/fastmcp/server/dependencies.py` | The SDK deliberately passes context as an argument with no ContextVar; FastMCP's public `get_context()` needs ambient access, and the shim also lifts `_meta`, which the SDK's `TypedDict` drops. No planned removal — this is a permanent boundary, not a beta gap. |
| `FastMCPServerMiddleware` | `fastmcp_slim/fastmcp/server/low_level.py` | Already the native SDK `ServerMiddleware` path; no cleaner hook exists. Permanent. |
| Client `get_session_id` header sniff | `fastmcp_slim/fastmcp/client/transports/http.py` | SDK exposes session id (or an `on_session_created` callback) from `streamable_http_client`, at parity with `sse_client` (sdk-feedback #5). |
| `_sdk_context_shim.py` — generic handler aliases | `fastmcp_slim/fastmcp/client/_sdk_context_shim.py` | The SDK's `ClientRequestContext` is not subscriptable, so FastMCP keeps the public generic `SamplingHandler`/`RootsHandler`/`ElicitationHandler` aliases. Permanent unless the SDK makes the context subscriptable (sdk-feedback #7). |
The `TaskNotificationHandler` binding (sdk-feedback #8) is the client-side equivalent: it registers a `NotificationBinding` for the SEP-1686 `notifications/tasks/status` because the SDK no longer tees custom server notifications to the message handler. It goes away with the SEP-1686 wire machinery it serves; the `fastmcp-tasks` client half registers its own binding for the SEP-2663 `notifications/tasks` shape when it ships (push notifications are deferred to a later `fastmcp-tasks` version — v1 is polling-only).
## Statelessness on 2026-07-28
The `2026-07-28` era is stateless by protocol construction, and the recurring maintainer question is whether that statelessness has to be woven through FastMCP everywhere. It does not — but the honest accounting has three parts: features that are legacy-only because the protocol removed the mechanism, features that already work because they never relied on a session, and a short list of design holes where the current code *doesn't error* but also *doesn't work*. Everything below concerns `2026-07-28` connections only. Every client in the field today negotiates a handshake era, where all of this behaves exactly as it always has.
**The SDK ground truth.** On the modern paths the SDK's `Connection` is strictly per-request: a fresh `Connection` is built from each POST's envelope, its `exit_stack` unwinds when the request returns, `connection.session_id` is always `None`, and `connection.state` is a fresh dict per request. The manager's `stateless` flag never enters the picture — modern routing short-circuits ahead of it. There is no standing server→client stream: notifications emitted *during* a request ride that POST's own SSE sink, and anything emitted after the POST returns is dropped (`_NO_CHANNEL`); server→client *requests* raise `NoBackChannelError`. The only replacement is `subscriptions/listen`, which carries four list-changed / resource-updated event kinds and nothing else — no logging, progress, or task-status events, no resumability, and it is not yet wired into FastMCP. There is no `EventStore` or `Last-Event-ID` on modern paths at all; both belong to the legacy transport.
### Legacy-only by construction — document, don't build
These are not bugs. The protocol removed the mechanism they depend on, so they are simply out of scope on `2026-07-28`:
- **Per-session log levels.** `logging/setLevel` is absent from the 2026 method registry, so the `_client_log_levels` handler is unreachable. There is no per-session log-level state because there is no session.
- **`EventStore` / resumability.** `EventStore`, `SessionScopedEventStore`, and Last-Event-ID resumption are never constructed on the modern paths. Resumability presupposes a durable stream, which the era does not have.
- **Ping keepalive.** Server-initiated ping is a server→client request and is therefore structurally a no-op on modern connections; the SDK owns SSE-level pings on this transport.
### Already stateless by construction — works on 2026
These work on `2026-07-28` today because they never leaned on a protocol session:
- **`tasks/get` polling.** Task result retrieval is keyed by `task_id` and backed by Docket/Redis, so a client polls across independent requests without any session affinity. This session-free polling is exactly why the execution engine survives the SEP-1686-to-SEP-2663 rework: the SEP-2663 wire shape (poll `tasks/get`, resolve in-task input via `tasks/update`) maps onto the same durable store, and SEP-2663's `Mcp-Name: <taskId>` routing header is moot for a shared-Redis deployment where any replica can serve the poll. See [the xfail register](#the-xfail-register).
- **OAuth bearer validation.** Auth is per-request bearer validation — every POST carries and re-validates its own credential.
- **In-request progress and logging notifications.** Notifications emitted while a request is still streaming ride that POST's SSE sink and are delivered normally.
### Design holes deferred to the multi-protocol workstream
The remaining items are real holes, deferred to the [first-class 2026 client](feature-program.md#first-class-2026-client) workstream because they all reduce to one unanswered question — *what is a session when the protocol has none?* The danger in each is that the code currently returns without erroring, which reads as "works" but is actually silent degradation. Again: these affect `2026-07-28` connections only; on the handshake eras every one of them behaves correctly.
- **`ctx.session_id` and `ctx.set_state` / `ctx.get_state` (broken even single-replica).** On a modern request `ctx.session_id` mints a fresh `uuid4`, cached on the per-request `connection.state` that is discarded when the request returns. So `ctx.set_state` and `ctx.get_state` silently never round-trip across requests — no error, just lost data. The open design decision is whether `session_id` should become `None` with `set_state` documented as session-era-only, or be re-based on an app-level key (the auth subject, or a client-supplied header).
- **Task push and in-task input — resolved by the SEP-2663 design, not a statelessness hole.** This was previously framed as a hole because SEP-1686 leaned on a push back-channel (the notification/elicitation relay) that dies once the submitting request returns. SEP-2663 removes the dependency: in-task input is *poll-based* — the task enters `input_required`, surfaces its outstanding elicit/sample/roots requests in an `inputRequests` map on `tasks/get`, and the client answers via `tasks/update`. That round-trips through the durable store with no session affinity, so it is stateless-safe by construction. The SEP-1686 push relay (`server/tasks/elicitation.py`, `notifications.py`) is removed; the `fastmcp-tasks` rebuild implements the poll-based channel instead. Foreground (non-task) elicitation on 2026 remains the guard-mode `InputRequiredResult`.
- **Stateful proxy affinity (degraded).** The stateful proxy's `_caches` are keyed by the per-request `Connection`, so on modern connections the proxy collapses to stateless proxying: results stay correct, but the per-session affinity guarantee is lost. This is decided alongside the `session_id` question — same root — or gated to the legacy/stdio transports.
Multi-replica concerns (per-process rate-limiter buckets, shared Redis backends for state and tasks, a Redis `SubscriptionBus`) are deployment configuration rather than protocol gaps and are out of scope for this section.
## Upstream advisory dossier
FastMCP acts as an advisor to the SDK team. The migration produced a dossier of ten findings (`sdk-feedback.md`) — verified bugs and hard edges to report upstream, plus questions to bundle into a feedback thread. The highest-priority items:
- **#1 (bug)** — SEP-1686 task result types ship but the method registries omit them. *Moot: the SEP-1686 wire shape was removed from the spec; the SEP-2663 rebuild claims `CreateTaskResult` on `tools/call` through the extensions mechanism, which the registries already admit.*
- **#2 (bug/question)** — `capabilities.extensions` stripped at pre-2026 negotiated versions. **Elevated:** this now gates the `io.modelcontextprotocol/tasks` extension (and MCP Apps) on the modern era, so it blocks a flagship v4 feature rather than an edge case. Worth prioritizing in the upstream thread.
- **#4 (security)** — DCR redirect-URI validation accepts `javascript:`/`data:` schemes.
- **#5 (hard edge)** — `streamable_http_client` drops session-id access with no replacement.
- **#8 (hard edge)** — custom server notifications are dropped, not tee'd to `message_handler`.
- **#10 (hard edge)** — 2026 push-feature degradation error quality is inconsistent. *Resolved on the FastMCP side: `ctx.elicit` / `ctx.sample` are era-gated to raise a clear error on modern connections (#4448).*
Filing is gated on maintainer approval of each issue text.
Separately, the [SDK delegation round two](feature-program.md#sdk-delegation-round-two) work depends on **three upstream feature requests** — per-session event-store scoping, a user-middleware injection hook, and a lifespan hook — that would let FastMCP collapse its HTTP builders onto the SDK's and inherit the SDK's session-owner credential enforcement.
## GA transition checklist
The beta-to-stable transition is a small set of tracked steps:
- **Swap the pins.** When `mcp 2.0.0` reaches GA, change `mcp-types==2.0.0b1` (core) and the `mcp` pin (the `[mcp]` extra) in `fastmcp_slim/pyproject.toml` from the beta to the stable release, and cut `4.0.0` instead of another pre-release.
- **Re-run the xfail suite against the GA SDK.** Any strict xfail that starts passing means a gap closed — remove the marker and, where applicable, the corresponding shim.
- **Confirm `release/3.x`** is cut from pre-merge `main` and receiving upstream security patches for users who stay on the SDK v1 line.

View file

@ -0,0 +1,53 @@
---
title: 2026-07-28 Protocol Support
---
FastMCP v4 serves the sessionless `2026-07-28` protocol era and the session-based handshake eras from a single server, with per-connection auto-detection. This page catalogs what FastMCP provides for the modern era — both the protocol machinery it inherits from the MCP Python SDK and the capabilities FastMCP implements itself on top of that layer. It is the reference for what a v4 deployment can actually do on the modern protocol today.
## Identity assertion (SEP-990)
SEP-990 defines enterprise "on-behalf-of" access: a corporate identity provider (Okta, Microsoft Entra, etc.) issues a signed *ID-JAG* asserting an employee's identity, the employee's agent presents it at the MCP authorization server's token endpoint via the RFC 7523 `jwt-bearer` grant, and receives a short-lived access token — no browser login, no per-user consent screen, and revocation lives at the IdP.
The protocol layer for this flow — grant parsing, the `exchange_identity_assertion` provider hook, and metadata advertisement — comes from the SDK. The validation and issuance logic that makes the flow actually work is FastMCP's implementation, and enabling it is one parameter on the existing auth providers:
```python
from fastmcp import FastMCP
from fastmcp.server.auth import OAuthProxy, IdentityAssertion
auth = OAuthProxy(
..., # existing upstream configuration unchanged
identity_assertion=IdentityAssertion(
trusted_issuers=["https://login.acme-corp.com"],
),
)
mcp = FastMCP("Internal API", auth=auth)
```
Behind that one parameter, FastMCP performs the full SEP-990 §5.1 / RFC 7523 §3 processing: JWKS-based signature verification with automatic OIDC discovery of issuer keys, `typ`/`iss`/`aud`/`sub` validation, temporal checks (`exp`, `iat`, `nbf`, maximum assertion lifetime), enforcement of the assertion's signed `client_id` and `resource` bindings, `jti` replay rejection, scope derivation from the signed assertion (client requests can narrow but never widen), short-lived token issuance with no refresh token, and revocation tracking for the issued tokens. The asserted subject flows into the normal FastMCP auth context, so tools read it through `get_access_token()` like any other identity. See [Identity Assertion](https://gofastmcp.com/servers/auth/oauth-proxy#identity-assertion-sep-990) for the full documentation.
This slots into FastMCP's existing authorization-server stack — the OAuth proxy's dynamic client registration, the consent flow, and self-issued JWTs — which is what makes a one-parameter enterprise deployment possible.
## Modern-era capability inventory
The complete picture of what a FastMCP v4 server and client provide on the `2026-07-28` era:
| Capability | What FastMCP provides |
| --- | --- |
| **Dual-era serving** | One server answers both `server/discover` (modern, sessionless) and `initialize` (handshake) connections, auto-detected per connection. Any replica behind a plain load balancer can answer a modern request. |
| **Identity assertion (SEP-990)** | Complete server-side implementation, one parameter to enable (above). |
| **Authorization server** | Full AS stack: `OAuthProxy` bridges DCR-expecting MCP clients to non-DCR enterprise IdPs, ~18 built-in providers, consent UI, self-issued JWTs, protected-resource metadata (RFC 9728). |
| **Cache hints (SEP-2549)** | Server-level authoring (`FastMCP(cache_ttl=..., cache_scope=...)`) stamps every cacheable result; the FastMCP client honors hints with an opt-in response cache. |
| **Distributed response caching** | `KeyValueResponseCacheStore` backs the client cache with any key-value store (Redis, memory, filetree), so a fleet of clients or proxy replicas shares cache fills across processes. |
| **Resource path security** | Templated resource parameters are screened for traversal, absolute paths, and null bytes before handlers run — on by default, including provider-sourced and mounted templates. |
| **Client protocol negotiation** | `Client(mode="auto")` — the default as of v4 — probes `server/discover` and falls back to the classic handshake; the client answers multi-round-trip `input_required` requests through its existing handlers. Pin `mode="legacy"` to force the handshake. |
| **Elicitation on the modern protocol (SEP-2322)** | Tools request user input via multi-round trips: a tool returns an `InputRequiredResult` and re-runs per round, reading the client's answers off `ctx.input_responses` / `ctx.request_state` (the [guard pattern](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)). Each round is a complete request→response cycle; the framework seals `request_state` on the wire and unseals it before the tool runs, and a shared-key `request_state_security` policy carries state across replicas. On handshake-era connections returning this result produces a clear era error. |
| **Spec-standard errors (SEP-2164)** | Missing-resource reads return `-32602`; push-feature calls on modern connections fail with clear era-specific errors rather than generic method-not-found. |
| **Middleware** | Typed per-method hooks (`on_call_tool`, `on_list_tools`, …) and a suite of built-ins (auth, rate limiting, caching, error handling, logging, timing, and more). |
| **Composition** | `mount()`, providers, proxying, and tool transforms compose servers dynamically at runtime, with lifespans and middleware driven through the SDK session manager. |
| **Pagination** | Declarative `FastMCP(list_page_size=...)` paginates all list operations in the high-level server; the client auto-paginates with cycle detection. |
| **Telemetry** | OpenTelemetry spans on by default (no-op without an exporter), SDK-aligned attributes (`mcp.method.name`, `mcp.protocol.version`, `gen_ai.*`), plus auth and provider-delegation spans; `FASTMCP_TELEMETRY_MODE` selects `native`, `propagation_only` (interop with an outer MCP instrumentation layer), or `off`. |
| **Background tasks (SEP-2663)** | `fastmcp-tasks` implements the `io.modelcontextprotocol/tasks` extension end to end: `mcp.add_extension(TasksExtension())` plus `task=True` runs a tool as a background task, driven by the same Docket engine FastMCP 3 used. A client transparently completes a tasked call; gathering input mid-task uses the same guard pattern as foreground multi-round-trip tools, so a tool is written once and works either way. Modern-protocol only — the `task=True` runtime this replaced (SEP-1686) is gone entirely, not bridged. See [Background Tasks (SEP-2663)](background-tasks.md) for the design and [servers/tasks](https://gofastmcp.com/servers/tasks) for usage. |
## Still in the program
Elicitation on the modern protocol is now shipped in its **guard form** — a tool returns an `InputRequiredResult` and re-runs per round to gather user input via multi-round trips (see [Elicitation on the modern protocol](https://gofastmcp.com/servers/elicitation#elicitation-on-the-modern-protocol)). The declarative `Resolve(...)` layer over that primitive remains staged, tracked in the [Feature Program](feature-program.md), along with the unified `subscriptions/listen` stream. The [Known Gaps](known-gaps.md) page tracks the upstream dependencies that gate them.

View file

@ -0,0 +1,217 @@
# Stateless session state (2026-07-28)
> Design spec. Status: building.
## Problem
The `2026-07-28` era is stateless by protocol construction: each request builds a
fresh `Connection`, `connection.session_id` is always `None`, and
`connection.state` is a new dict discarded when the request returns. So
`ctx.session_id` mints a throwaway `uuid4` per request and `ctx.set_state` /
`ctx.get_state` **silently never round-trip** — no error, just lost data. A user
who wants cross-call state (a cart, a conversation, accumulated context) has no
safe mechanism, and the failure is invisible.
The one identifier every modern request carries that is stable and
**non-spoofable** is the authenticated principal — `get_access_token().claims["sub"]`,
or the `(client_id, issuer, subject)` triple. Everything else on the wire is
client-declared and forgeable.
## The model
State lives **server-side** in the one `AsyncKeyValue` (py-key-value) store the
server already holds (`session_state_store`). The framework calls `get`/`put`/
`delete` and **never imposes a TTL** — retention is entirely the store's
(configure it on the store you pass: a Redis TTL, a py-key-value TTL wrapper,
whatever). There is no second store and no framework-owned TTL knob.
Isolation comes from the **authenticated principal, not from the session id.**
State is keyed by `(principal, session_id)`. A request under principal B keys
into B's own namespace — it can never address A's keys no matter what
`session_id` it passes. The id only organizes sessions *within* a principal. The
handle is a bare `uuid4` string; it is **not sealed** — the principal prefix is
the wall. Sessions are also create-then-validate (below): an id that was never
minted by `create_session` under this principal is rejected outright, not
resolved to an empty session.
## Two explicit patterns
A tool opts into exactly one, on purpose. There is deliberately **no** optional
"id if given, else default" parameter — that would silently misroute a call
whose id the agent forgot to pass into the shared per-user bucket, which is the
invisible-degradation failure this whole feature exists to remove.
### Per-user state — injected
```python
from fastmcp.server.sessions import UserSession
@mcp.tool
async def remember(fact: str, session: UserSession) -> str:
await session.set("fact", fact)
return "noted"
```
`session: UserSession` is **dependency-injected** (like `ctx: Context`): keyed by
the request's authenticated principal, not present in the input schema, nothing
for the agent to pass. Requires auth — with no principal it raises a clear error.
Use it when one bucket per user is what you want. `UserSession` is only the
injection annotation — the value the handler receives is an ordinary `Session`,
so its `get`/`set`/`delete`/`clear` accessors work as usual.
### Distinct sessions — an argument
```python
from fastmcp.server.sessions import SessionId
from fastmcp.server.dependencies import get_session
@mcp.tool
async def add_to_cart(item: str, session_id: SessionId) -> str:
session = await get_session(session_id)
cart = await session.get("cart", default=[])
cart.append(item)
await session.set("cart", cart)
return f"{len(cart)} items"
```
`session_id: SessionId` is a **required string argument** — it *is* in the schema,
the agent supplies it. `SessionId` is a marker type so the framework
auto-populates the argument's description with the protocol:
> "Session identifier. Use a tool to create a session, then pass the resulting id
> here to persist state across calls in the same session."
The tool becomes self-teaching — an agent reads the schema and learns the
create-then-pass contract with no hand-prompting. The description names no
specific tool: composition can rename the lifecycle tool (mounting under a
namespace exposes it as `child_create_session`), so it points at the
*capability* rather than a name that may not exist under that mount.
The standalone `await get_session(session_id)` resolves the id to a `Session`
keyed by `(principal, session_id)`, **validating** that it was created under this
principal — an unknown or foreign id raises `InvalidSession` rather than opening a
fresh bucket. It is a plain function, not a `Context` method, so it needs no
foreground context and works from a `task=True` tool's worker. Use this pattern
when a user needs more than one session.
## The `Session` object
Async accessors over the server store, scoped to one `(principal, session_id)`:
- `session.id` — the session's id (set for a `session_id`-resolved session; `None`
for an injected `UserSession`, which has no distinct id).
- `await session.get(key, default=None)`
- `await session.set(key, value)`
- `await session.delete(key)`
- `await session.clear()` — empties user state but **keeps the session valid**.
- `await session.end()` — deletes the session (what `end_session` calls).
A session's state is stored as a **single dict under one key**
(`session:{sha256(principal)}:{session_id}`, and `session:anon:{session_id}` when
unauthenticated — the principal is hashed into a fixed-length, delimiter-safe
segment, never embedded raw). That dict holds user state in a `state` sub-dict
alongside a small `_created` marker, so a created-but-empty session is
distinguishable from a missing one even if the store collapses empty dicts.
`get`/`set`/`delete` read-modify-write the sub-dict and never touch the marker;
`clear` resets the sub-dict but leaves the marker (the session still resolves);
`end` deletes the key. Namespacing user state under `state` is what keeps a user
key named `_created` from colliding with the marker. One key per session means
one TTL per session (the store's), refreshed on write — no key index to maintain,
and `end` is a single delete. (Trade-off: 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 — noted, not hidden.)
## `SessionProvider`
Session ids are minted by `SessionProvider`, which contributes two tools:
- `create_session()` → mints an unguessable `uuid4`, **records** the session
under the current principal, and returns the id as a string.
- `end_session(session_id: SessionId)` → validates the id, then deletes the
session so it no longer resolves.
Register it whenever your tools take a `session_id` — providers are the idiomatic
way to add functionality like this:
```python
from fastmcp.server.sessions import SessionProvider
mcp.add_provider(SessionProvider())
```
There is **no enforcement** that a provider is registered, and there was: an
earlier version scanned the tool set at list/resolve time and raised if a
`session_id` tool had no provider. That check had to reason about the whole
composition pipeline — `isinstance` on providers, unwrapping namespaced ones,
tool transforms, session visibility, enabled state — and produced false
positives that broke valid servers (a namespaced provider, a session-disabled
tool). It was deleted. The guarantee never needed it: `get_session` validates
that an id was recorded (create-then-validate), so a server with no provider
simply cannot mint ids, and every `get_session` rejects — a misconfiguration
caught the first time the tools run, not a security hole.
`SessionProvider` subclasses `Provider`, takes **no store** (uses the server's)
and **no ttl** (the store's). It exists to mint and end owned ids.
`create_session` matters most without auth, where an unguessable id is the only
defense against a caller *guessing* onto another session.
When an application already mints its own identifiers — conversation ids, workflow
ids — take them as ordinary string arguments rather than `SessionId`, and register
no provider; `SessionId` is specifically the create-then-pass contract backed by
`create_session`.
## Security
Keyed by `(principal, session_id)`:
- **Authenticated → strong isolation.** `principal` is the validated token
subject, unforgeable. B keys into B's namespace; A's data is unreachable no
matter what id B passes. Guessing is pointless; a session id appearing in agent
context or logs is harmless (it is not a capability without the principal).
Caller-chosen ids are safe here.
- **Unauthenticated → single-tenant-safe only.** No principal, so the key is just
the id in a shared namespace: the id becomes a bearer capability, and exposure
in logs/conversation leaks the session. `create_session`'s `uuid4` gives
guess-*resistance*, not isolation. Documented in bold: not a tenant boundary;
without auth, force minted ids and never treat sessions as a wall between
clients.
- **Isolation is auth; the id is organization.** No id scheme substitutes for a
principal, which is why sealing the handle buys nothing load-bearing and is
dropped.
- **Not FastMCP's job:** transport (use TLS), encryption at rest (the store's), a
malicious *authorized* client acting within its rights.
## Rework plan (from the current prototype)
The prototype (`sessions.py`, `context.py`, `function_tool.py`, `server.py`) built
a `Scope` enum, a sealed `SessionCodec`, and `ctx.get_state(scope=...)`. Rework to
the above:
1. **Remove `Scope`** and the `scope=` parameter; revert `ctx.get_state`/
`set_state` to their original request-scoped behavior.
2. **Remove the `SessionCodec`/sealing** — ids are bare `uuid4`.
3. **`Session` object** with async `get`/`set`/`delete`/`clear` over the server
store, single-dict-per-session key scheme.
4. **`session: UserSession`** injection (principal-keyed; error without auth) —
wire into the same parameter-detection path as `Context`. `UserSession` is the
injection marker; the injected value is a `Session`.
5. **`session_id: SessionId`** marker type: string in the schema, auto-filled
description, standalone `await get_session(id)` resolver that validates the id
(works from a task worker — no foreground context needed).
6. **`SessionProvider(Provider)`** with `create_session` (records the session) /
`end_session` (deletes it), registered explicitly via `add_provider`. No
enforcement that it is present — `get_session`'s validation is the guarantee.
7. Rewrite the tests to cover both patterns, principal isolation, no-auth
behavior, and `end_session`.
## Docs plan
Written against the final API once the rework verifies:
- A concept guide — why stateless removes the session, the two patterns, when to
reach for each. Why before how.
- A security page — the two tiers, "isolation is auth, the id is organization,"
the bold no-multitenant-without-auth warning.
- Fully runnable examples for both patterns (pass the doc-import guard, register
in `docs.json`).
- A migration note from the old `ctx.session_id` / `set_state`.

View file

@ -29,11 +29,9 @@ When you mark a tool with `app=True` or `@app.ui()`, FastMCP wires up the metada
### The `app=True` flag
`app` on `@mcp.tool` accepts `True`, an `AppConfig`, or a dict. When you pass `True`, FastMCP checks whether the tool's return type is a Prefab type (`PrefabApp`, `Component`, or unions containing them). If it qualifies, FastMCP expands `True` into a full `AppConfig` — setting the renderer URI, CSP headers, and visibility — and stores it in the tool's `meta["ui"]` dict.
`app` on `@mcp.tool` accepts `True`, an `AppConfig`, or a dict. When you pass `True`, FastMCP explicitly marks the tool as a Prefab UI tool and stamps placeholder UI metadata so the provider can synthesize the correct renderer resource later. When you omit `app`, FastMCP only applies this automatically if the tool's return type is a Prefab type (`PrefabApp`, `Component`, or unions containing them).
This expansion also registers the shared Prefab renderer resource (below). The tool and the renderer are linked through a `resourceUri` field in the metadata: the tool says "render me with `ui://prefab/renderer.html`" and the host fetches that resource when it displays the result.
Type inference works the same way. If the return type is a Prefab type and you haven't set `app` explicitly, FastMCP auto-wires the metadata as if you'd written `app=True`.
The tool and renderer are linked through a `resourceUri` field in the metadata. Internally, registration uses the placeholder URI `ui://prefab/renderer.html`; when tools and resources are listed or read, FastMCP rewrites that placeholder to a per-tool URI like `ui://prefab/tool/<hash>/renderer.html` and synthesizes the matching renderer resource on demand.
### FastMCPApp registration
@ -49,13 +47,13 @@ When a Prefab tool runs, its return value — a `PrefabApp` or a bare `Component
The entry point is `PrefabApp.to_json()`. It walks the component tree and produces a JSON object with three top-level keys: `view` (the component tree), `state` (initial state values), and `_meta` (routing metadata).
FastMCP passes a `tool_resolver` callback to `to_json()`. Whenever the tree contains a `CallTool` action that references a function (not a string), the resolver converts it to a `ResolvedTool` with the function's registered name. This is how `CallTool(save_contact)` becomes `CallTool("save_contact")` on the wire. The resolver also handles `unwrap_result` — a flag telling the renderer to unwrap single-value results from the `{"result": value}` envelope FastMCP uses for schema compliance.
FastMCP passes a `tool_resolver` callback to `to_json()`. Whenever the tree contains a `CallTool` action that references a function (not a string), the resolver converts it to a `ResolvedTool` with the function's registered name. For `FastMCPApp` backend tools, that registered name is then wrapped in the deterministic hashed format described below. The resolver also handles `unwrap_result` — a flag telling the renderer to unwrap single-value results from the `{"result": value}` envelope FastMCP uses for schema compliance.
### The `_meta.fastmcp.app` tag
### Hashed backend tool references
After `to_json()` produces the tree, FastMCP injects `_meta.fastmcp.app` with the app's name (if the tool belongs to a `FastMCPApp`). This tag rides along inside `structuredContent` all the way to the renderer.
FastMCP still tags app tools with `meta["fastmcp"]["app"]`, but backend routing no longer depends on sending the app name through each tool call. During serialization, FastMCP passes a resolver to `PrefabApp.to_json()`. When the tree contains `CallTool(save_contact)`, the resolver turns it into a deterministic hashed name such as `<hash>_save_contact`, where the hash is derived from the app name and backend tool name.
When the renderer calls a backend tool, it includes `_meta.fastmcp.app` in the `CallTool` request. The server sees this tag and routes the call through a special path that bypasses transforms (below).
That hashed name rides along inside `structuredContent` all the way to the renderer. When the renderer calls the backend tool, it sends the hashed tool name in the normal MCP `tools/call` request. The server recognizes that format and routes through the app-tool lookup path described below.
### ToolResult assembly
@ -63,29 +61,55 @@ The final tool result has two parts: `content` (a list of `TextContent` blocks f
## Tool call routing
Normal tool calls go through the provider chain, which applies transforms (namespace prefixes, visibility filters) before resolving by name. App UI calls need a different path.
A tool has two things that behave very differently. Its **name** is unstable by design — namespace transforms rename it, so `save_contact` becomes `contacts_save_contact` in one composition and something else in another. Its **identity** is a hash of the app name and the registered tool name, written once at registration and never changed.
### The `get_app_tool` bypass
A UI is serialized during the entry tool's call, deep inside whatever composition the server happens to have, so it cannot know what its backend tools will be called by the time the payload reaches a host.
Backend tools are typically hidden from the model (`visibility=["app"]`). Visibility transforms would filter them out of normal resolution. And namespace transforms might rename them — `save_contact` becomes `contacts_save_contact` — while the renderer still uses the original name.
### Late-bound tool names
`get_app_tool` solves both problems. When the server sees `_meta.fastmcp.app` on an incoming `CallTool` request, it calls `get_app_tool(app_name, tool_name)` instead of the normal `get_tool(name)`. This walks the provider tree directly, skipping transforms. It finds the tool by its original registered name and verifies that its `meta["fastmcp"]["app"]` matches the expected app.
The payload leaves the app addressed by identity, and every FastMCP server rewrites those references on the way out to whatever it lists that tool as. Servers unwind innermost-first, so the outermost server rewrites last — and its names are the only ones a client can actually invoke.
That's why `CallTool("save_contact")` keeps working when the server is mounted under a namespace. The renderer sends the original name plus the app identity; the server uses `get_app_tool` to find it without transforms in the way.
Rewriting a name in place would destroy the identity for the next layer up, so the payload carries a name-to-identity map under `_meta.fastmcp.toolNames`. Each layer resolves through the map and updates it. The action objects keep the exact shape `prefab_ui` defines: only the value of `tool` changes, and only ever to another valid tool name.
Authorization still applies. `get_app_tool` bypasses transforms but runs auth checks against the tool's `auth` config before executing.
The result is that a renderer receives names that exist in the listing the host is looking at. Under three layers of namespacing the button calls `c_b_a_save`; behind a gateway it calls whatever the gateway lists. No intermediary has to understand a FastMCP-specific convention.
A reference this server cannot resolve is left alone rather than corrupted. This is what keeps apps working behind [tool search](/servers/transforms/tool-search) and code mode, which replace `tools/list` with a handful of synthetic tools: there is no better name to bind to, so the reference stays identity-addressed and the fallback below carries it.
### One copy of an app per server
**An app name must be unique within a server.** Composing the same app twice breaks its UI, and no namespace or mount arrangement makes it work.
The reason is structural. Identity is derived from the app name and the tool's registered name, and deliberately nothing else — that is what makes it survive renaming. Two copies of one app therefore produce two tools claiming a single identity, and no fact anywhere in the listing says which copy a given button belongs to. The information needed to choose was never recorded.
FastMCP declines to bind rather than picking a copy, so buttons stop working instead of quietly invoking the wrong tenant's tool. Expect a message naming the cause:
```
Ambiguous app tool 'save': 2 components share the identity '10c0803009ff'.
The same app is composed more than once, so this call cannot be routed to a
single tool.
```
Give each copy its own app name. Two tenants running the same product want `FastMCPApp("contacts-acme")` and `FastMCPApp("contacts-globex")` — not two instances of `FastMCPApp("contacts")` under different namespaces, since namespaces rename tools and identity is immune to renaming by design.
### The hashed lookup fallback
The identity-addressed form `<hash>_<local_name>` remains callable. FastMCP first tries normal tool resolution; if no tool matches and the name has that shape, it calls `get_tool_by_hash(hash, local_name)`, which walks the provider tree directly, skipping transforms.
When one identity is claimed by more than one tool — which happens when the same app is composed into two branches — the call is refused rather than resolved, since picking either one would silently route into the wrong branch.
Authorization still applies. The hashed path skips name and visibility transforms, but auth checks still run against the tool's `auth` config before execution.
### Provider delegation
`get_app_tool` is defined on the `Provider` base class and overridden by aggregate and wrapped providers. Aggregate providers fan out the lookup across child providers in parallel. Wrapped providers (like `FastMCPProvider`, which wraps a nested `FastMCP` server) delegate to the inner server's `get_app_tool`. Backend tools are reachable through any depth of composition.
`get_tool_by_hash` is defined on the `Provider` base class and overridden by aggregate and wrapped providers. Aggregate providers fan out the lookup across child providers in parallel. Wrapped providers (like `FastMCPProvider`, which wraps a nested `FastMCP` server) delegate to the inner server's hashed lookup. Backend tools are reachable through any depth of composition.
## The renderer
The Prefab renderer is a self-contained JavaScript application that interprets the JSON component tree and renders it as a React UI.
### The shared resource
### Renderer resources
FastMCP registers the renderer as a `ui://prefab/renderer.html` resource with MIME type `text/html;profile=mcp-app`. The HTML is bundled inside the `prefab-ui` Python package; `get_renderer_html()` returns it as a string. All Prefab tools on a server share this single resource.
FastMCP exposes the renderer through per-tool resources such as `ui://prefab/tool/<hash>/renderer.html`, each with MIME type `text/html;profile=mcp-app`. The HTML is bundled inside the `prefab-ui` Python package; `get_renderer_html()` returns it as a string. The resources are synthesized on demand from each tool's UI metadata, so CSP and permissions can differ per tool even though they use the same Prefab renderer.
The resource also carries CSP metadata (via `get_renderer_csp()`) declaring the CDN domains the renderer needs. Hosts use this to configure the iframe's Content Security Policy.
@ -93,7 +117,7 @@ The resource also carries CSP metadata (via `get_renderer_csp()`) declaring the
The renderer lives in a sandboxed iframe and communicates with the host using `postMessage`. The protocol follows the [MCP Apps extension](https://modelcontextprotocol.io/docs/extensions/apps) spec:
The host pushes the tool result (with `structuredContent`) into the iframe. The renderer parses the component tree, initializes state, and renders the UI. When the user interacts — submitting a form, clicking a button — and the interaction triggers a `CallTool` action, the renderer sends a `callServerTool` message back to the host via `postMessage`. The host forwards it as a regular MCP `tools/call` request to the server, including `_meta.fastmcp.app` for routing.
The host pushes the tool result (with `structuredContent`) into the iframe. The renderer parses the component tree, initializes state, and renders the UI. When the user interacts — submitting a form, clicking a button — and the interaction triggers a `CallTool` action, the renderer sends a `callServerTool` message back to the host via `postMessage`. The host forwards it as a regular MCP `tools/call` request to the server, using the hashed backend name that FastMCP serialized into the action.
The response flows back the same way: server → host → iframe via `postMessage`, and the renderer updates state with the result.

View file

@ -1,76 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "p-6",
"type": "Column",
"children": [
{
"type": "BarChart",
"data": [
{
"quarter": "Q1",
"revenue": 42000,
"costs": 28000
},
{
"quarter": "Q2",
"revenue": 51000,
"costs": 31000
},
{
"quarter": "Q3",
"revenue": 47000,
"costs": 29000
},
{
"quarter": "Q4",
"revenue": 63000,
"costs": 35000
}
],
"series": [
{
"dataKey": "revenue",
"label": "Revenue"
},
{
"dataKey": "costs",
"label": "Costs"
}
],
"xAxis": "quarter",
"height": 250,
"stacked": false,
"horizontal": false,
"barRadius": 4,
"showLegend": true,
"showTooltip": true,
"animate": true,
"showGrid": true,
"showYAxis": true,
"yAxisFormat": "auto"
}
]
}
]
}
}</script>
</body>
</html>

View file

@ -1,172 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "gap-4 p-6",
"type": "Column",
"children": [
{
"type": "DataTable",
"columns": [
{
"key": "name",
"header": "Name",
"sortable": true
},
{
"key": "email",
"header": "Email",
"sortable": false
},
{
"key": "category",
"header": "Category",
"sortable": false
}
],
"rows": [
{
"name": "Arthur Dent",
"email": "arthur@earth.com",
"category": {
"type": "Badge",
"label": "Customer",
"variant": "success"
}
},
{
"name": "Ford Prefect",
"email": "ford@betelgeuse.org",
"category": {
"type": "Badge",
"label": "Partner",
"variant": "secondary"
}
},
{
"name": "Trillian Astra",
"email": "trillian@heartofgold.com",
"category": {
"type": "Badge",
"label": "Customer",
"variant": "success"
}
},
{
"name": "Zaphod Beeblebrox",
"email": "zaphod@galaxy.gov",
"category": {
"type": "Badge",
"label": "Vendor",
"variant": "outline"
}
}
],
"search": true,
"paginated": false,
"pageSize": 10
},
{
"type": "Separator",
"orientation": "horizontal"
},
{
"content": "Add Contact",
"type": "H3"
},
{
"cssClass": "gap-4",
"type": "Form",
"onSubmit": {
"action": "showToast",
"message": "Contact saved! (preview demo \u2014 no backend wired)",
"variant": "success"
},
"children": [
{
"cssClass": "gap-4",
"type": "Row",
"children": [
{
"name": "name",
"type": "Input",
"inputType": "text",
"placeholder": "Full name",
"disabled": false,
"readOnly": false,
"required": true
},
{
"name": "email",
"type": "Input",
"inputType": "text",
"placeholder": "name@example.com",
"disabled": false,
"readOnly": false,
"required": true
}
]
},
{
"name": "category",
"type": "Select",
"size": "default",
"disabled": false,
"required": false,
"invalid": false,
"children": [
{
"type": "SelectOption",
"value": "Customer",
"label": "Customer",
"selected": false,
"disabled": false
},
{
"type": "SelectOption",
"value": "Partner",
"label": "Partner",
"selected": false,
"disabled": false
},
{
"type": "SelectOption",
"value": "Vendor",
"label": "Vendor",
"selected": false,
"disabled": false
}
]
},
{
"type": "Button",
"label": "Save Contact",
"variant": "default",
"size": "default",
"disabled": false
}
]
}
]
}
]
}
}</script>
</body>
</html>

View file

@ -1,157 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "gap-4 p-6",
"type": "Column",
"children": [
{
"cssClass": "gap-6",
"type": "Row",
"children": [
{
"type": "Metric",
"label": "Revenue (Q1-Q4)",
"value": "$220,500"
},
{
"type": "Metric",
"label": "Deals",
"value": "4"
}
]
},
{
"type": "BarChart",
"data": [
{
"month": "Jan",
"revenue": 48200,
"costs": 31000
},
{
"month": "Feb",
"revenue": 52100,
"costs": 32500
},
{
"month": "Mar",
"revenue": 61800,
"costs": 34200
},
{
"month": "Apr",
"revenue": 58400,
"costs": 33800
}
],
"series": [
{
"dataKey": "revenue",
"label": "Revenue"
},
{
"dataKey": "costs",
"label": "Costs"
}
],
"xAxis": "month",
"height": 200,
"stacked": false,
"horizontal": false,
"barRadius": 4,
"showLegend": true,
"showTooltip": true,
"animate": true,
"showGrid": true,
"showYAxis": true,
"yAxisFormat": "auto"
},
{
"type": "Separator",
"orientation": "horizontal"
},
{
"type": "DataTable",
"columns": [
{
"key": "account",
"header": "Account",
"sortable": true
},
{
"key": "value",
"header": "Value",
"sortable": true
},
{
"key": "stage",
"header": "Stage",
"sortable": false
}
],
"rows": [
{
"account": "Acme Corp",
"value": "$84,000",
"stage": {
"type": "Badge",
"label": "Won",
"variant": "success"
}
},
{
"account": "Globex Inc",
"value": "$52,000",
"stage": {
"type": "Badge",
"label": "Negotiation",
"variant": "secondary"
}
},
{
"account": "Initech",
"value": "$31,500",
"stage": {
"type": "Badge",
"label": "Proposal",
"variant": "secondary"
}
},
{
"account": "Wayne Enterprises",
"value": "$45,000",
"stage": {
"type": "Badge",
"label": "Lost",
"variant": "destructive"
}
}
],
"search": false,
"paginated": false,
"pageSize": 10
}
]
}
]
}
}</script>
</body>
</html>

View file

@ -1,90 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "gap-4 p-6",
"type": "Column",
"children": [
{
"type": "DataTable",
"columns": [
{
"key": "name",
"header": "Name",
"sortable": true
},
{
"key": "role",
"header": "Role",
"sortable": true
},
{
"key": "dept",
"header": "Dept",
"sortable": true
}
],
"rows": [
{
"name": "Alice Chen",
"role": "Staff Engineer",
"dept": "Platform"
},
{
"name": "Bob Martinez",
"role": "Lead Designer",
"dept": "Design"
},
{
"name": "Carol Johnson",
"role": "Senior Engineer",
"dept": "Platform"
},
{
"name": "David Kim",
"role": "Product Manager",
"dept": "Product"
},
{
"name": "Eva Mueller",
"role": "Engineer",
"dept": "Platform"
},
{
"name": "Frank Lee",
"role": "Data Scientist",
"dept": "ML"
},
{
"name": "Grace Park",
"role": "Eng Manager",
"dept": "Platform"
}
],
"search": true,
"paginated": false,
"pageSize": 10
}
]
}
]
}
}</script>
</body>
</html>

File diff suppressed because it is too large Load diff

View file

@ -1,60 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "p-6",
"type": "Column",
"children": [
{
"type": "PieChart",
"data": [
{
"category": "Bug",
"count": 42
},
{
"category": "Feature",
"count": 28
},
{
"category": "Docs",
"count": 15
},
{
"category": "Infra",
"count": 10
}
],
"dataKey": "count",
"nameKey": "category",
"height": 240,
"innerRadius": 50,
"showLabel": false,
"paddingAngle": 0,
"showLegend": true,
"showTooltip": true,
"animate": true
}
]
}
]
}
}</script>
</body>
</html>

View file

@ -1,167 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "gap-4 p-6",
"let": {
"data": "{{ region == 'south' ? south : region == 'west' ? west : north }}"
},
"type": "Column",
"children": [
{
"cssClass": "gap-4 items-center",
"type": "Row",
"children": [
{
"cssClass": "w-40",
"name": "region",
"type": "Select",
"size": "default",
"disabled": false,
"required": false,
"invalid": false,
"children": [
{
"type": "SelectOption",
"value": "north",
"label": "North",
"selected": false,
"disabled": false
},
{
"type": "SelectOption",
"value": "south",
"label": "South",
"selected": false,
"disabled": false
},
{
"type": "SelectOption",
"value": "west",
"label": "West",
"selected": false,
"disabled": false
}
]
},
{
"cssClass": "ml-auto",
"name": "show_target",
"value": false,
"type": "Switch",
"size": "default",
"disabled": false,
"required": false
},
{
"cssClass": "text-sm text-muted-foreground",
"content": "Show target",
"type": "Text"
}
]
},
{
"type": "BarChart",
"data": "{{ data }}",
"series": [
{
"dataKey": "sales",
"label": "Sales"
}
],
"xAxis": "month",
"height": 200,
"stacked": false,
"horizontal": false,
"barRadius": 4,
"showLegend": true,
"showTooltip": true,
"animate": true,
"showGrid": true,
"showYAxis": true,
"yAxisFormat": "auto"
},
{
"type": "Condition",
"cases": [
{
"when": "{{ show_target }}",
"children": [
{
"type": "Metric",
"label": "Q1 Target",
"value": "$75,000"
}
]
}
]
}
]
}
]
},
"state": {
"region": "north",
"north": [
{
"month": "Jan",
"sales": 22000
},
{
"month": "Feb",
"sales": 25500
},
{
"month": "Mar",
"sales": 24200
}
],
"south": [
{
"month": "Jan",
"sales": 5800
},
{
"month": "Feb",
"sales": 6400
},
{
"month": "Mar",
"sales": 5600
}
],
"west": [
{
"month": "Jan",
"sales": 6000
},
{
"month": "Feb",
"sales": 6000
},
{
"month": "Mar",
"sales": 5600
}
],
"show_target": true
}
}</script>
</body>
</html>

View file

@ -1,237 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "gap-4 p-6",
"type": "Column",
"children": [
{
"cssClass": "gap-4",
"type": "Grid",
"columnTemplate": "1fr 2fr",
"children": [
{
"type": "PieChart",
"data": [
{
"office": "San Francisco",
"count": 3
},
{
"office": "New York",
"count": 2
},
{
"office": "London",
"count": 1
},
{
"office": "Berlin",
"count": 1
}
],
"dataKey": "count",
"nameKey": "office",
"height": 300,
"innerRadius": 0,
"showLabel": false,
"paddingAngle": 0,
"showLegend": true,
"showTooltip": true,
"animate": true
},
{
"type": "DataTable",
"columns": [
{
"key": "name",
"header": "Name",
"sortable": true
},
{
"key": "role",
"header": "Role",
"sortable": true
},
{
"key": "office",
"header": "Office",
"sortable": true
}
],
"rows": [
{
"name": "Alice Chen",
"role": "Staff Engineer",
"office": "San Francisco",
"email": "alice@company.com",
"projects": 3
},
{
"name": "Bob Martinez",
"role": "Lead Designer",
"office": "New York",
"email": "bob@company.com",
"projects": 5
},
{
"name": "Carol Johnson",
"role": "Senior Engineer",
"office": "London",
"email": "carol@company.com",
"projects": 2
},
{
"name": "David Kim",
"role": "Product Manager",
"office": "San Francisco",
"email": "david@company.com",
"projects": 7
},
{
"name": "Eva Mueller",
"role": "Engineer",
"office": "Berlin",
"email": "eva@company.com",
"projects": 1
},
{
"name": "Frank Lee",
"role": "Data Scientist",
"office": "San Francisco",
"email": "frank@company.com",
"projects": 4
},
{
"name": "Grace Park",
"role": "Engineering Manager",
"office": "New York",
"email": "grace@company.com",
"projects": 6
}
],
"search": true,
"paginated": false,
"pageSize": 10,
"onRowClick": {
"action": "setState",
"key": "selected",
"value": "{{ $event }}"
}
}
]
},
{
"type": "Condition",
"cases": [
{
"when": "{{ selected }}",
"children": [
{
"type": "Card",
"children": [
{
"type": "CardHeader",
"children": [
{
"cssClass": "gap-2 items-center",
"type": "Row",
"children": [
{
"content": "{{ selected.name }}",
"type": "H3"
},
{
"type": "Badge",
"label": "{{ selected.office }}",
"variant": "default"
}
]
}
]
},
{
"type": "CardContent",
"children": [
{
"cssClass": "gap-4 grid-cols-3",
"type": "Grid",
"children": [
{
"cssClass": "gap-0",
"type": "Column",
"children": [
{
"content": "Role",
"type": "Small"
},
{
"content": "{{ selected.role }}",
"type": "Text"
}
]
},
{
"cssClass": "gap-0",
"type": "Column",
"children": [
{
"content": "Email",
"type": "Small"
},
{
"content": "{{ selected.email }}",
"type": "Text"
}
]
},
{
"cssClass": "gap-0",
"type": "Column",
"children": [
{
"content": "Active Projects",
"type": "Small"
},
{
"content": "{{ selected.projects }}",
"type": "Text"
}
]
}
]
}
]
}
]
}
]
}
]
}
]
}
]
},
"state": {
"selected": null
}
}</script>
</body>
</html>

View file

@ -1,127 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<title>Prefab</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.css">
<script type="module" crossorigin src="https://cdn.jsdelivr.net/npm/@prefecthq/prefab-ui@0.19.0/dist/app/renderer.js"></script>
</head>
<body>
<div id="root" style="max-width:64rem;margin:0 auto;padding:2rem"></div>
<script id="prefab:initial-data" type="application/json">{
"$prefab": {
"version": "0.2"
},
"view": {
"cssClass": "pf-app-root",
"type": "Div",
"children": [
{
"cssClass": "gap-4 p-6",
"type": "Column",
"children": [
{
"cssClass": "gap-4",
"type": "Grid",
"columnTemplate": "1fr 2fr",
"children": [
{
"type": "PieChart",
"data": [
{
"office": "San Francisco",
"count": 3
},
{
"office": "New York",
"count": 2
},
{
"office": "London",
"count": 1
},
{
"office": "Berlin",
"count": 1
}
],
"dataKey": "count",
"nameKey": "office",
"height": 300,
"innerRadius": 0,
"showLabel": false,
"paddingAngle": 0,
"showLegend": true,
"showTooltip": true,
"animate": true
},
{
"type": "DataTable",
"columns": [
{
"key": "name",
"header": "Name",
"sortable": true
},
{
"key": "role",
"header": "Role",
"sortable": true
},
{
"key": "office",
"header": "Office",
"sortable": true
}
],
"rows": [
{
"name": "Alice Chen",
"role": "Staff Engineer",
"office": "San Francisco"
},
{
"name": "Bob Martinez",
"role": "Lead Designer",
"office": "New York"
},
{
"name": "Carol Johnson",
"role": "Senior Engineer",
"office": "London"
},
{
"name": "David Kim",
"role": "Product Manager",
"office": "San Francisco"
},
{
"name": "Eva Mueller",
"role": "Engineer",
"office": "Berlin"
},
{
"name": "Frank Lee",
"role": "Data Scientist",
"office": "San Francisco"
},
{
"name": "Grace Park",
"role": "Engineering Manager",
"office": "New York"
}
],
"search": true,
"paginated": false,
"pageSize": 10
}
]
}
]
}
]
}
}</script>
</body>
</html>

View file

@ -54,6 +54,8 @@ fastmcp dev apps server.py:mcp --mcp-port 9000 --dev-port 9090 --no-reload
| MCP Port | `--mcp-port` | `8000` | Port for your MCP server |
| Dev Port | `--dev-port` | `8080` | Port for the dev UI |
| Auto-Reload | `--reload` / `--no-reload` | On | Watch files and restart the server on changes |
| Host | `--host` | `127.0.0.1` | Interface for both local servers to bind |
| Log Panel | `--log-panel` / `--no-log-panel` | On | Show or hide the log panel in the dev UI |
## Multiple tools

474
docs/apps/fastmcp-app.mdx Normal file
View file

@ -0,0 +1,474 @@
---
title: FastMCPApp
sidebarTitle: FastMCPApp
description: Wire an interactive UI to backend tools with managed visibility and composition safety.
icon: puzzle-piece
tag: NEW
---
import { VersionBadge } from '/snippets/version-badge.mdx'
import PrefabPinWarning from '/snippets/prefab-pin-warning.mdx'
import { PrefabDemoFrame } from '/snippets/prefab-demo-frame.mdx'
<VersionBadge version="3.2.0" />
<PrefabPinWarning />
<PrefabDemoFrame demo="contacts" height="650px" title="Contacts app demo" />
Search a list, fill out a form, click save, the list updates. That pattern — UI that reads and writes data on the server — needs two things: backend tools that actually do the work, and a way to call them from the UI. `FastMCPApp` handles the wiring.
You'll build up to the contacts app above by the end of this page. Let's start with something smaller.
## A minimal interactive app
The smallest interactive app: a form that saves a note, and a list that updates when the user submits.
```python
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge, Button, Column, ForEach, Form, Heading,
Input, Row, Separator, Text,
)
from prefab_ui.rx import RESULT
from fastmcp import FastMCP, FastMCPApp
app = FastMCPApp("Notes")
notes_db: list[dict] = []
@app.tool()
def add_note(title: str, body: str) -> list[dict]:
"""Save a note and return all notes."""
notes_db.append({"title": title, "body": body})
return list(notes_db)
@app.ui()
def notes_app() -> PrefabApp:
"""Open the notes app."""
with Column(gap=6, css_class="p-6") as view:
Heading("Notes")
with ForEach("notes") as note:
with Row(gap=2, align="center"):
Text(note.title, css_class="font-semibold")
Badge(note.body)
Separator()
with Form(
on_submit=CallTool(
"add_note",
on_success=[
SetState("notes", RESULT),
ShowToast("Note saved!", variant="success"),
],
on_error=ShowToast("Failed to save", variant="error"),
)
):
Input(name="title", label="Title", required=True)
Input(name="body", label="Body", required=True)
Button("Add Note")
return PrefabApp(view=view, state={"notes": list(notes_db)})
mcp = FastMCP("Notes Server", providers=[app])
```
The model sees one tool: `notes_app`. Calling it opens the UI. When the user submits the form, `CallTool("add_note")` fires, the server saves the note, returns the updated list, and `SetState("notes", RESULT)` writes that list back into state. `ForEach("notes")` re-renders. The model never sees `add_note` — it's UI-only.
## Why not just `@mcp.tool(app=True)`?
A fair question. Any [Interactive Tool](/apps/prefab) can call a server tool — there's nothing stopping you from putting `CallTool("add_note")` inside a regular `@mcp.tool(app=True)`. It works for one or two tools. Things get harder once the app grows:
- Which tools should the model see, and which are UI-only?
- What happens to `CallTool("add_note")` when you mount this server under a namespace and the tool becomes `notes_add_note`?
- How do you keep it all wired correctly as you compose servers?
`FastMCPApp` owns these concerns. Entry points register as model-visible, backend tools register as UI-only, and hosts act on those declarations to decide what the model sees.
Composition is handled by never writing the name down. `CallTool` takes a function reference, and FastMCP resolves it when the UI is serialized — to whatever that tool is actually called by then. Mount the server under a namespace and the button calls `notes_add_note`; put a gateway in front and it calls whatever the gateway lists. Since you never wrote a name, renaming cannot break it. [The architecture page](/apps/architecture) covers how that resolution works.
The one rule that comes with this: **an app name must be unique within a server.** Composing the same app twice breaks its UI — two copies of `FastMCPApp("notes")` are indistinguishable no matter what namespaces you mount them under, so FastMCP declines to bind rather than picking one. Name apps for what they serve: `FastMCPApp("notes-acme")` and `FastMCPApp("notes-globex")`. [The architecture page](/apps/architecture) explains why identity works this way.
The rest of this page covers each piece in turn.
## `@app.ui()` — entry points
Entry points are what the model sees. They return a `PrefabApp` and default to `visibility=["model"]`, showing up in the LLM tool list but not callable from within the UI.
```python
@app.ui()
def dashboard() -> PrefabApp:
"""The model calls this to open the dashboard."""
with Column(gap=4, css_class="p-6") as view:
Heading("Dashboard")
...
return PrefabApp(view=view)
```
`@app.ui()` supports the same options as `@mcp.tool`: `name`, `description`, `title`, `tags`, `icons`, `auth`, and `timeout`.
## `@app.tool()` — backend tools
Backend tools do the work. By default they're visible only to the UI (`visibility=["app"]`), not the model.
```python
@app.tool()
def save_contact(name: str, email: str) -> list[dict]:
"""Save a contact and return the updated list."""
db.append({"name": name, "email": email})
return list(db)
```
If you want a tool callable by both the model and the UI, pass `model=True`:
```python
@app.tool(model=True)
def list_contacts() -> list[dict]:
"""Both the model and the UI can call this."""
return list(db)
```
Backend tools support `name`, `description`, `auth`, and `timeout`.
## `CallTool` — UI → backend
`CallTool` is how the UI invokes a backend tool. Pass the tool's name (or a direct function reference):
```python
from prefab_ui.actions.mcp import CallTool
CallTool("save_contact", arguments={"name": "Alice", "email": "alice@example.com"})
# Or a function reference — resolves to a stable global key
CallTool(save_contact, arguments={...})
```
Arguments can reference state with `Rx`:
```python
from prefab_ui.rx import STATE
CallTool("search", arguments={"query": STATE.search_term})
```
### Handling results
Server calls are async. Use `on_success` and `on_error` callbacks:
```python
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.rx import RESULT
CallTool(
"save_contact",
on_success=[
SetState("contacts", RESULT),
ShowToast("Saved!", variant="success"),
],
on_error=ShowToast("Something went wrong", variant="error"),
)
```
`RESULT` is a reactive reference to the tool's return value, available inside `on_success`. `ERROR` (from `prefab_ui.rx`) is the counterpart inside `on_error`. Callbacks can be a single action or a list; they execute in order and short-circuit on error.
### `result_key` shorthand
When a tool's return value should replace a state key, use `result_key`:
```python
CallTool("list_contacts", result_key="contacts")
# same as:
CallTool("list_contacts", on_success=SetState("contacts", RESULT))
```
## Actions
`CallTool` is one of several actions. Actions attach to handlers like `on_click`, `on_submit`, and `on_change`.
Client-side actions run instantly in the browser, no server round-trip:
```python
from prefab_ui.actions import SetState, ToggleState, AppendState, PopState, ShowToast
SetState("count", 42)
ToggleState("expanded")
AppendState("items", {"name": "New Item"})
PopState("items", 0)
ShowToast("Done!", variant="success")
```
Pass a list to chain actions:
```python
Button(
"Reset",
on_click=[
SetState("query", ""),
SetState("results", []),
ShowToast("Cleared"),
],
)
```
### Loading states
A common pattern: disable a button and show a spinner while a call is in flight.
```python
from prefab_ui.rx import Rx
saving = Rx("saving")
Button(
saving.then("Saving...", "Save"),
disabled=saving,
on_click=[
SetState("saving", True),
CallTool(
"save_data",
on_success=[
SetState("saving", False),
SetState("result", RESULT),
ShowToast("Saved!", variant="success"),
],
on_error=[
SetState("saving", False),
ShowToast("Failed", variant="error"),
],
),
],
)
# PrefabApp(view=view, state={"saving": False, ...})
```
## Forms
Forms collect input and submit it to a tool. When submitted, named input values become the tool's arguments.
### Manual forms
```python
from prefab_ui.components import Form, Input, Select, SelectOption, Textarea, Button
with Form(
on_submit=CallTool(
"create_ticket",
on_success=ShowToast("Ticket created!", variant="success"),
)
):
Input(name="title", label="Title", required=True)
with Select(name="priority", label="Priority"):
SelectOption("Low", value="low")
SelectOption("Medium", value="medium")
SelectOption("High", value="high")
Textarea(name="description", label="Description")
Button("Create Ticket")
```
On submit, `CallTool` receives `{"title": ..., "priority": ..., "description": ...}`.
### Forms from Pydantic models
For structured input, `Form.from_model()` generates the whole form — inputs, labels, validation:
```python
from typing import Literal
from pydantic import BaseModel, Field
class BugReport(BaseModel):
title: str = Field(title="Bug Title")
severity: Literal["low", "medium", "high", "critical"] = Field(
title="Severity", default="medium"
)
description: str = Field(title="Description")
@app.ui()
def report_bug() -> PrefabApp:
with Column(gap=4, css_class="p-6") as view:
Heading("Report a Bug")
Form.from_model(
BugReport,
on_submit=CallTool(
"create_bug",
on_success=ShowToast("Bug filed!", variant="success"),
),
)
return PrefabApp(view=view)
@app.tool()
def create_bug(data: BugReport) -> str:
return f"Created: {data.title}"
```
`str` becomes a text input, `Literal` becomes a select, `bool` becomes a checkbox. Field titles and defaults are respected.
## Composition and namespacing
The reason `FastMCPApp` exists — and why you'd pick it over plain `@mcp.tool(app=True)` with string-based `CallTool` — is composition safety.
When you mount a server under a namespace, tool names get prefixed:
```python
platform = FastMCP("Platform")
platform.mount("contacts", contacts_server)
# "save_contact" becomes "contacts_save_contact"
```
`CallTool("save_contact")` would now be broken. But `CallTool(save_contact)` with a function reference resolves to a globally stable identifier that bypasses the namespace. Your app works the same whether standalone or mounted.
### Mounting
`FastMCPApp` is a Provider. Add it to a server with `providers=` or `add_provider`:
```python
mcp = FastMCP("Platform", providers=[app])
# or
mcp = FastMCP("Platform")
mcp.add_provider(app)
```
Multiple apps can coexist; each gets its own global keys, so there's no collision even if two apps have a tool named `save`.
```python
mcp = FastMCP("Platform", providers=[contacts_app, inventory_app, billing_app])
```
### Running standalone
For development, `FastMCPApp` has a `run()` shortcut that wraps itself in a temporary `FastMCP` server:
```python
app = FastMCPApp("Contacts")
# ... register tools ...
if __name__ == "__main__":
app.run()
```
## A full example: contact manager
This brings everything together — entry point, backend tools, Pydantic form, manual form, state, actions, and multi-visibility.
```python expandable
from __future__ import annotations
from typing import Literal
from prefab_ui.actions import SetState, ShowToast
from prefab_ui.actions.mcp import CallTool
from prefab_ui.app import PrefabApp
from prefab_ui.components import (
Badge, Button, Column, ForEach, Form,
Heading, Input, Muted, Row, Separator, Text,
)
from prefab_ui.rx import RESULT, Rx
from pydantic import BaseModel, Field
from fastmcp import FastMCP, FastMCPApp
contacts_db: list[dict] = [
{"name": "Arthur Dent", "email": "arthur@earth.com", "category": "Customer"},
{"name": "Ford Prefect", "email": "ford@betelgeuse.org", "category": "Partner"},
]
class ContactModel(BaseModel):
name: str = Field(title="Full Name", min_length=1)
email: str = Field(title="Email")
category: Literal["Customer", "Vendor", "Partner", "Other"] = "Other"
app = FastMCPApp("Contacts")
@app.tool()
def save_contact(data: ContactModel) -> list[dict]:
"""Save a new contact and return the updated list."""
contacts_db.append(data.model_dump())
return list(contacts_db)
@app.tool()
def search_contacts(query: str) -> list[dict]:
"""Filter contacts by name or email."""
q = query.lower()
return [
c for c in contacts_db
if q in c["name"].lower() or q in c["email"].lower()
]
@app.tool(model=True)
def list_contacts() -> list[dict]:
"""Return all contacts. Visible to both the model and the UI."""
return list(contacts_db)
@app.ui()
def contact_manager() -> PrefabApp:
"""Open the contact manager."""
with Column(gap=6, css_class="p-6") as view:
Heading("Contacts")
with ForEach("contacts") as contact:
with Row(gap=2, align="center"):
Text(contact.name, css_class="font-medium")
Muted(contact.email)
Badge(contact.category)
Separator()
Heading("Add Contact", level=3)
Form.from_model(
ContactModel,
on_submit=CallTool(
"save_contact",
on_success=[
SetState("contacts", RESULT),
ShowToast("Contact saved!", variant="success"),
],
on_error=ShowToast("Failed to save", variant="error"),
),
)
Separator()
Heading("Search", level=3)
with Form(
on_submit=CallTool(
"search_contacts",
arguments={"query": Rx("query")},
on_success=SetState("contacts", RESULT),
)
):
Input(name="query", placeholder="Search by name or email...")
Button("Search")
return PrefabApp(view=view, state={"contacts": list(contacts_db)})
mcp = FastMCP("Contacts Server", providers=[app])
if __name__ == "__main__":
mcp.run()
```
Also available as a runnable server at `examples/apps/contacts/contacts_server.py`.
## Next steps
- **[Interactive Tools](/apps/prefab)** — the building blocks: charts, tables, dashboards, reactive state
- **[Examples](/apps/examples)** — complete working servers
- **[Development](/apps/development)** — preview and test app tools locally
- **[Prefab UI docs](https://prefab.prefect.io)** — full component reference

View file

@ -43,7 +43,7 @@ def chart_view() -> str:
## AppConfig
`AppConfig` controls how a tool or resource participates in the Apps extension. Import it from `fastmcp.server.apps`:
`AppConfig` controls how a tool or resource participates in the Apps extension. Import it from `fastmcp.apps`:
```python
from fastmcp.apps import AppConfig
@ -70,11 +70,15 @@ def my_tool() -> str:
The `visibility` field controls where a tool appears:
- `["model"]` — visible to the LLM (the default behavior)
- `["app"]` — only callable from within the app UI, hidden from the LLM
- `["app"]` — callable from within the app UI, kept out of the LLM's tool list
- `["model", "app"]` — both
This is useful when you have tools that only make sense as part of the app's interactive flow, not as standalone LLM actions.
Visibility is a declaration, and on `tools/list` the host does the filtering — the division the MCP Apps specification defines. Every tool is advertised carrying its `visibility` metadata, which is also what lets a proxy or gateway forward it: an intermediary can only route to a tool it can see.
That division assumes a host stands between the server and the model. Where one doesn't, FastMCP applies the declaration itself. [Tool search](/servers/transforms/tool-search) and code mode reach the model as ordinary tool output rather than as an advertised listing, and their call-tool proxies execute a name the model supplies — nothing downstream can filter either, so app-only tools are excluded from both. The app's own UI still reaches its backends, because a UI calling by identity is not the model.
```python
@mcp.tool(
app=AppConfig(
@ -212,11 +216,11 @@ import base64
import io
import qrcode
from mcp import types
from fastmcp import FastMCP
from fastmcp.apps import AppConfig, ResourceCSP
from fastmcp.tools import ToolResult
from mcp.types import ImageContent
mcp = FastMCP("QR Code Server")
@ -236,7 +240,7 @@ def generate_qr(text: str = "https://gofastmcp.com") -> ToolResult:
b64 = base64.b64encode(buffer.getvalue()).decode()
return ToolResult(
content=[types.ImageContent(type="image", data=b64, mimeType="image/png")]
content=[ImageContent(type="image", data=b64, mime_type="image/png")]
)

View file

@ -8,6 +8,7 @@ mode: center
import { VersionBadge } from '/snippets/version-badge.mdx'
import PrefabPinWarning from '/snippets/prefab-pin-warning.mdx'
import { PrefabDemoFrame } from '/snippets/prefab-demo-frame.mdx'
<VersionBadge version="3.0.0" />
@ -21,7 +22,7 @@ A FastMCP app is a tool that returns an interactive UI instead of text. When the
maskImage: 'linear-gradient(to bottom, black 75%, transparent)',
WebkitMaskImage: 'linear-gradient(to bottom, black 75%, transparent)',
}}>
<iframe src="/apps/demos/hitchhikers.html" style={{width:"100%", height:"2000px", border:"none", borderRadius:"8px", background:"transparent"}} frameBorder="0" scrolling="no" allowtransparency="true"></iframe>
<PrefabDemoFrame demo="hitchhikers" height="2000px" title="Prefab showcase demo" />
</div>
The dashboard above is a [Prefab](https://prefab.prefect.io) showcase — a taste of what you can deliver from a FastMCP tool. Every card, chart, slider, dialog, and carousel is a Python component. Build a composition like this, add `@mcp.tool(app=True)`, and the host renders it inside the conversation.
@ -48,7 +49,7 @@ def team_directory() -> DataTable:
return DataTable(columns=[...], rows=employees, search=True)
```
### [FastMCPApp](/apps/interactive-apps) — when the UI calls back to the server
### [FastMCPApp](/apps/fastmcp-app) — when the UI calls back to the server
Forms that save data, buttons that trigger backend work, search that hits a database. `FastMCPApp` manages the wiring between UI actions and backend tools, with stable tool identifiers that survive server composition.

View file

@ -8,12 +8,13 @@ tag: NEW
import { VersionBadge } from '/snippets/version-badge.mdx'
import PrefabPinWarning from '/snippets/prefab-pin-warning.mdx'
import { PrefabDemoFrame } from '/snippets/prefab-demo-frame.mdx'
<VersionBadge version="3.1.0" />
<PrefabPinWarning />
<iframe src="/apps/demos/dashboard.html" style={{width:"100%", height:"680px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="dashboard" height="680px" title="Sales dashboard demo" />
Believe it or not, that dashboard is a FastMCP tool. The chart has tooltips. The table is sortable. The badges are styled by deal stage. The whole thing is about 40 lines of Python, and the user sees it right inside their conversation instead of a wall of JSON.
@ -23,7 +24,7 @@ The pattern behind every example on this page is the same: add `app=True` to you
Most tools return data the user wants to explore. A `DataTable` is often the smallest useful upgrade — your data goes from a JSON blob to a searchable, sortable table:
<iframe src="/apps/demos/data-table.html" style={{width:"100%", height:"530px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="data-table" height="530px" title="Data table demo" />
```python
from prefab_ui.components import DataTable, DataTableColumn
@ -62,7 +63,7 @@ That's it. Add `app=True`, return a Prefab component instead of raw dicts. FastM
When numbers tell a better story as a visual, swap in a chart. The API is the same: pass your data as a list of dicts, tell the chart which keys to plot.
<iframe src="/apps/demos/bar-chart.html" style={{width:"100%", height:"430px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="bar-chart" height="430px" title="Bar chart demo" />
```python
@mcp.tool(app=True)
@ -88,7 +89,7 @@ def quarterly_revenue(year: int) -> BarChart:
Each `ChartSeries` plots a different key from the data. `BarChart`, `LineChart`, `AreaChart`, `PieChart`, `RadarChart`, and `RadialChart` all follow the same pattern. Hover over the bars to see tooltips.
<iframe src="/apps/demos/pie-chart.html" style={{width:"100%", height:"410px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="pie-chart" height="410px" title="Pie chart demo" />
```python
@mcp.tool(app=True)
@ -116,7 +117,7 @@ See the [Prefab chart docs](https://prefab.prefect.io/docs/components) for stack
Tables and charts are useful on their own, but the real power comes from composing them. `Column` stacks children vertically, `Row` lays them out side by side, and `with` blocks establish nesting — the indentation is the layout.
<iframe src="/apps/demos/dashboard.html" style={{width:"100%", height:"680px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="dashboard" height="680px" title="Sales dashboard demo" />
```python expandable
@mcp.tool(app=True)
@ -184,7 +185,7 @@ Notice how `Badge` components can be placed inside table cells — any Prefab co
Everything above renders once from the data your Python provides. But interactive tools can also respond to user input in real time, without any server round-trips. Prefab's state system lets components read and write client-side values, so the UI updates instantly as the user interacts with it.
<iframe src="/apps/demos/reactive.html" style={{width:"100%", height:"500px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="reactive" height="500px" title="Reactive sales demo" />
Try switching regions in the dropdown, and toggling the switch on and off.
@ -288,7 +289,7 @@ The user sees the chart. The model sees the summary.
## Next steps
- **[FastMCPApp](/apps/interactive-apps)** — when your UI needs to call backend tools (forms, search, CRUD)
- **[FastMCPApp](/apps/fastmcp-app)** — when your UI needs to call backend tools (forms, search, CRUD)
- **[Generative UI](/apps/generative)** — let the LLM design the UI at runtime
- **[Custom HTML](/apps/low-level)** — when Prefab isn't enough (maps, 3D, your own framework)
- **[Examples](/apps/examples)** — complete working servers you can run today

View file

@ -59,16 +59,24 @@ This works with **stdio**, **SSE**, and **stateful HTTP** transports, where sess
In **stateless HTTP** mode, each request creates a new session object with a new ID. Files stored during one request (e.g. the UI upload) will be invisible to the next request (e.g. the LLM calling `list_files`). You **must** override `_get_scope_key` to use a stable identifier like a user ID from your auth token.
</Warning>
For stateless deployments, override `_get_scope_key` to return a stable identifier. For example, to scope files by authenticated user:
For stateless deployments, override `_get_scope_key` to return a stable identifier. To scope files by authenticated user, read the caller from `get_access_token()`.
Reject the request when there is no subject to key on. `get_access_token()` returns `None` on an unauthenticated request, and `subject` is optional even on a valid token, since not every verifier populates it. Returning a fallback in either case would put every such caller in one shared bucket, so they would see each other's uploads.
```python
from fastmcp.apps.file_upload import FileUpload
from fastmcp.server.dependencies import get_access_token
class UserScopedUpload(FileUpload):
def _get_scope_key(self, ctx):
return ctx.access_token["sub"]
token = get_access_token()
if token is None or not token.subject:
raise ValueError("File scoping requires an authenticated user with a subject")
return token.subject
```
If your provider carries the user identity in a different claim, read it from `token.claims` and validate it the same way.
For process-wide shared storage (all users see all files):
```python
@ -85,10 +93,17 @@ The default implementation stores files in memory for the lifetime of the server
import base64
from fastmcp.apps.file_upload import FileUpload
from fastmcp.server.dependencies import get_access_token
class S3Upload(FileUpload):
def _get_scope_key(self, ctx):
token = get_access_token()
if token is None or not token.subject:
raise ValueError("File scoping requires an authenticated user with a subject")
return token.subject
def on_store(self, files, ctx):
user_id = ctx.access_token["sub"]
user_id = self._get_scope_key(ctx)
for f in files:
s3.put_object(
Bucket="uploads",
@ -98,7 +113,7 @@ class S3Upload(FileUpload):
return self.on_list(ctx)
def on_list(self, ctx):
user_id = ctx.access_token["sub"]
user_id = self._get_scope_key(ctx)
objects = s3.list_objects(Bucket="uploads", Prefix=f"{user_id}/")
return [
{
@ -112,7 +127,7 @@ class S3Upload(FileUpload):
]
def on_read(self, name, ctx):
user_id = ctx.access_token["sub"]
user_id = self._get_scope_key(ctx)
obj = s3.get_object(Bucket="uploads", Key=f"{user_id}/{name}")
content = obj["Body"].read()
return {

View file

@ -7,12 +7,13 @@ tag: NEW
---
import { VersionBadge } from '/snippets/version-badge.mdx'
import { PrefabDemoFrame } from '/snippets/prefab-demo-frame.mdx'
<VersionBadge version="3.2.0" />
By the end of this page, you'll have a working tool that returns this:
<iframe src="/apps/demos/team-directory.html" style={{width:"100%", height:"545px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="team-directory" height="545px" title="Team directory demo" />
A pie chart the user can hover, a table they can sort and search — and a single Python tool.
@ -103,7 +104,7 @@ The UI above renders once from your Python. Prefab apps can also respond to user
Click a row in the demo below to see a detail card appear:
<iframe src="/apps/demos/team-directory-reactive.html" style={{width:"100%", height:"675px", border:"none", overflow:"hidden", borderRadius:"8px"}} frameBorder="0" scrolling="no"></iframe>
<PrefabDemoFrame demo="team-directory-reactive" height="675px" title="Reactive team directory demo" />
Add a few imports, give each member a couple more fields, wire up a click handler, and render a detail card when something's selected:
@ -192,5 +193,5 @@ The `state={"selected": None}` dict on `PrefabApp` sets the initial value. Every
You've built a tool that returns an interactive, reactive UI. This pattern covers a huge range of use cases: build a visualization, return it, and the user gets it rendered right in the conversation.
- **[Interactive Tools](/apps/prefab)** — charts, tables, dashboards, reactive state, with live demos
- **[FastMCPApp](/apps/interactive-apps)** — when the UI needs to call back to your server (forms, search, CRUD)
- **[FastMCPApp](/apps/fastmcp-app)** — when the UI needs to call back to your server (forms, search, CRUD)
- **[Examples](/apps/examples)** — complete working servers you can run today

View file

@ -5,6 +5,898 @@ 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)**
FastMCP 4 makes stateful MCP applications work on the sessionless `2026-07-28` protocol while one deployment continues serving handshake-era clients. Tools can ask follow-up questions across requests, preserve authenticated user state, and move long-running work into background tasks without sticky sessions. Protocol extensions and enterprise identity become first-class surfaces, and most FastMCP 3 servers upgrade unchanged even though MCP Python SDK v2 rewrote the engine underneath them. Server-initiated sampling and roots are removed from the server API; the [upgrade guide](/getting-started/upgrading/from-fastmcp-3) covers their replacements.
### New Features 🎉
* Migrate to MCP Python SDK v2 by [@jlowin](https://github.com/jlowin) in [#4437](https://github.com/PrefectHQ/fastmcp/pull/4437)
* Teach fastmcp.Client the modern protocol: mode negotiation, MRTR driver, response cache by [@jlowin](https://github.com/jlowin) in [#4450](https://github.com/PrefectHQ/fastmcp/pull/4450)
* Forward-port Hugging Face auth provider by [@jlowin](https://github.com/jlowin) in [#4475](https://github.com/PrefectHQ/fastmcp/pull/4475)
* Add server-side identity assertion (SEP-990 ID-JAG) by [@jlowin](https://github.com/jlowin) in [#4483](https://github.com/PrefectHQ/fastmcp/pull/4483)
* Add guard-mode multi-round-trip tools (SEP-2322) by [@jlowin](https://github.com/jlowin) in [#4544](https://github.com/PrefectHQ/fastmcp/pull/4544)
* Add FastMCP-native server extension API (SEP-2133) by [@jlowin](https://github.com/jlowin) in [#4602](https://github.com/PrefectHQ/fastmcp/pull/4602)
* Add stateless session state (UserSession / SessionId) by [@jlowin](https://github.com/jlowin) in [#4604](https://github.com/PrefectHQ/fastmcp/pull/4604)
* Add background tasks via the io.modelcontextprotocol/tasks extension (SEP-2663) by [@jlowin](https://github.com/jlowin) in [#4603](https://github.com/PrefectHQ/fastmcp/pull/4603)
### Breaking Changes ⚠️
* Emit one SERVER span per request and adopt spec-correct error codes by [@jlowin](https://github.com/jlowin) in [#4445](https://github.com/PrefectHQ/fastmcp/pull/4445)
* Remove 3.x deprecated module shims and dead parameters by [@jlowin](https://github.com/jlowin) in [#4447](https://github.com/PrefectHQ/fastmcp/pull/4447)
* Remove 3.0-deprecated FastMCP server methods by [@jlowin](https://github.com/jlowin) in [#4451](https://github.com/PrefectHQ/fastmcp/pull/4451)
* Remove 3.x deprecated parameters and object-mode decorators by [@jlowin](https://github.com/jlowin) in [#4453](https://github.com/PrefectHQ/fastmcp/pull/4453)
* Migrate to MCP SDK v2.0.0b2 (httpx2) by [@jlowin](https://github.com/jlowin) in [#4503](https://github.com/PrefectHQ/fastmcp/pull/4503)
* Fix typos by [@szepeviktor](https://github.com/szepeviktor) in [#4498](https://github.com/PrefectHQ/fastmcp/pull/4498)
* Stop proxies from validating backend results or mutating shared transports by [@jlowin](https://github.com/jlowin) in [#4552](https://github.com/PrefectHQ/fastmcp/pull/4552)
* Surface resource, prompt, and proxy errors on the modern protocol by [@jlowin](https://github.com/jlowin) in [#4579](https://github.com/PrefectHQ/fastmcp/pull/4579)
* Negotiate the best mutual protocol era by default by [@jlowin](https://github.com/jlowin) in [#4572](https://github.com/PrefectHQ/fastmcp/pull/4572)
* Remove server-initiated sampling and roots from the server API by [@jlowin](https://github.com/jlowin) in [#4648](https://github.com/PrefectHQ/fastmcp/pull/4648)
* Remove 3.x-era compatibility shims by [@jlowin](https://github.com/jlowin) in [#4661](https://github.com/PrefectHQ/fastmcp/pull/4661)
### Enhancements ✨
* Deprecate ctx.sample and add clear errors for push features on 2026 connections by [@jlowin](https://github.com/jlowin) in [#4448](https://github.com/PrefectHQ/fastmcp/pull/4448)
* Add server-level cache hints (SEP-2549) by [@jlowin](https://github.com/jlowin) in [#4464](https://github.com/PrefectHQ/fastmcp/pull/4464)
* Add KeyValueResponseCacheStore for distributed client response caching by [@jlowin](https://github.com/jlowin) in [#4479](https://github.com/PrefectHQ/fastmcp/pull/4479)
* Test lifespan fires once per process over HTTP by [@jlowin](https://github.com/jlowin) in [#4480](https://github.com/PrefectHQ/fastmcp/pull/4480)
* Add telemetry off-switch and mcp.protocol.version span attribute by [@jlowin](https://github.com/jlowin) in [#4481](https://github.com/PrefectHQ/fastmcp/pull/4481)
* Trace client task management requests by [@jlowin](https://github.com/jlowin) in [#4525](https://github.com/PrefectHQ/fastmcp/pull/4525)
* Stabilize upgraded ty checks by [@jlowin](https://github.com/jlowin) in [#4526](https://github.com/PrefectHQ/fastmcp/pull/4526)
* Improve DescopeProvider scope discovery and well-known URL support by [@gaokevin1](https://github.com/gaokevin1) in [#4489](https://github.com/PrefectHQ/fastmcp/pull/4489)
* Add examples/ to the ty static-analysis gate by [@jlowin](https://github.com/jlowin) in [#4466](https://github.com/PrefectHQ/fastmcp/pull/4466)
* Expose telemetry attributes on span start by [@zzstoatzz](https://github.com/zzstoatzz) in [#4487](https://github.com/PrefectHQ/fastmcp/pull/4487)
* Fix-issue-4284 : Add Auth0MCPProvider for Auth0 Auth for MCP by [@vijaydeepsinha](https://github.com/vijaydeepsinha) in [#4411](https://github.com/PrefectHQ/fastmcp/pull/4411)
* Run FastMCP middleware for every inbound message by [@jlowin](https://github.com/jlowin) in [#4553](https://github.com/PrefectHQ/fastmcp/pull/4553)
* Add 'prs welcome' label to waive the PR assignment gate by [@jlowin](https://github.com/jlowin) in [#4557](https://github.com/PrefectHQ/fastmcp/pull/4557)
* Rename martian workflows to marvin by [@jlowin](https://github.com/jlowin) in [#4558](https://github.com/PrefectHQ/fastmcp/pull/4558)
* Bump pinned Claude models to current versions by [@jlowin](https://github.com/jlowin) in [#4561](https://github.com/PrefectHQ/fastmcp/pull/4561)
* Make the unit suite fast: in-process HTTP tests, no real sleeps, parallel Windows CI by [@jlowin](https://github.com/jlowin) in [#4554](https://github.com/PrefectHQ/fastmcp/pull/4554)
* Mirror the frontend's protocol era on a proxy's backend connection by [@jlowin](https://github.com/jlowin) in [#4573](https://github.com/PrefectHQ/fastmcp/pull/4573)
* Drop forked client protocol helpers in favor of the SDK's by [@jlowin](https://github.com/jlowin) in [#4574](https://github.com/PrefectHQ/fastmcp/pull/4574)
* Bring the v4 developer notes up to date with what shipped by [@jlowin](https://github.com/jlowin) in [#4581](https://github.com/PrefectHQ/fastmcp/pull/4581)
* Trim fastmcp.types to FastMCP-unique types by [@jlowin](https://github.com/jlowin) in [#4584](https://github.com/PrefectHQ/fastmcp/pull/4584)
* Let a server answer argument-completion requests by [@jlowin](https://github.com/jlowin) in [#4582](https://github.com/PrefectHQ/fastmcp/pull/4582)
* Add machine-to-machine client authentication by [@jlowin](https://github.com/jlowin) in [#4583](https://github.com/PrefectHQ/fastmcp/pull/4583)
* Expose era-neutral client server metadata by [@zzstoatzz](https://github.com/zzstoatzz) in [#4599](https://github.com/PrefectHQ/fastmcp/pull/4599)
* Support routable transport headers for gateways (SEP-2243) by [@jlowin](https://github.com/jlowin) in [#4622](https://github.com/PrefectHQ/fastmcp/pull/4622)
* Emit scope step-up challenges for incremental authorization (SEP-2350) by [@jlowin](https://github.com/jlowin) in [#4623](https://github.com/PrefectHQ/fastmcp/pull/4623)
* Honor OAuth application_type in DCR (SEP-837) by [@jlowin](https://github.com/jlowin) in [#4621](https://github.com/PrefectHQ/fastmcp/pull/4621)
* Drop stale label-noting instructions from CLAUDE.md by [@jlowin](https://github.com/jlowin) in [#4654](https://github.com/PrefectHQ/fastmcp/pull/4654)
* Add require_roles auth check by [@jlowin](https://github.com/jlowin) in [#4656](https://github.com/PrefectHQ/fastmcp/pull/4656)
* Add `valid_scopes` parameter to OIDC proxy valid scopes by [@Educg550](https://github.com/Educg550) in [#4660](https://github.com/PrefectHQ/fastmcp/pull/4660)
* feat: Add telemetry interop mode for FastMCP by [@strawgate](https://github.com/strawgate) in [#4046](https://github.com/PrefectHQ/fastmcp/pull/4046)
* Note that review comment threads should get an acknowledgement by [@jlowin](https://github.com/jlowin) in [#4678](https://github.com/PrefectHQ/fastmcp/pull/4678)
* Soften the review-comment reply guidance by [@jlowin](https://github.com/jlowin) in [#4683](https://github.com/PrefectHQ/fastmcp/pull/4683)
* Resolve review threads on fix, reply on decline by [@jlowin](https://github.com/jlowin) in [#4685](https://github.com/PrefectHQ/fastmcp/pull/4685)
* Move to the stable MCP Python SDK 2.0.0 by [@jlowin](https://github.com/jlowin) in [#4655](https://github.com/PrefectHQ/fastmcp/pull/4655)
### Security 🔒
* Drive the FastMCP lifespan through the SDK session manager by [@jlowin](https://github.com/jlowin) in [#4446](https://github.com/PrefectHQ/fastmcp/pull/4446)
* Route skill file access through SDK path-security primitives by [@jlowin](https://github.com/jlowin) in [#4449](https://github.com/PrefectHQ/fastmcp/pull/4449)
* Screen templated resource parameters for path traversal by default by [@jlowin](https://github.com/jlowin) in [#4482](https://github.com/PrefectHQ/fastmcp/pull/4482)
* [codex] Add OAuthProxy RFC 9207 issuer responses by [@jlowin](https://github.com/jlowin) in [#4438](https://github.com/PrefectHQ/fastmcp/pull/4438)
* Apply app visibility where no host can by [@jlowin](https://github.com/jlowin) in [#4692](https://github.com/PrefectHQ/fastmcp/pull/4692)
### Fixes 🐞
* Capture SharedContext for task-enabled Docket servers by [@jlowin](https://github.com/jlowin) in [#4443](https://github.com/PrefectHQ/fastmcp/pull/4443)
* Fix stale mcp.types imports in examples by [@jlowin](https://github.com/jlowin) in [#4452](https://github.com/PrefectHQ/fastmcp/pull/4452)
* Forward-port HTTP host guard compatibility by [@jlowin](https://github.com/jlowin) in [#4474](https://github.com/PrefectHQ/fastmcp/pull/4474)
* Fix Azure scope fallback by [@zzstoatzz](https://github.com/zzstoatzz) in [#4469](https://github.com/PrefectHQ/fastmcp/pull/4469)
* fix(server): omit ScalarElicitationType wrapper title from elicitation schemas by [@syf2211](https://github.com/syf2211) in [#4502](https://github.com/PrefectHQ/fastmcp/pull/4502)
* Skip unsupported JWKS keys instead of failing the whole key set (#4515) by [@earfman](https://github.com/earfman) in [#4517](https://github.com/PrefectHQ/fastmcp/pull/4517)
* Don't mutate the caller's schema in compress_schema by [@winklemad](https://github.com/winklemad) in [#4492](https://github.com/PrefectHQ/fastmcp/pull/4492)
* Forward upstream instructions through create_proxy by [@verdie-g](https://github.com/verdie-g) in [#4512](https://github.com/PrefectHQ/fastmcp/pull/4512)
* Serialize deep object query parameters by [@jlowin](https://github.com/jlowin) in [#4523](https://github.com/PrefectHQ/fastmcp/pull/4523)
* Reject positional-only tool parameters by [@jlowin](https://github.com/jlowin) in [#4524](https://github.com/PrefectHQ/fastmcp/pull/4524)
* Clarify PR-reopen flow and fix label-race that broke auto-reopen by [@jlowin](https://github.com/jlowin) in [#4518](https://github.com/PrefectHQ/fastmcp/pull/4518)
* Clean up disconnected task sessions by [@jlowin](https://github.com/jlowin) in [#4519](https://github.com/PrefectHQ/fastmcp/pull/4519)
* Handle expired OAuth client registrations by [@jlowin](https://github.com/jlowin) in [#4520](https://github.com/PrefectHQ/fastmcp/pull/4520)
* Fix OAuth request annotation after httpx2 migration by [@jlowin](https://github.com/jlowin) in [#4534](https://github.com/PrefectHQ/fastmcp/pull/4534)
* Fix docs banner contrast by [@jlowin](https://github.com/jlowin) in [#4522](https://github.com/PrefectHQ/fastmcp/pull/4522)
* Preserve component metadata in response cache by [@jlowin](https://github.com/jlowin) in [#4521](https://github.com/PrefectHQ/fastmcp/pull/4521)
* Clean up task sessions on connection exit by [@jlowin](https://github.com/jlowin) in [#4535](https://github.com/PrefectHQ/fastmcp/pull/4535)
* Include scopes in auth challenges by [@jlowin](https://github.com/jlowin) in [#4527](https://github.com/PrefectHQ/fastmcp/pull/4527)
* Make examples/ actually trigger the ty gate by [@jlowin](https://github.com/jlowin) in [#4541](https://github.com/PrefectHQ/fastmcp/pull/4541)
* Add subject field to AccessToken initialization by [@piaudonn](https://github.com/piaudonn) in [#4267](https://github.com/PrefectHQ/fastmcp/pull/4267)
* Restore Mintlify's fixed banner positioning by [@jlowin](https://github.com/jlowin) in [#4542](https://github.com/PrefectHQ/fastmcp/pull/4542)
* Fix #4292: SSRF guard breaks OAuth/JWKS fetches behind a corporate HTTP proxy by [@endofcake](https://github.com/endofcake) in [#4412](https://github.com/PrefectHQ/fastmcp/pull/4412)
* Preserve telemetry attributes when a sampler does not forward them by [@jlowin](https://github.com/jlowin) in [#4539](https://github.com/PrefectHQ/fastmcp/pull/4539)
* Speed up the unit test suite, and fix the task-notification race it surfaced by [@jlowin](https://github.com/jlowin) in [#4550](https://github.com/PrefectHQ/fastmcp/pull/4550)
* Fix label triage applying no labels, and make blocked tool calls fail by [@jlowin](https://github.com/jlowin) in [#4555](https://github.com/PrefectHQ/fastmcp/pull/4555)
* Fix AI workflow allowlists being destroyed by tokenization by [@jlowin](https://github.com/jlowin) in [#4560](https://github.com/PrefectHQ/fastmcp/pull/4560)
* Make transformed tool `required` order deterministic by [@Kludex](https://github.com/Kludex) in [#4564](https://github.com/PrefectHQ/fastmcp/pull/4564)
* Stop gather() from creating coroutines it may never schedule by [@jlowin](https://github.com/jlowin) in [#4559](https://github.com/PrefectHQ/fastmcp/pull/4559)
* Restore upgraded dependency checks by [@zzstoatzz](https://github.com/zzstoatzz) in [#4576](https://github.com/PrefectHQ/fastmcp/pull/4576)
* Fix skill frontmatter parsing with UTF-8 BOM by [@hxaxd](https://github.com/hxaxd) in [#4533](https://github.com/PrefectHQ/fastmcp/pull/4533)
* Fix File helper extension handling by [@VectorPeak](https://github.com/VectorPeak) in [#4531](https://github.com/PrefectHQ/fastmcp/pull/4531)
* Fix percent-encoded skill file names unreadable in resources mode by [@jlowin](https://github.com/jlowin) in [#4590](https://github.com/PrefectHQ/fastmcp/pull/4590)
* Fix flaky stdio crash-recovery tests by [@jlowin](https://github.com/jlowin) in [#4594](https://github.com/PrefectHQ/fastmcp/pull/4594)
* Bridge camelCase ToolAnnotations reads by [@zzstoatzz](https://github.com/zzstoatzz) in [#4597](https://github.com/PrefectHQ/fastmcp/pull/4597)
* Preserve raw CallToolResult tool returns by [@LarryHu0217](https://github.com/LarryHu0217) in [#4587](https://github.com/PrefectHQ/fastmcp/pull/4587)
* Advertise only supported token endpoint auth methods in OAuthProxy metadata by [@jlowin](https://github.com/jlowin) in [#4608](https://github.com/PrefectHQ/fastmcp/pull/4608)
* Fix OAuth proxy override typing by [@zzstoatzz](https://github.com/zzstoatzz) in [#4612](https://github.com/PrefectHQ/fastmcp/pull/4612)
* Pin burner-redis below the Windows-crashing 0.1.7 release by [@jlowin](https://github.com/jlowin) in [#4618](https://github.com/PrefectHQ/fastmcp/pull/4618)
* fix : canonical mime type mapping from formats to remove inconsistency #4627 by [@Aman071106](https://github.com/Aman071106) in [#4628](https://github.com/PrefectHQ/fastmcp/pull/4628)
* fix: accept callable roots handlers by [@ShuyingZhang](https://github.com/ShuyingZhang) in [#4639](https://github.com/PrefectHQ/fastmcp/pull/4639)
* Pass the MCP conformance suite's draft and pending scenarios by [@jlowin](https://github.com/jlowin) in [#4650](https://github.com/PrefectHQ/fastmcp/pull/4650)
* Use issuer_url for OAuth issuer identity by [@jlowin](https://github.com/jlowin) in [#4652](https://github.com/PrefectHQ/fastmcp/pull/4652)
* Fix the ty failure blocking upgrade checks on main by [@jlowin](https://github.com/jlowin) in [#4657](https://github.com/PrefectHQ/fastmcp/pull/4657)
* Bind CIMD assertion audience to the advertised token endpoint by [@jlowin](https://github.com/jlowin) in [#4659](https://github.com/PrefectHQ/fastmcp/pull/4659)
* Record effective scopes on the OAuth transaction by [@jlowin](https://github.com/jlowin) in [#4670](https://github.com/PrefectHQ/fastmcp/pull/4670)
* Copy schemas iteratively so deep nesting still compresses by [@jlowin](https://github.com/jlowin) in [#4671](https://github.com/PrefectHQ/fastmcp/pull/4671)
* Fix OpenAPI allOf reference fields by [@hxaxd](https://github.com/hxaxd) in [#4653](https://github.com/PrefectHQ/fastmcp/pull/4653)
* Flatten OpenAPI discriminator subtypes into request bodies by [@jlowin](https://github.com/jlowin) in [#4677](https://github.com/PrefectHQ/fastmcp/pull/4677)
* Let maintenance releases publish without fastmcp-tasks by [@jlowin](https://github.com/jlowin) in [#4676](https://github.com/PrefectHQ/fastmcp/pull/4676)
* Read CLI-scanned MCP config files as UTF-8 explicitly by [@jlowin](https://github.com/jlowin) in [#4690](https://github.com/PrefectHQ/fastmcp/pull/4690)
* Late-bind app tool names so UIs survive composition by [@jlowin](https://github.com/jlowin) in [#4682](https://github.com/PrefectHQ/fastmcp/pull/4682)
### Docs 📚
* Docs: forward-port v3.4.4 changelog entries by [@jlowin](https://github.com/jlowin) in [#4476](https://github.com/PrefectHQ/fastmcp/pull/4476)
* Document icon theme support by [@jlowin](https://github.com/jlowin) in [#4537](https://github.com/PrefectHQ/fastmcp/pull/4537)
* Add missing 4.0.0 version badge to Path Security docs by [@jlowin](https://github.com/jlowin) in [#4540](https://github.com/PrefectHQ/fastmcp/pull/4540)
* Align server component docs by [@strawgate](https://github.com/strawgate) in [#4260](https://github.com/PrefectHQ/fastmcp/pull/4260)
* Align CLI, deployment, and config docs by [@strawgate](https://github.com/strawgate) in [#4259](https://github.com/PrefectHQ/fastmcp/pull/4259)
* Align client, Apps, and integration docs by [@strawgate](https://github.com/strawgate) in [#4261](https://github.com/PrefectHQ/fastmcp/pull/4261)
* Fix stale MRTR/elicitation framing in client and upgrade docs by [@jlowin](https://github.com/jlowin) in [#4551](https://github.com/PrefectHQ/fastmcp/pull/4551)
* docs: quote pip extras install examples by [@RachGranville](https://github.com/RachGranville) in [#4568](https://github.com/PrefectHQ/fastmcp/pull/4568)
* Document Windows CI parallelism and the subprocess_heavy marker by [@jlowin](https://github.com/jlowin) in [#4575](https://github.com/PrefectHQ/fastmcp/pull/4575)
* Document v3->v4 removals and add upgrade-reality tests by [@jlowin](https://github.com/jlowin) in [#4585](https://github.com/PrefectHQ/fastmcp/pull/4585)
* Archive v3 docs and publish v4 as the primary version by [@jlowin](https://github.com/jlowin) in [#4613](https://github.com/PrefectHQ/fastmcp/pull/4613)
* Document targeted v4 prerelease installation by [@zzstoatzz](https://github.com/zzstoatzz) in [#4598](https://github.com/PrefectHQ/fastmcp/pull/4598)
* Fix stale Mac/Windows-vs-Linux OAuth key/storage docs by [@jlowin](https://github.com/jlowin) in [#4617](https://github.com/PrefectHQ/fastmcp/pull/4617)
* v4 docs quality pass: stale task/era claims, broken links, polish by [@jlowin](https://github.com/jlowin) in [#4619](https://github.com/PrefectHQ/fastmcp/pull/4619)
* whats-new: add the argument completion capability by [@jlowin](https://github.com/jlowin) in [#4620](https://github.com/PrefectHQ/fastmcp/pull/4620)
* docs: fix ProxyProvider docstring example calling nonexistent with_namespace() by [@andrew-stelmach-fleet](https://github.com/andrew-stelmach-fleet) in [#4633](https://github.com/PrefectHQ/fastmcp/pull/4633)
* Unpublish v4 development notes; prep docs for beta 1 by [@jlowin](https://github.com/jlowin) in [#4644](https://github.com/PrefectHQ/fastmcp/pull/4644)
* Expand the FAQ for the v4 transition by [@jlowin](https://github.com/jlowin) in [#4649](https://github.com/PrefectHQ/fastmcp/pull/4649)
* Document the issuer_url identity change for upgraders by [@jlowin](https://github.com/jlowin) in [#4658](https://github.com/PrefectHQ/fastmcp/pull/4658)
* Cover require_roles in the v4 highlights by [@jlowin](https://github.com/jlowin) in [#4666](https://github.com/PrefectHQ/fastmcp/pull/4666)
* Fix FAQ: sampling/roots/elicitation legacy-mode advice, SessionProvider registration by [@jlowin](https://github.com/jlowin) in [#4672](https://github.com/PrefectHQ/fastmcp/pull/4672)
* Audit v4 docs: fix missing version badges, fill whats-new gaps by [@jlowin](https://github.com/jlowin) in [#4668](https://github.com/PrefectHQ/fastmcp/pull/4668)
* Docs: add v3.4.5 changelog entries to main by [@jlowin](https://github.com/jlowin) in [#4674](https://github.com/PrefectHQ/fastmcp/pull/4674)
* Split the SDK upgrade guides by SDK version by [@jlowin](https://github.com/jlowin) in [#4684](https://github.com/PrefectHQ/fastmcp/pull/4684)
### Dependencies 📦
* chore(deps): bump mcp from 1.26.0 to 1.27.2 in /examples/testing_demo in the uv group across 1 directory by [@dependabot](https://github.com/apps/dependabot) in [#4514](https://github.com/PrefectHQ/fastmcp/pull/4514)
* chore(deps): bump actions/setup-node from 6 to 7 by [@dependabot](https://github.com/apps/dependabot) in [#4546](https://github.com/PrefectHQ/fastmcp/pull/4546)
* Bump actions/upload-artifact from 4 to 7 by [@dependabot](https://github.com/apps/dependabot) in [#4640](https://github.com/PrefectHQ/fastmcp/pull/4640)
* Bump actions/setup-python from 6 to 7 by [@dependabot](https://github.com/apps/dependabot) in [#4641](https://github.com/PrefectHQ/fastmcp/pull/4641)
* chore(deps): bump mcp from 1.27.2 to 1.28.1 in /examples/testing_demo in the uv group across 1 directory by [@dependabot](https://github.com/apps/dependabot) in [#4614](https://github.com/PrefectHQ/fastmcp/pull/4614)
### Other Changes 🦾
* Test: HTTP lifespan fires once per process across sessions by [@jlowin](https://github.com/jlowin) in [#4470](https://github.com/PrefectHQ/fastmcp/pull/4470)
## New Contributors
* @syf2211 made their first contribution in [#4502](https://github.com/PrefectHQ/fastmcp/pull/4502)
* @earfman made their first contribution in [#4517](https://github.com/PrefectHQ/fastmcp/pull/4517)
* @winklemad made their first contribution in [#4492](https://github.com/PrefectHQ/fastmcp/pull/4492)
* @verdie-g made their first contribution in [#4512](https://github.com/PrefectHQ/fastmcp/pull/4512)
* @vijaydeepsinha made their first contribution in [#4411](https://github.com/PrefectHQ/fastmcp/pull/4411)
* @piaudonn made their first contribution in [#4267](https://github.com/PrefectHQ/fastmcp/pull/4267)
* @szepeviktor made their first contribution in [#4498](https://github.com/PrefectHQ/fastmcp/pull/4498)
* @endofcake made their first contribution in [#4412](https://github.com/PrefectHQ/fastmcp/pull/4412)
* @Kludex made their first contribution in [#4564](https://github.com/PrefectHQ/fastmcp/pull/4564)
* @RachGranville made their first contribution in [#4568](https://github.com/PrefectHQ/fastmcp/pull/4568)
* @hxaxd made their first contribution in [#4533](https://github.com/PrefectHQ/fastmcp/pull/4533)
* @VectorPeak made their first contribution in [#4531](https://github.com/PrefectHQ/fastmcp/pull/4531)
* @LarryHu0217 made their first contribution in [#4587](https://github.com/PrefectHQ/fastmcp/pull/4587)
* @andrew-stelmach-fleet made their first contribution in [#4633](https://github.com/PrefectHQ/fastmcp/pull/4633)
* @Aman071106 made their first contribution in [#4628](https://github.com/PrefectHQ/fastmcp/pull/4628)
* @ShuyingZhang made their first contribution in [#4639](https://github.com/PrefectHQ/fastmcp/pull/4639)
* @Educg550 made their first contribution in [#4660](https://github.com/PrefectHQ/fastmcp/pull/4660)
**Full Changelog**: [v3.4.5...v4.0.0b1](https://github.com/PrefectHQ/fastmcp/compare/v3.4.5...v4.0.0b1)
</Update>
<Update label="v3.4.5" description="2026-07-27">
**[v3.4.5: Key Change](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.5)**
FastMCP 3.4.5 collects five fixes for the 3.x line, led by `JWTVerifier` no longer rejecting every token when an authorization server publishes an unrecognized key type such as Ed25519.
### Fixes 🐞
* Backport #4517 to release/3.x: skip unsupported JWKS keys (#4515) by [@kakiii](https://github.com/kakiii) in [#4631](https://github.com/PrefectHQ/fastmcp/pull/4631)
* Backport #4469 to release/3.x: fix Azure scope fallback by [@jlowin](https://github.com/jlowin) in [#4662](https://github.com/PrefectHQ/fastmcp/pull/4662)
* Backport #4523 to release/3.x: serialize deep object query parameters by [@jlowin](https://github.com/jlowin) in [#4664](https://github.com/PrefectHQ/fastmcp/pull/4664)
* Backport #4564 to release/3.x: make transformed tool required order deterministic by [@jlowin](https://github.com/jlowin) in [#4665](https://github.com/PrefectHQ/fastmcp/pull/4665)
* Backport #4492 to release/3.x: don't mutate the caller's schema in compress_schema by [@jlowin](https://github.com/jlowin) in [#4663](https://github.com/PrefectHQ/fastmcp/pull/4663)
## New Contributors
* @kakiii made their first contribution in [#4631](https://github.com/PrefectHQ/fastmcp/pull/4631)
**Full Changelog**: [v3.4.4...v3.4.5](https://github.com/PrefectHQ/fastmcp/compare/v3.4.4...v3.4.5)
</Update>
<Update label="v3.4.4" description="2026-07-08">
**[v3.4.4: Host in Translation](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.4)**
FastMCP 3.4.4 restores HTTP deployment compatibility after the 3.4.3 Host/Origin guard changed default behavior for existing ASGI, serverless, and reverse-proxy deployments. The guard implementation remains available for deployments that opt in with explicit trusted hosts and origins, while 3.x returns to accepting traffic that worked before the patch. This release also adds Hugging Face OAuth provider support, with docs and examples for public and private apps, PKCE, Dynamic Client Registration, and CIMD.
### Enhancements ✨
* Hugging Face Auth Integration by [@evalstate](https://github.com/evalstate) in [#4385](https://github.com/PrefectHQ/fastmcp/pull/4385)
### Fixes 🐞
* Relax host origin guard defaults by [@jlowin](https://github.com/jlowin) in [#4439](https://github.com/PrefectHQ/fastmcp/pull/4439)
* Restore HTTP host guard compatibility by [@jlowin](https://github.com/jlowin) in [#4472](https://github.com/PrefectHQ/fastmcp/pull/4472)
## New Contributors
* @evalstate made their first contribution in [#4385](https://github.com/PrefectHQ/fastmcp/pull/4385)
**Full Changelog**: [v3.4.3...v3.4.4](https://github.com/PrefectHQ/fastmcp/compare/v3.4.3...v3.4.4)
</Update>
<Update label="v3.4.3" description="2026-07-05">
**[v3.4.3: The Fast and the Secure-ious](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.3)**
FastMCP 3.4.3 closes out a month of SSRF and OAuth hardening: NAT64, 6to4, Teredo, and ISATAP transition addresses can no longer smuggle private IPv4 targets past the SSRF allow-list, Streamable HTTP now validates Host and Origin before session handling to block DNS rebinding against localhost-bound servers, and OAuth redirect validation rejects unsafe schemes and unregistered DCR redirect URIs. Alongside the security work, this release also fixes proxy session teardown races, discriminator-tag handling in JSON schema conversion, and several smaller reliability issues.
### Enhancements ✨
* Dedupe discriminator-required helper across schema converters by [@jlowin](https://github.com/jlowin) in [#4362](https://github.com/PrefectHQ/fastmcp/pull/4362)
* Add real Monty sandbox e2e coverage for CodeMode call_tool by [@AlexlaGuardia](https://github.com/AlexlaGuardia) in [#4274](https://github.com/PrefectHQ/fastmcp/pull/4274)
* Switch prettier hook to rbubley/mirrors-prettier by [@jlowin](https://github.com/jlowin) in [#4366](https://github.com/PrefectHQ/fastmcp/pull/4366)
* feat(remote): add --verify flag for TLS certificate verification by [@jlowin](https://github.com/jlowin) in [#4369](https://github.com/PrefectHQ/fastmcp/pull/4369)
### Security 🔒
* fix(deps): clear Dependabot security alerts via lockfile bumps by [@jlowin](https://github.com/jlowin) in [#4393](https://github.com/PrefectHQ/fastmcp/pull/4393)
* Clarify resource path parameter safety by [@jlowin](https://github.com/jlowin) in [#4398](https://github.com/PrefectHQ/fastmcp/pull/4398)
* Fix dev apps launch escaping by [@jlowin](https://github.com/jlowin) in [#4399](https://github.com/PrefectHQ/fastmcp/pull/4399)
* Block NAT64 SSRF bypass by [@jlowin](https://github.com/jlowin) in [#4400](https://github.com/PrefectHQ/fastmcp/pull/4400)
* [codex] Fix event store replay isolation by [@jlowin](https://github.com/jlowin) in [#4402](https://github.com/PrefectHQ/fastmcp/pull/4402)
* Fix DCR redirect URI validation by [@jlowin](https://github.com/jlowin) in [#4408](https://github.com/PrefectHQ/fastmcp/pull/4408)
* Protect streamable HTTP from DNS rebinding by [@jlowin](https://github.com/jlowin) in [#4405](https://github.com/PrefectHQ/fastmcp/pull/4405)
* Block unsafe OAuth redirect schemes by [@jlowin](https://github.com/jlowin) in [#4419](https://github.com/PrefectHQ/fastmcp/pull/4419)
* Block IPv6 transition SSRF bypasses by [@jlowin](https://github.com/jlowin) in [#4426](https://github.com/PrefectHQ/fastmcp/pull/4426)
### Fixes 🐞
* fix: caching middleware TypeError on cache miss due to mismatched call_next parameter by [@gmenziesint](https://github.com/gmenziesint) in [#4301](https://github.com/PrefectHQ/fastmcp/pull/4301)
* Fix: async rate limiting middleware get_client_id callbacks by [@Chotom](https://github.com/Chotom) in [#4319](https://github.com/PrefectHQ/fastmcp/pull/4319)
* Recognize all GitHub issue-link forms in require-issue-link workflow by [@jlowin](https://github.com/jlowin) in [#4359](https://github.com/PrefectHQ/fastmcp/pull/4359)
* fix: preserve required discriminator tags by [@he-yufeng](https://github.com/he-yufeng) in [#4297](https://github.com/PrefectHQ/fastmcp/pull/4297)
* fix(proxy): shield stateful proxy disconnect during session teardown by [@jlowin](https://github.com/jlowin) in [#4363](https://github.com/PrefectHQ/fastmcp/pull/4363)
* fix(fs): isolate same-named package imports across providers by [@jlowin](https://github.com/jlowin) in [#4361](https://github.com/PrefectHQ/fastmcp/pull/4361)
* fix: StatefulProxyClient.clear() no longer causes KeyError on session teardown by [@tcconnally](https://github.com/tcconnally) in [#4328](https://github.com/PrefectHQ/fastmcp/pull/4328)
* fix: guard recursive refs in json_schema_to_type by [@Epochex](https://github.com/Epochex) in [#4312](https://github.com/PrefectHQ/fastmcp/pull/4312)
* Forward IdP auth errors to MCP client instead of showing HTML error page by [@bobbyjames839](https://github.com/bobbyjames839) in [#4293](https://github.com/PrefectHQ/fastmcp/pull/4293)
* fix(resources): round-trip path values with reserved characters in URI templates by [@jlowin](https://github.com/jlowin) in [#4368](https://github.com/PrefectHQ/fastmcp/pull/4368)
* fix: bracket IPv6 hosts in server startup log URL by [@jlowin](https://github.com/jlowin) in [#4372](https://github.com/PrefectHQ/fastmcp/pull/4372)
* fix: bound default OIDC discovery timeout and expose it on provider wrappers by [@jlowin](https://github.com/jlowin) in [#4374](https://github.com/PrefectHQ/fastmcp/pull/4374)
* fix: validate task tool arguments against declared types by [@jlowin](https://github.com/jlowin) in [#4373](https://github.com/PrefectHQ/fastmcp/pull/4373)
* fix(tools): honor serialize_by_alias in tool result serialization by [@jlowin](https://github.com/jlowin) in [#4391](https://github.com/PrefectHQ/fastmcp/pull/4391)
* Fix/cimd flow issue by [@twjackysu](https://github.com/twjackysu) in [#4206](https://github.com/PrefectHQ/fastmcp/pull/4206)
* Reject empty env var keys by [@CodingFeng101](https://github.com/CodingFeng101) in [#4410](https://github.com/PrefectHQ/fastmcp/pull/4410)
* fix: correct replace_type docstring parameter descriptions by [@hiSandog](https://github.com/hiSandog) in [#4375](https://github.com/PrefectHQ/fastmcp/pull/4375)
* Fix ty 0.0.55 diagnostics and prefab-ui protocol version drift by [@jlowin](https://github.com/jlowin) in [#4428](https://github.com/PrefectHQ/fastmcp/pull/4428)
* [codex] Fix OpenAPI resource template requests by [@jlowin](https://github.com/jlowin) in [#4407](https://github.com/PrefectHQ/fastmcp/pull/4407)
### Docs 📚
* fix: RST docstrings in fastmcp.types render raw on gofastmcp.com by [@jlowin](https://github.com/jlowin) in [#4367](https://github.com/PrefectHQ/fastmcp/pull/4367)
* docs: fix 5 broken internal links (auth & providers pages) by [@Michael-WhiteCapData](https://github.com/Michael-WhiteCapData) in [#4344](https://github.com/PrefectHQ/fastmcp/pull/4344)
* docs: add audit/event-record recipe for tool-call middleware by [@AlexlaGuardia](https://github.com/AlexlaGuardia) in [#4345](https://github.com/PrefectHQ/fastmcp/pull/4345)
### Dependencies 📦
* chore(deps): bump actions/checkout from 6 to 7 by [@dependabot](https://github.com/apps/dependabot) in [#4343](https://github.com/PrefectHQ/fastmcp/pull/4343)
* chore(deps): bump joserfc from 1.6.5 to 1.6.7 in the uv group across 1 directory by [@dependabot](https://github.com/apps/dependabot) in [#4394](https://github.com/PrefectHQ/fastmcp/pull/4394)
* chore(deps): bump joserfc from 1.6.7 to 1.6.8 in the uv group across 1 directory by [@dependabot](https://github.com/apps/dependabot) in [#4429](https://github.com/PrefectHQ/fastmcp/pull/4429)
### Other Changes 🦾
* Raise fastmcp.ValidationError for invalid tool arguments by [@jlowin](https://github.com/jlowin) in [#4392](https://github.com/PrefectHQ/fastmcp/pull/4392)
* Fix versioned auth middleware checks by [@jlowin](https://github.com/jlowin) in [#4401](https://github.com/PrefectHQ/fastmcp/pull/4401)
## New Contributors
* @gmenziesint made their first contribution in [#4301](https://github.com/PrefectHQ/fastmcp/pull/4301)
* @Chotom made their first contribution in [#4319](https://github.com/PrefectHQ/fastmcp/pull/4319)
* @he-yufeng made their first contribution in [#4297](https://github.com/PrefectHQ/fastmcp/pull/4297)
* @AlexlaGuardia made their first contribution in [#4274](https://github.com/PrefectHQ/fastmcp/pull/4274)
* @tcconnally made their first contribution in [#4328](https://github.com/PrefectHQ/fastmcp/pull/4328)
* @Epochex made their first contribution in [#4312](https://github.com/PrefectHQ/fastmcp/pull/4312)
* @Michael-WhiteCapData made their first contribution in [#4344](https://github.com/PrefectHQ/fastmcp/pull/4344)
* @bobbyjames839 made their first contribution in [#4293](https://github.com/PrefectHQ/fastmcp/pull/4293)
* @twjackysu made their first contribution in [#4206](https://github.com/PrefectHQ/fastmcp/pull/4206)
* @CodingFeng101 made their first contribution in [#4410](https://github.com/PrefectHQ/fastmcp/pull/4410)
* @hiSandog made their first contribution in [#4375](https://github.com/PrefectHQ/fastmcp/pull/4375)
**Full Changelog**: [v3.4.2...v3.4.3](https://github.com/PrefectHQ/fastmcp/compare/v3.4.2...v3.4.3)
</Update>
<Update label="v3.4.2" description="2026-06-06">
**[v3.4.2: Heads Up](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.2)**
FastMCP 3.4.2 restores JWT compatibility for providers that include private, non-critical JWS header parameters. Tokens from providers like Clerk can carry header metadata such as `cat` without being rejected before signature and claim validation, while unsupported critical headers are still rejected.
### Fixes 🐞
* Allow private JWT headers by [@jlowin](https://github.com/jlowin) in [#4290](https://github.com/PrefectHQ/fastmcp/pull/4290)
### Docs 📚
* Docs: add v3.4.1 changelog entries by [@jlowin](https://github.com/jlowin) in [#4289](https://github.com/PrefectHQ/fastmcp/pull/4289)
**Full Changelog**: [v3.4.1...v3.4.2](https://github.com/PrefectHQ/fastmcp/compare/v3.4.1...v3.4.2)
</Update>
<Update label="v3.4.1" description="2026-06-05">
**[v3.4.1: Floor It](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.1)**
FastMCP 3.4.1 floors Starlette at `>=1.0.1` so installs can no longer resolve to a version affected by CVE-2026-48710, which was previously only constrained transitively through `mcp`. It also makes OAuthProxy log refresh-token cache misses instead of failing silently.
### Enhancements ✨
* Log refresh-token misses in OAuthProxy instead of failing silently by [@jlowin](https://github.com/jlowin) in [#4276](https://github.com/PrefectHQ/fastmcp/pull/4276)
### Security 🔒
* Add explicit starlette>=1.0.1 floor (CVE-2026-48710) by [@jlowin](https://github.com/jlowin) in [#4286](https://github.com/PrefectHQ/fastmcp/pull/4286)
### Docs 📚
* Document --notes-start-tag in release instructions by [@jlowin](https://github.com/jlowin) in [#4275](https://github.com/PrefectHQ/fastmcp/pull/4275)
**Full Changelog**: [v3.4.0...v3.4.1](https://github.com/PrefectHQ/fastmcp/compare/v3.4.0...v3.4.1)
</Update>
<Update label="v3.4.0" description="2026-06-02">
**[v3.4.0: Remote Control](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.4.0)**
FastMCP 3.4 is about reaching servers that live somewhere else. The headline is `fastmcp-remote`, a standalone bridge that connects stdio-only MCP hosts to servers hosted over HTTP. Around it, the proxy layer those connections depend on is hardened: a proxy now forwards `initialize` upstream and fails loudly when the backend is missing or misconfigured, instead of reporting a connected-but-empty proxy. And FastMCP-issued access tokens can now outlive short-lived upstream tokens, so authenticated sessions survive the long idle periods remote clients are prone to.
### New Features 🎉
* Add fastmcp-remote bridge package by [@jlowin](https://github.com/jlowin) in [#4208](https://github.com/PrefectHQ/fastmcp/pull/4208)
### Breaking Changes ⚠️
* Forward proxy initialize as bridge behavior by [@jlowin](https://github.com/jlowin) in [#4228](https://github.com/PrefectHQ/fastmcp/pull/4228)
### Enhancements ✨
* ci: require external PRs to link a tracked issue by [@strawgate](https://github.com/strawgate) in [#4173](https://github.com/PrefectHQ/fastmcp/pull/4173)
* feat: new options --host and --no-log-panel | --log-panel to cli dev apps by [@itaru2622](https://github.com/itaru2622) in [#4123](https://github.com/PrefectHQ/fastmcp/pull/4123)
* Add valid_scopes and extra_authorize_params to WorkOSProvider by [@tiagoskaneta](https://github.com/tiagoskaneta) in [#4135](https://github.com/PrefectHQ/fastmcp/pull/4135)
* Add token_expiry_threshold_seconds for proactive token refresh by [@mohankumarelec](https://github.com/mohankumarelec) in [#4142](https://github.com/PrefectHQ/fastmcp/pull/4142)
* Add review-issue skill for triaging gated external contributions by [@jlowin](https://github.com/jlowin) in [#4212](https://github.com/PrefectHQ/fastmcp/pull/4212)
* Add contract gate to review-issue skill by [@jlowin](https://github.com/jlowin) in [#4214](https://github.com/PrefectHQ/fastmcp/pull/4214)
* Let ToolResult return an error result via is_error by [@jlowin](https://github.com/jlowin) in [#4217](https://github.com/PrefectHQ/fastmcp/pull/4217)
* Update published docs after PyPI release by [@jlowin](https://github.com/jlowin) in [#4211](https://github.com/PrefectHQ/fastmcp/pull/4211)
* Allow pre-bound HTTP sockets by [@jlowin](https://github.com/jlowin) in [#4222](https://github.com/PrefectHQ/fastmcp/pull/4222)
* Add targeted coverage tests by [@strawgate](https://github.com/strawgate) in [#4230](https://github.com/PrefectHQ/fastmcp/pull/4230)
* Upgrade ty to 0.0.39 by [@jlowin](https://github.com/jlowin) in [#4225](https://github.com/PrefectHQ/fastmcp/pull/4225)
* Decouple FastMCP access token lifetime from upstream expires_in by [@jlowin](https://github.com/jlowin) in [#4254](https://github.com/PrefectHQ/fastmcp/pull/4254)
### Security 🔒
* feat(code-mode): default sandbox limits and per-execution tool-call cap by [@strawgate](https://github.com/strawgate) in [#4170](https://github.com/PrefectHQ/fastmcp/pull/4170)
* Security: Fix 3 findings in GitHub Actions workflows by [@jpr5](https://github.com/jpr5) in [#4183](https://github.com/PrefectHQ/fastmcp/pull/4183)
* Add outbound comment guardrails by [@jlowin](https://github.com/jlowin) in [#4196](https://github.com/PrefectHQ/fastmcp/pull/4196)
* Add uv dependency cooldown by [@jlowin](https://github.com/jlowin) in [#4213](https://github.com/PrefectHQ/fastmcp/pull/4213)
### Fixes 🐞
* fix: VersionSpec eq matching normalizes versions and selects deterministically by [@strawgate](https://github.com/strawgate) in [#4058](https://github.com/PrefectHQ/fastmcp/pull/4058)
* fix(tests): hoist azure-identity import out of the OBO test timeout window by [@strawgate](https://github.com/strawgate) in [#4176](https://github.com/PrefectHQ/fastmcp/pull/4176)
* fix(auth): disambiguate auth-denied vs missing component messages by [@strawgate](https://github.com/strawgate) in [#4165](https://github.com/PrefectHQ/fastmcp/pull/4165)
* fix: preserve annotations, meta, title, icons when creating resources from templates by [@strawgate](https://github.com/strawgate) in [#4061](https://github.com/PrefectHQ/fastmcp/pull/4061)
* fix: add OTEL spans to sampling step and tool execution by [@strawgate](https://github.com/strawgate) in [#4059](https://github.com/PrefectHQ/fastmcp/pull/4059)
* fix(config): read MCP config files as UTF-8 by [@pragnyanramtha](https://github.com/pragnyanramtha) in [#4164](https://github.com/PrefectHQ/fastmcp/pull/4164)
* fix(schema): preserve root metadata on fallback by [@yuyua9](https://github.com/yuyua9) in [#4178](https://github.com/PrefectHQ/fastmcp/pull/4178)
* fix(proxy): restore _current_server in _restore_request_context by [@strawgate](https://github.com/strawgate) in [#4168](https://github.com/PrefectHQ/fastmcp/pull/4168)
* fix(auth): add /.well-known/openid-configuration alias for OAuth server metadata by [@shigechika](https://github.com/shigechika) in [#4167](https://github.com/PrefectHQ/fastmcp/pull/4167)
* fix(code-mode): cancel Monty sandbox future on task cancellation by [@strawgate](https://github.com/strawgate) in [#4169](https://github.com/PrefectHQ/fastmcp/pull/4169)
* fix(auth): unprefix Azure scopes echoed back to MCP clients by [@rgillinlz](https://github.com/rgillinlz) in [#4130](https://github.com/PrefectHQ/fastmcp/pull/4130)
* fix(cli): forward stateless flag in uv run path by [@yuyua9](https://github.com/yuyua9) in [#4177](https://github.com/PrefectHQ/fastmcp/pull/4177)
* fix(ci): scope minimize-reviews concurrency by event name by [@strawgate](https://github.com/strawgate) in [#4174](https://github.com/PrefectHQ/fastmcp/pull/4174)
* Fix docs app demo iframe assets by [@jlowin](https://github.com/jlowin) in [#4194](https://github.com/PrefectHQ/fastmcp/pull/4194)
* Guard require-issue-link check job to pull_request_target events by [@jlowin](https://github.com/jlowin) in [#4209](https://github.com/PrefectHQ/fastmcp/pull/4209)
* Migrate auth JWTs to joserfc by [@jlowin](https://github.com/jlowin) in [#4221](https://github.com/PrefectHQ/fastmcp/pull/4221)
* Skip published docs update for prereleases by [@jlowin](https://github.com/jlowin) in [#4224](https://github.com/PrefectHQ/fastmcp/pull/4224)
* Surface proxy upstream failures by [@jlowin](https://github.com/jlowin) in [#4227](https://github.com/PrefectHQ/fastmcp/pull/4227)
* Close upstream OAuth clients by [@jlowin](https://github.com/jlowin) in [#4248](https://github.com/PrefectHQ/fastmcp/pull/4248)
* Fix GitHub MCP resource integration test by [@jlowin](https://github.com/jlowin) in [#4253](https://github.com/PrefectHQ/fastmcp/pull/4253)
* Fix resource templates with query params on proxied servers by [@rene84](https://github.com/rene84) in [#4251](https://github.com/PrefectHQ/fastmcp/pull/4251)
### Docs 📚
* Document pip upgrade recovery for the fastmcp-slim package split by [@jlowin](https://github.com/jlowin) in [#4215](https://github.com/PrefectHQ/fastmcp/pull/4215)
* Move pip upgrade recovery into a Troubleshooting section by [@jlowin](https://github.com/jlowin) in [#4219](https://github.com/PrefectHQ/fastmcp/pull/4219)
* Restore Horizon docs banner by [@jlowin](https://github.com/jlowin) in [#4240](https://github.com/PrefectHQ/fastmcp/pull/4240)
* fix: Trendshift link and badge in README.md by [@bhantos](https://github.com/bhantos) in [#4236](https://github.com/PrefectHQ/fastmcp/pull/4236)
* docs: add tool fingerprinting recipe by [@dgenio](https://github.com/dgenio) in [#4233](https://github.com/PrefectHQ/fastmcp/pull/4233)
### Dependencies 📦
* chore(deps): bump the uv group across 2 directories with 1 update by [@dependabot](https://github.com/dependabot) in [#4113](https://github.com/PrefectHQ/fastmcp/pull/4113)
* chore(deps-dev): bump pydantic-monty from 0.0.16 to 0.0.17 by [@dependabot](https://github.com/dependabot) in [#4023](https://github.com/PrefectHQ/fastmcp/pull/4023)
### Other Changes 🦾
* Exempt maintainers from MRE auto-close by [@jlowin](https://github.com/jlowin) in [#4220](https://github.com/PrefectHQ/fastmcp/pull/4220)
## New Contributors
* @pragnyanramtha made their first contribution in [#4164](https://github.com/PrefectHQ/fastmcp/pull/4164)
* @yuyua9 made their first contribution in [#4178](https://github.com/PrefectHQ/fastmcp/pull/4178)
* @tiagoskaneta made their first contribution in [#4135](https://github.com/PrefectHQ/fastmcp/pull/4135)
* @mohankumarelec made their first contribution in [#4142](https://github.com/PrefectHQ/fastmcp/pull/4142)
* @rgillinlz made their first contribution in [#4130](https://github.com/PrefectHQ/fastmcp/pull/4130)
* @jpr5 made their first contribution in [#4183](https://github.com/PrefectHQ/fastmcp/pull/4183)
* @bhantos made their first contribution in [#4236](https://github.com/PrefectHQ/fastmcp/pull/4236)
* @rene84 made their first contribution in [#4251](https://github.com/PrefectHQ/fastmcp/pull/4251)
**Full Changelog**: [v3.3.1...v3.4.0](https://github.com/PrefectHQ/fastmcp/compare/v3.3.1...v3.4.0)
</Update>
<Update label="v3.3.1" description="2026-05-15">
**[v3.3.1: Loop There It Is](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.3.1)**
A hotfix for the 3.3 packaging split. Clean installs could fail on standalone component imports like `from fastmcp.tools import tool`, because component modules reached auth and task primitives through `fastmcp.server` and pulled in the full server/provider stack. Those primitives now live in lightweight utility modules, with the old server import paths preserved as compatibility re-exports.
### Fixes 🐞
* fix(docs): use valid FA icon on client-only package page by [@jlowin](https://github.com/jlowin) in [#4139](https://github.com/PrefectHQ/fastmcp/pull/4139)
* Decouple component imports from server by [@jlowin](https://github.com/jlowin) in [#4150](https://github.com/PrefectHQ/fastmcp/pull/4150)
**Full Changelog**: [v3.3.0...v3.3.1](https://github.com/PrefectHQ/fastmcp/compare/v3.3.0...v3.3.1)
</Update>
<Update label="v3.3.0" description="2026-05-15">
**[v3.3.0: Slim Reaper](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.3.0)**
FastMCP 3.3 ships `fastmcp-slim`, a dependency-light distribution that separates the client from the server stack — install FastMCP's client and transport layer without Starlette, Uvicorn, or the rest of the server machinery. The import namespace is unchanged. It also closes out a backlog of OAuth proxy security hardening, MCP-compliant OTEL instrumentation, and auth additions that accumulated through the 3.2 cycle.
### New Features 🎉
* Add fastmcp-slim for client-only installs by [@jlowin](https://github.com/jlowin) in [#4122](https://github.com/PrefectHQ/fastmcp/pull/4122)
### Enhancements ✨
* Add default prefill to FormInput.collect_input by [@jlowin](https://github.com/jlowin) in [#3937](https://github.com/PrefectHQ/fastmcp/pull/3937)
* OTEL: Fix attribute compliance with MCP semantic conventions by [@strawgate](https://github.com/strawgate) in [#3889](https://github.com/PrefectHQ/fastmcp/pull/3889)
* OTEL: Instrument all MCP list operations and enrich delegate spans by [@strawgate](https://github.com/strawgate) in [#3890](https://github.com/PrefectHQ/fastmcp/pull/3890)
* Improve real-world schema crash test: failure dump, cluster analysis, TypeErrors baseline ratchet by [@jlowin](https://github.com/jlowin) in [#3958](https://github.com/PrefectHQ/fastmcp/pull/3958)
* feat: add AzureB2CProvider for Azure AD B2C user flows by [@carlos-rian](https://github.com/carlos-rian) in [#3995](https://github.com/PrefectHQ/fastmcp/pull/3995)
* Add run_in_thread opt-out for sync tools with thread affinity by [@jlowin](https://github.com/jlowin) in [#4010](https://github.com/PrefectHQ/fastmcp/pull/4010)
* Add missing return type annotation to __getattr__ by [@ZLeventer](https://github.com/ZLeventer) in [#4026](https://github.com/PrefectHQ/fastmcp/pull/4026)
* Add experimental_capabilities kwarg to FastMCP constructor by [@jlowin](https://github.com/jlowin) in [#4042](https://github.com/PrefectHQ/fastmcp/pull/4042)
* Add log_level parameter to FastMCP errors by [@daniel-tsiang](https://github.com/daniel-tsiang) in [#4036](https://github.com/PrefectHQ/fastmcp/pull/4036)
* Bump pydocket to 0.20.0 by [@chrisguidry](https://github.com/chrisguidry) in [#4031](https://github.com/PrefectHQ/fastmcp/pull/4031)
* enh: Add public API for updating OAuthProxy scopes after initialization by [@taylorwilsdon](https://github.com/taylorwilsdon) in [#4091](https://github.com/PrefectHQ/fastmcp/pull/4091)
* Refine fastmcp-slim packaging by [@jlowin](https://github.com/jlowin) in [#4125](https://github.com/PrefectHQ/fastmcp/pull/4125)
### Security 🔒
* Harden OAuth Proxy silent consent against AS-in-the-middle by [@jlowin](https://github.com/jlowin) in [#3960](https://github.com/PrefectHQ/fastmcp/pull/3960)
* Reject dot-segments in redirect URI allowlist matching by [@jlowin](https://github.com/jlowin) in [#3963](https://github.com/PrefectHQ/fastmcp/pull/3963)
* Bump deps with open dependabot alerts by [@jlowin](https://github.com/jlowin) in [#3965](https://github.com/PrefectHQ/fastmcp/pull/3965)
* Partition ResponseCachingMiddleware cache by access token by [@jlowin](https://github.com/jlowin) in [#4041](https://github.com/PrefectHQ/fastmcp/pull/4041)
### Fixes 🐞
* fix: reject self-mount to prevent infinite recursion by [@strawgate](https://github.com/strawgate) in [#3925](https://github.com/PrefectHQ/fastmcp/pull/3925)
* fix: ProxyTool crashes on non-TextContent error responses by [@strawgate](https://github.com/strawgate) in [#3926](https://github.com/PrefectHQ/fastmcp/pull/3926)
* fix: _prune_param and _convert_nullable_field mutate input schemas by [@strawgate](https://github.com/strawgate) in [#3927](https://github.com/PrefectHQ/fastmcp/pull/3927)
* fix: narrow OpenAI audio format dict to Literal for ty by [@jlowin](https://github.com/jlowin) in [#3936](https://github.com/PrefectHQ/fastmcp/pull/3936)
* fix: allow hyphens in resource template parameter names by [@strawgate](https://github.com/strawgate) in [#3929](https://github.com/PrefectHQ/fastmcp/pull/3929)
* fix: OpenAPI request director sends multipart and form-urlencoded as JSON by [@strawgate](https://github.com/strawgate) in [#3932](https://github.com/PrefectHQ/fastmcp/pull/3932)
* Fix raise_on_error handling for tool tasks by [@gnanirahulnutakki](https://github.com/gnanirahulnutakki) in [#3946](https://github.com/PrefectHQ/fastmcp/pull/3946)
* fix: FileSystemProvider reload race condition by [@strawgate](https://github.com/strawgate) in [#3938](https://github.com/PrefectHQ/fastmcp/pull/3938)
* fix tests that relied on task=True returning error results by [@jlowin](https://github.com/jlowin) in [#3954](https://github.com/PrefectHQ/fastmcp/pull/3954)
* Restore task snapshot via a worker-level dependency by [@chrisguidry](https://github.com/chrisguidry) in [#3945](https://github.com/PrefectHQ/fastmcp/pull/3945)
* Forward backend capabilities in ProxyProvider by [@jlowin](https://github.com/jlowin) in [#3956](https://github.com/PrefectHQ/fastmcp/pull/3956)
* Allow upstream client_id to be used directly without DCR by [@jlowin](https://github.com/jlowin) in [#3957](https://github.com/PrefectHQ/fastmcp/pull/3957)
* Graceful fallback for unsupported regex patterns in json_schema_to_type by [@jlowin](https://github.com/jlowin) in [#3959](https://github.com/PrefectHQ/fastmcp/pull/3959)
* Revert "Forward backend capabilities in ProxyProvider (#3956)" by [@jlowin](https://github.com/jlowin) in [#3964](https://github.com/PrefectHQ/fastmcp/pull/3964)
* fix: skip stdio subprocess test on Windows CI by [@jlowin](https://github.com/jlowin) in [#3966](https://github.com/PrefectHQ/fastmcp/pull/3966)
* fix: bound _refresh_locks with LRU eviction to prevent memory leak by [@jlowin](https://github.com/jlowin) in [#3968](https://github.com/PrefectHQ/fastmcp/pull/3968)
* fix: handle circular JSON Pointer $ref in dereference_refs by [@lawrence3699](https://github.com/lawrence3699) in [#3896](https://github.com/PrefectHQ/fastmcp/pull/3896)
* fix: honor upstream refresh token expiry in OAuthProxy by [@jlowin](https://github.com/jlowin) in [#3990](https://github.com/PrefectHQ/fastmcp/pull/3990)
* fix: narrow _token_validator with isinstance for ty in AzureProvider.from_b2c by [@jlowin](https://github.com/jlowin) in [#4007](https://github.com/PrefectHQ/fastmcp/pull/4007)
* fix: cancel orphaned session_task when Client._disconnect times out by [@jlowin](https://github.com/jlowin) in [#4011](https://github.com/PrefectHQ/fastmcp/pull/4011)
* fix: preserve @tool metadata in from_function by [@lawrence3699](https://github.com/lawrence3699) in [#4072](https://github.com/PrefectHQ/fastmcp/pull/4072)
* fix(openapi): keep blank values in parse_qs (refs #4056) by [@MukundaKatta](https://github.com/MukundaKatta) in [#4076](https://github.com/PrefectHQ/fastmcp/pull/4076)
* Fix #4056: keep blank query values, add token bucket regression test by [@MukundaKatta](https://github.com/MukundaKatta) in [#4069](https://github.com/PrefectHQ/fastmcp/pull/4069)
* fix(ping): exit ping loop cleanly when session stream is closed by [@ashwin153](https://github.com/ashwin153) in [#4087](https://github.com/PrefectHQ/fastmcp/pull/4087)
* Fix sampling from background tasks by [@cuyua9](https://github.com/cuyua9) in [#4068](https://github.com/PrefectHQ/fastmcp/pull/4068)
* Make Docket reentrant; mounted servers enter their own lifespan by [@jlowin](https://github.com/jlowin) in [#4095](https://github.com/PrefectHQ/fastmcp/pull/4095)
* fix(tool_transform): hoist $defs to schema root when ArgTransform introduces them by [@SarthakB11](https://github.com/SarthakB11) in [#4101](https://github.com/PrefectHQ/fastmcp/pull/4101)
* fix(auth): silence authlib.jose DeprecationWarning at JWT import by [@SarthakB11](https://github.com/SarthakB11) in [#4100](https://github.com/PrefectHQ/fastmcp/pull/4100)
* fix: don't cache import map in dev apps bundle by [@jlowin](https://github.com/jlowin) in [#4106](https://github.com/PrefectHQ/fastmcp/pull/4106)
* #4084 [Issues] Windows startup crash due to UnicodeDecodeError when l… by [@doneman536](https://github.com/doneman536) in [#4092](https://github.com/PrefectHQ/fastmcp/pull/4092)
* fix: drop exc_info for expected tool failures, remove unreachable ValidationError by [@sergeykad](https://github.com/sergeykad) in [#4029](https://github.com/PrefectHQ/fastmcp/pull/4029)
* fix: cli option --no-banner is NOT passed to cli but server-spec in-correctly when cli --reload option is specified. by [@itaru2622](https://github.com/itaru2622) in [#4083](https://github.com/PrefectHQ/fastmcp/pull/4083)
* Fix None backend_* span attributes on un-renamed proxy components by [@ringerc](https://github.com/ringerc) in [#4109](https://github.com/PrefectHQ/fastmcp/pull/4109)
* Fix OCI Provider issue in 3.x version. Add OCI auth provider example … by [@kiranthakkar](https://github.com/kiranthakkar) in [#4116](https://github.com/PrefectHQ/fastmcp/pull/4116)
* fix(http): terminate active streamable-HTTP transports before lifespan shutdown by [@SarthakB11](https://github.com/SarthakB11) in [#4118](https://github.com/PrefectHQ/fastmcp/pull/4118)
### Docs 📚
* Restructure docs navigation by [@jlowin](https://github.com/jlowin) in [#3951](https://github.com/PrefectHQ/fastmcp/pull/3951)
* docs: standardize ToolAnnotations examples by [@gnanirahulnutakki](https://github.com/gnanirahulnutakki) in [#3952](https://github.com/PrefectHQ/fastmcp/pull/3952)
* Be constructively skeptical of bot reviews on own PRs by [@jlowin](https://github.com/jlowin) in [#3971](https://github.com/PrefectHQ/fastmcp/pull/3971)
* Add UTM params to Horizon docs links by [@aaazzam](https://github.com/aaazzam) in [#4018](https://github.com/PrefectHQ/fastmcp/pull/4018)
* Add a sandboxed-agents deployment guide by [@strawgate](https://github.com/strawgate) in [#4027](https://github.com/PrefectHQ/fastmcp/pull/4027)
* docs: add best practices for custom telemetry spans by [@MukundaKatta](https://github.com/MukundaKatta) in [#4001](https://github.com/PrefectHQ/fastmcp/pull/4001)
* Refresh landing page copy by [@jlowin](https://github.com/jlowin) in [#4043](https://github.com/PrefectHQ/fastmcp/pull/4043)
* Refresh landing page copy by [@jlowin](https://github.com/jlowin) in [#4047](https://github.com/PrefectHQ/fastmcp/pull/4047)
* Add UTM tracking to Horizon links by [@jlowin](https://github.com/jlowin) in [#4064](https://github.com/PrefectHQ/fastmcp/pull/4064)
* docs(integrations): add Pydantic AI FastMCP toolset guide by [@MukundaKatta](https://github.com/MukundaKatta) in [#4070](https://github.com/PrefectHQ/fastmcp/pull/4070)
* docs: fix broken links in Pydantic AI guide by [@jlowin](https://github.com/jlowin) in [#4094](https://github.com/PrefectHQ/fastmcp/pull/4094)
### Dependencies 📦
* chore(deps-dev): bump pydantic-monty from 0.0.11 to 0.0.12 by [@dependabot](https://github.com/dependabot) in [#3940](https://github.com/PrefectHQ/fastmcp/pull/3940)
* chore(deps-dev): bump pydantic-monty from 0.0.14 to 0.0.16 by [@dependabot](https://github.com/dependabot) in [#3984](https://github.com/PrefectHQ/fastmcp/pull/3984)
### Other Changes 🦾
* fix: Don't completely hide plain mcp.tool app-only tools by [@owtaylor](https://github.com/owtaylor) in [#4112](https://github.com/PrefectHQ/fastmcp/pull/4112)
## New Contributors
* @gnanirahulnutakki made their first contribution in [#3946](https://github.com/PrefectHQ/fastmcp/pull/3946)
* @lawrence3699 made their first contribution in [#3896](https://github.com/PrefectHQ/fastmcp/pull/3896)
* @carlos-rian made their first contribution in [#3995](https://github.com/PrefectHQ/fastmcp/pull/3995)
* @ZLeventer made their first contribution in [#4026](https://github.com/PrefectHQ/fastmcp/pull/4026)
* @MukundaKatta made their first contribution in [#4001](https://github.com/PrefectHQ/fastmcp/pull/4001)
* @daniel-tsiang made their first contribution in [#4036](https://github.com/PrefectHQ/fastmcp/pull/4036)
* @ashwin153 made their first contribution in [#4087](https://github.com/PrefectHQ/fastmcp/pull/4087)
* @cuyua9 made their first contribution in [#4068](https://github.com/PrefectHQ/fastmcp/pull/4068)
* @taylorwilsdon made their first contribution in [#4091](https://github.com/PrefectHQ/fastmcp/pull/4091)
* @SarthakB11 made their first contribution in [#4101](https://github.com/PrefectHQ/fastmcp/pull/4101)
* @doneman536 made their first contribution in [#4092](https://github.com/PrefectHQ/fastmcp/pull/4092)
* @sergeykad made their first contribution in [#4029](https://github.com/PrefectHQ/fastmcp/pull/4029)
* @ringerc made their first contribution in [#4109](https://github.com/PrefectHQ/fastmcp/pull/4109)
**Full Changelog**: [v3.2.4...v3.3.0](https://github.com/PrefectHQ/fastmcp/compare/v3.2.4...v3.3.0)
</Update>
<Update label="v3.2.4" description="2026-04-14">
**[v3.2.4: Patch Me If You Can](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.2.4)**
A grab bag of fixes, hardening, and polish. The headline behavior change: background tasks are now scoped to the authorization context rather than the MCP session, so a task survives session churn and stays tied to who started it — a breaking change for anyone relying on the old session-scoped semantics. Plus actual-size validation in `FileUpload`, a Keycloak OAuth provider, automatic parameter descriptions from docstrings, and dozens of schema and sampling fixes.
### Breaking Changes ⚠️
* Scope tasks to authorization context, not session by [@chrisguidry](https://github.com/chrisguidry) in [#3800](https://github.com/PrefectHQ/fastmcp/pull/3800)
### Enhancements ✨
* Bump pydocket>=0.19.0, drop fakeredis pin by [@chrisguidry](https://github.com/chrisguidry) in [#3822](https://github.com/PrefectHQ/fastmcp/pull/3822)
* Add real-world schema crash test (232K schemas from APIs.guru) by [@strawgate](https://github.com/strawgate) in [#3826](https://github.com/PrefectHQ/fastmcp/pull/3826)
* Enable 7 zero-violation ruff rules by [@strawgate](https://github.com/strawgate) in [#3841](https://github.com/PrefectHQ/fastmcp/pull/3841)
* Promote 7 ty rules from ignore to warn by [@strawgate](https://github.com/strawgate) in [#3852](https://github.com/PrefectHQ/fastmcp/pull/3852)
* Replace ___ with hash-based backend tool routing and per-tool prefab resources by [@jlowin](https://github.com/jlowin) in [#3824](https://github.com/PrefectHQ/fastmcp/pull/3824)
* Enable 4 ruff rules (DTZ, ERA, ISC, INP) and fix 9 violations by [@strawgate](https://github.com/strawgate) in [#3842](https://github.com/PrefectHQ/fastmcp/pull/3842)
* Extract parameter descriptions from docstrings by [@jlowin](https://github.com/jlowin) in [#3872](https://github.com/PrefectHQ/fastmcp/pull/3872)
* ci: speed up schema crash test (CSafeLoader + xdist-safe aggregation) by [@jlowin](https://github.com/jlowin) in [#3873](https://github.com/PrefectHQ/fastmcp/pull/3873)
* test: bump OpenAPI init perf threshold to 200ms for Windows CI by [@jlowin](https://github.com/jlowin) in [#3879](https://github.com/PrefectHQ/fastmcp/pull/3879)
* refactor: unify object-schema conversion through _object_schema_to_type by [@jlowin](https://github.com/jlowin) in [#3884](https://github.com/PrefectHQ/fastmcp/pull/3884)
* Add Keycloak OAuth Provider for Enterprise Authentication and local dev by [@stephaneberle9](https://github.com/stephaneberle9) in [#1937](https://github.com/PrefectHQ/fastmcp/pull/1937)
* Allow auth providers to override protected resource base URLs by [@aaazzam](https://github.com/aaazzam) in [#3900](https://github.com/PrefectHQ/fastmcp/pull/3900)
* Enable PERF and T20 ruff rules by [@strawgate](https://github.com/strawgate) in [#3845](https://github.com/PrefectHQ/fastmcp/pull/3845)
* Add response_title and response_description to ctx.elicit() by [@jlowin](https://github.com/jlowin) in [#3912](https://github.com/PrefectHQ/fastmcp/pull/3912)
* Deprecate ctx.elicit() without response_type by [@jlowin](https://github.com/jlowin) in [#3916](https://github.com/PrefectHQ/fastmcp/pull/3916)
### Security 🔒
* Validate actual base64 data size in FileUpload, not client-reported size by [@strawgate](https://github.com/strawgate) in [#3816](https://github.com/PrefectHQ/fastmcp/pull/3816)
* Stop forwarding inbound HTTP headers to unrelated remote servers by [@jlowin](https://github.com/jlowin) in [#3837](https://github.com/PrefectHQ/fastmcp/pull/3837)
* AuthKit: auto-bind token audience to resource URL (RFC 8707) by [@jlowin](https://github.com/jlowin) in [#3905](https://github.com/PrefectHQ/fastmcp/pull/3905)
### Fixes 🐞
* Version-check is_docket_available() to avoid transitive pydocket crash by [@jlowin](https://github.com/jlowin) in [#3807](https://github.com/PrefectHQ/fastmcp/pull/3807)
* fix: materialize generators before result conversion, handle bytes gracefully by [@strawgate](https://github.com/strawgate) in [#3830](https://github.com/PrefectHQ/fastmcp/pull/3830)
* Fix json_schema_to_type crashes on keywords, boolean schemas, empty enums, and name collisions by [@strawgate](https://github.com/strawgate) in [#3818](https://github.com/PrefectHQ/fastmcp/pull/3818)
* fix: replace `or` with `is not None` checks for config/override merging by [@strawgate](https://github.com/strawgate) in [#3833](https://github.com/PrefectHQ/fastmcp/pull/3833)
* fix: TransformedTool sync fn crash and schema mutation by [@strawgate](https://github.com/strawgate) in [#3823](https://github.com/PrefectHQ/fastmcp/pull/3823)
* fix: cross-provider duplicate detection, error visibility, mask propagation by [@strawgate](https://github.com/strawgate) in [#3827](https://github.com/PrefectHQ/fastmcp/pull/3827)
* fix: don't pass HTTP kwargs when transport is unspecified by [@strawgate](https://github.com/strawgate) in [#3838](https://github.com/PrefectHQ/fastmcp/pull/3838)
* fix: strip title fields from tool schemas for Gemini 2.5 Flash compatibility by [@strawgate](https://github.com/strawgate) in [#3861](https://github.com/PrefectHQ/fastmcp/pull/3861)
* fix: retry when LLM returns text instead of calling final_response by [@strawgate](https://github.com/strawgate) in [#3850](https://github.com/PrefectHQ/fastmcp/pull/3850)
* Raise on unhandled content types in sampling handler dispatch chains by [@strawgate](https://github.com/strawgate) in [#3857](https://github.com/PrefectHQ/fastmcp/pull/3857)
* Fix broken code examples in docs by [@strawgate](https://github.com/strawgate) in [#3869](https://github.com/PrefectHQ/fastmcp/pull/3869)
* fix: GoogleGenaiSamplingHandler leaks thought parts and gives unhelpful errors on empty responses by [@strawgate](https://github.com/strawgate) in [#3849](https://github.com/PrefectHQ/fastmcp/pull/3849)
* fix: cap consecutive final_response validation retries by [@strawgate](https://github.com/strawgate) in [#3851](https://github.com/PrefectHQ/fastmcp/pull/3851)
* Fix test quality issues by [@strawgate](https://github.com/strawgate) in [#3854](https://github.com/PrefectHQ/fastmcp/pull/3854)
* Fix MCP tool on docs welcome page by [@lkiesow](https://github.com/lkiesow) in [#3874](https://github.com/PrefectHQ/fastmcp/pull/3874)
* Fix CIMD clients getting required_scopes instead of valid_scopes by [@jlowin](https://github.com/jlowin) in [#3836](https://github.com/PrefectHQ/fastmcp/pull/3836)
* Rename filesystem-provider example dir to avoid mcp/ collision by [@jlowin](https://github.com/jlowin) in [#3878](https://github.com/PrefectHQ/fastmcp/pull/3878)
* fix: drop configurable dedupe from AggregateProvider, always warn by [@jlowin](https://github.com/jlowin) in [#3877](https://github.com/PrefectHQ/fastmcp/pull/3877)
* fix: resolve list[dict] return type producing Root() instead of dicts by [@KeWang0622](https://github.com/KeWang0622) in [#3880](https://github.com/PrefectHQ/fastmcp/pull/3880)
* fix: strip titles from bare-metadata nodes (Gemini 2.5 Flash) by [@jlowin](https://github.com/jlowin) in [#3881](https://github.com/PrefectHQ/fastmcp/pull/3881)
* Fix wildcard resource template params in mounted servers by [@jlowin](https://github.com/jlowin) in [#3899](https://github.com/PrefectHQ/fastmcp/pull/3899)
* Harden forced client disconnect cleanup by [@vonbai](https://github.com/vonbai) in [#3885](https://github.com/PrefectHQ/fastmcp/pull/3885)
* fix: elicitation scalar return, resource auto-serialization, Client.new() state, prompt errors by [@strawgate](https://github.com/strawgate) in [#3859](https://github.com/PrefectHQ/fastmcp/pull/3859)
* fix: task.wait() hangs indefinitely when task enters input_required by [@mrishav](https://github.com/mrishav) in [#3798](https://github.com/PrefectHQ/fastmcp/pull/3798)
* Fix RetryMiddleware not retrying tool errors by [@strawgate](https://github.com/strawgate) in [#3858](https://github.com/PrefectHQ/fastmcp/pull/3858)
* Stop pydantic 2.13 from leaking _WrappedResult docstring into tool output schemas by [@jlowin](https://github.com/jlowin) in [#3918](https://github.com/PrefectHQ/fastmcp/pull/3918)
### Docs 📚
* Note generate-notes API in release workflow docs by [@jlowin](https://github.com/jlowin) in [#3806](https://github.com/PrefectHQ/fastmcp/pull/3806)
* docs: require agents to respect DNM markers on PRs by [@jlowin](https://github.com/jlowin) in [#3871](https://github.com/PrefectHQ/fastmcp/pull/3871)
* docs: add uv-managed dependencies and uvx examples to mcp-json configuration by [@vincent067](https://github.com/vincent067) in [#3843](https://github.com/PrefectHQ/fastmcp/pull/3843)
* docs: link fastmcp-keycloak-local companion project from Keycloak integration page by [@stephaneberle9](https://github.com/stephaneberle9) in [#3904](https://github.com/PrefectHQ/fastmcp/pull/3904)
* Overhaul apps docs by [@jlowin](https://github.com/jlowin) in [#3915](https://github.com/PrefectHQ/fastmcp/pull/3915)
### Dependencies 📦
* chore(deps): bump extractions/setup-just from 3 to 4 by [@dependabot](https://github.com/dependabot) in [#3863](https://github.com/PrefectHQ/fastmcp/pull/3863)
* chore(deps): bump astral-sh/setup-uv from 6 to 7 by [@dependabot](https://github.com/dependabot) in [#3865](https://github.com/PrefectHQ/fastmcp/pull/3865)
* chore(deps): bump actions/checkout from 4 to 6 by [@dependabot](https://github.com/dependabot) in [#3864](https://github.com/PrefectHQ/fastmcp/pull/3864)
* chore(deps-dev): bump pydantic-monty from 0.0.9 to 0.0.10 by [@dependabot](https://github.com/dependabot) in [#3809](https://github.com/PrefectHQ/fastmcp/pull/3809)
* chore(deps): bump the uv group across 2 directories with 1 update by [@dependabot](https://github.com/dependabot) in [#3913](https://github.com/PrefectHQ/fastmcp/pull/3913)
## New Contributors
* @lkiesow made their first contribution in [#3874](https://github.com/PrefectHQ/fastmcp/pull/3874)
* @KeWang0622 made their first contribution in [#3880](https://github.com/PrefectHQ/fastmcp/pull/3880)
* @vonbai made their first contribution in [#3885](https://github.com/PrefectHQ/fastmcp/pull/3885)
**Full Changelog**: [v3.2.3...v3.2.4](https://github.com/PrefectHQ/fastmcp/compare/v3.2.3...v3.2.4)
</Update>
<Update label="v3.2.3" description="2026-04-09">
**[v3.2.3: Redis or Not](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.2.3)**
A stopgap pin: fakeredis 2.35.0 shipped an undocumented rename that broke pydocket's `memory://` backend, causing `fastmcp[tasks]` installs to fail at startup with an `ImportError`. This pins `fakeredis<2.35.0` in the `tasks` extra until a fixed pydocket ships.
### Fixes 🐞
* Pin `fakeredis<2.35.0` in tasks extra by [@jlowin](https://github.com/jlowin) in [#3804](https://github.com/PrefectHQ/fastmcp/pull/3804)
### Docs 📚
* Document session state isolation across mount boundaries by [@jlowin](https://github.com/jlowin) in [#3801](https://github.com/PrefectHQ/fastmcp/pull/3801)
**Full Changelog**: [v3.2.2...v3.2.3](https://github.com/PrefectHQ/fastmcp/compare/v3.2.2...v3.2.3)
</Update>
<Update label="v3.2.2" description="2026-04-09">
**[v3.2.2: Audience Appreciation](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.2.2)**
Fixes the Azure audience regression from 3.2.1: validation switched from `client_id` to `identifier_uri`, which fixed custom Application ID URIs but broke the default case where Azure AD v2 tokens set `aud` to the bare client ID GUID. Both formats are now accepted.
### Fixes 🐞
* fix: accept both client_id and identifier_uri as Azure audience by [@jlowin](https://github.com/jlowin) in [#3797](https://github.com/PrefectHQ/fastmcp/pull/3797)
### Dependencies 📦
* chore(deps): bump the uv group across 2 directories with 1 update by [@dependabot](https://github.com/dependabot) in [#3795](https://github.com/PrefectHQ/fastmcp/pull/3795)
**Full Changelog**: [v3.2.1...v3.2.2](https://github.com/PrefectHQ/fastmcp/compare/v3.2.1...v3.2.2)
</Update>
<Update label="v3.2.1" description="2026-04-08">
**[v3.2.1: Audience Participation](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.2.1)**
A patch focused on auth-provider audience validation. Cognito tokens now validate on `client_id` (they carry no `aud`), Azure honors the `identifier_uri` parameter for Entra v2.0 tokens, and consent cookies are LRU-capped to prevent unbounded growth past reverse proxy header limits. Also fixes OpenAPI 3.0 `nullable` fields leaking into tool input schemas and server-variable substitution in base URLs.
### Breaking Changes ⚠️
* fix(google): use sub (user ID) for client_id instead of aud (app ID) by [@shigechika](https://github.com/shigechika) in [#3722](https://github.com/PrefectHQ/fastmcp/pull/3722)
* fix: remove CSP from tool metadata, keep on resource only by [@jlowin](https://github.com/jlowin) in [#3754](https://github.com/PrefectHQ/fastmcp/pull/3754)
### Enhancements ✨
* [codex] Add FastMCP docs telemetry by [@aaazzam](https://github.com/aaazzam) in [#3727](https://github.com/PrefectHQ/fastmcp/pull/3727)
* chore: split SDK navigation into standalone $ref file by [@jlowin](https://github.com/jlowin) in [#3773](https://github.com/PrefectHQ/fastmcp/pull/3773)
* fix: bump ty to >=0.0.29 and suppress new false positives by [@jlowin](https://github.com/jlowin) in [#3790](https://github.com/PrefectHQ/fastmcp/pull/3790)
### Fixes 🐞
* fix: use explicit None checks for JWT exp validation by [@jlowin](https://github.com/jlowin) in [#3724](https://github.com/PrefectHQ/fastmcp/pull/3724)
* Unify background task context forwarding, fix concurrent dependency bugs by [@chrisguidry](https://github.com/chrisguidry) in [#3710](https://github.com/PrefectHQ/fastmcp/pull/3710)
* fix: add proxy timeouts and modernize networking in apps dev by [@mateeaaa](https://github.com/mateeaaa) in [#3741](https://github.com/PrefectHQ/fastmcp/pull/3741)
* fix: ResponseLimitingMiddleware no longer breaks outputSchema tools by [@jlowin](https://github.com/jlowin) in [#3756](https://github.com/PrefectHQ/fastmcp/pull/3756)
* fix: substitute server variable defaults when building base URL from OpenAPI spec by [@mrishav](https://github.com/mrishav) in [#3770](https://github.com/PrefectHQ/fastmcp/pull/3770)
* fix: FastAPI TestClient compatibility and lifespan re-initialization by [@kvdhanush06](https://github.com/kvdhanush06) in [#3736](https://github.com/PrefectHQ/fastmcp/pull/3736)
* fix: propagate upstream_claims in load_access_token by [@kvdhanush06](https://github.com/kvdhanush06) in [#3750](https://github.com/PrefectHQ/fastmcp/pull/3750)
* Remove deprecated asyncio.iscoroutinefunction fallback by [@kaiisfree](https://github.com/kaiisfree) in [#3767](https://github.com/PrefectHQ/fastmcp/pull/3767)
* fix: changeable allowed_client_redirect_uris on OAuthProxy by [@fengarix](https://github.com/fengarix) in [#3772](https://github.com/PrefectHQ/fastmcp/pull/3772)
* fix: broken link in changelog by [@jlowin](https://github.com/jlowin) in [#3775](https://github.com/PrefectHQ/fastmcp/pull/3775)
* fix(docs): correct FastMCP tool name in welcome docs by [@buyua9](https://github.com/buyua9) in [#3781](https://github.com/PrefectHQ/fastmcp/pull/3781)
* fix: cap consent cookie size to prevent header overflow by [@jlowin](https://github.com/jlowin) in [#3784](https://github.com/PrefectHQ/fastmcp/pull/3784)
* Fix boolean property schemas in JSON Schema parsing by [@jlowin](https://github.com/jlowin) in [#3785](https://github.com/PrefectHQ/fastmcp/pull/3785)
* Fix OpenAPI 3.0 nullable fields in tool input schemas by [@kvdhanush06](https://github.com/kvdhanush06) in [#3768](https://github.com/PrefectHQ/fastmcp/pull/3768)
* fix: Cognito token verification checks client_id instead of aud by [@jlowin](https://github.com/jlowin) in [#3786](https://github.com/PrefectHQ/fastmcp/pull/3786)
* fix: use identifier_uri as audience for Azure token validation by [@jlowin](https://github.com/jlowin) in [#3787](https://github.com/PrefectHQ/fastmcp/pull/3787)
* Harden client tool result error handling by [@aimable100](https://github.com/aimable100) in [#3778](https://github.com/PrefectHQ/fastmcp/pull/3778)
### Docs 📚
* Github integraiton documentation fix: use result.data otherwise CallToolResult not scriptable by [@c4jquick](https://github.com/c4jquick) in [#3753](https://github.com/PrefectHQ/fastmcp/pull/3753)
* chore: split v2 docs navigation into separate file by [@jlowin](https://github.com/jlowin) in [#3762](https://github.com/PrefectHQ/fastmcp/pull/3762)
* docs: document forward_resource parameter on OAuthProxy by [@jlowin](https://github.com/jlowin) in [#3788](https://github.com/PrefectHQ/fastmcp/pull/3788)
### Examples & Contrib 💡
* fix: boolean false values dropped in form submissions by [@jlowin](https://github.com/jlowin) in [#3776](https://github.com/PrefectHQ/fastmcp/pull/3776)
### Dependencies 📦
* chore(deps): bump fastmcp from 3.1.1 to 3.2.0 in /examples/testing_demo in the uv group across 1 directory by [@dependabot](https://github.com/dependabot) in [#3728](https://github.com/PrefectHQ/fastmcp/pull/3728)
* chore(deps): bump anthropic from 0.86.0 to 0.87.0 in the uv group across 1 directory by [@dependabot](https://github.com/dependabot) in [#3742](https://github.com/PrefectHQ/fastmcp/pull/3742)
## New Contributors
* @c4jquick made their first contribution in [#3753](https://github.com/PrefectHQ/fastmcp/pull/3753)
* @mateeaaa made their first contribution in [#3741](https://github.com/PrefectHQ/fastmcp/pull/3741)
* @mrishav made their first contribution in [#3770](https://github.com/PrefectHQ/fastmcp/pull/3770)
* @kvdhanush06 made their first contribution in [#3736](https://github.com/PrefectHQ/fastmcp/pull/3736)
* @kaiisfree made their first contribution in [#3767](https://github.com/PrefectHQ/fastmcp/pull/3767)
* @fengarix made their first contribution in [#3772](https://github.com/PrefectHQ/fastmcp/pull/3772)
* @buyua9 made their first contribution in [#3781](https://github.com/PrefectHQ/fastmcp/pull/3781)
* @aimable100 made their first contribution in [#3778](https://github.com/PrefectHQ/fastmcp/pull/3778)
**Full Changelog**: [v3.2.0...v3.2.1](https://github.com/PrefectHQ/fastmcp/compare/v3.2.0...v3.2.1)
</Update>
<Update label="v3.2.0" description="2026-03-30">
**[v3.2.0: Show Don't Tool](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.2.0)**
FastMCP 3.2 is the Apps release: your tools can now return interactive UIs — charts, dashboards, forms, maps — rendered right inside the conversation. `FastMCPApp` separates the tools the LLM sees from the backend tools the UI calls, five built-in providers (FileUpload, Approval, Choice, FormInput, GenerativeUI) cover common interaction patterns, and `fastmcp dev apps` gives you a browser preview. The release also lands a significant security hardening pass across SSRF/path-traversal, JWT algorithm restrictions, OAuth scope enforcement, and CSRF.
### New Features 🎉
* Add FastMCPApp — a Provider for composable MCP applications by [@jlowin](https://github.com/jlowin) in [#3385](https://github.com/PrefectHQ/fastmcp/pull/3385)
* Add fastmcp dev apps command with browser UI preview by [@jlowin](https://github.com/jlowin) in [#3489](https://github.com/PrefectHQ/fastmcp/pull/3489)
* Add GenerativeUI provider, bump prefab-ui 0.14.0 by [@jlowin](https://github.com/jlowin) in [#3647](https://github.com/PrefectHQ/fastmcp/pull/3647)
* Add FileUpload provider by [@jlowin](https://github.com/jlowin) in [#3669](https://github.com/PrefectHQ/fastmcp/pull/3669)
* Add Approval and Choice providers by [@jlowin](https://github.com/jlowin) in [#3686](https://github.com/PrefectHQ/fastmcp/pull/3686)
* Add FormInput provider, bump prefab-ui to 0.15.0 by [@jlowin](https://github.com/jlowin) in [#3687](https://github.com/PrefectHQ/fastmcp/pull/3687)
### Breaking Changes ⚠️
* Route app tool calls via ___-prefixed names by [@jlowin](https://github.com/jlowin) in [#3667](https://github.com/PrefectHQ/fastmcp/pull/3667)
### Enhancements ✨
* feat: add `--config-path` flag to claude-desktop install command by [@Sumanshu-Nankana](https://github.com/Sumanshu-Nankana) in [#3380](https://github.com/PrefectHQ/fastmcp/pull/3380)
* Support ImageContent and AudioContent in Message class by [@ericrobinson-indeed](https://github.com/ericrobinson-indeed) in [#3396](https://github.com/PrefectHQ/fastmcp/pull/3396)
* Deprecate PromptToolMiddleware and ResourceToolMiddleware by [@jlowin](https://github.com/jlowin) in [#3389](https://github.com/PrefectHQ/fastmcp/pull/3389)
* Block HS* algorithms when JWTVerifier is configured with JWKS by [@jlowin](https://github.com/jlowin) in [#3419](https://github.com/PrefectHQ/fastmcp/pull/3419)
* Remove prek from Marvin workflows by [@jlowin](https://github.com/jlowin) in [#3444](https://github.com/PrefectHQ/fastmcp/pull/3444)
* Add dependency version compatibility guidance to code-review skill by [@jlowin](https://github.com/jlowin) in [#3475](https://github.com/PrefectHQ/fastmcp/pull/3475)
* Remove "good first issue" label by [@jlowin](https://github.com/jlowin) in [#3482](https://github.com/PrefectHQ/fastmcp/pull/3482)
* Cache component lists in ProxyProvider by [@jlowin](https://github.com/jlowin) in [#3479](https://github.com/PrefectHQ/fastmcp/pull/3479)
* Support logging/setLevel and add client_log_level by [@jlowin](https://github.com/jlowin) in [#3491](https://github.com/PrefectHQ/fastmcp/pull/3491)
* Propagate x-fastmcp-wrap-result in tool result _meta by [@jlowin](https://github.com/jlowin) in [#3490](https://github.com/PrefectHQ/fastmcp/pull/3490)
* feat(auth): add external_consent param to suppress misleading warning by [@mtthidoteu](https://github.com/mtthidoteu) in [#3473](https://github.com/PrefectHQ/fastmcp/pull/3473)
* Add `verify` parameter for SSL certificate configuration by [@jlowin](https://github.com/jlowin) in [#3487](https://github.com/PrefectHQ/fastmcp/pull/3487)
* Expose minimum_check_interval, reduce task pickup latency by [@jlowin](https://github.com/jlowin) in [#3500](https://github.com/PrefectHQ/fastmcp/pull/3500)
* Fix test timeouts, suppress deprecation warnings, speed up auth tests by [@jlowin](https://github.com/jlowin) in [#3504](https://github.com/PrefectHQ/fastmcp/pull/3504)
* Auto-close upgrade check issue when build passes by [@jlowin](https://github.com/jlowin) in [#3505](https://github.com/PrefectHQ/fastmcp/pull/3505)
* feat: make upstream_client_secret optional in OAuthProxy by [@jlowin](https://github.com/jlowin) in [#3486](https://github.com/PrefectHQ/fastmcp/pull/3486)
* Add security label to triage workflow and release notes by [@jlowin](https://github.com/jlowin) in [#3516](https://github.com/PrefectHQ/fastmcp/pull/3516)
* Claude/review contributor guidelines by [@jlowin](https://github.com/jlowin) in [#3517](https://github.com/PrefectHQ/fastmcp/pull/3517)
* pin pydantic-monty to 0.0.8 by [@jlowin](https://github.com/jlowin) in [#3539](https://github.com/PrefectHQ/fastmcp/pull/3539)
* Support ImageContent and AudioContent in sampling handlers by [@jlowin](https://github.com/jlowin) in [#3550](https://github.com/PrefectHQ/fastmcp/pull/3550)
* Graceful degradation for multi-server proxy setup by [@jlowin](https://github.com/jlowin) in [#3546](https://github.com/PrefectHQ/fastmcp/pull/3546)
* Extract TokenCache utility, add caching to GitHubTokenVerifier by [@jlowin](https://github.com/jlowin) in [#3547](https://github.com/PrefectHQ/fastmcp/pull/3547)
* Add review-pr skill for Codex bot workflow by [@jlowin](https://github.com/jlowin) in [#3552](https://github.com/PrefectHQ/fastmcp/pull/3552)
* Add MCP message inspector to dev apps UI by [@jlowin](https://github.com/jlowin) in [#3570](https://github.com/PrefectHQ/fastmcp/pull/3570)
* Comprehensive MCP Apps docs, string CallTool resolution by [@jlowin](https://github.com/jlowin) in [#3575](https://github.com/PrefectHQ/fastmcp/pull/3575)
* Replace UUID global keys with (app_name, tool_name) registry by [@jlowin](https://github.com/jlowin) in [#3585](https://github.com/PrefectHQ/fastmcp/pull/3585)
* Route app tool calls through provider chain by [@jlowin](https://github.com/jlowin) in [#3587](https://github.com/PrefectHQ/fastmcp/pull/3587)
* Dev apps: show more/less for long tool descriptions by [@jlowin](https://github.com/jlowin) in [#3600](https://github.com/PrefectHQ/fastmcp/pull/3600)
* Apps Phase 1: docs, examples, app-only tool filtering by [@jlowin](https://github.com/jlowin) in [#3593](https://github.com/PrefectHQ/fastmcp/pull/3593)
* Forward enable_cimd to OAuthProxy in all provider subclasses by [@jlowin](https://github.com/jlowin) in [#3608](https://github.com/PrefectHQ/fastmcp/pull/3608)
* Tune too-long triage heuristic by [@jlowin](https://github.com/jlowin) in [#3610](https://github.com/PrefectHQ/fastmcp/pull/3610)
* Update ty ignore comments for 0.0.25 compatibility by [@jlowin](https://github.com/jlowin) in [#3614](https://github.com/PrefectHQ/fastmcp/pull/3614)
* Move app modules to fastmcp.apps package by [@jlowin](https://github.com/jlowin) in [#3616](https://github.com/PrefectHQ/fastmcp/pull/3616)
* Tighten too-long heuristic for design-document issues by [@jlowin](https://github.com/jlowin) in [#3620](https://github.com/PrefectHQ/fastmcp/pull/3620)
* Run MCP conformance tests by [@strawgate](https://github.com/strawgate) in [#3628](https://github.com/PrefectHQ/fastmcp/pull/3628)
* Add PrefabAppConfig for customizable Prefab tool setup by [@jlowin](https://github.com/jlowin) in [#3648](https://github.com/PrefectHQ/fastmcp/pull/3648)
* Clean error when dev apps ports are in use by [@jlowin](https://github.com/jlowin) in [#3658](https://github.com/PrefectHQ/fastmcp/pull/3658)
* Add Clerk OAuth provider by [@mostafa6765](https://github.com/mostafa6765) in [#3677](https://github.com/PrefectHQ/fastmcp/pull/3677)
* Add interactive map example with geocoding by [@jlowin](https://github.com/jlowin) in [#3702](https://github.com/PrefectHQ/fastmcp/pull/3702)
* Bump pydantic-monty to 0.0.9 by [@jlowin](https://github.com/jlowin) in [#3707](https://github.com/PrefectHQ/fastmcp/pull/3707)
* Add forward_resource flag to OAuthProxy by [@jlowin](https://github.com/jlowin) in [#3711](https://github.com/PrefectHQ/fastmcp/pull/3711)
### Security 🔒
* fix: enforce per-tool auth checks in sampling tool wrapper by [@jlowin](https://github.com/jlowin) in [#3494](https://github.com/PrefectHQ/fastmcp/pull/3494)
* fix: handle re.error from malformed URI templates by [@jlowin](https://github.com/jlowin) in [#3501](https://github.com/PrefectHQ/fastmcp/pull/3501)
* fix: reject empty/OIDC-only required_scopes in AzureProvider by [@jlowin](https://github.com/jlowin) in [#3503](https://github.com/PrefectHQ/fastmcp/pull/3503)
* fix: restrict $ref resolution to local refs only (SSRF/LFI) by [@jlowin](https://github.com/jlowin) in [#3502](https://github.com/PrefectHQ/fastmcp/pull/3502)
* fix: URL-encode path params to prevent SSRF/path traversal (GHSA-vv7q-7jx5-f767) by [@jlowin](https://github.com/jlowin) in [#3507](https://github.com/PrefectHQ/fastmcp/pull/3507)
* fix: prevent path traversal in skill download by [@jlowin](https://github.com/jlowin) in [#3493](https://github.com/PrefectHQ/fastmcp/pull/3493)
* fix: prefer IdP-granted scopes over client-requested scopes in OAuthProxy by [@jlowin](https://github.com/jlowin) in [#3492](https://github.com/PrefectHQ/fastmcp/pull/3492)
* fix: remove forced follow_redirects from httpx_client_factory calls by [@jlowin](https://github.com/jlowin) in [#3496](https://github.com/PrefectHQ/fastmcp/pull/3496)
* Bump PyJWT >= 2.12.0 (CVE-2026-32597) by [@jlowin](https://github.com/jlowin) in [#3515](https://github.com/PrefectHQ/fastmcp/pull/3515)
* Drop diskcache from examples/testing_demo lockfile (CVE-2025-69872) by [@jlowin](https://github.com/jlowin) in [#3518](https://github.com/PrefectHQ/fastmcp/pull/3518)
* fix: CSRF double-submit cookie check in consent flow by [@jlowin](https://github.com/jlowin) in [#3519](https://github.com/PrefectHQ/fastmcp/pull/3519)
* fix: validate server names in install commands by [@jlowin](https://github.com/jlowin) in [#3522](https://github.com/PrefectHQ/fastmcp/pull/3522)
* fix: reject refresh tokens used as Bearer access tokens by [@jlowin](https://github.com/jlowin) in [#3524](https://github.com/PrefectHQ/fastmcp/pull/3524)
* fix: route ResourcesAsTools/PromptsAsTools through server middleware by [@jlowin](https://github.com/jlowin) in [#3495](https://github.com/PrefectHQ/fastmcp/pull/3495)
### Fixes 🐞
* Update docs banner and fix mobile layout by [@jlowin](https://github.com/jlowin) in [#3370](https://github.com/PrefectHQ/fastmcp/pull/3370)
* Remove form-action from consent CSP, forward consent_csp_policy in providers by [@jlowin](https://github.com/jlowin) in [#3372](https://github.com/PrefectHQ/fastmcp/pull/3372)
* Fix resource templates with query params on mounted servers by [@jlowin](https://github.com/jlowin) in [#3373](https://github.com/PrefectHQ/fastmcp/pull/3373)
* Increase uv transport test timeout for CI cold starts by [@jlowin](https://github.com/jlowin) in [#3376](https://github.com/PrefectHQ/fastmcp/pull/3376)
* Fix stale catalog in CodeMode execute by [@jlowin](https://github.com/jlowin) in [#3375](https://github.com/PrefectHQ/fastmcp/pull/3375)
* Deduplicate versioned tools in CatalogTransform catalog by [@jlowin](https://github.com/jlowin) in [#3374](https://github.com/PrefectHQ/fastmcp/pull/3374)
* Fix ty 0.0.20 compatibility by [@jlowin](https://github.com/jlowin) in [#3377](https://github.com/PrefectHQ/fastmcp/pull/3377)
* Forward scopes_supported through RemoteAuthProvider subclasses by [@jlowin](https://github.com/jlowin) in [#3388](https://github.com/PrefectHQ/fastmcp/pull/3388)
* Enforce token scopes in WorkOS verifier to prevent scope bypass by [@jlowin](https://github.com/jlowin) in [#3407](https://github.com/PrefectHQ/fastmcp/pull/3407)
* Bind Discord token verification to configured client_id by [@jlowin](https://github.com/jlowin) in [#3405](https://github.com/PrefectHQ/fastmcp/pull/3405)
* Return after `McpError` in initialization middleware to prevent fallthrough by [@jlowin](https://github.com/jlowin) in [#3413](https://github.com/PrefectHQ/fastmcp/pull/3413)
* Escape client_id in OAuth consent advanced details by [@jlowin](https://github.com/jlowin) in [#3418](https://github.com/PrefectHQ/fastmcp/pull/3418)
* Bound client auto-pagination loops to prevent unbounded list fetches by [@jlowin](https://github.com/jlowin) in [#3411](https://github.com/PrefectHQ/fastmcp/pull/3411)
* Raise ValueError for invalid boolean query params in resource templates by [@jlowin](https://github.com/jlowin) in [#3434](https://github.com/PrefectHQ/fastmcp/pull/3434)
* Validate workspace path is a directory in cursor install by [@jlowin](https://github.com/jlowin) in [#3435](https://github.com/PrefectHQ/fastmcp/pull/3435)
* Validate version metadata to reject non-scalar types by [@jlowin](https://github.com/jlowin) in [#3437](https://github.com/PrefectHQ/fastmcp/pull/3437)
* Bind AWS Cognito token verification to configured app client by [@jlowin](https://github.com/jlowin) in [#3406](https://github.com/PrefectHQ/fastmcp/pull/3406)
* Avoid stale context leakage when proxying with an alreadyconnected ProxyClient by [@jlowin](https://github.com/jlowin) in [#3408](https://github.com/PrefectHQ/fastmcp/pull/3408)
* Prevent skills manifests from hashing files outside the skill directory by [@jlowin](https://github.com/jlowin) in [#3410](https://github.com/PrefectHQ/fastmcp/pull/3410)
* Harden fastmcp metadata parsing in proxy paths by [@jlowin](https://github.com/jlowin) in [#3412](https://github.com/PrefectHQ/fastmcp/pull/3412)
* Re-hash response caching keys to avoid persisting raw request input by [@jlowin](https://github.com/jlowin) in [#3414](https://github.com/PrefectHQ/fastmcp/pull/3414)
* Handle Windows npx detection when npx.cmd is missing by [@jlowin](https://github.com/jlowin) in [#3416](https://github.com/PrefectHQ/fastmcp/pull/3416)
* Guard OAuth callback result from post-completion overwrites by [@jlowin](https://github.com/jlowin) in [#3417](https://github.com/PrefectHQ/fastmcp/pull/3417)
* Fix tool argument rename collisions with passthrough params by [@jlowin](https://github.com/jlowin) in [#3431](https://github.com/PrefectHQ/fastmcp/pull/3431)
* Guard default progress handler against total=0 notifications by [@jlowin](https://github.com/jlowin) in [#3432](https://github.com/PrefectHQ/fastmcp/pull/3432)
* Fix get_* returning None when latest version is disabled by [@jlowin](https://github.com/jlowin) in [#3439](https://github.com/PrefectHQ/fastmcp/pull/3439)
* Fix server lifespan overlap teardown by [@jlowin](https://github.com/jlowin) in [#3415](https://github.com/PrefectHQ/fastmcp/pull/3415)
* Fix $ref output schema object detection regression by [@jlowin](https://github.com/jlowin) in [#3420](https://github.com/PrefectHQ/fastmcp/pull/3420)
* Preserve kw-only defaults when rebuilding functions for resolved annotations by [@jlowin](https://github.com/jlowin) in [#3429](https://github.com/PrefectHQ/fastmcp/pull/3429)
* Redact sensitive headers in OpenAPI provider debug logging by [@jlowin](https://github.com/jlowin) in [#3436](https://github.com/PrefectHQ/fastmcp/pull/3436)
* Fix async partial callables rejected by iscoroutinefunction by [@jlowin](https://github.com/jlowin) in [#3438](https://github.com/PrefectHQ/fastmcp/pull/3438)
* Block insecure HS* JWT verification with JWKS/public keys by [@jlowin](https://github.com/jlowin) in [#3430](https://github.com/PrefectHQ/fastmcp/pull/3430)
* Sanitize untrusted output in `fastmcp list` and `fastmcp call` by [@jlowin](https://github.com/jlowin) in [#3409](https://github.com/PrefectHQ/fastmcp/pull/3409)
* fix: propagate `version` to components in FileSystemProvider by [@martimfasantos](https://github.com/martimfasantos) in [#3458](https://github.com/PrefectHQ/fastmcp/pull/3458)
* fix: use intent-based flag for OIDC scope patch in load_access_token by [@voidborne-d](https://github.com/voidborne-d) in [#3465](https://github.com/PrefectHQ/fastmcp/pull/3465)
* Set readOnlyHint=True on ResourcesAsTools generated tools by [@jlowin](https://github.com/jlowin) in [#3476](https://github.com/PrefectHQ/fastmcp/pull/3476)
* fix: normalize Google scope shorthands and surface valid_scopes by [@jlowin](https://github.com/jlowin) in [#3477](https://github.com/PrefectHQ/fastmcp/pull/3477)
* fix: resolve ty 0.0.23 type-checking errors by [@jlowin](https://github.com/jlowin) in [#3481](https://github.com/PrefectHQ/fastmcp/pull/3481)
* fix: shield lifespan teardown from cancellation by [@jlowin](https://github.com/jlowin) in [#3480](https://github.com/PrefectHQ/fastmcp/pull/3480)
* fix: forward custom_route endpoints from mounted servers by [@voidborne-d](https://github.com/voidborne-d) in [#3462](https://github.com/PrefectHQ/fastmcp/pull/3462)
* fix: use dynamic version in CLI help text instead of hardcoded 2.0 by [@saschabuehrle](https://github.com/saschabuehrle) in [#3456](https://github.com/PrefectHQ/fastmcp/pull/3456)
* Fix Monty 0.0.8 compatibility by [@hkc5](https://github.com/hkc5) in [#3468](https://github.com/PrefectHQ/fastmcp/pull/3468)
* Fix task test teardown hanging 5s per test by [@jlowin](https://github.com/jlowin) in [#3499](https://github.com/PrefectHQ/fastmcp/pull/3499)
* fix: validate workspace path is a directory before cursor install by [@nightcityblade](https://github.com/nightcityblade) in [#3440](https://github.com/PrefectHQ/fastmcp/pull/3440)
* Treat `refresh_expires_in=0` as missing, fall back to 30-day default by [@jlowin](https://github.com/jlowin) in [#3514](https://github.com/PrefectHQ/fastmcp/pull/3514)
* fix: use raw strings for regex in pytest.raises match by [@jlowin](https://github.com/jlowin) in [#3523](https://github.com/PrefectHQ/fastmcp/pull/3523)
* fix: resolve Pyright "Module is not callable" on @tool, @resource, @prompt decorators by [@jlowin](https://github.com/jlowin) in [#3540](https://github.com/PrefectHQ/fastmcp/pull/3540)
* fix: flaky KEY_PREFIX warning test in lowest-direct deps by [@jlowin](https://github.com/jlowin) in [#3549](https://github.com/PrefectHQ/fastmcp/pull/3549)
* fix: suppress output schema for ToolResult subclass annotations by [@jlowin](https://github.com/jlowin) in [#3548](https://github.com/PrefectHQ/fastmcp/pull/3548)
* Bump anthropic minimum to 0.48.0 by [@jlowin](https://github.com/jlowin) in [#3553](https://github.com/PrefectHQ/fastmcp/pull/3553)
* Update startup banner deploy URL to Prefect Horizon by [@zzstoatzz](https://github.com/zzstoatzz) in [#3557](https://github.com/PrefectHQ/fastmcp/pull/3557)
* fix: increase sleep duration in proxy cache tests by [@strawgate](https://github.com/strawgate) in [#3567](https://github.com/PrefectHQ/fastmcp/pull/3567)
* fix: store absolute token expiry to prevent stale expires_in on reload by [@jlowin](https://github.com/jlowin) in [#3572](https://github.com/PrefectHQ/fastmcp/pull/3572)
* fix: preserve tool properties named 'title' during schema compression by [@jlowin](https://github.com/jlowin) in [#3582](https://github.com/PrefectHQ/fastmcp/pull/3582)
* Add `encoding` parameter to `FileResource` by [@shulkx](https://github.com/shulkx) in [#3580](https://github.com/PrefectHQ/fastmcp/pull/3580)
* Transparently refresh upstream token in OAuthProxy.load_access_token() by [@jlowin](https://github.com/jlowin) in [#3584](https://github.com/PrefectHQ/fastmcp/pull/3584)
* Fix loopback redirect URI port matching per RFC 8252 §7.3 by [@radoshi](https://github.com/radoshi) in [#3589](https://github.com/PrefectHQ/fastmcp/pull/3589)
* Fix app tool routing: visibility check and middleware propagation by [@jlowin](https://github.com/jlowin) in [#3591](https://github.com/PrefectHQ/fastmcp/pull/3591)
* Fix query parameter serialization to respect OpenAPI explode setting by [@jlowin](https://github.com/jlowin) in [#3595](https://github.com/PrefectHQ/fastmcp/pull/3595)
* Fix dev apps form: union types, textarea support, JSON parsing by [@jlowin](https://github.com/jlowin) in [#3597](https://github.com/PrefectHQ/fastmcp/pull/3597)
* Respect OpenAPI content type in request body serialization by [@jlowin](https://github.com/jlowin) in [#3611](https://github.com/PrefectHQ/fastmcp/pull/3611)
* fix(google): replace deprecated /oauth2/v1/tokeninfo with /oauth2/v3/userinfo by [@shigechika](https://github.com/shigechika) in [#3603](https://github.com/PrefectHQ/fastmcp/pull/3603)
* fix: resolve EntraOBOToken dependency injection through MultiAuth by [@jer805](https://github.com/jer805) in [#3609](https://github.com/PrefectHQ/fastmcp/pull/3609)
* fix: filesystem provider import machinery by [@strawgate](https://github.com/strawgate) in [#3626](https://github.com/PrefectHQ/fastmcp/pull/3626)
* fix: recover StdioTransport after subprocess exits by [@strawgate](https://github.com/strawgate) in [#3630](https://github.com/PrefectHQ/fastmcp/pull/3630)
* fix(server): preserve mounted tool task metadata by [@pandego](https://github.com/pandego) in [#3632](https://github.com/PrefectHQ/fastmcp/pull/3632)
* fix: scope deprecation warning filter to FastMCPDeprecationWarning by [@jlowin](https://github.com/jlowin) in [#3649](https://github.com/PrefectHQ/fastmcp/pull/3649)
* fix: resolve CurrentFastMCP/ctx.fastmcp to child server in mounted background tasks by [@jlowin](https://github.com/jlowin) in [#3651](https://github.com/PrefectHQ/fastmcp/pull/3651)
* Fix blocking docs issues: chart imports, Select API, Rx consistency by [@jlowin](https://github.com/jlowin) in [#3652](https://github.com/PrefectHQ/fastmcp/pull/3652)
* Fix prompt caching round-trip on cache miss by [@strawgate](https://github.com/strawgate) in [#3666](https://github.com/PrefectHQ/fastmcp/pull/3666)
* fix: serialize object query params per OpenAPI style/explode rules by [@4444J99](https://github.com/4444J99) in [#3662](https://github.com/PrefectHQ/fastmcp/pull/3662)
* fix: HTTP request headers not accessible in background task workers by [@pandego](https://github.com/pandego) in [#3631](https://github.com/PrefectHQ/fastmcp/pull/3631)
* fix: restore HTTP headers in worker execution path for background tasks by [@jlowin](https://github.com/jlowin) in [#3681](https://github.com/PrefectHQ/fastmcp/pull/3681)
* fix: strip discriminator after dereferencing schemas by [@jlowin](https://github.com/jlowin) in [#3682](https://github.com/PrefectHQ/fastmcp/pull/3682)
* fix: remove stale ty:ignore directives for ty 0.0.26 by [@jlowin](https://github.com/jlowin) in [#3684](https://github.com/PrefectHQ/fastmcp/pull/3684)
* fix: dev apps log panel UX improvements by [@jlowin](https://github.com/jlowin) in [#3698](https://github.com/PrefectHQ/fastmcp/pull/3698)
* Add quiz example app, fix dev server empty string args by [@jlowin](https://github.com/jlowin) in [#3700](https://github.com/PrefectHQ/fastmcp/pull/3700)
### Docs 📚
* Add early-development warning to Prefab docs by [@jlowin](https://github.com/jlowin) in [#3362](https://github.com/PrefectHQ/fastmcp/pull/3362)
* Add tag to docs by [@jlowin](https://github.com/jlowin) in [#3382](https://github.com/PrefectHQ/fastmcp/pull/3382)
* Add settings and environment variables reference by [@jlowin](https://github.com/jlowin) in [#3384](https://github.com/PrefectHQ/fastmcp/pull/3384)
* Add contributing guidelines and update issue/PR templates by [@jlowin](https://github.com/jlowin) in [#3485](https://github.com/PrefectHQ/fastmcp/pull/3485)
* [Documentation] Move stateless_http transport kwarg to http_app as FastMCP constructor… by [@mhallo](https://github.com/mhallo) in [#3510](https://github.com/PrefectHQ/fastmcp/pull/3510)
* Update security policy by [@jlowin](https://github.com/jlowin) in [#3521](https://github.com/PrefectHQ/fastmcp/pull/3521)
* Add release instructions to CLAUDE.md by [@jlowin](https://github.com/jlowin) in [#3583](https://github.com/PrefectHQ/fastmcp/pull/3583)
* fix(docs): correct misleading stateless_http header by [@jlowin](https://github.com/jlowin) in [#3622](https://github.com/PrefectHQ/fastmcp/pull/3622)
* Add tag to deployment pages by [@jlowin](https://github.com/jlowin) in [#3624](https://github.com/PrefectHQ/fastmcp/pull/3624)
* Docs: generative UI page, fix imports, add PrefabAppConfig by [@jlowin](https://github.com/jlowin) in [#3650](https://github.com/PrefectHQ/fastmcp/pull/3650)
* docs: improve contributor guidelines for framework contributions by [@jlowin](https://github.com/jlowin) in [#3653](https://github.com/PrefectHQ/fastmcp/pull/3653)
* Add release notes for v3.1.0, v3.1.1, and v2.14.6 by [@jlowin](https://github.com/jlowin) in [#3659](https://github.com/PrefectHQ/fastmcp/pull/3659)
* Docs: showcase hero, narrative improvements, panel closed by default by [@jlowin](https://github.com/jlowin) in [#3657](https://github.com/PrefectHQ/fastmcp/pull/3657)
* Docs: add FileTreeStore sanitization warnings and update examples by [@strawgate](https://github.com/strawgate) in [#3661](https://github.com/PrefectHQ/fastmcp/pull/3661)
* Add prefab-ui version pinning warning to docs by [@jlowin](https://github.com/jlowin) in [#3688](https://github.com/PrefectHQ/fastmcp/pull/3688)
* Reorganize apps overview TOC by [@jlowin](https://github.com/jlowin) in [#3689](https://github.com/PrefectHQ/fastmcp/pull/3689)
* Fix docs gaps in app provider pages by [@jlowin](https://github.com/jlowin) in [#3690](https://github.com/PrefectHQ/fastmcp/pull/3690)
* Polish apps docs for 3.2 release by [@jlowin](https://github.com/jlowin) in [#3693](https://github.com/PrefectHQ/fastmcp/pull/3693)
* Add apps quickstart tutorial by [@jlowin](https://github.com/jlowin) in [#3695](https://github.com/PrefectHQ/fastmcp/pull/3695)
* Improve quickstart: pie chart, interactive row selection, screenshots by [@jlowin](https://github.com/jlowin) in [#3699](https://github.com/PrefectHQ/fastmcp/pull/3699)
* Add sales dashboard and live system monitor examples, bump prefab-ui to 0.17 by [@jlowin](https://github.com/jlowin) in [#3696](https://github.com/PrefectHQ/fastmcp/pull/3696)
* Add examples gallery page by [@jlowin](https://github.com/jlowin) in [#3705](https://github.com/PrefectHQ/fastmcp/pull/3705)
* docs: note that custom routes are unauthenticated by [@jlowin](https://github.com/jlowin) in [#3706](https://github.com/PrefectHQ/fastmcp/pull/3706)
* Remove hardcoded prefab-ui version from pinning warnings by [@jlowin](https://github.com/jlowin) in [#3708](https://github.com/PrefectHQ/fastmcp/pull/3708)
### Examples & Contrib 💡
* Block recursive self-invocation in BulkToolCaller by [@jlowin](https://github.com/jlowin) in [#3433](https://github.com/PrefectHQ/fastmcp/pull/3433)
### Dependencies 📦
* Bump authlib from 1.6.6 to 1.6.7 in /examples/testing_demo in the uv group across 1 directory by [@dependabot](https://github.com/dependabot) in [#3390](https://github.com/PrefectHQ/fastmcp/pull/3390)
* Bump actions/create-github-app-token from 2 to 3 by [@dependabot](https://github.com/dependabot) in [#3511](https://github.com/PrefectHQ/fastmcp/pull/3511)
* chore(deps): bump pyasn1 from 0.6.2 to 0.6.3 in the uv group across 1 directory by [@dependabot](https://github.com/dependabot) in [#3538](https://github.com/PrefectHQ/fastmcp/pull/3538)
* chore(deps): bump j178/prek-action from 1 to 2 by [@dependabot](https://github.com/dependabot) in [#3578](https://github.com/PrefectHQ/fastmcp/pull/3578)
* chore(deps): bump requests from 2.32.5 to 2.33.0 in the uv group across 1 directory by [@dependabot](https://github.com/dependabot) in [#3638](https://github.com/PrefectHQ/fastmcp/pull/3638)
* chore(deps): bump cryptography from 46.0.5 to 46.0.6 in /examples/testing_demo in the uv group across 1 directory by [@dependabot](https://github.com/dependabot) in [#3685](https://github.com/PrefectHQ/fastmcp/pull/3685)
* chore(deps): bump actions/setup-node from 4 to 6 by [@dependabot](https://github.com/dependabot) in [#3691](https://github.com/PrefectHQ/fastmcp/pull/3691)
## New Contributors
* @Sumanshu-Nankana made their first contribution in [#3380](https://github.com/PrefectHQ/fastmcp/pull/3380)
* @ericrobinson-indeed made their first contribution in [#3396](https://github.com/PrefectHQ/fastmcp/pull/3396)
* @voidborne-d made their first contribution in [#3465](https://github.com/PrefectHQ/fastmcp/pull/3465)
* @mtthidoteu made their first contribution in [#3473](https://github.com/PrefectHQ/fastmcp/pull/3473)
* @saschabuehrle made their first contribution in [#3456](https://github.com/PrefectHQ/fastmcp/pull/3456)
* @hkc5 made their first contribution in [#3468](https://github.com/PrefectHQ/fastmcp/pull/3468)
* @nightcityblade made their first contribution in [#3440](https://github.com/PrefectHQ/fastmcp/pull/3440)
* @mhallo made their first contribution in [#3510](https://github.com/PrefectHQ/fastmcp/pull/3510)
* @radoshi made their first contribution in [#3589](https://github.com/PrefectHQ/fastmcp/pull/3589)
* @shigechika made their first contribution in [#3603](https://github.com/PrefectHQ/fastmcp/pull/3603)
* @pandego made their first contribution in [#3632](https://github.com/PrefectHQ/fastmcp/pull/3632)
* @4444J99 made their first contribution in [#3662](https://github.com/PrefectHQ/fastmcp/pull/3662)
* @mostafa6765 made their first contribution in [#3677](https://github.com/PrefectHQ/fastmcp/pull/3677)
**Full Changelog**: [v3.1.0...v3.2.0](https://github.com/PrefectHQ/fastmcp/compare/v3.1.0...v3.2.0)
</Update>
<Update label="v3.1.1" description="2026-03-14">
**[v3.1.1: 'Tis But a Patch](https://github.com/PrefectHQ/fastmcp/releases/tag/v3.1.1)**
@ -743,6 +1635,19 @@ Breaking changes are minimal: for most servers, updating the import statement is
</Update>
<Update label="v2.14.7" description="2026-04-13">
**[v2.14.7: Fake It Till You Break It](https://github.com/PrefectHQ/fastmcp/releases/tag/v2.14.7)**
A 2.x backport of the fakeredis pin: fakeredis 2.35.0 renamed a connection class that pydocket's `memory://` backend depended on, crashing `fastmcp[tasks]` installs at startup. This caps `fakeredis<2.35.0` on the 2.x line.
### Fixes 🐞
* fix(deps): cap fakeredis to `<2.35.0` to prevent startup crash on 2.x by [@vincent067](https://github.com/vincent067) in [#3883](https://github.com/PrefectHQ/fastmcp/pull/3883)
**Full Changelog**: [v2.14.6...v2.14.7](https://github.com/PrefectHQ/fastmcp/compare/v2.14.6...v2.14.7)
</Update>
<Update label="v2.14.6" description="2026-03-27">
**[v2.14.6: $Ref Dead Redemption](https://github.com/PrefectHQ/fastmcp/releases/tag/v2.14.6)**
@ -1274,7 +2179,7 @@ Thank you to our new contributors and everyone who tested preview builds. Your f
* Add configurable redirect URI validation for OAuth providers by [@jlowin](https://github.com/jlowin) in [#1582](https://github.com/PrefectHQ/fastmcp/pull/1582)
* Remove invalid-argument-type ignore and fix type errors by [@jlowin](https://github.com/jlowin) in [#1588](https://github.com/PrefectHQ/fastmcp/pull/1588)
* Remove generate-schema from public CLI by [@jlowin](https://github.com/jlowin) in [#1591](https://github.com/PrefectHQ/fastmcp/pull/1591)
* Skip flaky windows test / mulit-client garbage collection by [@jlowin](https://github.com/jlowin) in [#1592](https://github.com/PrefectHQ/fastmcp/pull/1592)
* Skip flaky windows test / multi-client garbage collection by [@jlowin](https://github.com/jlowin) in [#1592](https://github.com/PrefectHQ/fastmcp/pull/1592)
* Add setting to disable logging configuration by [@isra17](https://github.com/isra17) in [#1575](https://github.com/PrefectHQ/fastmcp/pull/1575)
* Improve debug logging for nested Servers / Clients by [@strawgate](https://github.com/strawgate) in [#1604](https://github.com/PrefectHQ/fastmcp/pull/1604)
* Add GitHub pull request template by [@strawgate](https://github.com/strawgate) in [#1581](https://github.com/PrefectHQ/fastmcp/pull/1581)
@ -3063,4 +3968,4 @@ This release is highlighted by the ability to handle complex JSON objects as MCP
The very first release of FastMCP! 🎉
**Full Changelog**: [Initial commits](https://github.com/PrefectHQ/fastmcp/commits/v0.1.0)
</Update>
</Update>

View file

@ -23,21 +23,24 @@ fastmcp auth cimd create \
```json
{
"client_id": "https://your-domain.com/oauth/client.json",
"client_id": "https://YOUR-DOMAIN.com/path/to/client.json",
"client_name": "My App",
"redirect_uris": ["http://localhost:*/callback"],
"token_endpoint_auth_method": "none"
"token_endpoint_auth_method": "none",
"grant_types": ["authorization_code"],
"response_types": ["code"]
}
```
The generated document includes a placeholder `client_id` — update it to match the URL where you'll host the document before deploying.
By default, the generated document includes a placeholder `client_id`. Update it to match the URL where you'll host the document before deploying, or pass `--client-id` when generating the file.
### Options
| Option | Flag | Description |
| ------ | ---- | ----------- |
| Name | `--name` | **Required.** Human-readable client name |
| Redirect URI | `--redirect-uri` | **Required.** Allowed redirect URIs (repeatable) |
| Redirect URI | `--redirect-uri`, `-r` | **Required.** Allowed redirect URIs (repeatable) |
| Client ID | `--client-id` | URL where this document will be hosted; defaults to a placeholder |
| Client URI | `--client-uri` | Client's home page URL |
| Logo URI | `--logo-uri` | Client's logo URL |
| Scope | `--scope` | Space-separated list of scopes |
@ -51,6 +54,7 @@ fastmcp auth cimd create \
--name "My Production App" \
--redirect-uri "http://localhost:*/callback" \
--redirect-uri "https://myapp.example.com/callback" \
--client-id "https://myapp.example.com/oauth/client.json" \
--client-uri "https://myapp.example.com" \
--scope "read write" \
--output client.json

View file

@ -104,11 +104,28 @@ Some tools request additional input during execution through MCP's elicitation m
| ------ | ---- | ----------- |
| Command | `--command` | Connect via stdio |
| Transport | `--transport`, `-t` | Force `http` or `sse` |
| Prompt | `--prompt` | Treat the target as a prompt name instead of a tool/resource |
| Input JSON | `--input-json` | Base arguments as JSON (merged with `key=value`) |
| JSON | `--json` | Raw JSON output |
| Timeout | `--timeout` | Connection timeout in seconds |
| Auth | `--auth` | `oauth`, a bearer token, or `none` |
## Reading Resources and Getting Prompts
`fastmcp call` can also read resources and render prompts. If the target contains `://`, the CLI treats it as a resource URI and calls `read_resource`:
```bash
fastmcp call server.py resource://docs/readme
fastmcp call server.py file:///tmp/example.txt --json
```
To get a prompt, pass `--prompt`; prompt arguments use the same `key=value` and `--input-json` forms as tool calls:
```bash
fastmcp call server.py summarize --prompt topic=weather
fastmcp call server.py summarize --prompt --input-json '{"topic": "weather"}'
```
## Discovering Configured Servers
`fastmcp discover` scans your machine for MCP servers configured in editors and tools. It checks:
@ -138,3 +155,7 @@ Any server that appears here can be used by name with `list`, `call`, and other
For LLM agents that can execute shell commands but don't have native MCP support, the CLI provides a clean bridge. The agent calls `fastmcp list --json` to discover available tools with full schemas, then `fastmcp call --json` to invoke them with structured results.
Because the CLI handles connection management, transport selection, and type coercion internally, the agent doesn't need to understand MCP protocol details — it just reads JSON and constructs shell commands.
## Remote Stdio Bridges
For MCP hosts that expect a local stdio command but need to connect to a remote HTTP server, use [`fastmcp-remote`](/clients/fastmcp-remote). It provides a small standalone bridge for host configuration, while `fastmcp list` and `fastmcp call` remain focused on direct inspection and invocation from the terminal.

View file

@ -55,6 +55,11 @@ fastmcp inspect server.py --format mcp -o manifest.json
| ------ | ---- | ----------- |
| Format | `--format`, `-f` | `fastmcp` or `mcp` (required when using `-o`) |
| Output File | `--output`, `-o` | Save to file instead of stdout |
| Python | `--python` | Python version to use when running via `uv` |
| Extra Packages | `--with` | Additional packages to install (repeatable) |
| Project | `--project` | Run within a specific uv project directory |
| Requirements | `--with-requirements` | Install from a requirements file |
| Skip Env | `--skip-env` | Do not set up a uv environment |
## Entrypoints

View file

@ -14,7 +14,7 @@ import { VersionBadge } from '/snippets/version-badge.mdx'
```bash
fastmcp install claude-desktop server.py
fastmcp install claude-code server.py --with pandas --with matplotlib
fastmcp install cursor server.py -e .
fastmcp install cursor server.py --with-editable .
```
<Warning>
@ -41,14 +41,13 @@ Because MCP clients run servers in isolation, you need to tell the install comma
```bash
fastmcp install claude-desktop server.py --with pandas --with "sqlalchemy>=2.0"
fastmcp install cursor server.py -e . --with-requirements requirements.txt
fastmcp install cursor server.py --with-editable . --with-requirements requirements.txt
```
**`fastmcp.json`** configuration files declare dependencies alongside the server definition. When you install from a config file, dependencies are picked up automatically:
**`fastmcp.json`** configuration files declare dependencies alongside the server definition. When you install from a config file explicitly, dependencies are picked up automatically:
```bash
fastmcp install claude-desktop fastmcp.json
fastmcp install claude-desktop # auto-detects fastmcp.json in current directory
```
See [Server Configuration](/deployment/server-configuration) for the full config format.
@ -57,15 +56,19 @@ See [Server Configuration](/deployment/server-configuration) for the full config
| Option | Flag | Description |
| ------ | ---- | ----------- |
| Server Name | `--server-name`, `-n` | Custom name for the server |
| Editable Package | `--with-editable`, `-e` | Install a directory in editable mode |
| Server Name | `--name`, `-n` | Custom name for the server |
| Editable Package | `--with-editable` | Install a directory in editable mode |
| Extra Packages | `--with` | Additional packages (repeatable) |
| Environment Variables | `--env` | `KEY=VALUE` pairs (repeatable) |
| Environment File | `--env-file`, `-f` | Load env vars from a `.env` file |
| Environment File | `--env-file` | Load env vars from a `.env` file |
| Python | `--python` | Python version (e.g., `3.11`) |
| Project | `--project` | Run within a uv project directory |
| Requirements | `--with-requirements` | Install from a requirements file |
| Config Path | `--config-path` | Custom path to Claude Desktop config directory (`claude-desktop` only) |
| Workspace | `--workspace` | Install to the workspace directory instead of globally (`cursor` only) |
| Copy | `--copy` | Copy the generated output to the clipboard (`mcp-json` and `stdio` only) |
`goose` installs through a deeplink that runs your server with `uvx`, so it accepts only `--name`, `--with`, and `--python`. Options that depend on a local uv project — `--with-editable`, `--project`, and `--with-requirements` — are unavailable there. Deeplinks also cannot carry environment variables: passing `--env` or `--env-file` exits with an error directing you to `fastmcp install mcp-json`, which generates a config you can add to Goose by hand with the variables included.
## Examples
@ -73,12 +76,12 @@ See [Server Configuration](/deployment/server-configuration) for the full config
# Basic install with auto-detected server instance
fastmcp install claude-desktop server.py
# Install from fastmcp.json with auto-detection
fastmcp install claude-desktop
# Install from fastmcp.json
fastmcp install claude-desktop fastmcp.json
# Explicit entrypoint with dependencies
fastmcp install claude-desktop server.py:my_server \
--server-name "My Analysis Server" \
--name "My Analysis Server" \
--with pandas
# With environment variables

View file

@ -23,7 +23,7 @@ fastmcp --help
| [`install`](/cli/install-mcp) | Install a server into Claude Code, Claude Desktop, Cursor, Gemini CLI, or Goose |
| [`inspect`](/cli/inspecting) | Print a server's tools, resources, and prompts as a summary or JSON report |
| [`list`](/cli/client) | List a server's tools (and optionally resources and prompts) |
| [`call`](/cli/client#calling-tools) | Call a single tool with arguments |
| [`call`](/cli/client#calling-tools) | Call a tool, read a resource, or get a prompt |
| [`discover`](/cli/client#discovering-configured-servers) | Find MCP servers configured in your editors and tools |
| [`generate-cli`](/cli/generate-cli) | Scaffold a standalone typed CLI from a server's tool schemas |
| [`project prepare`](/cli/running#pre-building-environments) | Pre-install dependencies into a reusable uv project |
@ -89,10 +89,10 @@ To skip authentication entirely — useful for local development servers — pas
fastmcp call http://localhost:8000/mcp my_tool --auth none
```
You can also pass a bearer token directly:
You can also pass a bearer token directly. Give the token value on its own; FastMCP adds the `Bearer` prefix when it builds the `Authorization` header.
```bash
fastmcp list http://localhost:8000/mcp --auth "Bearer sk-..."
fastmcp list http://localhost:8000/mcp --auth "sk-..."
```
## Transport Override

View file

@ -69,19 +69,22 @@ fastmcp run mcp.json
```
<Warning>
`fastmcp run` completely ignores the `if __name__ == "__main__"` block. Any setup code in that block won't execute. If you need initialization logic to run, use a [factory function](/cli/overview#factory-functions).
`fastmcp run` completely ignores the `if __name__ == "__main__"` block. Any setup code in that block won't execute. If you need initialization logic to run, use a [factory function](#entrypoints).
</Warning>
### Options
| Option | Flag | Description |
| ------ | ---- | ----------- |
| Transport | `--transport`, `-t` | `stdio` (default), `http`, or `sse` |
| Transport | `--transport`, `-t` | `stdio` (default), `http` / `streamable-http`, or `sse` |
| Host | `--host` | Bind address for HTTP (default: `127.0.0.1`) |
| Port | `--port`, `-p` | Bind port for HTTP (default: `8000`) |
| Path | `--path` | URL path for HTTP (default: `/mcp/`) |
| Path | `--path` | URL path for HTTP (default: `/mcp` for `http`, `/sse` for `sse`) |
| Log Level | `--log-level`, `-l` | `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
| No Banner | `--no-banner` | Suppress the startup banner |
| Stateless | `--stateless` | Run without sessions, for serverless and multi-worker deployments |
| Module Mode | `--module`, `-m` | Run a Python module via `python -m` instead of a file path |
| Skip Source | `--skip-source` | Skip source preparation (use when the source is already prepared) |
| Auto-Reload | `--reload` / `--no-reload` | Watch for file changes and restart automatically |
| Reload Dirs | `--reload-dir` | Directories to watch (repeatable) |
| Skip Env | `--skip-env` | Don't set up a uv environment (use when already in one) |
@ -127,7 +130,7 @@ Auto-reload is on by default — save a file and the MCP server restarts automat
```bash
fastmcp dev inspector server.py
fastmcp dev inspector server.py -e . --with pandas
fastmcp dev inspector server.py --with-editable . --with pandas
```
<Tip>
@ -140,7 +143,7 @@ The Inspector connects over **stdio only**. When it launches, you may need to se
| Option | Flag | Description |
| ------ | ---- | ----------- |
| Editable Package | `--with-editable`, `-e` | Install a directory in editable mode |
| Editable Package | `--with-editable` | Install a directory in editable mode |
| Extra Packages | `--with` | Additional packages (repeatable) |
| Inspector Version | `--inspector-version` | MCP Inspector version to use |
| UI Port | `--ui-port` | Port for the Inspector UI |

View file

@ -37,7 +37,7 @@ async with Client(
"https://your-server.fastmcp.app/mcp",
auth="<your-token>",
) as client:
await client.ping()
await client.list_tools()
```
You can also supply a Bearer token to a transport instance, such as `StreamableHttpTransport` or `SSETransport`:
@ -52,12 +52,12 @@ transport = StreamableHttpTransport(
)
async with Client(transport) as client:
await client.ping()
await client.list_tools()
```
## `BearerAuth` Helper
If you prefer to be more explicit and not rely on FastMCP to transform your string token, you can use the `BearerAuth` class yourself, which implements the `httpx.Auth` interface.
If you prefer to be more explicit and not rely on FastMCP to transform your string token, you can use the `BearerAuth` class yourself, which implements the `httpx2.Auth` interface.
```python {6}
from fastmcp import Client
@ -67,7 +67,7 @@ async with Client(
"https://your-server.fastmcp.app/mcp",
auth=BearerAuth(token="<your-token>"),
) as client:
await client.ping()
await client.list_tools()
```
## Custom Headers
@ -84,5 +84,5 @@ async with Client(
headers={"X-API-Key": "<your-token>"},
),
) as client:
await client.ping()
await client.list_tools()
```

View file

@ -32,7 +32,7 @@ async with Client(
client_metadata_url="https://myapp.example.com/oauth/client.json",
),
) as client:
await client.ping()
await client.list_tools()
```
When the server supports CIMD, the client uses your metadata URL as its `client_id` instead of performing Dynamic Client Registration. The server fetches your document, validates it, and proceeds with the standard OAuth authorization flow.

View file

@ -0,0 +1,89 @@
---
title: Machine-to-Machine Authentication
sidebarTitle: Client Credentials
description: Authenticate your FastMCP client to a protected server without a browser.
icon: robot
---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="4.0.0" />
<Tip>
Machine-to-machine authentication is only relevant for HTTP-based transports.
</Tip>
When a FastMCP client runs without a human present — a backend service, a scheduled job, a CI pipeline, one MCP server calling another — it cannot complete the browser-based [OAuth](/clients/auth/oauth) flow. Instead it authenticates as itself using the OAuth 2.0 **client credentials** grant: the client presents its own credentials directly to the authorization server, receives an access token, and attaches that token to every request. There is no redirect, no consent screen, and no user.
FastMCP provides two providers for this, both implementing the `httpx2.Auth` interface so they drop into the same `auth=` parameter as every other client auth option. You pass the **MCP server URL**, not a token endpoint — the token endpoint is discovered from the server's OAuth metadata, exactly as the interactive `OAuth` helper does. As with `OAuth`, you can omit the URL entirely and let the transport supply it.
## Client ID and Secret
The common case is a pre-registered client with an ID and a secret. Use `ClientCredentialsOAuthProvider` and pass it to the `auth` parameter of your `Client` or transport:
```python {2, 4-8, 10}
from fastmcp import Client
from fastmcp.client.auth import ClientCredentialsOAuthProvider
auth = ClientCredentialsOAuthProvider(
client_id="my-client-id",
client_secret="my-client-secret",
scopes=["read", "write"],
)
async with Client("https://example.com/mcp", auth=auth) as client:
await client.list_tools()
```
The provider discovers the authorization server, exchanges the credentials for an access token, and caches the token in memory for the life of the client. When the token expires it is re-acquired automatically on the next request. Because re-acquiring a token is a single non-interactive request, tokens are held in memory by default with no warning — unlike the interactive `OAuth` flow, losing the cache on restart costs nothing.
### `ClientCredentialsOAuthProvider` Parameters
- **`mcp_url`** (`str`, optional): Full URL to the MCP endpoint. Omit it when passing the provider to `Client(auth=...)` — the transport supplies the URL automatically.
- **`client_id`** (`str`, required): The pre-registered OAuth client ID.
- **`client_secret`** (`str`, required): The OAuth client secret.
- **`scopes`** (`str | list[str]`, optional): Scopes to request, as a space-separated string or a list.
- **`token_endpoint_auth_method`** (`"client_secret_basic" | "client_secret_post"`, optional): How the credentials are presented to the token endpoint. Defaults to `"client_secret_basic"` (an HTTP Basic `Authorization` header); use `"client_secret_post"` to send them in the request body instead.
- **`token_storage`** (`AsyncKeyValue`, optional): A key-value store for the acquired token. Defaults to in-memory storage.
## Private Key JWT
Some authorization servers require the client to prove its identity with a signed JWT assertion (RFC 7523 `private_key_jwt`) instead of a shared secret. This is common with workload identity federation, where the assertion comes from a cloud identity provider. Use `PrivateKeyJWTOAuthProvider` and supply an `assertion_provider` — an async callback that receives the authorization server's issuer identifier (the required JWT audience) and returns the assertion.
For a locally signed assertion, build the callback with `SignedJWTParameters`:
```python {4-7, 9, 11-15, 17-20, 22}
from pathlib import Path
from fastmcp import Client
from fastmcp.client.auth import (
PrivateKeyJWTOAuthProvider,
SignedJWTParameters,
)
private_key_pem = Path("client-signing-key.pem").read_text()
jwt_params = SignedJWTParameters(
issuer="my-client-id",
subject="my-client-id",
signing_key=private_key_pem,
)
auth = PrivateKeyJWTOAuthProvider(
client_id="my-client-id",
assertion_provider=jwt_params.create_assertion_provider(),
)
async with Client("https://example.com/mcp", auth=auth) as client:
await client.list_tools()
```
If you already have a JWT from an identity provider, wrap it with `static_assertion_provider`, or pass your own `async def provider(audience: str) -> str` callback to fetch one on demand.
### `PrivateKeyJWTOAuthProvider` Parameters
- **`mcp_url`** (`str`, optional): Full URL to the MCP endpoint. Omit it when passing the provider to `Client(auth=...)`.
- **`client_id`** (`str`, required): The OAuth client ID.
- **`assertion_provider`** (`Callable[[str], Awaitable[str]]`, required): Async callback that receives the authorization server's issuer identifier and returns a signed JWT assertion.
- **`scopes`** (`str | list[str]`, optional): Scopes to request, as a space-separated string or a list.
- **`token_storage`** (`AsyncKeyValue`, optional): A key-value store for the acquired token. Defaults to in-memory storage.

View file

@ -29,13 +29,13 @@ from fastmcp import Client
# Uses default OAuth settings
async with Client("https://your-server.fastmcp.app/mcp", auth="oauth") as client:
await client.ping()
await client.list_tools()
```
### `OAuth` Helper
To fully configure the OAuth flow, use the `OAuth` helper and pass it to the `auth` parameter of the `Client` or transport instance. `OAuth` manages the complexities of the OAuth 2.1 Authorization Code Grant with PKCE (Proof Key for Code Exchange) for enhanced security, and implements the full `httpx.Auth` interface.
To fully configure the OAuth flow, use the `OAuth` helper and pass it to the `auth` parameter of the `Client` or transport instance. `OAuth` manages the complexities of the OAuth 2.1 Authorization Code Grant with PKCE (Proof Key for Code Exchange) for enhanced security, and implements the full `httpx2.Auth` interface.
```python {2, 4, 6}
from fastmcp import Client
@ -44,7 +44,7 @@ from fastmcp.client.auth import OAuth
oauth = OAuth(scopes=["user"])
async with Client("https://your-server.fastmcp.app/mcp", auth=oauth) as client:
await client.ping()
await client.list_tools()
```
<Note>
@ -61,7 +61,7 @@ You don't need to pass `mcp_url` when using `OAuth` with `Client(auth=...)` —
- **`token_storage`** (`AsyncKeyValue`, optional): Storage backend for persisting OAuth tokens. Defaults to in-memory storage (tokens lost on restart). See [Token Storage](#token-storage) for encrypted storage options
- **`additional_client_metadata`** (`dict[str, Any]`, optional): Extra metadata for client registration
- **`callback_port`** (`int`, optional): Fixed port for OAuth callback server. If not specified, uses a random available port
- **`httpx_client_factory`** (`McpHttpClientFactory`, optional): Factory for creating httpx clients
- **`httpx_client_factory`** (`McpHttpClientFactory`, optional): Factory for creating httpx2 clients
## OAuth Flow
@ -125,7 +125,7 @@ encrypted_storage = FernetEncryptionWrapper(
oauth = OAuth(token_storage=encrypted_storage)
async with Client("https://your-server.fastmcp.app/mcp", auth=oauth) as client:
await client.ping()
await client.list_tools()
```
You can use any `AsyncKeyValue`-compatible backend from the [key-value library](https://github.com/strawgate/py-key-value) including Redis, DynamoDB, and more. Wrap your storage in `FernetEncryptionWrapper` for encryption.
@ -150,7 +150,7 @@ async with Client(
client_metadata_url="https://myapp.example.com/oauth/client.json",
),
) as client:
await client.ping()
await client.list_tools()
```
See the [CIMD Authentication](/clients/auth/cimd) page for complete documentation on creating, hosting, and validating CIMD documents.
@ -172,7 +172,7 @@ async with Client(
client_secret="my-client-secret",
),
) as client:
await client.ping()
await client.list_tools()
```
Public clients that rely on PKCE for security can omit `client_secret`:

View file

@ -0,0 +1,89 @@
---
title: Client-Only Package
description: Use FastMCP's client without installing the full server framework.
icon: box
---
import { VersionBadge } from '/snippets/version-badge.mdx'
<VersionBadge version="3.3.0" />
FastMCP's full `fastmcp` package includes everything needed to build and run MCP servers, apps, proxies, and clients. If you are only embedding an MCP client in another framework, building your own LLM host, or testing MCP servers, you can install the smaller client-only package instead.
```bash
pip install "fastmcp-slim[client]"
```
The client-only package uses the `fastmcp` import namespace:
```python
from fastmcp import Client
client = Client("https://example.com/mcp")
```
Use `fastmcp-slim[client]` when your code connects to MCP servers but does not define or run FastMCP servers itself. For example, framework authors can depend on `fastmcp-slim[client]` to provide MCP connectivity without requiring users to install the full FastMCP server stack.
## Supported Usage
Client-only installs support remote and subprocess transports:
```python
from fastmcp import Client
# Remote MCP server
http_client = Client("https://example.com/mcp")
# Local MCP server over stdio
stdio_client = Client("my_server.py")
```
Single-server MCP configuration works as well:
```python
from fastmcp import Client
config = {
"mcpServers": {
"weather": {
"url": "https://weather.example.com/mcp"
}
}
}
client = Client(config)
```
Optional sampling handlers are available through the same extras as the full package:
```bash
pip install "fastmcp-slim[client,openai]"
pip install "fastmcp-slim[client,anthropic]"
pip install "fastmcp-slim[client,gemini]"
```
## When to Use the Full Package
Install `fastmcp` when you need server-side FastMCP features:
```bash
pip install fastmcp
```
The full package remains the default for most users and continues to support the existing import style:
```python
from fastmcp import Client, FastMCP
server = FastMCP("Example")
client = Client(server)
```
Use the full package for:
- defining or running FastMCP servers
- in-memory clients connected directly to `FastMCP` server objects
- multi-server MCP configurations
- FastMCP apps, proxies, server auth, middleware, and other server-side features
The `fastmcp-slim` package is intentionally narrower: it is for client-only consumers who want FastMCP's MCP client behavior without depending on the full framework.

View file

@ -37,9 +37,6 @@ client = Client("my_mcp_server.py")
async def main():
async with client:
# Basic server interaction
await client.ping()
# List available operations
tools = await client.list_tools()
resources = await client.list_resources()
@ -67,16 +64,21 @@ server = FastMCP("TestServer")
client = Client(server) # In-memory, no network or subprocess
```
**STDIO transport** launches a server as a subprocess and communicates through stdin/stdout pipes. This is the standard mechanism used by desktop clients like Claude Desktop. The subprocess runs in an isolated environment, so you must explicitly pass any environment variables the server needs.
**STDIO transport** launches a server as a subprocess and communicates through stdin/stdout pipes. This is the standard mechanism used by desktop clients like Claude Desktop. By default, the subprocess receives the MCP SDK's default environment; pass an explicit transport when you need to add environment variables, set a working directory, or control process reuse.
```python
from fastmcp import Client
from fastmcp.client.transports import PythonStdioTransport
# Simple inference from file path
client = Client("my_server.py")
# With explicit environment configuration
client = Client("my_server.py", env={"API_KEY": "secret"})
transport = PythonStdioTransport(
"my_server.py",
env={"API_KEY": "secret"},
)
client = Client(transport)
```
**HTTP transport** connects to servers running as web services. Use this for production deployments where the server runs independently and manages its own lifecycle.
@ -121,7 +123,7 @@ async with client:
## Connection Lifecycle
The client uses context managers for connection management. When you enter the context, the client establishes a connection and performs an MCP initialization handshake with the server. This handshake exchanges capabilities, server metadata, and instructions.
The client uses context managers for connection management. When you enter the context, the client establishes a connection and negotiates the protocol era with the server. Metadata returned by either legacy initialization or modern discovery is exposed through the same client properties.
```python
from fastmcp import Client, FastMCP
@ -134,18 +136,20 @@ def greet(name: str) -> str:
return f"Hello, {name}!"
async with Client(mcp) as client:
# Initialization already happened automatically
print(f"Server: {client.initialize_result.serverInfo.name}")
print(f"Instructions: {client.initialize_result.instructions}")
print(f"Capabilities: {client.initialize_result.capabilities.tools}")
# Protocol negotiation already happened automatically
assert client.server_info is not None
assert client.server_capabilities is not None
print(f"Server: {client.server_info.name}")
print(f"Instructions: {client.instructions}")
print(f"Capabilities: {client.server_capabilities.tools}")
```
For advanced scenarios where you need precise control over when initialization happens, disable automatic initialization and call `initialize()` manually:
For advanced scenarios where you need precise control over when initialization happens, disable automatic initialization and call `initialize()` manually. `initialize()` is a handshake-era operation, so pin the connection with `mode="legacy"`: the modern protocol has no `initialize` round trip, and calling it on a modern connection raises.
```python
from fastmcp import Client
client = Client("my_mcp_server.py", auto_initialize=False)
client = Client("my_mcp_server.py", auto_initialize=False, mode="legacy")
async with client:
# Connection established, but not initialized yet
@ -154,12 +158,144 @@ async with client:
# Initialize manually with custom timeout
result = await client.initialize(timeout=10.0)
print(f"Server: {result.serverInfo.name}")
print(f"Server: {result.server_info.name}")
# Now ready for operations
tools = await client.list_tools()
```
## Protocol negotiation
<VersionBadge version="4.0.0" />
MCP has two protocol eras: the original *legacy* era, which begins every connection with an `initialize` handshake, and the *modern* era (protocol version `2026-07-28` and later), which a client discovers by probing the server's `server/discover` endpoint. The `mode` parameter controls which era the client negotiates when it connects.
By default, `mode="auto"`. The client probes `server/discover` and adopts the modern protocol when the server responds; for any server that is not positive evidence of modern support, it falls back to the legacy handshake. This makes the default safe against a mixed fleet of legacy and modern servers.
```python
from fastmcp import Client
# Negotiate the newest era the server supports (the default)
client = Client("https://example.com/mcp", mode="auto")
```
Set `mode="legacy"` to force the initialize handshake. This behaves identically to earlier FastMCP versions and is the opt-out if a server misbehaves under discovery or you need the legacy `initialize` result object.
```python
client = Client("https://example.com/mcp", mode="legacy")
```
Legacy mode is also what carries the *pushed* form of a server's requests. The handshake opens a persistent back-channel down which a server can send a sampling, roots, or elicitation request mid-call, and the modern era removed it. Your handlers are unaffected by that: a [sampling](/clients/sampling), [roots](/clients/roots), or [elicitation](/clients/elicitation) handler you register answers a modern server's [input-required rounds](/clients/elicitation#input-required-rounds) from the same registration. Pin `mode="legacy"` when you connect to a server that pushes, or when your code calls `client.ping()` or `transport.get_session_id()`, which need the session the modern era does not open.
Conversely, [background tasks](/clients/tasks) are **modern-only**: the tasks capability is negotiated over `2026-07-28` connections, so `mode="legacy"` never triggers one and a task-enabled tool just runs synchronously.
A FastMCP server serves both eras, so a default client negotiates the modern one and the session-dependent calls raise an era-specific error there. Pinning the handshake restores them.
You can also pin a specific modern protocol version to adopt it directly, without a discovery probe:
```python
client = Client("https://example.com/mcp", mode="2026-07-28")
```
Once connected, the negotiated version, server identity, capabilities, and instructions are available as properties. They are populated from either the legacy `InitializeResult` or modern `DiscoverResult`, and reset to `None` when the client disconnects. `instructions` is also `None` when the server does not provide any.
When you pin a modern version directly, the client skips discovery and adopts that version with minimal synthesized metadata. In that mode, `server_info` has an empty name and `instructions` is `None`.
```python
async with Client("https://example.com/mcp", mode="auto") as client:
print(client.protocol_version) # e.g. "2026-07-28"
print(client.server_info) # Implementation | None
print(client.server_capabilities) # ServerCapabilities | None
print(client.instructions) # str | None
```
<Note>
`mode="auto"` is the default as of FastMCP 4.0. Earlier versions defaulted to `"legacy"`. If a server behaves unexpectedly under discovery, or you depend on the legacy `initialize` result, pin the old behavior with `Client(..., mode="legacy")`.
The SSE transport is legacy-only — it cannot carry the sessionless modern era — so a client connecting over SSE always negotiates the legacy handshake, even under `mode="auto"`. A multi-server config (`MCPConfigTransport` with more than one server) is likewise legacy-only, because it mounts each backend behind a legacy-era proxy; a single-server config mirrors its one backend transport's era.
</Note>
## Response caching
<VersionBadge version="4.0.0" />
The client can cache the results of `list_tools`, `list_resources`, and `list_prompts` so that repeated calls avoid a network round-trip. Caching is opt-in and honors the server's own cache hints, so it only takes effect against modern-era servers that advertise them — a cache is inert on a legacy connection.
Enable the default in-memory cache by passing `cache=True`. It respects the `ttlMs` and `cacheScope` hints the server attaches to each response.
```python
from fastmcp import Client
client = Client("https://example.com/mcp", mode="auto", cache=True)
async with client:
tools = await client.list_tools() # fetched from the server
tools = await client.list_tools() # served from the cache
```
The default (`cache=None`) and `cache=False` both disable caching. For control over the store, TTL, or partitioning, pass a `CacheConfig`. A custom config requires a `target_id`, since in-memory FastMCP transports expose no server URL to derive a shared-store identity from.
```python
from fastmcp import Client
from mcp.client.caching import CacheConfig
config = CacheConfig(target_id="weather-api", default_ttl_ms=60_000)
client = Client("https://example.com/mcp", mode="auto", cache=config)
```
The high-level `list_tools`, `list_resources`, and `list_prompts` methods always use the cache when one is configured. To override the behavior for a single call, use the lower-level `list_tools_mcp`, `list_resources_mcp`, `list_resource_templates_mcp`, and `list_prompts_mcp` variants, which accept a `cache_mode` argument: `"use"` (the default) serves and stores, `"refresh"` stores a fresh result without serving a cached one, and `"bypass"` skips the cache entirely.
```python
async with client:
fresh = await client.list_tools_mcp(cache_mode="refresh")
```
### Sharing a cache across clients
The default cache lives in each client's process. To share cached responses across a fleet — a set of proxy replicas backed by one Redis, for example — pass a `KeyValueResponseCacheStore`, FastMCP's adapter over the same `AsyncKeyValue` key-value abstraction the event store and OAuth proxy use. It accepts any compatible backend (memory, Redis, and more).
A shared store mingles responses from different principals, so it requires an explicit `partition` that isolates them. Derive the partition from a verified credential — never from request data or the server URL — and construct a new client when the principal changes. Only responses the server marks `"public"` are ever served across partitions.
```python
from fastmcp import Client
from fastmcp.client.caching import KeyValueResponseCacheStore
from mcp.client.caching import CacheConfig
from key_value.aio.stores.redis import RedisStore
backend = RedisStore(url="redis://localhost")
store = KeyValueResponseCacheStore(storage=backend)
config = CacheConfig(store=store, partition="tenant-a", target_id="weather-api")
client = Client("https://example.com/mcp", mode="auto", cache=config)
```
The adapter serializes each result through a type-tagged envelope validated against an allowlist of cacheable result models, so a value naming an unknown type is treated as a cache miss rather than deserialized blindly. Each store instance owns its own collection namespace; `clear()` affects only that namespace, never another tenant's entries.
## Client extensions
<VersionBadge version="4.0.0" />
Client extensions (SEP-2133) are the advanced mechanism a client uses to opt into vendor capabilities that live outside the core protocol. An extension is a `ClientExtension` instance that bundles three things: a capability *advertisement* the server can read, one or more *result claims* that let the client parse extra `tools/call` result shapes, and *notification bindings* that observe server notifications the core protocol doesn't define. Pass a sequence of them to `extensions=`.
```python
from fastmcp import Client
from myproject.extensions import AppsExtension
client = Client("https://example.com/mcp", extensions=[AppsExtension()])
```
Each extension's contributions are threaded into the underlying session. FastMCP folds in its own internal extension for [background tasks](/clients/tasks) automatically, and your own extensions *compose* with it rather than replacing it — pass your own tasks extension with the same identifier if you need to override it. When a tool returns a shape an extension claims, `client.call_tool()` resolves it transparently through the owning claim's resolver and hands you back an ordinary result. Result claims and their advertisements are honored only on modern-era connections, so they are inert on a legacy handshake.
For the rare case where you need to register additional result claims against an extension that is already advertised, pass them through `result_claims=`, keyed by the extension's identifier. Prefer declaring claims on the extension itself; this parameter merges extra claims with an extension's own.
```python
client = Client(
"https://example.com/mcp",
extensions=[AppsExtension()],
result_claims={"example.com/apps": [extra_claim]},
)
```
## Operations
FastMCP clients interact with three types of server components.
@ -201,6 +337,8 @@ See [Prompts](/clients/prompts) for detailed documentation including argument se
The client supports callback handlers for advanced server interactions. These let you respond to server-initiated requests and receive notifications.
Sampling, elicitation, and roots are the requests a server makes of the client. A server reaches your handler by whichever route its [era](#protocol-negotiation) allows — pushed down the open session on the handshake, returned as an input-required result on the modern protocol — and both routes dispatch to the same handler, so one registration covers both. Logging and progress arrive as notifications on the response stream and work in either era.
```python
from fastmcp import Client
from fastmcp.client.logging import LogMessage

View file

@ -13,6 +13,10 @@ Use this when you need to respond to server requests for user input during tool
Elicitation allows MCP servers to request structured input from users during operations. Instead of requiring all inputs upfront, servers can interactively ask for missing parameters, request clarification, or gather additional context.
<Note>
**These sections show the server-initiated flow, which the handshake-era protocol uses.** On `2026-07-28` the server asks by returning a request instead — see [input-required rounds](#input-required-rounds). One `elicitation_handler` serves both, so the examples below pin `mode="legacy"` only to exercise the pushed form.
</Note>
## Handler Template
```python
@ -30,8 +34,8 @@ async def elicitation_handler(
Args:
message: The prompt to display to the user
response_type: Python dataclass type for the response (None if no data expected)
params: Original MCP elicitation parameters including raw JSON schema
response_type: Python dataclass type for form responses (None for URL requests or empty schemas)
params: Original MCP elicitation parameters
context: Request context with metadata
Returns:
@ -44,18 +48,24 @@ async def elicitation_handler(
if not user_input:
return ElicitResult(action="decline")
# URL requests and empty-object schemas have no response type to construct,
# so accepting is the whole response.
if response_type is None:
return ElicitResult(action="accept")
# Create response using the provided dataclass type
return response_type(value=user_input)
client = Client(
"my_mcp_server.py",
mode="legacy",
elicitation_handler=elicitation_handler,
)
```
## How It Works
When a server needs user input, it sends an elicitation request with a message prompt and a JSON schema describing the expected response structure. FastMCP automatically converts this schema into a Python dataclass type, making it easy to construct properly typed responses without manually parsing JSON schemas.
When a server needs user input, it sends an elicitation request with a message prompt. Form elicitation requests include a JSON schema describing the expected response structure, and FastMCP automatically converts that schema into a Python dataclass type. URL elicitation requests and empty-object schemas use `response_type=None`.
The handler receives four parameters:
@ -65,11 +75,11 @@ The handler receives four parameters:
</ResponseField>
<ResponseField name="response_type" type="type | None">
A Python dataclass type that FastMCP created from the server's JSON schema. Use this to construct your response with proper typing. If the server requests an empty object, this will be `None`.
A Python dataclass type that FastMCP created from a form request's JSON schema. Use this to construct your response with proper typing. For URL requests or empty-object schemas, this will be `None`.
</ResponseField>
<ResponseField name="params" type="ElicitRequestParams">
The original MCP elicitation parameters, including the raw JSON schema in `params.requestedSchema`
The original MCP elicitation parameters. Form requests carry the raw JSON schema on `params.requested_schema`; URL requests carry `params.url` instead and have no schema.
</ResponseField>
<ResponseField name="context" type="RequestContext">
@ -133,6 +143,24 @@ async def elicitation_handler(message, response_type, params, context):
client = Client(
"my_mcp_server.py",
mode="legacy",
elicitation_handler=elicitation_handler
)
```
## Input-required rounds
<VersionBadge version="4.0.0" />
On protocol version `2026-07-28` and later, a server can ask for input before it returns a final result. Nothing is held open: the tool *returns* a description of what it needs, which completes that round as an ordinary response, and the client answers by issuing a **new** `call_tool`, `get_prompt`, or `read_resource` request carrying the answer. `fastmcp.Client` drives that loop for you — it fulfils each round's requests using the callbacks you already configured (your `elicitation_handler`, `sampling_handler`, and roots) and repeats until the call reaches a terminal result. No extra wiring is needed beyond the handlers described above.
The `input_required_max_rounds` parameter caps how many rounds the client will answer before giving up, guarding against a server that never terminates. It defaults to `10`.
```python
client = Client(
"https://example.com/mcp",
mode="auto",
elicitation_handler=elicitation_handler,
input_required_max_rounds=5,
)
```

View file

@ -0,0 +1,169 @@
---
title: fastmcp-remote
description: Bridge remote MCP servers into stdio-only MCP hosts with uvx fastmcp-remote.
icon: bridge
---
`fastmcp-remote` is FastMCP's standalone stdio bridge for remote MCP servers. Use it when an MCP host expects to launch a local command, but the server you want to use is hosted over Streamable HTTP or SSE.
```json
{
"mcpServers": {
"linear": {
"command": "uvx",
"args": ["fastmcp-remote", "https://mcp.linear.app/mcp"]
}
}
}
```
The package is powered by FastMCP. It builds one FastMCP client for the remote URL, exposes that client as a local stdio proxy, and keeps the executable focused on that bridge. For running Python server files, local project environments, FastMCP config files, and development reload loops, use [`fastmcp run`](/cli/running).
The command shape follows the original [`mcp-remote`](https://github.com/geelen/mcp-remote) npm project, which established this stdio-to-remote bridge pattern for MCP hosts.
## Installation
Most MCP hosts can run `fastmcp-remote` directly through `uvx`, so you usually do not need to install it yourself:
```bash
uvx fastmcp-remote https://example.com/mcp
```
If your host requires an already-installed command, install the package with your Python package manager:
```bash
uv tool install fastmcp-remote
```
## Host Configuration
For hosts that use `mcpServers` JSON configuration, set the command to `uvx` and pass `fastmcp-remote` plus the remote server URL as arguments:
```json
{
"mcpServers": {
"remote-api": {
"command": "uvx",
"args": ["fastmcp-remote", "https://example.com/mcp"]
}
}
}
```
## Endpoint URLs and Connection Status
Pass the full MCP endpoint URL for the remote server. Many FastMCP HTTP servers expose MCP at `/mcp`, so a local development server may need `http://localhost:8000/mcp` rather than `http://localhost:8000`.
`fastmcp-remote` starts a local stdio bridge, then connects to the upstream server when the MCP host initializes that bridge. If the upstream server is unavailable, the URL does not point to an MCP endpoint, or authentication cannot complete, initialization fails and the host should report the remote server as failed. After initialization succeeds, later tool, resource, prompt, and ping requests continue to proxy through the same remote server configuration.
OAuth is enabled automatically unless you provide an `Authorization` header or pass `--auth none`. The first connection opens the browser-based OAuth flow when the server requires authentication, then stores tokens locally for future runs.
To pass a bearer token or another custom header directly, provide `--header` in `Name: Value` form. The header name ends at the first colon, so values can contain additional colons. Quote the header when the value contains spaces, just like any other shell argument. An `Authorization` header disables OAuth by default:
```json
{
"mcpServers": {
"private-api": {
"command": "uvx",
"args": [
"fastmcp-remote",
"https://example.com/mcp",
"--header",
"Authorization: Bearer <token>"
]
}
}
}
```
Repeat `--header` to send multiple headers:
```bash
uvx fastmcp-remote https://example.com/mcp \
--header "Authorization: Bearer <token>" \
--header "X-Workspace: production" \
--header "X-Client-Name: My MCP Host" \
--header "X-Callback-Url: https://example.com/oauth/callback"
```
Some MCP hosts on Windows have trouble preserving spaces inside command arguments. Put the spaced value in an environment variable and reference it from the header value:
```json
{
"mcpServers": {
"remote-api": {
"command": "uvx",
"args": [
"fastmcp-remote",
"https://example.com/mcp",
"--header",
"Authorization:${AUTH_HEADER}"
],
"env": {
"AUTH_HEADER": "Bearer <token>"
}
}
}
}
```
For local development servers over plain HTTP, disable OAuth when the server is unauthenticated:
```bash
uvx fastmcp-remote http://localhost:8000/mcp --auth none
```
## Self-Signed Certificates
For servers behind a self-signed certificate, point `--verify` at a CA bundle that trusts the certificate:
```bash
uvx fastmcp-remote https://internal.example.com/mcp --verify /path/to/ca-bundle.pem
```
To disable certificate verification entirely, pass `--verify false`. This is insecure and should only be used for trusted servers on private networks:
```bash
uvx fastmcp-remote https://internal.example.com/mcp --verify false
```
To trust a CA bundle without a flag, set the standard `SSL_CERT_FILE` environment variable, which OpenSSL reads automatically:
```bash
SSL_CERT_FILE=/path/to/ca-bundle.pem uvx fastmcp-remote https://internal.example.com/mcp
```
## OAuth Storage
OAuth tokens are stored under `~/.fastmcp/remote` by default. Set `FASTMCP_REMOTE_CONFIG_DIR` to use another directory:
```bash
FASTMCP_REMOTE_CONFIG_DIR=~/.config/fastmcp-remote uvx fastmcp-remote https://example.com/mcp
```
Use `--resource` to isolate tokens for a particular remote server identity:
```bash
uvx fastmcp-remote https://example.com/mcp --resource example-prod
```
If the remote authorization server requires a fixed callback port or hostname, pass them after the URL:
```bash
uvx fastmcp-remote https://example.com/mcp 3334 --host 127.0.0.1
```
## Options
| Option | Description |
| ------ | ----------- |
| `--transport` | Choose `http` or `sse`. Defaults to `http`. |
| `--header` | Add a header to upstream requests, for example `--header "Authorization: Bearer <token>"`. Values may contain colons. Quote headers whose values contain spaces. Use `${VAR}` to expand environment variables inside values. Repeat for multiple headers. |
| `--auth` | Choose `oauth` or `none`. The default uses OAuth unless an `Authorization` header is provided. |
| `--verify` | Control TLS certificate verification. Pass a path to a CA bundle to trust a self-signed certificate, or `false` to disable verification (insecure). Defaults to verification enabled. |
| `--resource` | Isolate OAuth token storage for a named remote resource. |
| `--host` | Set the OAuth callback hostname. Defaults to `localhost`. |
| `--auth-timeout` | Set how long to wait for the OAuth callback. Defaults to 300 seconds. |
| `--ignore-tool` | Hide tools whose names match a glob pattern. Repeat for multiple patterns. |
| `--debug` | Enable debug logging. |
| `--silent` | Suppress non-critical logs. |

View file

@ -28,12 +28,32 @@ logging.basicConfig(
)
logger = logging.getLogger(__name__)
LOGGING_LEVEL_MAP = logging.getLevelNamesMapping()
LOGGING_LEVEL_MAP = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"NOTICE": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL,
"ALERT": logging.CRITICAL,
"EMERGENCY": logging.CRITICAL,
}
async def log_handler(message: LogMessage):
"""Forward MCP server logs to Python's logging system."""
msg = message.data.get('msg')
extra = message.data.get('extra')
data = message.data
if isinstance(data, dict):
msg = data.get('msg', data)
extra = data.get('extra')
else:
msg = data
extra = None
# Python's logging requires `extra` to be a mapping, but a server can send
# any JSON value, so fold anything else into the message instead.
if extra is not None and not isinstance(extra, dict):
msg = f"{msg} ({extra})"
extra = None
level = LOGGING_LEVEL_MAP.get(message.level.upper(), logging.INFO)
logger.log(level, msg, extra=extra)
@ -55,19 +75,20 @@ The handler receives a `LogMessage` object:
The logger name (may be None)
</ResponseField>
<ResponseField name="data" type="dict">
The log payload, containing `msg` and `extra` keys
<ResponseField name="data" type="Any">
The JSON-serializable log payload sent by the server. FastMCP's structured logger uses a dictionary with `msg` and `extra` keys, but other MCP servers may send any JSON value.
</ResponseField>
</Card>
## Structured Logs
The `message.data` attribute is a dictionary containing the log payload. This enables structured logging with rich contextual information.
The `message.data` attribute contains the server's JSON-serializable log payload. FastMCP servers commonly send a dictionary with `msg` and `extra` keys, which enables structured logging with rich contextual information.
```python
async def detailed_log_handler(message: LogMessage):
msg = message.data.get('msg')
extra = message.data.get('extra')
data = message.data
msg = data.get('msg', data) if isinstance(data, dict) else data
extra = data.get('extra') if isinstance(data, dict) else None
if message.level == "error":
print(f"ERROR: {msg} | Details: {extra}")

View file

@ -22,8 +22,8 @@ from fastmcp import Client
async def message_handler(message):
"""Handle MCP notifications from the server."""
if hasattr(message, 'root'):
method = message.root.method
if hasattr(message, 'method'):
method = message.method
if method == "notifications/tools/list_changed":
print("Tools have changed - refresh tool cache")
@ -31,6 +31,8 @@ async def message_handler(message):
print("Resources have changed")
elif method == "notifications/prompts/list_changed":
print("Prompts have changed")
elif method == "notifications/resources/updated":
print("A resource was updated")
client = Client(
"my_mcp_server.py",
@ -113,6 +115,18 @@ class MyMessageHandler(MessageHandler):
"""Called for progress updates during long-running operations."""
pass
async def on_resource_updated(
self, notification: mcp.types.ResourceUpdatedNotification
) -> None:
"""Called when a specific resource changes."""
pass
async def on_cancelled(
self, notification: mcp.types.CancelledNotification
) -> None:
"""Called when a request is cancelled."""
pass
async def on_logging_message(
self, notification: mcp.types.LoggingMessageNotification
) -> None:

View file

@ -21,7 +21,7 @@ Request a rendered prompt with `get_prompt()`:
async with client:
# Simple prompt without arguments
result = await client.get_prompt("welcome_message")
# result -> mcp.types.GetPromptResult
# result -> mcp_types.GetPromptResult
# Access the generated messages
for message in result.messages:
@ -128,12 +128,12 @@ See [Metadata](/servers/versioning#version-discovery) for how to discover availa
## Multi-Server Clients
When using multi-server clients, prompts are accessible directly without prefixing:
When using multi-server clients, prompts are mounted with the server name as a prefix, just like tools:
```python
async with client: # Multi-server client
result1 = await client.get_prompt("weather_prompt", {"city": "London"})
result2 = await client.get_prompt("assistant_prompt", {"query": "help"})
result1 = await client.get_prompt("weather_weather_prompt", {"city": "London"})
result2 = await client.get_prompt("assistant_assistant_prompt", {"query": "help"})
```
## Raw Protocol Access
@ -143,5 +143,5 @@ For complete control, use `get_prompt_mcp()` which returns the full MCP protocol
```python
async with client:
result = await client.get_prompt_mcp("example_prompt", {"arg": "value"})
# result -> mcp.types.GetPromptResult
# result -> mcp_types.GetPromptResult
```

View file

@ -53,23 +53,30 @@ async with client:
for item in content:
if hasattr(item, 'text'):
print(f"Text content: {item.text}")
print(f"MIME type: {item.mimeType}")
print(f"MIME type: {item.mime_type}")
```
Binary resources include images, PDFs, and other non-text data:
Binary resources arrive as `BlobResourceContents`, whose `blob` field is a base64 **string**, so decode it before writing bytes to disk:
```python
import base64
from mcp_types import BlobResourceContents
async with client:
content = await client.read_resource("resource://images/logo.png")
for item in content:
if hasattr(item, 'blob'):
print(f"Binary content: {len(item.blob)} bytes")
print(f"MIME type: {item.mimeType}")
if isinstance(item, BlobResourceContents):
data = base64.b64decode(item.blob)
print(f"Binary content: {len(data)} bytes")
print(f"MIME type: {item.mime_type}")
# Save to file
with open("downloaded_logo.png", "wb") as f:
f.write(item.blob)
f.write(data)
```
## Multi-Server Clients
@ -106,5 +113,5 @@ For complete control, use `read_resource_mcp()` which returns the full MCP proto
```python
async with client:
result = await client.read_resource_mcp("resource://example")
# result -> mcp.types.ReadResourceResult
# result -> mcp_types.ReadResourceResult
```

View file

@ -1,7 +1,7 @@
---
title: Client Roots
sidebarTitle: Roots
description: Provide local context and resource boundaries to MCP servers.
description: Tell servers which local paths your client can reach.
icon: folder-tree
---
@ -11,24 +11,26 @@ import { VersionBadge } from '/snippets/version-badge.mdx'
Use this when you need to tell servers what local resources the client has access to.
Roots inform servers about resources the client can provide. Servers can use this information to adjust behavior or provide more relevant responses.
A root is a path your client is willing to expose — a project directory, a workspace, a document store. Servers read them to scope their work, so a tool that searches files searches where you pointed it, and a server that gets no roots has to ask the user for paths instead. Roots describe where the client can reach; the server takes them as its working boundary.
Register them once with `roots=`, and the client answers however the server asks. A handshake-era server pushes a `roots/list` request down the open session and reads the reply mid-call; a modern (`2026-07-28`) server has no such channel, so it returns a roots request and `fastmcp.Client` fulfils it from the same registration and re-issues the call with the answer attached. The default `mode="auto"` negotiates whichever era the server speaks, so the examples below work on either — see [protocol negotiation](/clients/client#protocol-negotiation) for how that choice is made, and [the guard pattern](/servers/elicitation#sampling-and-roots) for how a server issues the modern form.
## Static Roots
Provide a list of roots when creating the client:
When the paths are known up front, pass them as a list. The client holds them for the life of the connection and hands back the same set every time a server asks.
```python
from fastmcp import Client
client = Client(
"my_mcp_server.py",
roots=["/path/to/root1", "/path/to/root2"]
roots=["file:///path/to/root1", "file:///path/to/root2"]
)
```
## Dynamic Roots
Use a callback to compute roots dynamically when the server requests them:
Pass a callback instead when the roots depend on something the client learns at runtime, such as the workspace the user has open. It runs at the moment a server asks, on either route, and receives the request context so you can see which request it is answering:
```python
from fastmcp import Client
@ -36,7 +38,7 @@ from fastmcp.client.roots import RequestContext
async def roots_callback(context: RequestContext) -> list[str]:
print(f"Server requested roots (Request ID: {context.request_id})")
return ["/path/to/root1", "/path/to/root2"]
return ["file:///path/to/root1", "file:///path/to/root2"]
client = Client(
"my_mcp_server.py",

View file

@ -1,7 +1,7 @@
---
title: LLM Sampling
sidebarTitle: Sampling
description: Handle server-initiated LLM completion requests.
description: Answer a server's request for an LLM completion.
icon: robot
---
@ -9,52 +9,46 @@ import { VersionBadge } from "/snippets/version-badge.mdx";
<VersionBadge version="2.0.0" />
Use this when you need to respond to server requests for LLM completions.
Use this when a server asks your client to run an LLM completion on its behalf.
MCP servers can request LLM completions from clients during tool execution. This enables servers to delegate AI reasoning to the client, which controls which LLM is used and how requests are made.
Sampling is how a server borrows your model. Rather than hold an API key of its own, the server describes the messages it wants completed and asks you to run them — you pick the model, and you pay for the tokens. Your side of that arrangement is one function, a **sampling handler**, registered when you create the client.
The handler receives the conversation the server wants completed, the parameters it asked for, and a request context carrying metadata about the call. Return the generated text as a string and FastMCP wraps it in the protocol's result for you; return a `CreateMessageResult` yourself when you want to report the real model name or hand back content that isn't text. If the handler raises, the client sends the error back in place of a completion and the server's tool decides what to do about it.
## Handler Template
```python
from fastmcp import Client
from fastmcp.client.sampling import SamplingMessage, SamplingParams, RequestContext
from mcp.types import TextContent
async def sampling_handler(
messages: list[SamplingMessage],
params: SamplingParams,
context: RequestContext
context: RequestContext,
) -> str:
"""
Handle server requests for LLM completions.
"""Run the server's messages against your LLM and return the completion."""
conversation = [
f"{message.role}: {message.content.text}"
for message in messages
if isinstance(message.content, TextContent)
]
system_prompt = params.system_prompt or "You are a helpful assistant."
Args:
messages: Conversation messages to send to the LLM
params: Sampling parameters (temperature, max_tokens, etc.)
context: Request context with metadata
Returns:
Generated text response from your LLM
"""
# Extract message content
conversation = []
for message in messages:
content = message.content.text if hasattr(message.content, 'text') else str(message.content)
conversation.append(f"{message.role}: {content}")
# Use the system prompt if provided
system_prompt = params.systemPrompt or "You are a helpful assistant."
# Integrate with your LLM service here
# Call your LLM here with `conversation` and `system_prompt`.
return "Generated response based on the messages"
client = Client(
"my_mcp_server.py",
sampling_handler=sampling_handler,
)
client = Client("my_mcp_server.py", sampling_handler=sampling_handler)
```
The client answers with this handler however the server asks for a completion. The default `mode="auto"` negotiates whichever protocol era the server speaks, and one handler covers both of the routes an era can use — see [Request Routes](#request-routes).
## Handler Parameters
Everything the server sends arrives in the first two arguments. The messages are the conversation to complete; the parameters are how the server would like it completed. You decide how much of that to honor, since the client owns the model — a preference your provider cannot express is yours to ignore.
<Card icon="code" title="SamplingMessage">
<ResponseField name="role" type='Literal["user", "assistant"]'>
The role of the message
@ -66,11 +60,11 @@ client = Client(
</Card>
<Card icon="code" title="SamplingParams">
<ResponseField name="systemPrompt" type="str | None">
<ResponseField name="system_prompt" type="str | None">
Optional system prompt the server wants to use
</ResponseField>
<ResponseField name="modelPreferences" type="ModelPreferences | None">
<ResponseField name="model_preferences" type="ModelPreferences | None">
Server preferences for model selection (hints, cost/speed/intelligence priorities)
</ResponseField>
@ -78,11 +72,11 @@ client = Client(
Sampling temperature
</ResponseField>
<ResponseField name="maxTokens" type="int">
<ResponseField name="max_tokens" type="int">
Maximum tokens to generate
</ResponseField>
<ResponseField name="stopSequences" type="list[str] | None">
<ResponseField name="stop_sequences" type="list[str] | None">
Stop sequences for sampling
</ResponseField>
@ -90,14 +84,14 @@ client = Client(
Tools the LLM can use during sampling
</ResponseField>
<ResponseField name="toolChoice" type="ToolChoice | None">
<ResponseField name="tool_choice" type="ToolChoice | None">
Tool usage behavior (`auto`, `required`, or `none`)
</ResponseField>
</Card>
## Built-in Handlers
FastMCP provides built-in handlers for OpenAI, Anthropic, and Google Gemini APIs that support the full sampling API including tool use.
Writing the provider call yourself is rarely worth it. FastMCP ships handlers for OpenAI, Anthropic, and Google Gemini that implement the full sampling API, tool use included, and translate the protocol's parameters into each provider's own. Give one a default model and pass it where your own handler would go. Write a custom handler when you need routing across providers, caching, or a provider FastMCP does not cover.
### OpenAI Handler
@ -113,9 +107,11 @@ client = Client(
)
```
For OpenAI-compatible APIs (like local models):
Point the handler at any OpenAI-compatible API, including a local model server, by passing your own provider client:
```python
from fastmcp import Client
from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
from openai import AsyncOpenAI
client = Client(
@ -128,7 +124,7 @@ client = Client(
```
<Note>
Install the OpenAI handler with `pip install fastmcp[openai]`.
Install the OpenAI handler with `pip install 'fastmcp[openai]'`.
</Note>
### Anthropic Handler
@ -146,7 +142,7 @@ client = Client(
```
<Note>
Install the Anthropic handler with `pip install fastmcp[anthropic]`.
Install the Anthropic handler with `pip install 'fastmcp[anthropic]'`.
</Note>
### Google Gemini Handler
@ -164,27 +160,35 @@ client = Client(
```
<Note>
Install the Google Gemini handler with `pip install fastmcp[gemini]`.
Install the Google Gemini handler with `pip install 'fastmcp[gemini]'`.
</Note>
## Sampling Capabilities
The [source of these handlers](https://github.com/PrefectHQ/fastmcp/tree/main/fastmcp_slim/fastmcp/client/sampling/handlers) is the best reference for writing your own.
When you provide a `sampling_handler`, FastMCP automatically advertises full sampling capabilities to the server, including tool support. To disable tool support for simpler handlers:
## Tool Use
A sampling request can carry tools. When it does, your handler passes them to the model and returns whatever comes back, tool calls included — the server executes the tools itself and sends a follow-up sampling request with the results if it needs another turn. Your handler never runs a tool.
Registering any `sampling_handler` advertises full sampling support, tools included. A handler that only generates text should say so, so servers know not to send tools it will drop:
```python
from fastmcp import Client
from mcp.types import SamplingCapability
async def text_only_handler(messages, params, context) -> str:
return "Generated response based on the messages"
client = Client(
"my_mcp_server.py",
sampling_handler=basic_handler,
sampling_capabilities=SamplingCapability(), # No tool support
sampling_handler=text_only_handler,
sampling_capabilities=SamplingCapability(),
)
```
## Tool Execution
## Request Routes
Tool execution happens on the server side. The client's role is to pass tools to the LLM and return the LLM's response (which may include tool use requests). The server then executes the tools and may send follow-up sampling requests with tool results.
Servers reach your handler by two routes, and which one applies depends on the protocol era the connection negotiated. A handshake-era server pushes a `sampling/createMessage` request down the open session while a tool is running and waits for the reply. A modern (`2026-07-28`) connection has no such channel, so the tool ends its round by returning a request for a completion instead; the client answers from your handler and calls the tool again with the result attached.
<Tip>
To implement a custom sampling handler, see the [handler source code](https://github.com/PrefectHQ/fastmcp/tree/main/src/fastmcp/client/sampling/handlers) as a reference.
</Tip>
One registration covers both, so this is rarely something you configure — it matters only when you pin an era, since `mode="legacy"` is the sole route that carries a pushed request. See [protocol negotiation](/clients/client#protocol-negotiation) for how the era is chosen, and [Sampling](/servers/sampling) under Servers for how a server issues these requests.

View file

@ -1,180 +1,138 @@
---
title: Background Tasks
sidebarTitle: Tasks
description: Execute operations asynchronously and track their progress.
description: Call long-running tools without blocking, and answer questions they ask mid-run.
icon: clock
tag: "NEW"
---
import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.14.0" />
<VersionBadge version="4.0.0" />
Use this when you need to run long operations asynchronously while doing other work.
Some tool calls take a while. The MCP background tasks extension lets a server run one in the background instead of holding the request open, and FastMCP's client drives the whole thing for you — most of the time you don't need to know a call was tasked at all.
The MCP task protocol lets you request operations to run in the background. The call returns a Task object immediately, letting you track progress, cancel operations, or await results.
<Note>
**Client task support is opt-in.** Install the `fastmcp-tasks` package (`pip install "fastmcp[tasks]"`) and import it — importing `fastmcp_tasks` anywhere (which you do to use `call_tool_task`) enables task support for every `Client` in the process. Without it, a `Client` never advertises the tasks capability, so the server runs its calls synchronously and background tasks simply don't happen.
## Requesting Background Execution
**Tasks also require the modern protocol.** The capability is negotiated over `2026-07-28` connections. `mode="auto"` (the client default) negotiates it automatically; `mode="legacy"` never does. See [protocol negotiation](/clients/client#protocol-negotiation).
</Note>
Pass `task=True` to run an operation as a background task:
## Transparent Calls
With task support enabled, just call the tool. If the server runs it as a background task, `call_tool` polls it to completion under the hood and returns the same result you'd get from a synchronous call — the task is invisible.
```python
import fastmcp_tasks # enables client task support
from fastmcp import Client
async with Client(server, mode="auto") as client:
result = await client.call_tool("slow_computation", {"duration": 10})
print(result.data)
```
This is the right default for most code: it works whether or not the server actually tasks the call, so you can write ordinary tool-calling code without checking server capabilities.
## Driving a Task Explicitly
When you want to do other work while a task runs — or check on it, or cancel it — use `call_tool_task` instead. It returns a `ToolTask` handle immediately rather than waiting for completion.
```python
from fastmcp import Client
from fastmcp_tasks import call_tool_task
async with Client(server) as client:
# Start a background task
task = await client.call_tool("slow_computation", {"duration": 10}, task=True)
async with Client(server, mode="auto") as client:
task = await call_tool_task(client, "slow_computation", {"duration": 10})
print(f"Task started: {task.task_id}")
# Do other work while it runs...
# Get the result when ready
result = await task.result()
```
This works with tools, resources, and prompts:
```python
tool_task = await client.call_tool("my_tool", args, task=True)
resource_task = await client.read_resource("file://large.txt", task=True)
prompt_task = await client.get_prompt("my_prompt", args, task=True)
```
## Task API
All task types share a common interface.
### Getting Results
Call `await task.result()` or simply `await task` to block until the task completes:
```python
task = await client.call_tool("analyze", {"text": "hello"}, task=True)
# Wait for result (blocking)
result = await task.result()
# or: result = await task
```
`call_tool_task` requires the server to actually run the call as a task — if the tool isn't `task=True`, or the server doesn't have the tasks extension registered, it raises `ToolError`. Use it when you specifically need the handle; use `call_tool` when you just want the result.
### Checking Status
Check the current status without blocking:
```python
status = await task.status()
print(f"{status.status}: {status.statusMessage}")
# status.status is "working", "completed", "failed", or "cancelled"
print(f"{status.status}: {status.status_message}")
# status.status is "working", "input_required", "completed", "failed", or "cancelled"
```
### Waiting with Control
Use `task.wait()` for more control over waiting:
`task.wait()` polls until a terminal state (or a specific one you name), without answering any input the task asks for — use it when you want to observe an `input_required` pause yourself rather than have it answered automatically.
```python
# Wait up to 30 seconds for completion
status = await task.wait(timeout=30.0)
# Wait for a specific state
status = await task.wait(state="completed", timeout=30.0)
status = await task.wait(state="input_required", timeout=30.0)
```
### Cancellation
### Getting the Result
Cancel a running task:
`task.result()` drives the task the rest of the way — including answering any input it asks for — and returns the finished result, same as `client.call_tool` would. Awaiting the task directly is shorthand for this.
```python
result = await task.result()
# or: result = await task
```
By default a failed or cancelled task raises `ToolError`. Pass `raise_on_error=False` to `call_tool_task` to get an error result back instead.
### Cancellation
```python
await task.cancel()
```
## Status Updates
Cancellation is cooperative — the task may still finish before the server notices the request.
Register callbacks to receive real-time status updates as the server reports progress:
## Answering Questions Mid-Task
```python
def on_status_change(status):
print(f"Task {status.taskId}: {status.status} - {status.statusMessage}")
task.on_status_change(on_status_change)
# Async callbacks work too
async def on_status_async(status):
await log_status(status)
task.on_status_change(on_status_async)
```
### Handler Template
A task can pause partway through to ask a question, the same way a foreground [multi-round-trip](/clients/elicitation#input-required-rounds) tool does. Pass an `elicitation_handler` and both `call_tool` and `task.result()` answer it automatically as part of driving the task to completion:
```python
from fastmcp import Client
def status_handler(status):
"""
Handle task status updates.
async def handle_elicitation(message, response_type, params, context):
return {"cuisine": "Thai", "vegetarian": True}
Args:
status: Task status object with:
- taskId: Unique task identifier
- status: "working", "completed", "failed", or "cancelled"
- statusMessage: Optional progress message from server
"""
if status.status == "working":
print(f"Progress: {status.statusMessage}")
elif status.status == "completed":
print("Task completed")
elif status.status == "failed":
print(f"Task failed: {status.statusMessage}")
task.on_status_change(status_handler)
async with Client(server, mode="auto", elicitation_handler=handle_elicitation) as client:
result = await client.call_tool("plan_dinner", {})
print(result.data)
```
## Graceful Degradation
You can always pass `task=True` regardless of whether the server supports background tasks. Per the MCP specification, servers without task support execute the operation immediately and return the result inline.
```python
task = await client.call_tool("my_tool", args, task=True)
if task.returned_immediately:
print("Server executed immediately (no background support)")
else:
print("Running in background")
# Either way, this works
result = await task.result()
```
This lets you write task-aware client code without worrying about server capabilities.
Without an `elicitation_handler`, a task that asks for input raises `ToolError` rather than hanging. See [server-side background tasks](/servers/tasks#gathering-input-mid-task) for how a tool asks a question in the first place.
## Example
Putting it together, here is a client that submits a background task with `call_tool_task` and awaits its result:
```python
import asyncio
from fastmcp import Client
from fastmcp_tasks import call_tool_task
async def main():
async with Client(server) as client:
# Start background task
task = await client.call_tool(
"slow_computation",
{"duration": 10},
task=True,
)
async with Client(server, mode="auto") as client:
# Return immediately and drive the task yourself
task = await call_tool_task(client, "slow_computation", {"duration": 10})
print(f"Task started: {task.task_id}")
# Subscribe to updates
def on_update(status):
print(f"Progress: {status.statusMessage}")
# Do other work while the task runs
while True:
status = await task.status()
if status.status in ("completed", "failed", "cancelled"):
break
print(f"Still working... ({status.status})")
await asyncio.sleep(1)
task.on_status_change(on_update)
# Do other work while task runs
print("Doing other work...")
await asyncio.sleep(2)
# Wait for completion and get result
result = await task.result()
print(f"Result: {result.content}")
print(f"Result: {result.data}")
asyncio.run(main())
```

View file

@ -80,7 +80,7 @@ async with client:
Fully hydrated Python objects with complex type support (datetimes, UUIDs, custom classes). FastMCP exclusive.
</ResponseField>
<ResponseField name=".content" type="list[mcp.types.ContentBlock]">
<ResponseField name=".content" type="list[mcp_types.ContentBlock]">
Standard MCP content blocks (`TextContent`, `ImageContent`, `AudioContent`, etc.).
</ResponseField>
@ -173,9 +173,9 @@ For complete control, use `call_tool_mcp()` which returns the raw MCP protocol o
```python
async with client:
result = await client.call_tool_mcp("my_tool", {"param": "value"})
# result -> mcp.types.CallToolResult
# result -> mcp_types.CallToolResult
if result.isError:
if result.is_error:
print(f"Tool failed: {result.content}")
else:
print(f"Tool succeeded: {result.content}")

View file

@ -16,7 +16,9 @@ Transports handle the underlying connection between your client and MCP servers.
STDIO transport communicates with MCP servers through subprocess pipes. When using STDIO, your client launches and manages the server process, controlling its lifecycle and environment.
<Warning>
STDIO servers run in isolated environments by default. They do not inherit your shell's environment variables. You must explicitly pass any configuration the server needs.
STDIO servers inherit only a small allowlist of environment variables — just enough to locate an interpreter and a home directory. Anything else in your shell, including API keys and other credentials, does not reach the server unless you pass it through `env` explicitly.
The allowlist is platform-specific. On POSIX systems it is `HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM`, and `USER`; on Windows it is `APPDATA`, `HOMEDRIVE`, `HOMEPATH`, `LOCALAPPDATA`, `PATH`, `PATHEXT`, `PROCESSOR_ARCHITECTURE`, `SYSTEMDRIVE`, `SYSTEMROOT`, `TEMP`, `USERNAME`, and `USERPROFILE`.
</Warning>
```python
@ -42,7 +44,7 @@ client = Client("my_server.py") # Limited - no configuration options
### Environment Variables
Since STDIO servers do not inherit your environment, you need strategies for passing configuration.
Values you pass through `env` are merged on top of the inherited allowlist, so you add configuration rather than replacing the base environment. Anything your server needs beyond those six variables has to be listed explicitly.
**Selective forwarding** passes only the variables your server needs:
@ -63,7 +65,11 @@ client = Client(transport)
from dotenv import dotenv_values
from fastmcp.client.transports import StdioTransport
env = dotenv_values(".env")
env = {
key: value
for key, value in dotenv_values(".env").items()
if value is not None
}
transport = StdioTransport(command="python", args=["server.py"], env=env)
client = Client(transport)
```
@ -80,7 +86,7 @@ client = Client(transport)
async def efficient_multiple_operations():
async with client:
await client.ping()
await client.list_tools()
async with client: # Reuses the same subprocess
await client.call_tool("process_data", {"file": "data.csv"})
@ -126,7 +132,7 @@ client = Client(
### SSL Verification
By default, HTTPS connections verify the server's SSL certificate. You can customize this behavior with the `verify` parameter, which accepts the same values as [httpx](https://www.python-httpx.org/advanced/ssl/):
By default, HTTPS connections verify the server's SSL certificate. You can customize this behavior with the `verify` parameter, which accepts the same values as httpx2 (documented in [httpx's SSL guide](https://www.python-httpx.org/advanced/ssl/), which httpx2 follows):
```python
from fastmcp import Client

View file

@ -1,7 +1,9 @@
/* Banner styling -- improve readability with better contrast */
/* Banner: an animated brand-rainbow wash behind Mintlify's white text.
Mintlify always renders banner text white, so every gradient stop is a
deep, saturated shade (all >=7:1 on white) the colors evoke the FastMCP
watercolor logo while keeping the announcement legible in both themes.
A dark fallback color is configured in docs.json for the no-CSS case. */
#banner {
background: #f1f5f9 !important;
color: #1e293b !important;
font-size: 0.95rem !important;
font-weight: 600 !important;
padding-top: 12px !important;
@ -12,58 +14,41 @@
#banner::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
inset: 0;
z-index: 0;
background: linear-gradient(
90deg,
rgba(6, 182, 212, 0.25) 0%,
rgba(6, 182, 212, 0.05) 25%,
rgba(6, 182, 212, 0.35) 50%,
rgba(6, 182, 212, 0.08) 75%,
rgba(6, 182, 212, 0.28) 100%
#1e40af 0%,
#5b21b6 22%,
#115e59 44%,
#9a3412 66%,
#9d174d 88%,
#1e40af 100%
);
background-size: 300% 100%;
animation: colorWave 14s ease-in-out infinite alternate;
background-size: 250% 100%;
animation: colorWave 18s ease-in-out infinite alternate;
pointer-events: none;
}
.dark #banner {
background: #475569 !important;
color: #f1f5f9 !important;
}
.dark #banner::before {
background: linear-gradient(
90deg,
rgba(247, 37, 133, 0.35) 0%,
rgba(247, 37, 133, 0.08) 25%,
rgba(247, 37, 133, 0.45) 50%,
rgba(247, 37, 133, 0.12) 75%,
rgba(247, 37, 133, 0.38) 100%
);
background-size: 300% 100%;
/* Keep the announcement text above the animated wash. */
#banner > * {
position: relative;
z-index: 1;
}
@keyframes colorWave {
0% {
background-position: 0% 0%;
background-position: 0% 50%;
}
100% {
background-position: 100% 0%;
background-position: 100% 50%;
}
}
#banner * {
color: #1e293b !important;
margin: 0 !important;
}
.dark #banner * {
color: #f1f5f9 !important;
}
@media (max-width: 767px) {
#banner {
font-size: 0.8rem !important;
@ -71,4 +56,3 @@
padding-bottom: 8px !important;
}
}

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

@ -57,6 +57,42 @@ h6 code:not(pre code) {
background: linear-gradient(135deg, #2d00f7 0%, #4cc9f0 100%);
}
/* V3 banner - inside content-container, breaks out of padding with negative margins */
#v3-banner {
display: block;
background: linear-gradient(135deg, #4cc9f0 0%, #2d00f7 100%);
color: white;
text-align: center;
padding: 10px 16px;
font-size: 0.875rem;
font-weight: 600;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin: -2rem -2rem 1.5rem -2rem;
width: calc(100% + 4rem);
border-radius: 8px 8px 0 0;
}
#v3-banner a {
color: white;
text-decoration: underline;
font-weight: 700;
}
#v3-banner a:hover {
opacity: 0.9;
}
@media (min-width: 1024px) {
#v3-banner {
margin: -3rem -4rem 1.5rem -4rem;
width: calc(100% + 8rem);
}
}
.dark #v3-banner {
background: linear-gradient(135deg, #2d00f7 0%, #4cc9f0 100%);
}

View file

@ -79,17 +79,17 @@ The ASGI approach shines in production environments where you need reliability a
### Custom Path
By default, your MCP server is accessible at `/mcp/` on your domain. You can customize this path to fit your URL structure or avoid conflicts with existing endpoints. This is particularly useful when integrating MCP into an existing application or following specific API conventions.
By default, your MCP server is accessible at `/mcp` on your domain. You can customize this path to fit your URL structure or avoid conflicts with existing endpoints. This is particularly useful when integrating MCP into an existing application or following specific API conventions.
```python
# Option 1: With mcp.run()
mcp.run(transport="http", host="0.0.0.0", port=8000, path="/api/mcp/")
mcp.run(transport="http", host="0.0.0.0", port=8000, path="/api/mcp")
# Option 2: With ASGI app
app = mcp.http_app(path="/api/mcp/")
app = mcp.http_app(path="/api/mcp")
```
Now your server is accessible at `http://localhost:8000/api/mcp/`.
Now your server is accessible at `http://localhost:8000/api/mcp`.
### Authentication
@ -101,6 +101,96 @@ FastMCP supports multiple authentication methods to secure your remote server. S
If you're mounting an authenticated server under a path prefix, see [Mounting Authenticated Servers](#mounting-authenticated-servers) below for important routing considerations.
### Host and Origin Protection
FastMCP can validate `Host` and browser `Origin` headers for Streamable HTTP requests before they reach MCP session handling. This request guard protects localhost-bound servers from DNS rebinding attacks, and it stays opt-in to preserve compatibility with existing ASGI, serverless, and reverse-proxy deployments.
Think of this as a request guard rather than CORS middleware. It decides whether a request can reach MCP session handling. CORS remains a separate browser response-header policy; configure CORS middleware separately when browser JavaScript must read cross-origin responses.
Enable strict validation with `host_origin_protection=True`. When you deploy behind a public hostname, add the hostname clients use to reach your MCP endpoint. If a browser-based MCP client runs on a separate origin, add that origin as well:
```python
from fastmcp import FastMCP
mcp = FastMCP("My Server")
app = mcp.http_app(
host_origin_protection=True,
allowed_hosts=["mcp.example.com"],
allowed_origins=["https://app.example.com"],
)
```
For the direct server approach, pass the same values to `run()`:
```python
from fastmcp import FastMCP
mcp = FastMCP("My Server")
if __name__ == "__main__":
mcp.run(
transport="http",
host="0.0.0.0",
port=8000,
host_origin_protection=True,
allowed_hosts=["mcp.example.com"],
allowed_origins=["https://app.example.com"],
)
```
You can also configure these values with environment variables:
```bash
export FASTMCP_HTTP_HOST_ORIGIN_PROTECTION=true
export FASTMCP_HTTP_ALLOWED_HOSTS='["mcp.example.com"]'
export FASTMCP_HTTP_ALLOWED_ORIGINS='["https://app.example.com"]'
```
Use `host_origin_protection="auto"` to protect localhost-bound direct servers while allowing ASGI, serverless, and reverse-proxy deployments to keep their existing Host handling unless they configure explicit trust rules. Use `host_origin_protection=False` to keep the request guard disabled.
### Gateway Routing Headers
<VersionBadge version="4.0.0" />
A gateway, load balancer, or reverse proxy in front of your MCP server often needs to route a request before it reads the JSON-RPC body — the body may be an SSE stream, or the gateway may simply want to avoid parsing it. On a connection that negotiates the modern `2026-07-28` protocol, Streamable HTTP clients built on the MCP Python SDK (including FastMCP's own client) attach routing information to each request as HTTP headers so an intermediary can dispatch on headers alone:
- `Mcp-Method` carries the JSON-RPC method (for example `tools/call`) on every request.
- `Mcp-Name` carries the target's name on named operations — the tool name for `tools/call`, the prompt name for `prompts/get`, the resource URI for `resources/read`.
- `Mcp-Param-*` carries selected argument values for a `tools/call`, one header per opted-in parameter.
FastMCP's HTTP transport neither strips nor rewrites these headers, so a gateway sees them exactly as the client sent them. The `Host`/`Origin` request guard inspects only `Host` and `Origin` and leaves the routing headers untouched.
<Warning>
These headers are a feature of the modern `2026-07-28` protocol. A client connected over an earlier protocol revision — including one running in legacy mode or one that has fallen back to a legacy server — sends no routing headers at all. Design gateway routing to require the headers rather than assume their presence: if a request arrives without them, fall back to inspecting the body or route it to a default backend, rather than dropping it.
</Warning>
To expose an argument as an `Mcp-Param-*` header, annotate the parameter with the `x-mcp-header` JSON Schema extension. FastMCP carries the annotation into the tool's advertised input schema, and a conforming client mirrors the argument into a header named `Mcp-Param-<token>`:
```python
from typing import Annotated
from pydantic import Field
from fastmcp import FastMCP
mcp = FastMCP("My Server")
@mcp.tool
def query_tenant(
tenant: Annotated[str, Field(json_schema_extra={"x-mcp-header": "Tenant"})],
sql: str,
) -> str:
"""A call to this tool sends the tenant value as an `Mcp-Param-Tenant` header."""
...
```
A gateway can now route on `Mcp-Param-Tenant` — for example, pinning each tenant to a dedicated backend — without inspecting the request body. The annotation is only permitted on `string`, `integer`, and `boolean` parameters. These headers advertise routing intent; treat them as untrusted hints, since the server still validates the request body as the source of truth.
<Tip>
When you put a FastMCP [proxy](/servers/providers/proxy) in front of another server, the proxy re-advertises each backend tool's `x-mcp-header` annotation, so routing headers work across the proxy hop as well. The headers themselves are regenerated per hop rather than forwarded verbatim, since each describes a single HTTP request.
</Tip>
### Health Checks
Health check endpoints are essential for monitoring your deployed server and ensuring it's responding correctly. FastMCP allows you to add custom routes alongside your MCP endpoints, making it easy to implement health checks that work with both deployment approaches.
@ -156,6 +246,8 @@ Most MCP clients, including those that you access through a browser like ChatGPT
CORS (Cross-Origin Resource Sharing) is needed when JavaScript running in a web browser connects directly to your MCP server. This is different from using an LLM through a browser—in that case, the browser connects to the LLM service, and the LLM service connects to your MCP server (no CORS needed).
Host and Origin protection runs before CORS when it is active for a request. Add browser client origins to `allowed_origins` so trusted browser requests reach the CORS middleware, then configure CORS to let browser JavaScript read the MCP response headers it needs. Setting `allowed_origins` trusts the request; it does not emit `Access-Control-Allow-Origin` or other CORS response headers.
Browser-based MCP clients that need CORS include:
- **MCP Inspector** - Browser-based debugging tool for testing MCP servers
@ -295,7 +387,7 @@ def analyze(data: str) -> dict:
return {"result": f"Analyzed: {data}"}
# Create the ASGI app
mcp_app = mcp.http_app(path='/mcp')
mcp_app = mcp.http_app(path="/mcp")
# Create a Starlette app and mount the MCP server
app = Starlette(
@ -307,7 +399,7 @@ app = Starlette(
)
```
The MCP endpoint will be available at `/mcp-server/mcp/` of the resulting Starlette app.
The MCP endpoint will be available at `/mcp-server/mcp` of the resulting Starlette app.
<Warning>
For Streamable HTTP transport, you **must** pass the lifespan context from the FastMCP app to the resulting Starlette app, as nested lifespans are not recognized. Otherwise, the FastMCP server's session manager will not be properly initialized.
@ -326,7 +418,7 @@ from starlette.routing import Mount
mcp = FastMCP("MyServer")
# Create the ASGI app
mcp_app = mcp.http_app(path='/mcp')
mcp_app = mcp.http_app(path="/mcp")
# Create nested application structure
inner_app = Starlette(routes=[Mount("/inner", app=mcp_app)])
@ -336,7 +428,7 @@ app = Starlette(
)
```
In this setup, the MCP server is accessible at the `/outer/inner/mcp/` path.
In this setup, the MCP server is accessible at the `/outer/inner/mcp` path.
### FastAPI Integration
@ -454,7 +546,7 @@ base_url="http://localhost:8000/api" # Includes mount prefix
mcp_path="/mcp" # Internal MCP path, NOT the mount prefix
```
**`issuer_url`** (optional) controls the authorization server identity for OAuth discovery. Defaults to `base_url`.
**`issuer_url`** (optional) controls the authorization server identity for OAuth discovery. Defaults to `base_url`. It sets the `issuer` advertised in the authorization server metadata and the `iss` on issued tokens, while the endpoints in that metadata continue to point at `base_url`.
```python
# Usually not needed - just set base_url and it works
@ -584,7 +676,7 @@ if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```
For more details on OAuth authentication, see the [Authentication guide](/servers/auth).
For more details on OAuth authentication, see the [Authentication guide](/servers/auth/authentication).
## Production Deployment
@ -608,7 +700,7 @@ When deploying FastMCP behind a load balancer or running multiple server instanc
#### Understanding Sessions
By default, FastMCP's Streamable HTTP transport maintains server-side sessions. Sessions enable stateful MCP features like [elicitation](/servers/elicitation) and [sampling](/servers/sampling), where the server needs to maintain context across multiple requests from the same client.
By default, FastMCP's Streamable HTTP transport maintains server-side sessions. A session holds the context a server keeps across multiple requests from the same client, and it carries the handshake-era back-channel that server-initiated requests like [elicitation](/servers/elicitation) push down.
This works perfectly for single-instance deployments. However, sessions are stored in memory on each server instance, which creates challenges when scaling horizontally.
@ -691,9 +783,7 @@ If you're using the [OAuth Proxy](/servers/auth/oauth-proxy), FastMCP issues its
**Default Behavior (Development Only):**
By default, FastMCP automatically manages cryptographic keys:
- **Mac/Windows**: Keys are generated and stored in your system keyring, surviving server restarts. Suitable **only** for development and local testing.
- **Linux**: Keys are ephemeral (random salt at startup), so tokens are invalidated on restart.
By default, FastMCP automatically manages cryptographic keys the same way on every platform: the signing key is deterministically derived from your OAuth client secret, so it survives server restarts as long as the secret doesn't change. Suitable **only** for development and local testing.
This automatic approach is convenient for development but not suitable for production deployments.

View file

@ -5,7 +5,7 @@ description: The MCP platform from the FastMCP team
icon: cloud
---
[Prefect Horizon](https://www.prefect.io/horizon) is a platform for deploying and managing MCP servers. Built by the FastMCP team at [Prefect](https://www.prefect.io), Horizon provides managed hosting, authentication, access control, and a registry of MCP capabilities.
[Prefect Horizon](https://www.prefect.io/horizon?utm_source=gofastmcp&utm_medium=docs&utm_campaign=docs_horizon&utm_content=guide_intro) is a platform for deploying and managing MCP servers. Built by the FastMCP team at [Prefect](https://www.prefect.io), Horizon provides managed hosting, authentication, access control, and a registry of MCP capabilities.
Horizon includes a **free personal tier for FastMCP users**, making it the fastest way to get a secure, production-ready server URL with built-in OAuth authentication.
@ -54,7 +54,7 @@ There are just three steps to deploying a server to Horizon:
### Step 1: Select a Repository
Visit [horizon.prefect.io](https://horizon.prefect.io) and sign in with your GitHub account. Connect your GitHub account to grant Horizon access to your repositories, then select the repo you want to deploy.
Visit [horizon.prefect.io](https://horizon.prefect.io?utm_source=gofastmcp&utm_medium=docs) and sign in with your GitHub account. Connect your GitHub account to grant Horizon access to your repositories, then select the repo you want to deploy.
<img src="/assets/images/horizon/select-repo.png" alt="Horizon repository selection" />

View file

@ -240,7 +240,7 @@ if __name__ == "__main__":
mcp.run(transport="http") # Health check at http://localhost:8000/health
```
Custom routes are served by the same web server as your MCP endpoint. They're available at the root of your domain while the MCP endpoint is at `/mcp/`. For more complex web applications, consider [mounting your MCP server into a FastAPI or Starlette app](/deployment/http#integration-with-web-frameworks).
Custom routes are served by the same web server as your MCP endpoint. They're available at the root of your domain while the MCP endpoint is at `/mcp`. For more complex web applications, consider [mounting your MCP server into a FastAPI or Starlette app](/deployment/http#integration-with-web-frameworks).
## Alternative Initialization Patterns

View file

@ -0,0 +1,262 @@
---
title: Sandboxed Agents
sidebarTitle: Sandboxed Agents
description: Expose MCP tools to isolated agents without giving the sandbox long-lived credentials.
icon: box-open
---
This guide is for deployments where an agent runs inside an isolated container, subprocess, or remote worker and still needs MCP access. In that setup, the sandbox itself becomes part of your trust boundary.
The core recommendation is simple: use FastMCP as the capability boundary. Run a remote FastMCP server, authenticate the sandbox with short-lived scoped credentials, and keep privileged credentials on the server side.
## When to Use This Pattern
This pattern is useful when:
- your agent runs in an ephemeral container or subprocess
- you do not want long-lived credentials inside that sandbox
- you need per-run, per-tenant, or per-job scoping
- the sandbox must call internal APIs, databases, or upstream MCP servers indirectly
If you are building a local desktop integration, STDIO and normal local configuration may be enough. This guide is for cases where the sandbox is isolated enough that secret distribution, credential lifetimes, and privilege boundaries become part of the design.
## What Changes in a Sandboxed Deployment
A desktop MCP client usually runs on a developer's machine and launches local servers with configuration the developer controls. A sandboxed agent is different:
- It often runs in an ephemeral container or subprocess.
- Its filesystem may be inspected after the fact.
- Its environment variables may be broader than you intend.
- You may launch many sandboxes concurrently for different users, tenants, or jobs.
That means convenience patterns that are acceptable locally become risky in sandboxes. Passing a GitHub token, database password, or cloud credentials directly into the sandbox creates a secret distribution problem you do not need to have.
The safer approach is to make your FastMCP server the only component with privileged access and let the sandbox call it over MCP.
## Recommended Architecture
Use this shape by default:
```mermaid
flowchart LR
A["Sandboxed agent"] -->|"short-lived token"| B["FastMCP server"]
B --> C["internal APIs"]
B --> D["databases"]
B --> E["other MCP servers"]
```
The sandbox gets:
- the MCP server URL
- a short-lived token scoped to its job, tenant, or run
- no long-lived upstream credentials
The FastMCP server does the privileged work:
- verifies the sandbox token
- authorizes the request from token claims, scopes, or other server-side policy
- exposes only the tools that sandbox should see
- talks to internal APIs, databases, or upstream MCP servers on the sandbox's behalf
The key design rule is simple:
<Tip>
Give the sandbox capabilities, not credentials.
</Tip>
With that boundary in place, the next questions are how the sandbox connects, how the server verifies and authorizes it, and how you design the tools the sandbox is allowed to call.
## Prefer HTTP for Sandboxed Agents
For sandboxes, prefer a remote HTTP server over a local STDIO server.
STDIO is still excellent for local development, but a remote HTTP server is usually the better production boundary for sandboxed agents because:
- authentication is explicit
- the server lifecycle is independent from the sandbox lifecycle
- secrets stay on the server
- one deployment can safely serve many sandboxes
- auditing and revocation happen in one place
This means the sandbox should connect as a client:
```python
from fastmcp import Client
from fastmcp.client.auth import BearerAuth
client = Client(
"https://sandbox-tools.example.com/mcp",
auth=BearerAuth("short-lived-sandbox-token"),
)
```
And your FastMCP server should run remotely:
```python
from fastmcp import FastMCP
mcp = FastMCP("Sandbox Tools")
if __name__ == "__main__":
mcp.run(transport="http", host="0.0.0.0", port=8000)
```
For production transport setup, see [HTTP Deployment](/deployment/http).
## Use Short-Lived, Scoped Credentials
For sandboxed agents, it is usually cleaner to issue credentials for the sandbox session than to place long-lived upstream credentials directly inside the container.
In practice, that usually means issuing a short-lived bearer token for each sandbox, run, or tenant and validating it on your FastMCP server with a token verifier.
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.jwt import JWTVerifier
auth = JWTVerifier(
jwks_uri="https://auth.example.com/.well-known/jwks.json",
issuer="https://auth.example.com",
audience="sandbox-mcp",
)
mcp = FastMCP("Sandbox Tools", auth=auth)
```
The token should identify the sandbox's scope. Depending on your system, it may represent a job, a tenant, a run, or a user-authorized session. Useful claims often include:
- sandbox or run id
- tenant or installation id
- user or actor id when applicable
- expiration
- optional capability scopes
Avoid shared static tokens across many sandboxes. If one sandbox token leaks, you want the blast radius to be small and the lifetime to be short.
Token verification is only one half of the boundary. Authorization still belongs on the FastMCP server: use scopes, claims, middleware, or custom auth checks to decide which tools and resources that sandbox can actually access.
For example, you can verify the token globally and still require a narrower scope on a specific tool:
```python
from fastmcp import FastMCP
from fastmcp.server.auth import require_scopes
from fastmcp.server.auth.providers.jwt import JWTVerifier
auth = JWTVerifier(
jwks_uri="https://auth.example.com/.well-known/jwks.json",
issuer="https://auth.example.com",
audience="sandbox-mcp",
)
mcp = FastMCP("Sandbox Tools", auth=auth)
@mcp.tool(auth=require_scopes("write:summary"))
def write_summary(content: str) -> str:
return f"Stored summary with {len(content)} characters"
```
For validation patterns, see [Token Verification](/servers/auth/token-verification). For policy enforcement, see [Authorization](/servers/authorization).
## Expose Capabilities, Not Raw Access
The sandbox should not need:
- GitHub app private keys
- database passwords
- upstream OAuth client secrets
- cloud provider credentials
Instead, expose MCP tools that perform privileged work on the server side.
Good sandbox-facing tools tend to look like this:
- `get_recent_updates`
- `write_summary`
- `fetch_repo_context`
- `publish_review_comment`
These tools describe the capability the sandbox needs, not the low-level credentialed action required to perform it.
That distinction matters. A tool like `write_summary` lets the server decide where and how to persist the summary. A tool like `run_sql` or `call_internal_api` pushes privilege and policy into the sandbox where they are much harder to control.
Sandboxed agents behave best when those tools are narrow and structured:
```python
from fastmcp import FastMCP
mcp = FastMCP("Sandbox Tools")
@mcp.tool
def write_summary(content: str) -> str:
"""Store the final summary for the current run."""
return f"Stored summary with {len(content)} characters"
@mcp.tool
def publish_review_comment(pr_number: int, body: str) -> str:
"""Queue a review comment for a specific pull request."""
return f"Queued comment for PR #{pr_number}"
```
These are easier to audit, easier to authorize, and easier for agents to use reliably than a broad catch-all tool like `mutate_state(kind: str, payload: dict)`.
Narrow tools also let you express different policies per tool instead of creating one large privileged escape hatch.
## Use a Proxy When Upstream Systems Are More Privileged
If the sandbox needs access to other MCP servers or internal systems, put FastMCP in front of them instead of forwarding secrets into the sandbox.
This is where proxying becomes useful. Your public-facing FastMCP server can authenticate the sandbox, then forward allowed capabilities to upstream systems with stronger credentials.
Typical examples:
- a sandbox-safe MCP gateway in front of internal MCP servers
- a FastMCP layer in front of internal HTTP APIs
- a job-scoped server that fronts a Git provider, issue tracker, or storage system
If the upstream system is itself an MCP server, FastMCP's proxy support is a natural fit. See [MCP Proxy](/servers/providers/proxy).
## mcp.json for Sandboxed Clients
If your sandboxed agent is configured through `mcp.json`, keep that configuration minimal. Point it at the remote FastMCP server and pass only the values the sandbox actually needs.
```json
{
"mcpServers": {
"sandbox-tools": {
"url": "https://sandbox-tools.example.com/mcp",
"transport": "http"
}
}
}
```
In many systems, authentication is injected by the launcher or environment rather than hardcoded in `mcp.json`. That is usually the right tradeoff for sandboxes. Avoid baking long-lived credentials directly into generated config files, and avoid treating `mcp.json` as the place where secret material should live.
That is all this section needs to do: tell the sandbox where the server lives. Keep auth and secret handling elsewhere.
For configuration details, see [MCP.json](/integrations/mcp-json-configuration).
## Common Mistakes
The same few mistakes show up again and again in sandboxed deployments:
- passing long-lived API keys directly into the sandbox
- treating helper scripts in the sandbox as a security boundary
- exposing broad mutation tools instead of narrow capabilities
- using one shared token for every sandbox
- relying on STDIO inheritance for configuration in production
Each of these works at first. Each becomes painful once you have multiple tenants, multiple jobs, or an incident that requires revoking access quickly.
## Production Checklist
Before shipping a sandbox-facing FastMCP server, check these:
- The sandbox connects over HTTP, not with privileged local credentials.
- Tokens are short-lived and scoped to a run, tenant, or job.
- The FastMCP server verifies tokens on every request.
- Long-lived secrets stay on the server side.
- Tools are narrow, explicit, and structured.
- Upstream privileged systems sit behind the FastMCP server or proxy.
- Revocation and audit live at the server boundary, not inside the sandbox.
If you adopt those defaults, sandbox support stops being a special case and becomes a normal deployment pattern: isolated workers talk to a constrained FastMCP surface, and the server handles the privileged parts centrally.

View file

@ -39,30 +39,33 @@ The `fastmcp.json` configuration answers three fundamental questions about your
This conceptual model helps you understand the purpose of each configuration section and organize your settings effectively. The configuration file maps directly to these three concerns:
`source` is the *where*, `environment` the *what*, and `deployment` the *how*:
```json
{
"$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",
"source": {
// WHERE: Location of your server code
"type": "filesystem", // Optional, defaults to "filesystem"
"type": "filesystem",
"path": "server.py",
"entrypoint": "mcp"
},
"environment": {
// WHAT: Environment setup and dependencies
"type": "uv", // Optional, defaults to "uv"
"type": "uv",
"python": ">=3.10",
"dependencies": ["pandas", "numpy"]
},
"deployment": {
// HOW: Runtime configuration
"transport": "stdio",
"log_level": "INFO"
}
}
```
Only the `source` field is required. The `environment` and `deployment` sections are optional and provide additional configuration when needed.
Only the `source` field is required. The `environment` and `deployment` sections are optional and provide additional configuration when needed. Both `type` fields shown above are optional too, defaulting to `"filesystem"` and `"uv"` respectively.
<Warning>
`fastmcp.json` is parsed as strict JSON, so it accepts no comments or trailing commas.
</Warning>
### JSON Schema Support
@ -229,9 +232,10 @@ Environment variables are included in this section because they're runtime confi
<Expandable title="Deployment Fields">
<ParamField body="transport" type="string" default="stdio">
Protocol for client communication:
Protocol for client communication. `"http"` and `"streamable-http"` both select FastMCP's Streamable HTTP transport:
- `"stdio"`: Standard input/output for desktop clients
- `"http"`: Network-accessible HTTP server
- `"http"`: Network-accessible Streamable HTTP server
- `"streamable-http"`: Explicit alias for Streamable HTTP
- `"sse"`: Server-sent events
</ParamField>
@ -241,12 +245,12 @@ Environment variables are included in this section because they're runtime confi
- `"0.0.0.0"`: All network interfaces
</ParamField>
<ParamField body="port" type="integer" default="3000">
Port number for HTTP transport.
<ParamField body="port" type="integer" default="8000">
Port number for HTTP transport. If omitted, FastMCP uses the server runtime default.
</ParamField>
<ParamField body="path" type="string" default="/mcp/">
URL path for the MCP endpoint when using HTTP transport.
<ParamField body="path" type="string" default="/mcp">
URL path for the MCP endpoint when using HTTP transport. The default is `/mcp` for Streamable HTTP and `/sse` for SSE.
</ParamField>
<ParamField body="log_level" type="string" default="INFO">
@ -396,20 +400,20 @@ This flag tells FastMCP: "I already have the source code, skip any download/clon
Note: For filesystem sources (local Python files), this flag has no effect since they don't require preparation.
The configuration file works with all FastMCP commands:
The configuration file works with server-loading commands that explicitly accept FastMCP config files:
- **`run`** - Start the server in production mode
- **`dev`** - Launch with the Inspector UI for development
- **`dev inspector`** - Launch with the Inspector UI for development
- **`inspect`** - View server capabilities and configuration
- **`install`** - Install to Claude Desktop, Cursor, or other MCP clients
- **`install`** - Install to Claude Desktop, Cursor, or another MCP client
When no file argument is provided, FastMCP searches the current directory for `fastmcp.json`. This means you can simply navigate to your project directory and run `fastmcp run` to start your server with all its configured settings.
`run`, `dev inspector`, and `inspect` search the current directory for a file named exactly `fastmcp.json` when you don't pass a file argument, so you can navigate to your project directory and run `fastmcp run` to start your server with all its configured settings. `install` requires an explicit path to the config file — it never searches.
### CLI Override Behavior
Command-line arguments take precedence over configuration file values, allowing ad-hoc adjustments without modifying the file:
```bash
# Config specifies port 3000, CLI overrides to 8080
# Config specifies port 8000, CLI overrides to 8080
fastmcp run fastmcp.json --port 8080
# Config specifies stdio, CLI overrides to HTTP
@ -434,7 +438,7 @@ You can use different configuration files for different environments:
- `prod.fastmcp.json` - Production settings
- `test_fastmcp.json` - Test configuration
Any file with "fastmcp.json" in the name is recognized as a configuration file.
Only a file named exactly `fastmcp.json` is auto-detected when you omit the path. Other FastMCP configuration files can use any `.json` name, but you must pass them explicitly.
## Examples
@ -471,7 +475,7 @@ A configuration optimized for local development:
"type": "uv",
"python": "3.12",
"dependencies": ["fastmcp[dev]"],
"editable": "."
"editable": ["."]
},
// HOW should it run?
"deployment": {
@ -510,7 +514,7 @@ A production-ready configuration with full dependency management:
"transport": "http",
"host": "0.0.0.0",
"port": 3000,
"path": "/api/mcp/",
"path": "/api/mcp",
"log_level": "INFO",
"env": {
"ENV": "production",

View file

@ -134,7 +134,7 @@ Tests are documentation that shows how features work. Good tests give reviewers
uv run pytest tests/server/ -v
# Run all tests before submitting PR
uv run pytest
uv run pytest -n auto
```
Every new feature needs tests. See the [Testing Guide](/development/tests) for patterns and requirements.
@ -166,7 +166,7 @@ just api-ref-all
#### Before Submitting
1. **Run all checks**: `uv run prek run --all-files && uv run pytest`
1. **Run all checks**: `uv run prek run --all-files && uv run pytest -n auto`
2. **Keep scope small**: One feature or fix per PR
3. **Write clear description**: Your PR description becomes permanent documentation
4. **Update docs**: Include documentation for API changes

View file

@ -20,7 +20,7 @@ Major versions represent fundamental shifts. FastMCP 2.x is entirely different f
Unlike traditional semantic versioning, minor versions **may** include [breaking changes](#breaking-changes) when necessary for the ecosystem's evolution. This flexibility is essential in a young ecosystem where perfect backwards compatibility would prevent important improvements.
</Warning>
FastMCP always targets the most current MCP Protocol version. Breaking changes in the MCP spec or MCP SDK automatically flow through to FastMCP - we prioritize staying current with the latest features and conventions over maintaining compatibility with older protocol versions.
FastMCP tracks the current MCP Protocol version while serving earlier handshake versions alongside it. Building on MCP SDK v2, a FastMCP server negotiates the protocol era each client speaks — the sessionless `2026-07-28` era and earlier session-based eras are both handled by the same server. New features and conventions from the spec flow through to FastMCP as they land; for the details of which capabilities are available on each era, see [Upgrading from FastMCP 3](/getting-started/upgrading/from-fastmcp-3#protocol-version-support).
**Patch (2.0.x)**: Bug fixes and refinements
@ -53,8 +53,8 @@ We expect this exemption to last through at least the 2.12.x and 2.13.x release
Pin to exact versions:
```
fastmcp==2.11.0 # Good
fastmcp>=2.11.0 # Bad - will install breaking changes
fastmcp==4.0.0 # Good
fastmcp>=4.0.0 # Bad - will install breaking changes
```
## Creating Releases
@ -65,6 +65,8 @@ 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` 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.
### Release Cadence

View file

@ -14,7 +14,7 @@ Good tests are the foundation of reliable software. In FastMCP, we treat tests a
```bash
# Run all tests
uv run pytest
uv run pytest -n auto
# Run specific test file
uv run pytest tests/server/test_auth.py
@ -26,14 +26,14 @@ uv run pytest --cov=fastmcp
uv run pytest -m "not integration"
# Skip tests that spawn processes
uv run pytest -m "not integration and not client_process"
uv run pytest -m "not integration and not client_process and not subprocess_heavy"
```
Tests should complete in under 1 second unless marked as integration tests. This speed encourages running them frequently, catching issues early.
### Test Organization
Our test organization mirrors the `src/` directory structure, creating a predictable mapping between code and tests. When you're working on `src/fastmcp/server/auth.py`, you'll find its tests in `tests/server/test_auth.py`. In rare cases tests are split further - for example, the OpenAPI tests are so comprehensive they're split across multiple files.
Our test organization mirrors the source package structure, creating a predictable mapping between code and tests. When you're working on `fastmcp_slim/fastmcp/server/auth.py`, you'll find its tests in `tests/server/test_auth.py`. In rare cases tests are split further - for example, the OpenAPI tests are so comprehensive they're split across multiple files.
### Test Markers
@ -61,6 +61,40 @@ async def test_stdio_transport():
assert result.content[0].text == "test"
```
A third marker, `subprocess_heavy`, exists specifically for Windows CI stability. See [Windows CI and Test Parallelism](#windows-ci-and-test-parallelism) below for when to use it and why it exists.
### Windows CI and Test Parallelism
Windows CI ran the unit suite serially for months. [#2715](https://github.com/PrefectHQ/fastmcp/pull/2715) tried enabling `pytest-xdist` parallelism there in December 2025; [#2726](https://github.com/PrefectHQ/fastmcp/pull/2726) reverted it the next day because "Windows tests continue to fail with intermittent worker crashes." [#4554](https://github.com/PrefectHQ/fastmcp/pull/4554) re-enabled it after removing most of the subprocess pressure that caused those crashes, taking the Windows unit step from roughly 460s to 175s.
That pressure came from three sources, all addressed by #4554: most HTTP tests moved in-process via `asgi_client` instead of binding real sockets, stdio lifecycle tests spawn a minimal stdlib responder (`tests/client/minimal_stdio_server.py`, ~0.03s to start) instead of a subprocess that runs `import fastmcp` (~0.7s), and roughly 80 real `sleep()` calls became deterministic waits on the condition each test actually cared about. Fewer, cheaper subprocesses competing under parallel workers left fewer chances for a worker to die.
#### The `subprocess_heavy` marker
One class of test still spawns a full Python interpreter that imports FastMCP — checking that a bare install doesn't need optional dependencies, or that a decorator works from a fresh process. Each spawn pays a full interpreter's startup and memory footprint, and a 2-core Windows runner already running 2 xdist workers has little headroom left to absorb that. These tests carry `@pytest.mark.subprocess_heavy` and run in the existing serial `client_process` CI step instead of alongside the parallel workers — `.github/actions/run-pytest/action.yml` routes `client_process or subprocess_heavy` to that step (`MAX_PROCS=0`) and excludes both markers from the parallel unit step.
If a test runs `subprocess.run([sys.executable, "-c", ...])`, or otherwise starts a fresh interpreter that imports `fastmcp`, mark it `subprocess_heavy`. A subprocess that runs a minimal stdlib script with no FastMCP import doesn't need the marker — it's the interpreter startup and import that's expensive, not the subprocess itself.
#### This is a mitigation, not a proof
There is no root-cause diagnosis behind this fix, only a plausible one. During validation, one Windows run genuinely crashed a worker on `test_fastmcp_imports_without_legacy_httpx` — a fresh-interpreter test — with pytest-xdist reporting `worker 'gw1' crashed while running '...'` after execnet's channel saw `ConnectionResetError: [WinError 10054]`. Nothing in that log says *why* the worker died: memory exhaustion, handle exhaustion, and some Windows-specific `subprocess`/`execnet` interaction are all still consistent with what was observed. Marking the fresh-interpreter tests `subprocess_heavy` made the crash stop recurring, but "it stopped" is not the same as "we know why."
Treat the next Windows worker crash as a test of this diagnosis. **If it lands on a test that is not a fresh-interpreter spawner, the `subprocess_heavy` theory was wrong** — the real problem is subprocess-under-xdist on Windows more generally, and isolating one marker's worth of tests was never going to fix that. The fallback is one conditional back in `run-pytest/action.yml`, restoring the pre-#4554 behavior:
```bash
PARALLEL_FLAGS=""
if [ "$MAX_PROCS" != "0" ] && [ "${{ runner.os }}" != "Windows" ]; then
PARALLEL_FLAGS="--numprocesses auto --maxprocesses $MAX_PROCS --dist worksteal"
fi
```
#### Two traps that aren't Windows-specific
Two test-authoring bugs surfaced while validating this change. Neither is about Windows or parallelism, but both are worth watching for anywhere a real `sleep()` gets replaced with a wait:
- **Match the wait condition to the assertion.** A test waited for "any callback fired," then asserted that a `completed` callback existed. That races, because an earlier `working` notification satisfies the wait before the `completed` one arrives. A deterministic wait is only as good as the condition it waits on — wait for the thing you actually assert.
- **Don't assert on incidental timing.** A crash-recovery test asserted "at least one concurrent request fails" while a subprocess restarts, which quietly depended on the restart being slow. Once restart got faster, recovery could beat every in-flight request and the test started failing because the behavior *improved*. Assert the invariant instead: no hang, and no result served by the dead process.
## Writing Tests
@ -228,7 +262,7 @@ async def test_tool_schema_generation():
return {"amount": amount, "tax": amount * rate, "total": amount * (1 + rate)}
tools = mcp.list_tools()
schema = tools[0].inputSchema
schema = tools[0].input_schema
# First run: snapshot() is empty, gets auto-populated
# Subsequent runs: compares against stored snapshot
@ -299,22 +333,19 @@ async def test_database_tool():
### Testing Network Transports
While in-memory testing covers most unit testing needs, you'll occasionally need to test actual network transports like HTTP or SSE. FastMCP provides two approaches: in-process async servers (preferred), and separate subprocess servers (for special cases).
In-memory testing covers most unit testing needs, but some behavior only exists over HTTP: middleware, authentication, session management, header handling, and SSE streaming. To test those, serve your server over HTTP with `asgi_client`.
#### In-Process Network Testing (Preferred)
#### Testing Over HTTP
<VersionBadge version="2.13.0" />
<VersionBadge version="3.5.0" />
For most network transport tests, use `run_server_async` as an async context manager. This runs the server as a task in the same process, providing fast, deterministic tests with full debugger support:
`asgi_client` builds your server's real Starlette app, starts its lifespan, and hands you a connected `Client` that talks to it over the full HTTP stack. The one thing it skips is the socket: requests are dispatched straight into the ASGI application on the current event loop, so there is no port to bind, no uvicorn to start, and no connection to negotiate. Everything else — middleware, authentication, session management, SSE framing — runs exactly as it does in production.
```python
import pytest
from fastmcp import FastMCP, Client
from fastmcp.client.transports import StreamableHttpTransport
from fastmcp.utilities.tests import run_server_async
from fastmcp import FastMCP
from fastmcp.utilities.tests import asgi_client
def create_test_server() -> FastMCP:
"""Create a test server instance."""
server = FastMCP("TestServer")
@server.tool
@ -323,26 +354,89 @@ def create_test_server() -> FastMCP:
return server
@pytest.fixture
async def http_server() -> str:
"""Start server in-process for testing."""
server = create_test_server()
async with run_server_async(server) as url:
yield url
async def test_http_transport(http_server: str):
"""Test actual HTTP transport behavior."""
async with Client(
transport=StreamableHttpTransport(http_server)
) as client:
result = await client.ping()
assert result is True
async def test_greet_over_http():
async with asgi_client(create_test_server()) as client:
greeting = await client.call_tool("greet", {"name": "World"})
assert greeting.data == "Hello, World!"
```
The `run_server_async` context manager automatically handles server lifecycle and cleanup. This approach is faster than subprocess-based testing and provides better error messages.
Pass `transport="sse"` to exercise the SSE app instead of streamable HTTP, `path=` to serve on a custom path, `headers=` and `auth=` to configure the client's requests, and any other keyword argument to configure the `Client` itself.
```python
async def test_tenant_header_is_visible_to_tools():
async with asgi_client(
create_test_server(),
headers={"X-Tenant-ID": "acme"},
timeout=5,
) as client:
await client.list_tools()
```
#### Sharing One Server Across Tests
When several tests share a server but each needs its own client, use `asgi_server` in a fixture. It yields an `ASGIServer`, whose `client()` method produces a fresh client — with its own session — on demand.
```python
import pytest
from fastmcp import FastMCP
from fastmcp.utilities.tests import ASGIServer, asgi_server
@pytest.fixture
async def http_server():
server = FastMCP("TestServer")
@server.tool
def greet(name: str) -> str:
return f"Hello, {name}!"
async with asgi_server(server) as running_server:
yield running_server
async def test_greet(http_server: ASGIServer):
async with http_server.client() as client:
greeting = await client.call_tool("greet", {"name": "World"})
assert greeting.data == "Hello, World!"
async def test_sessions_are_isolated(http_server: ASGIServer):
async with (
http_server.client(mode="legacy") as first,
http_server.client(mode="legacy") as second,
):
assert await first.ping() is True
assert await second.ping() is True
```
Sessions belong to the handshake era of the MCP protocol, and so does `ping`, so a test that is about session behavior pins `mode="legacy"`. Every keyword argument `client()` doesn't consume itself is passed straight to `Client`. See [protocol negotiation](/clients/client#protocol-negotiation).
For assertions about raw HTTP — status codes, response headers, metadata endpoints — `http_client()` returns an `httpx.AsyncClient` bound to the same app. Because nothing is listening on the network, this is the only way to make raw requests; a plain `httpx.AsyncClient()` cannot reach the server.
```python
async def test_unauthenticated_request_is_rejected(http_server: ASGIServer):
async with http_server.http_client() as http:
response = await http.post(http_server.url, json={"jsonrpc": "2.0", "id": 1})
assert response.status_code in (400, 401)
```
If you need to build the client transport yourself, `transport()` returns a `StreamableHttpTransport` or `SSETransport` already wired to the in-process app.
#### Testing on a Real Port
<VersionBadge version="2.13.0" />
`run_server_async` starts a real uvicorn server on a real TCP port as a task in the current process and yields its URL. Reach for it only when the subject of the test is the network itself — real sockets, TLS, or a server that must be reachable by something other than an in-process client.
```python
from fastmcp import FastMCP, Client
from fastmcp.utilities.tests import run_server_async
async def test_server_binds_a_real_port():
server = FastMCP("TestServer")
async with run_server_async(server) as url:
assert url.startswith("http://127.0.0.1:")
async with Client(url) as client:
assert await client.list_tools() == []
```
#### Subprocess Testing (Special Cases)
@ -375,8 +469,8 @@ async def test_http_transport(http_server: str):
async with Client(
transport=StreamableHttpTransport(http_server)
) as client:
result = await client.ping()
assert result is True
tools = await client.list_tools()
assert "greet" in [tool.name for tool in tools]
```
The `run_server_in_process` utility handles server lifecycle, port allocation, and cleanup automatically. Use this only when subprocess isolation is truly necessary, as it's slower and harder to debug than in-process testing. FastMCP uses the `client_process` marker to isolate these tests in CI.
@ -393,4 +487,4 @@ just docs
mintlify dev
```
The local server watches for changes and automatically refreshes. This preview catches formatting issues and helps you see documentation as users will experience it.
The local server watches for changes and automatically refreshes. This preview catches formatting issues and helps you see documentation as users will experience it.

View file

@ -12,7 +12,11 @@
"decoration": "gradient"
},
"banner": {
"content": "Deploy FastMCP servers for free on [Prefect Horizon](https://www.prefect.io/horizon)"
"color": {
"dark": "#475569",
"light": "#1e3a5f"
},
"content": "FastMCP 4 is in beta — build stateful applications on sessionless MCP. [See what's new](/getting-started/whats-new)."
},
"colors": {
"dark": "#f72585",
@ -20,10 +24,7 @@
"primary": "#2d00f7"
},
"contextual": {
"options": [
"copy",
"view"
]
"options": ["copy", "view"]
},
"description": "The fast, Pythonic way to build MCP servers and clients.",
"errors": {
@ -66,7 +67,7 @@
"label": ""
},
{
"href": "https://prefect.io/horizon",
"href": "https://www.prefect.io/horizon?utm_source=gofastmcp&utm_medium=docs&utm_campaign=docs_horizon&utm_content=header",
"icon": "cloud",
"label": "Prefect Horizon"
}
@ -88,7 +89,8 @@
"pages": [
"getting-started/welcome",
"getting-started/installation",
"getting-started/quickstart"
"getting-started/quickstart",
"getting-started/whats-new"
]
},
{
@ -108,30 +110,23 @@
},
{
"collapsed": true,
"group": "Features",
"icon": "stars",
"group": "Working with Tools",
"icon": "wand-magic-sparkles",
"pages": [
"servers/tasks",
"servers/composition",
"servers/dependency-injection",
"servers/elicitation",
"servers/icons",
"servers/lifespan",
"servers/logging",
"servers/middleware",
"servers/pagination",
"servers/progress",
"servers/sampling",
"servers/storage-backends",
"servers/telemetry",
"servers/testing",
"servers/versioning"
],
"tag": "UPDATED"
"servers/transforms/transforms",
"servers/transforms/tool-transformation",
"servers/transforms/code-mode",
"servers/transforms/tool-search",
"servers/transforms/namespace",
"servers/visibility",
"servers/transforms/resources-as-tools",
"servers/transforms/prompts-as-tools",
"servers/tool-fingerprinting"
]
},
{
"collapsed": true,
"group": "Providers",
"group": "MCP Providers",
"icon": "layer-group",
"pages": [
"servers/providers/overview",
@ -139,22 +134,37 @@
"servers/providers/filesystem",
"servers/providers/proxy",
"servers/providers/skills",
"servers/composition",
"servers/providers/custom"
]
},
{
"collapsed": true,
"group": "Transforms",
"icon": "wand-magic-sparkles",
"group": "Interactivity",
"icon": "comments",
"pages": [
"servers/transforms/transforms",
"servers/transforms/namespace",
"servers/transforms/tool-transformation",
"servers/visibility",
"servers/transforms/code-mode",
"servers/transforms/tool-search",
"servers/transforms/resources-as-tools",
"servers/transforms/prompts-as-tools"
"servers/elicitation",
"servers/sampling",
"servers/completions",
"servers/progress",
"servers/logging",
"servers/pagination",
"servers/icons"
]
},
{
"collapsed": true,
"group": "Extensibility",
"icon": "puzzle-piece",
"pages": [
"servers/middleware",
"servers/dependency-injection",
"servers/lifespan",
"servers/storage-backends",
"servers/sessions",
"servers/extensions",
"servers/tasks",
"servers/versioning"
]
},
{
@ -186,8 +196,11 @@
"pages": [
"deployment/running-server",
"deployment/http",
"deployment/sandboxed-agents",
"deployment/prefect-horizon",
"deployment/server-configuration"
"deployment/server-configuration",
"servers/testing",
"servers/telemetry"
]
}
]
@ -197,27 +210,26 @@
"pages": [
"apps/overview",
"apps/quickstart",
"apps/fastmcp-app",
"apps/prefab",
"apps/interactive-apps",
"apps/generative",
"apps/low-level",
{
"collapsed": true,
"group": "Providers",
"icon": "layer-group",
"pages": [
"apps/providers/approval",
"apps/providers/choice",
"apps/providers/file-upload",
"apps/providers/form"
],
"tag": "NEW"
},
{
"collapsed": true,
"group": "Reference",
"icon": "book",
"pages": [
{
"collapsed": true,
"group": "Prefab Providers",
"icon": "cube",
"pages": [
"apps/providers/approval",
"apps/providers/choice",
"apps/providers/file-upload",
"apps/providers/form"
]
},
"apps/development",
"apps/examples",
"apps/architecture"
@ -229,29 +241,24 @@
"group": "Clients",
"pages": [
"clients/client",
"clients/client-only-package",
"clients/transports",
"clients/fastmcp-remote",
{
"collapsed": true,
"group": "Core Operations",
"group": "Operations",
"icon": "toolbox",
"pages": [
"clients/tools",
"clients/resources",
"clients/prompts"
]
},
{
"collapsed": true,
"group": "Handlers",
"icon": "hand",
"pages": [
"clients/notifications",
"clients/prompts",
"clients/sampling",
"clients/elicitation",
"clients/tasks",
"clients/progress",
"clients/logging",
"clients/roots"
"clients/roots",
"clients/notifications"
],
"tag": "UPDATED"
},
@ -261,6 +268,7 @@
"icon": "key",
"pages": [
"clients/auth/oauth",
"clients/auth/client-credentials",
"clients/auth/cimd",
"clients/auth/bearer"
],
@ -285,6 +293,7 @@
"integrations/eunomia-authorization",
"integrations/github",
"integrations/google",
"integrations/huggingface",
"integrations/keycloak",
"integrations/oci",
"integrations/permit",
@ -298,10 +307,7 @@
"collapsed": true,
"group": "Web Frameworks",
"icon": "code",
"pages": [
"integrations/fastapi",
"integrations/openapi"
]
"pages": ["integrations/fastapi", "integrations/openapi"]
},
{
"collapsed": true,
@ -323,36 +329,42 @@
"pages": [
"integrations/anthropic",
"integrations/gemini",
"integrations/openai"
"integrations/openai",
"integrations/pydantic-ai"
]
},
"integrations/mcp-json-configuration"
]
},
{
"group": "CLI",
"pages": [
"cli/overview",
"cli/running",
"cli/install-mcp",
"cli/inspecting",
"cli/client",
"cli/generate-cli",
"cli/auth"
]
},
{
"group": "More",
"pages": [
"more/settings",
{
"collapsed": true,
"group": "CLI",
"icon": "terminal",
"pages": [
"cli/overview",
"cli/running",
"cli/install-mcp",
"cli/inspecting",
"cli/client",
"cli/generate-cli",
"cli/auth"
]
},
{
"collapsed": true,
"group": "Upgrading",
"icon": "up",
"pages": [
"getting-started/upgrading/from-fastmcp-3",
"getting-started/upgrading/from-fastmcp-2",
"getting-started/upgrading/from-mcp-sdk",
"getting-started/upgrading/from-low-level-sdk"
"getting-started/upgrading/from-mcp-sdk-v1",
"getting-started/upgrading/from-mcp-sdk-v2",
"getting-started/upgrading/from-low-level-sdk-v1",
"getting-started/upgrading/from-low-level-sdk-v2"
]
},
{
@ -370,11 +382,9 @@
"collapsed": true,
"group": "What's New",
"icon": "sparkles",
"pages": [
"updates",
"changelog"
]
}
"pages": ["updates", "changelog"]
},
"more/faq"
]
}
],
@ -394,7 +404,10 @@
"icon": "code"
}
],
"version": "v3"
"version": "v4.0.0 (beta 1)"
},
{
"$ref": "./v3-navigation.json"
},
{
"$ref": "./v2-navigation.json"
@ -402,6 +415,34 @@
]
},
"redirects": [
{
"destination": "/getting-started/whats-new",
"source": "/development/v4-notes/index"
},
{
"destination": "/getting-started/upgrading/from-fastmcp-3",
"source": "/development/v4-notes/change-register"
},
{
"destination": "/getting-started/whats-new",
"source": "/development/v4-notes/feature-program"
},
{
"destination": "/getting-started/whats-new",
"source": "/development/v4-notes/protocol-2026"
},
{
"destination": "/getting-started/upgrading/from-fastmcp-3",
"source": "/development/v4-notes/known-gaps"
},
{
"destination": "/servers/tasks",
"source": "/development/v4-notes/background-tasks"
},
{
"destination": "/apps/fastmcp-app",
"source": "/apps/interactive-apps"
},
{
"destination": "/apps/generative",
"source": "/apps/providers/generative"
@ -471,12 +512,24 @@
"source": "/development/upgrade-guide"
},
{
"destination": "/getting-started/upgrading/from-mcp-sdk",
"destination": "/getting-started/upgrading/from-mcp-sdk-v1",
"source": "/getting-started/upgrading-from-sdk"
},
{
"destination": "/getting-started/upgrading/from-low-level-sdk",
"destination": "/getting-started/upgrading/from-mcp-sdk-v1",
"source": "/getting-started/upgrading/from-mcp-sdk"
},
{
"destination": "/getting-started/upgrading/from-low-level-sdk-v1",
"source": "/getting-started/low-level-sdk"
},
{
"destination": "/getting-started/upgrading/from-low-level-sdk-v1",
"source": "/getting-started/upgrading/from-low-level-sdk"
},
{
"destination": "/getting-started/upgrading/from-fastmcp-3",
"source": "/getting-started/upgrading/to-mcp-sdk-v2"
}
],
"search": {

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