About Fastmcp Rust
Fastmcp Rust is an MCP server published by Dicklesworthstone in the AI category: rust framework for building Model Context Protocol servers with cancel-correct async, zero-copy serialization, and first-class tool/resource/prompt abstractions.
The repository has 39 stars and 12 forks, with the last commit 4 hours ago. Recent commit activity is the strongest signal that reported issues will get attention.
Install
git clone https://github.com/Dicklesworthstone/fastmcp_rustThis server has no ConduID identity, so agent calls to it are not receipted. Pin the version you install and review the source before granting it credentials.
Ask AI
Ask AI about Fastmcp Rust
Powered by Claude · Grounded in docs
Security checks
Static checks derived from the repository 3 hours ago. Heuristics on the source, not an audit.
- ✓README presentThe repository ships documentation.
- ✓License declaredUsable under a stated license.
- ✓Tests presentA test suite exists in the repository.
- ✓Dependencies pinnedA lockfile pins dependency versions.
- !Scoped permissionsDoesn't declare a permission scope. Assume it can do anything its process can.
1 check has not been run yet.
Releases
README
Protocol status (2026-08-27): MCP 2026-07-28 support is under implementation and remains unverified. The root compatibility
PROTOCOL_VERSIONis2024-11-05; the modern facade'smodern::PROTOCOL_VERSIONis2026-07-28. Source presence, examples, and historical parity rows are not conformance or release evidence. Versions through 0.13.0 have been published, but publication and source edits alone do not prove historical workflow identities, queued runs, or credentials inert; provider-side release-safety evidence is still required.
Measured official-conformance standing
Run it yourself with scripts/run_official_conformance.sh; it owns the suite
pin and the result tally. Measurements use
@modelcontextprotocol/conformance@0.2.0-alpha.10,
--spec-version 2026-07-28 --suite all, server mode against the in-tree
conformance_server adapter:
| revision | date | scenarios | checks | SUCCESS | FAILURE | WARNING | INFO |
|---|---|---|---|---|---|---|---|
1c2dc896 |
2026-10-12 | 40 | 115 | 112 | 0 | 2 | 1 |
e2a0ac5c |
2026-10-12 | 40 | 115 | 110 | 0 | 4 | 1 |
99a3b4e8 |
2026-10-05 | 40 | 115 | 110 | 0 | 4 | 1 |
| working tree (unanchored) | 2026-10-04 | 40 | 115 | 110 | 0 | 4 | 1 |
6b54e023 |
2026-10-03 | 40 | 114 | 108 | 1 | 4 | 1 |
bba5a09f |
2026-10-01 | 40 | 92 | 54 | 38 | 0 | 0 |
The 99a3b4e8 row is bound to identity rather than to a date, which the row
above it is not: 98 commits and 388 lines across four server-mode source files
(fastmcp-core/src/context.rs, fastmcp-protocol/src/server_discovery.rs,
fastmcp-server/src/lib.rs, fastmcp/src/lib.rs) landed after the 2026-10-04
measurement, which under this project's own receipt rules invalidated it. The
re-measurement reproduces it exactly, so the standing held across that drift —
but that is now a measured fact rather than an assumption. Its bindings:
HEAD 99a3b4e8f0ebd56357f34953754ac6912df0597b
adapter blob 0b887aedeb0b7f6ad3ddceb5ea3cc3523bbab29b
adapter sha256 a66f0bee...e149b4 crates/fastmcp/examples/conformance_server.rs
binary sha256 74c18713...e54a1a target/debug/conformance_server
toolchain rustc 1.100.0-nightly (e7769602a 2026-08-24)
host hz3 (x86_64 linux), direct ssh, RCH scheduler bypassed
build cargo build --locked -p fastmcp-rust --features tasks
--bin conformance_server, rc 0, 32m24s
--baseline cannot currently pass, and that is a property of the gate, not
of the server. The suite's own --expected-failures treats a scenario
carrying a SHOULD-level WARNING as a scenario failure, so this run reported
suite exit status: 1 and named server-stateless,
input-required-result-missing-input-response and
input-required-result-ignore-extra-params as "unexpected failures" while its
own tally printed 110 passed, 0 failed. Anyone wiring --baseline into a
gate today gets a permanent red. Resolving that means either listing those
scenarios (an expected-failures edit, which scripts/conformance-expected-failures.yaml
deliberately reserves to its owner) or gating on the tally instead; it is not
resolved here.
These rows are not a ratio, and the denominator is not fixed. It rose 92 →
114 → 115 because a scenario that fails an early check never runs its later
ones, so fixing one check can add checks to the run. The corollary is a trap:
a regression that makes a scenario abort earlier shrinks the denominator and can
push a percentage up. Compare the sets of failing check ids, which is what
scripts/conformance-expected-failures.yaml records and what the suite's own
--expected-failures gates on.
Client mode. The gate is the harness passing in both modes. 32 scenarios / 155 checks: SUCCESS=55, FAILURE=46, SKIPPED=2, WARNING=1, INFO=51. Measured 2026-10-13, bound to:
revision 2b6c519e, crates tree 6a57e7ca
adapter binary sha256 2d47186b24962718e3e9a01be48f746449823ecf...
suite @modelcontextprotocol/conformance@0.2.0-alpha.10,
client --suite all --spec-version 2026-07-28
host hz3 (x86_64 linux), cold dependency rebuild
exit build rc 0, suite rc 1 (FAILUREs present, as expected)
This row previously read "most recent run" with no revision, date, host or toolchain, which made it unverifiable; the re-measurement reproduces all five counts exactly. Split it before quoting it, because the halves measure different things:
| checks | SUCCESS | FAILURE | |
|---|---|---|---|
| non-authorization | 55 | 52 | 0 |
| authorization | 100 | 3 | 46 |
-
Non-authorization: no FAILURE-level check remains.
http-custom-headers18/18,http-invalid-tool-headers11/11,http-standard-headers9/9 (2 skipped),sep-2322-client-request-state5/5,json-schema-ref-no-deref,request-metadata(1 SHOULD warning) andtools_callclean. SEP-2243 parameter-header mirroring is exercised end to end: designated parameters are sent asMcp-Param-*, encoded where the value is header-unsafe, omitted when null, and never added for an undesignated parameter — and a tool whosex-mcp-headerannotations are invalid is excluded rather than called. -
Authorization: the adapter, not the library.
conformance_clientsupplies no interactive OAuth driver, so these measure adapter completeness. It does ship a non-interactive authorization-code driver —examples/conformance_oauth.rsplus itsmanagedsubmodule, compiled into the adapter as a module and wired atconformance_client.rs:376— but that driver is inert unlessFASTMCP_CONFORMANCE_OAUTHcarries its configuration, and nothing in this repository sets it, includingscripts/run_official_conformance.sh. So these checks measure the adapter with authorization switched off. No value of that variable can switch it on, though. Measured 2026-10-12 against the pinned suite:configurerequires theresourcemember to equal the MCP endpoint and to usehttps(conformance_oauth.rs:306), andissuerandauthorization_endpointare required static pins rather than discovered values. The suite serves plain HTTP on an ephemeral loopback port and has no TLS capability at all — a census of its 472,891-byte bundle findshttp://localhost:${this.port}andhttp://127.0.0.1:${e}against zero occurrences ofcreateSecureServer,node:tls, or any cert/key material — and it stands up a fresh authorization server per scenario, across 25auth/*client scenarios that deliberately vary the issuer (iss-wrong-issuer,metadata-issuer-mismatch,authorization-server-migration). So the driver refuses any configuration naming the suite's endpoint, on two independent grounds. Closing these needs more than an adapter profile, which is worth stating precisely because the cheap-sounding estimate is wrong. The HTTPS requirement is not one check in the conformance adapter: a census ofcrates/fastmcp-client/src, withcfg(test)modules excluded, finds 23 production HTTPS enforcement points across 18 files: 21 independentscheme() != "https"orstarts_with("https://")refusals inhttp_auth.rs,challenge.rs,private_key_jwt.rs,metadata_document.rs,dpop.rs,dpop/native/core/stream/task_subscription/watch/checkpoint.rs,driver.rs,redirect.rs,http_client.rs,managed/client.rs,resume.rs,oauth.rs,revocation.rs,recovery.rs,repair.rs,http_executor.rsandparameter_headers.rs, plus the two central helpersvalidate_httpsandhttps_urlindiscovery.rs. Thirteen further call sites — inchallenge.rs,step_up.rs,issuer.rsandregistration.rs— inherit those helpers' refusal rather than repeating it, so they are not separate edits. (This row previously read "32 production HTTPS hard-gates across 19 files" and then named 18. Both figures were wrong when written rather than stale: the same instrument returns 22 across 17 both at the authoring commitaac6f67cand at HEAD, so the subject never moved. The corrected figure is smaller, i.e. the earlier row overstated the work.) Reaching the suite's ephemeral plain-HTTP loopback authorization server therefore means threading a loopback exemption through all of them, which is a change to the transport security posture of the whole client authorization subsystem, plus accepting a discovered issuer whereOAuthDiscoveryPlancurrently takes a caller-suppliedTrustedOAuthIssuerallowlist. And the exemption is not spec-backed in the direction that matters: RFC 8252 §7.3 permits loopbackhttpfor the client's own redirect URI, which is not what blocks us, while OAuth 2.1 requireshttpsfor the authorization server's own endpoints — exactly the URLs these 23 enforcement points refuse. The pinned suite serves its authorization server over plainhttpas a harness convenience, not because the spec allows it. So permitting it would be a real relaxation beyond the spec, not a reviewed alignment with it, and it is a library decision rather than adapter plumbing. It is not taken here.But a reviewed loopback-HTTP exemption already exists in this library, and the conformance adapter already uses it. This row previously claimed "no loopback exemption anywhere", which is false.
ReviewedToolHeaders::new_for_loopback_http(http_executor/parameter_headers.rs) is public and documented: it admits canonical IPv4/IPv6 loopback literals over plainhttpand deliberately refuses DNS names,localhostincluded, "because a name can be rebound and is therefore not proof of a loopback peer". Its doc states the threat model it accepts — "loopback provides neither peer authentication nor secrecy from other local processes" — and requires per-binding caller review.examples/conformance_client.rsbranches on the endpoint scheme to call it, and resolves the harness'shttp://localhost:<port>to the loopback literal in the adapter, on the stated ground that "resolving the name is the HOST's decision to make, not the library's … the library's literal-only boundary stays intact". So the precedent, the threat model, and the host-versus-library trust split are all settled here already — for parameter headers. What is not settled, and is the actual decision, is whether the same split is acceptable for the authorization server's own endpoints, where these 23 points protect credential transport rather than header mirroring. That is a strictly stronger property, so the existing precedent narrows the question rather than answering it.A trap for whoever does take it. Gating the exemption behind a conformance-only feature or
cfgwould be the cheap version and is self-defeating as proof: the 46 passing checks would then measure a profile no user can build, so they would be evidence about a conformance-only code path rather than about shipped behaviour. Either the shipped validators take a beyond-spec loopback exemption as an explicit, reviewed decision, or these 46 stay closed and are reported as a deliberate boundary — which, given that OAuth 2.1 requireshttpsfor authorization-server endpoints, is a defensible place to land rather than a gap to apologise for. They are also not one problem. The pinned suite drives PKCE (code_challenge),authorization_code, dynamicregister, and 401WWW-Authenticate+resource_metadatadiscovery, all of which this client implements. None of the 46 is DPoP, which this row used to imply. The suite does carry DPoP client scenarios —auth/dpopandauth/dpop-nonce— but both are tagged[extension]rather than a dated spec version, so--spec-version 2026-07-28filters them out:list --clientreports 43 scenarios unfiltered and 32 at that version, anddpop/sep-1932appear zero times anywhere in the run. So DPoP is not measured at this pin, and the 46 are entirely authorization-flow checks (protected-resource and authorization-server metadata, client registration, authorization and token requests,isshandling, scope derivation and step-up, the three token-endpoint auth methods, CIMD, pre-registration, offline access and AS migration). DPoP (RFC 9449) primitives now exist and compile, which was not true before 2026-10-12, and the surface is growing faster than this row can be rewritten: measured 2026-10-16 at7bd44cd0,fastmcp_client::http_auth::dpopis 57 files, 24,095 lines, 151 public items and 311 in-module tests, plus 515 lines and 7 tests infastmcp_protocol::dpopbehind thejosefeature — 24,610 lines in all. The trajectory is the point rather than any one reading: 781 lines on 2026-10-12, 6,699 ata6559ff2, 10,541 atacc20148, and 24,095 at7bd44cd0two days after that — 30.8× in four days, with the in-workspace caller count zero at every reading. That is the module keeping its own promise, not a widening gap: it is caller-driven by design, so the consumer is the application. Treat the counts as a dated reading of a module under active construction, not a durable fact; the gate below deliberately does not pin them, because a check that reddens on ordinary growth is a check that gets switched off. It is reachable by facade users throughpub use fastmcp_client::http_auth. It had been unwired rather than absent — the file was created by2612a7d4, thepub mod dpop;that puts it in the build was added only byac00c6ad, and the onlymod dpopdeclaration inhttp_auth.rsis that one, so those lines had never been compiled until then. (They had never been formatted either;c65eced1restoredcargo fmt --checkafterwards.) It has no in-workspace consumer, and that is its design rather than a gap — a correction to what this row said earlier today. The module documentation states that it "never promotes a DPoP token into the existing bearer-only OAuth driver" and "does not install automatic OAuth negotiation or HTTP retries", so the intended consumer is the application, not this SDK. See Sender-constrained credentials: DPoP under Authenticated HTTP clients for the caller-facing flow; the real gap was that nothing pointed a reader at it, which is now fixed. Soreadme_mechanical_claims.rsgates the zero in the opposite sense from the one this row first claimed: the check fails if the library ever starts driving DPoP itself, which is the promise the module makes and the thing worth protecting. The size and its growth rate are still worth recording: 781 lines on 2026-10-12 to 24,610 across two crates four days later. (An earlier version of this sentence ranked that against "http.rsis 14,734 lines andwebsocket.rs6,828". That comparison was wrong and is withdrawn: it set a whole module against a whole module, while the unclaimed surface in those two is one adapter struct and onecfg(test)codec respectively.http.rsitself is heavily consumed —HttpResponse,HttpStatus,HttpRequestandHttpMethodalone account for 680 mentions infastmcp-server/src— so its line count measures something else entirely.) Tracked asbd-iaqgd. Across every membersrc/file outside the two module trees, the lowercase path spellingdpopoccurs exactly twice, and both are thepub mod dpop;declarations that put the modules in the build (http_auth.rs:35,fastmcp-protocol/src/lib.rs:44); it occurs zero times in everycrates/**file outsidesrc/, so not even a test target drives it. Case is the discriminator — Rust spells the pathdpopwhile prose and wire values spell itDPoP. Beyond those two declarations, the automatic path still states "No automatic login/retry, DPoP, DCR, DNS pinning, or OIDC identity authentication is installed" (http_auth/discovery/challenge.rs), and the client-credentials path still rejects a sender-constrained token (token_type: "DPoP", or acnfholdingjkt) under the testmachine_token_cannot_downgrade_sender_constraints_or_exchange_grants. So the five DPoP checks stay unreachable, but the estimate changed: it is now "drive an existing primitive from the adapter", not "implement DPoP" — and it is still behind the loopback-HTTP blocker above, since the adapter cannot address the suite's authorization server at all. The split across causes is now measured, and it is not a split: all 46 are the adapter-profile blocker and none is a missing library capability. The nine in-treeoauth_*test targets are gated onnative-tls-roots; each one now carries a matchingrequired-featuresstanza, so a default run excludes them and naming one explicitly makes cargo refuse. They are therefore not a vacuous pass — but they are also not evidence those flows work, because a default run does not execute them at all.
Client-mode conformance is measured; aggregate conformance is still not claimed, in either mode.
No server-mode FAILURE-level check remains, and two of the four SHOULD-level
warnings are now gone. The two that cleared were
sep-2575-server-sends-tools-list-changed-on-subscription and its prompts
counterpart, which the adapter had declined on the stated grounds that "the
server has no runtime catalog-mutation API". That was false: McpContext
exposes disable_tool/enable_tool and the resource and prompt pairs, each
publishing a catalog change, and the server already attached both the session
state and the subscriptions/listen publisher. Serving the suite's two trigger
fixtures through that API took no library change at all — only
examples/conformance_server.rs, +93/-4. The e2a0ac5c and 1c2dc896 rows
above are a measured before/after over an identical 99-check id set, with
exactly those two statuses changing and nothing else moving, so the +2 is not a
denominator shift.
The two remaining warnings are enumerated in that same file: both are the deliberate fail-closed choice about empty MRTR response maps that the suite would prefer we relax.
What this is not. It is a count of named checks at one revision, under one
adapter, over HTTP. It is not aggregate MCP 2026-07-28 conformance, and it says
nothing about the qualification boundaries below — several of which (OAuth/OIDC
production profile, end-to-end quiescence, awaitCleanup) the suite does not
exercise at all. The suite's default --suite active omits roughly half the
scenarios, including every input-required one, so a measurement taken without
--suite all is not comparable to these rows.
Current qualification boundaries
- Wire cancellation is only partially qualified: on Unix, the primary
stdio path keeps receiving while bounded modern requests run in independent
request-owned children, so it can route cancellation during handler
execution. Response and notification commits remain serialized at the
output writer, while exact MCP 2024-11-05 traffic remains serialized through
its lifecycle worker. Non-Unix stdio and custom/SSE/WebSocket entry points
retain sequential or blocking boundaries, except that an unsplit custom
transport runs
subscriptions/listenoff its receive loop and queues output produced whilerecvblocks untilrecvreturns. A non-cooperative handler can still exceed the bounded process-exit drain, so end-to-end quiescence and reliableawaitCleanupsemantics remain unverified. - Bidirectional calls are only partly qualified: the Unix stdio receive
pump can route sampling, elicitation, and roots responses while exact-2024
lifecycle work or modern request children are active. The WebSocket server
and custom split transports share that pump: live
bind_websockettests show an exact-2024 handler awaitingctx.sampleorctx.list_roots(including a synchronous handler that bridges withblock_on) receives the client's reply, and a client without the capability gets a typed refusal instead of a hang. Non-Unix stdio, unsplit custom transports, and SSE still reject or lack that split routing. Public HTTP has its own dual-era request and response routing, but end-to-end bidirectional lifecycle/cancellation evidence is incomplete. - Response caching is conservatively partitioned: eligible production requests are keyed by committed authentication facts plus opaque session identity and revision. Uncommitted authentication, local-only state views, allocation failure, or state mutation during a request cause cache admission to fail closed rather than sharing an entry.
- Authentication admission is incomplete: native HTTP accepts credentials
only from
Authorization; recognized body/meta and query credential fields are rejected before the provider or application runs. Other adapters retain a stripped legacy JSON-RPC credential fallback. Complete authorization, lease/revocation, and OAuth challenge qualification remain open. - Legacy Tasks RPC stays dead:
tasks/listandtasks/submitreturn JSON-RPCMethodNotFound. Official MCP 2026-07-28 methodstasks/get,tasks/update, andtasks/cancelare served by default (process-local in-memory store). CallServerBuilder::final_tasksto supply an application-owned store. - Task creation needs an application supervisor. Configure
ServerBuilder::task_supervisor(Arc::new(supervisor))to host anApplicationTaskSupervisoron the default runtime or the runtime supplied byfinal_tasks. The server starts the service within the caller-owned serve lifetime, waits for readiness, and settles it on exit. The shippedecho_serveruses this hook. A server without a ready service still refuses creation withFinal task creation requires an installed ready task service. Applications may instead install and driveAuthorizedTaskServiceRunnerexplicitly; combining that installation with the builder hook is rejected. - Authenticated local Tasks retain their caller: task creation atomically stores a private principal binding. Request get/update/cancel and Tasks subscriptions enforce that binding; a refreshed credential for the same verified owner can continue the task. Custom stores must implement atomic authenticated creation and preserve the binding in every snapshot. Context-free runtime and subscription APIs are trusted embedding controls. Anonymous client isolation, proxy Tasks ownership, durable authorization, grant revalidation, and revocation remain unqualified.
- OAuth/OIDC are unpromoted source surfaces: their public building blocks remain available for development, but production security/profile conformance is unverified and no production-support claim is made for them.
- CLI inspection is bounded diagnostics, not conformance evidence: with
default features in a current source checkout,
fastmcp inspect --protocol-policyreports the selectedauto,modern-only, orlegacy-onlyera. A selected modern session requires valid_meta.io.modelcontextprotocol/serverInfometadata and retains the open discovery capability shape (includingcompletionsandextensions) subject to output bounds and credential/control-text sanitization; a selected legacy session renders only the exact legacy capability shape. A--no-default-featuresbuild supportsmodern-onlyonly. This does not qualify either protocol era as aggregate conformance or production readiness. - Subprocess cleanup is explicit and platform-bounded:
Client::close(&mut self)returns cleanup failures. The opt-in owned-group mode used byfastmcp testis Unix-only and fails before spawn elsewhere. Its--protocol-policyoption binds both client negotiation and the launched FastMCP server profile. It uses a live anchor plus an owner-death channel, but cannot contain descendants that change group/session, withstand a competing global child reaper, or close a control descriptor copied by a host-side fork. Drop is best effort.
# Current published package; publication is not aggregate conformance evidence
cargo add fastmcp-rust@0.13.0
# Or use the git dependency for bleeding-edge changes
cargo add fastmcp-rust --git https://github.com/Dicklesworthstone/fastmcp_rust
TL;DR
The Problem
MCP server implementations need to solve several recurring problems:
- Handler schemas and JSON-RPC dispatch
- Cooperative cancellation and request budgets
- Ownership of concurrent child work
- Transport framing and session lifecycle
The Solution
FastMCP Rust is an MCP framework with asupersync capability contexts, attribute macros, and explicit cancellation/budget surfaces:
use asupersync::runtime::{RuntimeBuilder, reactor::create_reactor};
use fastmcp_rust::{auto::ServerBuilder, prelude::*};
#[tool]
async fn greet(ctx: &McpContext, name: String) -> McpResult<String> {
ctx.checkpoint()?; // Cancellation point
Ok(format!("Hello, {name}!"))
}
fn main() {
let runtime = RuntimeBuilder::current_thread()
.with_reactor(create_reactor().expect("create I/O reactor"))
.blocking_threads(0, 16)
.build()
.expect("create application runtime");
runtime.block_on(async {
let cx = Cx::current().expect("application context");
ServerBuilder::new("my-server", "1.0.0")
// Attribute macros generate PascalCase handler values.
.tool(Greet)
.build()
.run_stdio_with_cx(&cx)
.await
});
}
The application creates the runtime once and supplies its context. FastMCP does
not create a runtime at this entry point. run_stdio_with_cx needs a blocking
pool because its receive pump blocks on recv; that is a property of this entry
point, not of the framework. On Unix you can instead serve reactor-driven
process stdio with no blocking pool at all — see
Non-blocking stdio. See Quick Start below for
the dependency declarations.
auto::ServerBuilder serves MCP 2026-07-28 clients and also the exact
2024-11-05 initialize handshake that today's desktop clients and the MCP
Inspector open with. modern::ServerBuilder pins a server to 2026-07-28 alone,
so it refuses those clients.
Why FastMCP Rust?
| Feature | FastMCP Rust | Manual Implementation |
|---|---|---|
| Async handler API | #[tool] async fn plus handler trait hooks |
Manual Future boxing |
| Cancellation | Local request checkpoints; live wire interruption remains unverified | Application-specific checks |
| Timeouts | Request and handler budget surfaces | Application-specific timers |
| Concurrent-future ownership | Context combinators poll caller-owned futures | Manual ownership |
| Error handling | 4-valued Outcome | 2-valued Result |
| Boilerplate | Generated handler/schema implementations | Handwritten handler/schema implementations |
AGENTS.md
This project includes an AGENTS.md file with guidelines for AI coding agents. Key points:
- Porting methodology: Extract spec from legacy → implement from spec → never translate line-by-line
- Runtime: Uses asupersync exclusively; Tokio and Tokio-based adapters are unsupported
- Unsafe code: Forbidden (
#![forbid(unsafe_code)]) - Toolchain: Rust 2024 edition; pinned
nightly-2026-08-25/ rustc 1.100.0-nightly (rust-version = "1.100") - MCP 2026-07-28 support is under implementation and remains unverified.
- Aggregate MCP 2026-07-28 support is not claimed by FND-01.
- The root compatibility
PROTOCOL_VERSIONis2024-11-05; the modern facade'smodern::PROTOCOL_VERSIONis2026-07-28. Neither is proof of negotiated 2026-07-28 support.
Quick Example
use asupersync::runtime::{RuntimeBuilder, reactor::create_reactor};
use fastmcp_rust::{auto::ServerBuilder, prelude::*};
// Define a tool with automatic JSON schema generation
#[tool(description = "Calculate the sum of two numbers")]
async fn add(ctx: &McpContext, a: i64, b: i64) -> McpResult<String> {
ctx.checkpoint()?; // Check the local cancellation token and budget
Ok((a + b).to_string())
}
// Define an in-memory resource. Potentially blocking filesystem work is not
// performed inline on the dispatch worker.
#[resource(uri = "config://settings", description = "Application config")]
fn config(ctx: &McpContext) -> McpResult<String> {
ctx.checkpoint()?;
Ok(r#"{"theme":"dark"}"#.to_owned())
}
// Define a prompt template
#[prompt(description = "Generate a greeting message")]
async fn greeting(ctx: &McpContext, name: String) -> McpResult<Vec<PromptMessage>> {
ctx.checkpoint()?;
Ok(vec![PromptMessage {
role: Role::User,
content: Content::text(format!("Please greet {name} warmly.")),
}])
}
fn main() {
let runtime = RuntimeBuilder::current_thread()
.with_reactor(create_reactor().expect("create I/O reactor"))
.blocking_threads(0, 16)
.build()
.expect("create application runtime");
runtime.block_on(async {
let cx = Cx::current().expect("application context");
ServerBuilder::new("example-server", "1.0.0")
.tool(Add)
.resource(ConfigResource)
.prompt(GreetingPrompt)
.request_timeout(30) // 30-second budget per request
.build()
.run_stdio_with_cx(&cx)
.await
});
}
Run it:
# echo_server is a shipped binary target of the facade crate, not an example
cargo run -p fastmcp-rust --bin echo_server
Design Philosophy
1. Explicit Cooperative Cancellation
Handlers should check cancellation at natural suspension or iteration boundaries. FastMCP exposes cooperative checkpoints. These local context semantics do not, by themselves, make cancellation interruptible over a live connection; see the qualification boundaries above.
#[tool]
async fn process_items(
ctx: &McpContext,
items: Vec<String>,
) -> McpResult<Vec<Content>> {
let mut results = vec![];
for item in items {
ctx.checkpoint()?; // Allow graceful cancellation between items
results.push(Content::text(process(item).await?));
}
Ok(results)
}
2. Budgets, Not Timeouts
Timeouts are "we gave up." Budgets are "you have X resources." The Budget type represents deadline, poll-quota, and cost-quota dimensions:
// Called from the application's runtime with its context.
async fn serve(cx: &Cx) -> ! {
ServerBuilder::new("server", "1.0.0")
.request_timeout(30) // 30-second server-owned request ceiling
.tool(MyTool)
.build()
.run_stdio_with_cx(cx)
.await
}
// Handler can check remaining budget
#[tool]
async fn my_tool(ctx: &McpContext) -> McpResult<String> {
ctx.checkpoint()?;
// ... work ...
Ok("work completed".to_string())
}
3. Four-Valued Outcomes
Result<T, E> has no distinct cancellation or panic variants. FastMCP's asynchronous handler boundary uses Outcome<T, E>:
enum Outcome<T, E> {
Ok(T), // Success
Err(E), // Expected failure
Cancelled(CancelReason), // External interruption
Panicked(PanicPayload), // Internal failure
}
4. Capability-oriented handlers
Request authority flows through McpContext; application dependencies should likewise be passed explicitly instead of hidden in globals:
// BAD: Global state access
async fn bad_tool() {
let db = GLOBAL_DB.lock().await; // Hidden dependency
}
// GOOD: Explicit capability
async fn good_tool(ctx: &McpContext, db: &DbHandle) {
db.query(ctx.cx(), "SELECT ...").await; // Explicit
}
5. Owned Concurrent Futures
Concurrent child futures remain owned by the request handler and are polled together by context combinators:
use std::future::Future;
use std::pin::Pin;
#[tool]
async fn parallel_fetch(
ctx: &McpContext,
urls: Vec<String>,
) -> McpResult<Vec<Content>> {
type FetchFuture = Pin<Box<dyn Future<Output = McpResult<String>> + Send>>;
let futures: Vec<FetchFuture> = urls
.into_iter()
.map(|url| Box::pin(fetch(url)) as FetchFuture)
.collect();
let results = ctx.join_all(futures).await?;
results
.into_iter()
.map(|result| result.map(Content::text))
.collect()
}
Design Positioning
These are FastMCP Rust design surfaces, not benchmark results or an MCP 2026-07-28 conformance certificate. Competing projects change independently and should be evaluated from their current documentation rather than a static comparison table.
| Area | FastMCP Rust design |
|---|---|
| Handler API | #[tool], #[resource], and #[prompt] macros plus explicit handler traits |
| Cancellation | McpContext checkpoints and masks backed by asupersync |
| Timeouts | Request and handler budget surfaces |
| Runtime | asupersync only; Tokio adapters are unsupported |
| Outcomes | Four-valued Outcome: success, expected error, cancellation, or panic |
| Unsafe code | Forbidden in workspace crates with #![forbid(unsafe_code)] |
Installation
From crates.io (current 0.13.0 package)
The 0.13.0 package was published on 2026-10-12. Publication does
not establish aggregate MCP 2026-07-28 conformance, production readiness, or
qualification of every in-tree feature.
[dependencies]
fastmcp-rust = "0.13.0"
As a Git Dependency
[dependencies]
fastmcp-rust = { git = "https://github.com/Dicklesworthstone/fastmcp_rust" }
asupersync = "=0.5.0"
From Source
git clone https://github.com/Dicklesworthstone/fastmcp_rust.git
cd fastmcp_rust
cargo build --release
CLI binaries (GitHub Releases)
The latest published release, v0.13.0, provides prebuilt fastmcp binaries on
GitHub Releases. The fastmcp-cli source package is also available from
crates.io for Cargo-based installation. Archives follow a fastmcp-<os>-<arch>
pattern (.tar.xz on Unix, .zip on Windows).
This repository does not establish what the published archives are named.
The checked-in release workflow is a quarantined verification surface and does
not publish new GitHub Releases: it has held contents: read since 2026-08-02,
and that permission cannot create a Release. v0.13.0 was built and published
with the maintainer's local release tooling, not this workflow, so this
repository does not establish whether those archives are downloadable either,
and nothing in it can. That workflow's build matrix — the
SURF-RELEASE-ASSET-CLOSURE rows in
evidence/fnd-01/dependency-verification.toml — describes what the quarantined
workflow would produce, which is not evidence of what the release contains;
do not read it as the published filenames.
Take the exact filename from the v0.13.0 release page. The command below pins
the tag rather than releases/latest — under a workflow that does not publish,
latest is a moving pointer whose meaning is not stated anywhere.
If the download does not resolve, build from source as shown above; that path
is verified by this repository and the download is not.
# Replace <asset> with the exact filename listed on the v0.13.0 release page.
curl -fsSL -O https://github.com/Dicklesworthstone/fastmcp_rust/releases/download/v0.13.0/<asset>
tar -xJf <asset>
./fastmcp --version
CLI via Cargo (optional)
rustup toolchain install nightly-2026-08-25
cargo +nightly-2026-08-25 install fastmcp-cli --version 0.13.0 --locked
Client request deadlines (current source tree)
Ordinary client requests use separate idle and absolute response-wait deadlines. Both begin after the request send commits. The idle deadline defaults to 30 seconds; the non-resettable absolute deadline defaults to 120 seconds. Serialization, sending, and teardown are outside these timers. Unix subprocess sends have a separate two-second bound covering writer-lock acquisition and the native pipe commit. These commits remain synchronous; non-Unix sends retain blocking-I/O limits. Only a valid matching progress notification on a request that actually supplied a progress token can reset idle.
On Unix, eager ClientBuilder::connect_stdio_with_cx initialization also
yields between bounded receive turns, including partial responses and Auto
negotiation. A fallback child starts only after the disposable modern child
has been cleaned up. With auto_initialize(true), async requests and
Client::ensure_initialized_with_cx also yield during the first handshake.
Dropping that future preserves the handshake, partial response and original
deadline; the next async or synchronous call resumes it without another send.
Explicit cancellation after the handshake starts fails the connection.
Synchronous constructors and synchronous first use retain their blocking
boundaries; subprocess creation and write commits remain synchronous.
use std::time::Duration;
use fastmcp_rust::prelude::{Client, ClientBuilder, Cx, McpResult, RequestTimeoutPolicy};
async fn connect(cx: &Cx) -> McpResult<Client> {
let policy = RequestTimeoutPolicy::new(
Duration::from_secs(20),
Duration::from_secs(90),
)?;
ClientBuilder::new()
.request_timeout_policy(policy)
.connect_stdio_with_cx(cx, "my-mcp-server", &[])
.await
}
A live modern subscriptions/listen can stay open on the same stdio
Client while other requests complete. Call
Client::open_subscriptions_listener and then
Client::next_subscription_event to drain acknowledgement, catalog, and
resource-update events without collecting the stream to terminal.
On Unix, open_subscriptions_listener_with_cx and
next_subscription_event_with_cx yield during initialization and between
bounded receive turns. Tasks offer the corresponding
open_final_task_subscription_listener_with_cx and
next_final_task_subscription_event_with_cx APIs. Dropping an event future
preserves the stream and partial frame for resumption; explicit cancellation
retires only that listener, leaving sibling requests usable. Cancellation
write failures retain the listener and its error. Writes remain synchronous.
listen_subscriptions_typed remains the collect-to-terminal adapter.
The same incremental pattern exists on HTTP (HttpClient::start_subscriptions_listener),
modern WebSocket (WebSocketClient::open_subscriptions_listener), and
ProxyClient::start_catalog_listener for stdio and modern HTTP upstreams.
Proxy catalog and Tasks listener startup and event methods are async and
take the caller's &Cx. HTTP opening yields while awaiting headers;
cancelling or dropping that opening closes its socket and releases the
route for another attempt. Dropping an event future preserves the installed
listener for resumption. Stdio startup and bounded receive turns retain
their synchronous I/O limits.
ProxyUpstreamBindingRegistry::connect_http_with_protocol_plan and
connect_stdio_with_protocol_plan are async and take the caller's &Cx
first. HTTP negotiation and exact-2024 initialization await that runtime;
Unix stdio initialization uses the client's yielding receive path. Interrupted
openings leave the registry cache unchanged, allowing a fresh attempt. Keep
the caller runtime alive while using a cached legacy HTTP/SSE connection.
Use ProxyClient::catalog_typed_with_cx or catalog_with_cx to fetch HTTP or stdio
catalogs on that runtime, including every page and its modern cache hints.
These methods release the route lock while awaiting HTTP I/O or between bounded
stdio receive turns and reject cursor cycles without returning a partial
catalog. Stdio writes and individual receive turns retain their synchronous
I/O limits. Backends without an upstream binding retain their synchronous
catalog implementation.
Exact-2024 resource subscribe/unsubscribe hooks also have awaited variants:
ResourceHandler::on_subscribe_async and on_unsubscribe_async. The live
dispatcher and mounted resources forward these hooks on the caller runtime.
Native proxies release the route lock during HTTP/SSE waits and between bounded
stdio receive turns.
Failed or interrupted proxy requests preserve local URI rewrites, and failed
synchronous hooks roll back the session's subscription membership. Remote
effects already acknowledged upstream cannot be rolled back by these guarantees.
HTTP and WebSocket clients also expose typed list_tools/call_tool/
read_resource/get_prompt verbs so callers do not have to decode a raw
core result for ordinary catalog and invocation traffic. HTTP and WebSocket
list_tools_with_cancellation/call_tool_with_cancellation/
read_resource_with_cancellation/get_prompt_with_cancellation honor a
caller-owned cancellation domain for those ordinary verbs.
Exact MCP 2024-11-05 HTTP+SSE clients use Client::sse_with_cx when the GET
event stream and POST message endpoints are already known.
On Unix, Client::call_tool_with_cx, read_resource_with_cx, and
get_prompt_with_cx follow installed async reverse handlers when a modern
peer requests input. After initialization, all rounds and handler waits share
one absolute deadline; cancellation drops pending handler work and preserves
the connection. Deferred discovery keeps its separate initialization deadline
and connection-ending cancellation rules. Each
retry carries the original arguments and only the latest continuation state.
Without installed handlers, the input-required result is returned to the caller.
Installed modern MRTR callbacks also remain cancellable while pending in HTTP and WebSocket clients, including callbacks that never wake themselves. Dropping or interrupting a callback cancels its local token and prevents a continuation; callback panics become redacted errors. These checks run between callback polls and cannot preempt synchronous work or undo external effects inside user code.
With the tasks feature on Unix, Client::call_tool_final_outcome_with_cx
creates tasks without blocking the runtime while waiting for the peer. It
returns the typed complete, task, or input-required outcome. A returned task ID
can be used with get_task_final_with_cx and cancel_task_final_with_cx on the
same client. An already-admitted valid task result survives caller cancellation;
other results remain cancellation-first. Input-required results are returned
without automatic continuation. Pipe writes remain synchronous.
The published 0.13.0 CLI includes these flags. From a current source checkout, run the CLI through the workspace to configure the two limits independently:
cargo run -p fastmcp-cli -- test --protocol-policy auto --idle-timeout 30 --absolute-timeout 120 my-mcp-server
The current fastmcp test subprocess runner is Unix-only because success
includes verified owned-process-group cleanup. Library callers should likewise
call client.close() and handle its McpResult; dropping a client is only a
best-effort safety net. The group anchor protects its numeric PGID while it is
live and closes an owner-death channel when the host exits, but this is not
portable process-tree containment or a substitute for Windows Job Objects.
Requirements:
- Rust nightly-2026-08-25 (see
rust-toolchain.toml) for Edition 2024. The last FND-01 evidence snapshot still recordsnightly-2026-07-11until that harness is re-attested.
Tasks commands (current source tree, optional)
Build the CLI with --features tasks to expose tasks get, watch, update,
and cancel. These commands require modern MCP and bilateral
io.modelcontextprotocol/tasks support. The pinned extension is experimental;
this source implementation remains provisional. The published default
binaries do not include these commands.
cargo run -p fastmcp-cli --features tasks -- tasks get TASK_ID --http-url http://127.0.0.1:8000/mcp --json
cargo run -p fastmcp-cli --features tasks -- tasks watch TASK_ID --http-url http://127.0.0.1:8000/mcp --timeout 60 --max-events 100 --json
cargo run -p fastmcp-cli --features tasks -- tasks update TASK_ID --http-url http://127.0.0.1:8000/mcp --input-file responses.json --json
cargo run -p fastmcp-cli --features tasks -- tasks cancel TASK_ID --http-url http://127.0.0.1:8000/mcp --json
The input file contains the inputResponses map itself, for example
{"roots":{"roots":[]}} when the task's outstanding input key is roots
and its method is roots/list. Files are limited to 1 MiB. Updates use the
current task's input request types. Update and cancellation success mean
acknowledgement; use get or watch to observe subsequent task state.
Watch emits an initial snapshot and exits successfully if the task is already
completed, failed, or cancelled. Otherwise it subscribes to live updates and
reads the task again after subscription acknowledgement, so a terminal change
during subscription setup is also reported. It ends successfully on a terminal
update or after --max-events updates. Each
successful exit includes a watch-ended event; ending a watch does not cancel
the task. It does not reconnect or promise replay across disconnects.
--timeout defaults to 30 seconds, and timeout is a failed command. JSON mode
emits one document per event; human output bounds and sanitizes fields and
redacts recognizable credentials.
Use --server EXECUTABLE and repeat --server-arg ARGUMENT for stdio. Each
command starts a fresh process, so previously issued task IDs require a store
retained outside the prior process. For authenticated HTTPS, Tasks commands and
inspect accept --bearer-token-file PATH:
cargo run -p fastmcp-cli --features tasks,native-tls-roots -- tasks get TASK_ID --http-url https://mcp.example.com/mcp --bearer-token-file token.txt --json
The file must contain a UTF-8 token of at most 16 KiB, including an optional
trailing LF or CRLF. Do not include a Bearer prefix or other whitespace or
control characters. The CLI reads a regular file once per invocation; callers
own token acquisition and refresh. Credentials require HTTPS and a modern or
auto protocol policy. Core-only builds omit Tasks from help and explain
the required feature when a Tasks command is attempted.
Authenticated HTTP clients (current source tree)
The SDK accepts a caller-acquired bearer credential bound to one exact HTTPS
endpoint. For example, with a caller-owned cx and an existing token:
use fastmcp_rust::{BoundBearerCredential, CanonicalHttpUrl, modern};
let endpoint = CanonicalHttpUrl::parse("https://mcp.example.com/mcp")?;
let credential = BoundBearerCredential::bind(endpoint.clone(), token)?;
let client = modern::ClientBuilder::new()
.http_bearer_credential(credential)
.connect_http_with_cx(cx, endpoint)
.await?;
The same credential binding covers discovery, later request/subscription
POSTs, and reverse-response POSTs. It never attaches to cleartext HTTP, a different path or query, or a
redirect target. An authenticated Auto client refuses legacy fallback.
Applications own token acquisition and refresh; create a new client when the
credential changes. The CLI's --bearer-token-file uses this same binding.
The bounded JSON/SSE readers withhold JSON-RPC errors that reflect the exact credential into their message or data, returning a typed diagnostic instead. Successful application results and the raw native-stream API remain unmodified.
HTTPS uses the transport's bundled WebPKI roots by default. Enable
native-tls-roots on fastmcp-rust, fastmcp-client, or fastmcp-cli for the platform trust
store. That profile also honors the native certificate provider's
SSL_CERT_FILE and SSL_CERT_DIR overrides; these select the trust source,
and do not disable certificate or hostname verification.
Sender-constrained credentials: DPoP (RFC 9449), caller-driven
fastmcp_rust::http_auth::dpop is a public, explicit, caller-driven API for
DPoP. It is deliberately not wired into the bearer OAuth driver: its module
documentation states that it "never promotes a DPoP token into the existing
bearer-only OAuth driver" and "does not install automatic OAuth negotiation or
HTTP retries". So the application owns the authenticated HTTPS I/O, the
response-size limits, cancellation of in-flight I/O, and every retry decision.
If you want DPoP, you drive it; nothing in this SDK will start doing so on your
behalf.
One session pins one HTTPS token endpoint, one exact HTTPS MCP resource, and
one ES256 proof key. The two types a caller must name to open one — DpopKey,
the first argument, and DpopError, carried by DpopClientError::Proof — are
re-exported from this same module, so fastmcp_rust::http_auth::dpop is
self-contained. They originate in fastmcp_protocol::dpop, which the facade
does not forward, so without that re-export the API would be reachable without
being constructible. The flow, in call order:
DpopSession::new— pin the endpoint, resource and key.DpopSession::authorization_jktexposes the key thumbprint for a confirmation claim.DpopSession::token_request_headers— build the headers for your token request, then perform that request yourself.DpopSession::admit_token_response— strict, bounded, duplicate-free admission of the response. It yields aDpopCredential, and refuses a bearer downgrade or a mismatched proof key rather than accepting one.DpopSession::resource_request_headers— build the headers for the MCP request, again performed by you.- On a nonce challenge, feed the nonce back with
DpopSession::observe_token_nonceorDpopSession::observe_resource_nonceand generate new headers for a retry you deliberately admit. Never replay a proof, and never automatically replay a possibly-executed MCP call.
DpopRequestHeaders::apply_to and DpopRequestHeaders::into_headers move the
prepared fields onto your request. DpopCredential::expires_at,
DpopCredential::revoke and DpopCredential::is_revoked cover lifetime and
revocation; DpopSession::revoke irreversibly retires the session and every
credential it issued. AS and RS nonce state are kept separate. Errors are the
redacted DpopClientError variants — no peer text, URL, proof, token or
response body is retained.
The full contract, including what each refusal means, is the module
documentation on fastmcp_client::http_auth::dpop; read it before driving the
flow, because several of the rules above are the caller's to honour rather than
the library's to enforce. fastmcp_protocol::dpop holds the ES256 proof and
RFC 7638 thumbprint primitives behind the jose feature. A bounded native
HTTPS resource POST is available under the module's native submodule for
callers who would rather not own that I/O.
Quick Start
1. Create a New Project
cargo new my-mcp-server
cd my-mcp-server
2. Add FastMCP
# Cargo.toml
[dependencies]
fastmcp-rust = { git = "https://github.com/Dicklesworthstone/fastmcp_rust" }
asupersync = "=0.5.0"
3. Write Your Server
// src/main.rs
use asupersync::runtime::{RuntimeBuilder, reactor::create_reactor};
use fastmcp_rust::{auto::ServerBuilder, prelude::*};
#[tool(description = "Echo the input message")]
async fn echo(ctx: &McpContext, message: String) -> McpResult<String> {
ctx.checkpoint()?;
Ok(message)
}
fn main() {
let runtime = RuntimeBuilder::current_thread()
.with_reactor(create_reactor().expect("create I/O reactor"))
.blocking_threads(0, 16)
.build()
.expect("create application runtime");
runtime.block_on(async {
let cx = Cx::current().expect("application context");
ServerBuilder::new("echo-server", "1.0.0")
.tool(Echo)
.instructions("A simple echo server for testing")
.build()
.run_stdio_with_cx(&cx)
.await
});
}
4. Run
cargo run
5. Test with MCP Inspector
npx @modelcontextprotocol/inspector cargo run
Non-blocking stdio (Unix, opt-in)
run_stdio_with_cx above is the portable default, and it is blocking: it hands
run_stdio_pump to spawn_blocking and reads through StdioTransport::stdio()
and AsyncStdout, whose own documentation records that they "perform blocking
I/O internally. An async trait alone does not make those standard-stream
operations nonblocking." Several stdio caveats in
Limitations are consequences of that choice rather than of the
framework, and the rows that describe only this entry point now say so. Others,
such as the client-subprocess rows, are unrelated to it and still apply.
On Unix there is a second path. NativePipeReader::from_stdin and
NativePipeWriter::from_stdout claim the real process descriptors, register
them with the caller's reactor, and observe that caller's cancellation and
deadline — no helper thread, no blocking pool, and no change to descriptor
flags that is not restored on release. serve_stdio_io then serves the
transport over them. modern::ServerBuilder is already modern-only, so no
protocol-policy call is needed:
use fastmcp_rust::modern::ServerBuilder;
use fastmcp_rust::{NativePipeReader, NativePipeWriter};
// Note blocking_threads(0, 0): this path needs no blocking pool at all.
let runtime = RuntimeBuilder::current_thread()
.with_reactor(create_reactor().expect("create I/O reactor"))
.blocking_threads(0, 0)
.build()
.expect("create application runtime");
runtime.block_on(async {
let cx = Cx::current().expect("application context");
let server = ServerBuilder::new("native-process-stdio", "1.0")
.tool(Echo)
.build();
let input = NativePipeReader::from_stdin(&cx)?;
let output = NativePipeWriter::from_stdout(&cx)?;
server.serve_stdio_io(&cx, input, output).await
})
That is the wiring, not a complete program: acquiring the second descriptor can
fail after the first succeeded, and the two halves report io::Error while
serve_stdio_io reports McpResult, so a real main has to reconcile both.
crates/fastmcp-server/examples/native_stdio.rs does, including closing the
already-claimed reader rather than implying a partial process binding was
released. It is a checked-in target with no required-features; run it with
cargo run -p fastmcp-server --example native_stdio.
Bind both endpoints to the same Cx that serves the transport. A pipe whose
own context is cancelled or past its deadline reports a cooperative stop on
every poll while the serving context stays live. The transport retries a
bounded number of those and then fails the endpoint with a diagnostic naming
this cause, instead of retrying without end.
What this does not claim. This is an opt-in transport pairing, not the
default, and not an aggregate cancellation, quiescence, or conformance
qualification — every boundary in Limitations still applies
except where it is explicitly about the blocking default. from_stdin and
from_stdout are #[cfg(unix)]; there is no non-Unix equivalent, because
asupersync's readiness Source is socket-bound on Windows while Windows
standard streams are handles.
Architecture
┌─────────────────────────────────────────────────────────────────┐
│ MCP Client │
└─────────────────────────────────────────────────────────────────┘
│
│ JSON-RPC over stdio
▼
┌─────────────────────────────────────────────────────────────────┐
│ StdioTransport │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Codec │───▶│ recv() │───▶│ send() │ │
│ │ (NDJSON) │ │ │ │ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Server │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Session │ │ Router │ │ Budget │ │
│ │ (state) │ │ (dispatch) │ │ (timeout) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────┐│
│ │ McpContext ││
│ │ ┌─────┐ ┌──────────┐ ┌────────┐ ┌──────┐ ││
│ │ │ Cx │ │checkpoint│ │ budget │ │masked│ ││
│ │ └─────┘ └──────────┘ └────────┘ └──────┘ ││
│ └─────────────────────────────────────────────────────────────┘│
│ │ │
│ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ ToolHandler │ │ResourceHandler│ │PromptHandler │ │
│ │ call_async │ │ read_async │ │ get_async │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ asupersync │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Runtime │ │ Scope │ │ Budget │ │ Outcome │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────────────────┘
Crate Structure
FastMCP is organized as a workspace with focused crates:
fastmcp_rust/
├── crates/
│ ├── fastmcp/ # Facade crate (published as fastmcp-rust)
│ ├── fastmcp-core/ # McpContext, errors, runtime helpers
│ ├── fastmcp-protocol/ # MCP types, JSON-RPC messages
│ ├── fastmcp-transport/ # Transport implementations (stdio, SSE, WebSocket, HTTP, memory)
│ ├── fastmcp-server/ # Server builder, router, handlers
│ ├── fastmcp-client/ # Client implementation
│ ├── fastmcp-macros/ # Proc-macro crate, published as fastmcp-derive
│ ├── fastmcp-console/ # Console rendering and statistics
│ └── fastmcp-cli/ # fastmcp command-line interface
| Crate | Purpose |
|---|---|
fastmcp-rust |
Convenience re-exports for simple use fastmcp_rust::prelude::* |
fastmcp-core |
McpContext wrapper, error types, block_on helper |
fastmcp-protocol |
MCP message types, capabilities, JSON-RPC framing |
fastmcp-transport |
Transport trait and stdio/SSE/WebSocket/HTTP/memory implementations |
fastmcp-server |
Server, ServerBuilder, routing, handler traits |
fastmcp-client |
Three clients: Client drives a subprocess over stdio; HttpClient covers modern HTTP and exact legacy SSE and is returned by Client::http_with_cx and (with legacy-2024-11-05) Client::sse_with_cx, with ClientHttpConnection beneath it; WebSocketClient exists only with the websocket-experimental feature, where it accepts owned native async transports and Auto negotiation uses a caller-owned factory that supplies a fresh upgraded transport for its permitted retry |
fastmcp-derive |
Procedural macros for handler generation |
Handler Traits
The signatures below are abridged; asynchronous trait methods return four-valued McpOutcome values, not ordinary McpResult values.
ToolHandler
pub trait ToolHandler: Send + Sync {
fn definition(&self) -> Tool;
fn call(
&self,
ctx: &McpContext,
arguments: serde_json::Value,
) -> McpResult<Vec<Content>>;
// Override for true async (default delegates to call())
fn call_async<'a>(&'a self, ctx: &'a McpContext, arguments: serde_json::Value)
-> std::pin::Pin<Box<dyn std::future::Future<Output = McpOutcome<Vec<Content>>> + Send + 'a>>;
}
ResourceHandler
pub trait ResourceHandler: Send + Sync {
fn definition(&self) -> Resource;
fn read(&self, ctx: &McpContext) -> McpResult<Vec<ResourceContent>>;
// Override for true async
fn read_async<'a>(&'a self, ctx: &'a McpContext)
-> std::pin::Pin<Box<dyn std::future::Future<Output = McpOutcome<Vec<ResourceContent>>> + Send + 'a>>;
}
PromptHandler
pub trait PromptHandler: Send + Sync {
fn definition(&self) -> Prompt;
fn get(&self, ctx: &McpContext, arguments: std::collections::HashMap<String, String>)
-> McpResult<Vec<PromptMessage>>;
// Override for true async
fn get_async<'a>(
&'a self,
ctx: &'a McpContext,
arguments: std::collections::HashMap<String, String>,
)
-> std::pin::Pin<Box<dyn std::future::Future<Output = McpOutcome<Vec<PromptMessage>>> + Send + 'a>>;
}
Troubleshooting
| Problem | Cause | Fix |
|---|---|---|
JSON-RPC InvalidParams (-32602) Unknown tool: <name> for tools/call |
Tool not registered | Register the generated handler, for example .tool(MyTool) |
| Request cancelled mid-operation | Local request cancellation or budget exhaustion | Add checkpoints and mask only the smallest atomic section that must finish; Unix stdio keeps receiving while bounded modern request children run, but output commits are serialized, non-Unix/custom/SSE/WebSocket loops retain blocking boundaries, and a non-cooperative handler can exceed the process-exit quiescence drain |
JSON-RPC RequestCancelled (-32004) error Request timeout exceeded |
The request outlived the server-owned deadline (.request_timeout(...), 30 seconds by default), whether the server or the handler's own checkpoint observed it first |
Add checkpoints so work stops promptly; increase .request_timeout(...) only for a deadline that is intentionally too short |
#[tool] macro compilation error |
Unsupported return conversion or argument schema | Prefer String, Vec<Content>, McpResult<String>, or McpResult<Vec<Content>> and ensure custom argument types implement JsonSchema |
TransportError::Io on startup |
stdin unavailable | Ensure nothing else reads stdin |
Critical Section Example
use std::sync::atomic::{AtomicU64, Ordering};
// A handler that owns `committed` can call this helper after validation.
fn commit_revision(
ctx: &McpContext,
revision: u64,
committed: &AtomicU64,
) -> McpResult<()> {
// Mask only a small, non-blocking atomic commit. Masking does not make
// synchronous filesystem or device I/O bounded or cancel-safe.
ctx.masked(|| committed.store(revision, Ordering::Release))
.map_err(|error| McpError::internal_error(error.to_string()))?;
Ok(())
}
Limitations
| Limitation | Details |
|---|---|
| Pinned Nightly Required | The project contract pins nightly-2026-08-25; do not substitute a different toolchain merely because it supports Edition 2024 |
| Protocol Modernization | The root compatibility PROTOCOL_VERSION remains 2024-11-05; the modern facade's modern::PROTOCOL_VERSION is 2026-07-28. MCP 2026-07-28 implementation and verification are incomplete |
| Poll-quota accounting is scoped to framework operations | McpContext::checkpoint keeps a clone-shared request debit counter. The synchronous client RequestExecutor also consumes a finite poll budget during execute, drive, and wait, sharing it across nested control maintenance and every frame of a wait. Exhausting this local ledger stops that call without cancelling the caller's shared Cx or unrelated request owners. This operation-admission limit also applies inside Cx::masked; runtime cancellation and deadline delivery retain the original mask semantics. An already exhausted raw budget retains the runtime's existing cancellation behavior. Separate executor calls start separate budget snapshots; this is not a global quota across calls or a bound inside an arbitrary blocking transport. Other APIs that checkpoint only a raw Cx still reject an already exhausted quota without consuming a positive one: asupersync 0.5.0 exposes that budget as a read-only Copy snapshot. Deadline and explicit cancellation remain effective at their documented boundaries |
| Runtime-context migration | Library client constructors and returning/custom transport runners require a caller-owned Cx. The process-owning CLI and Server::run_stdio_with_cx install the ambient context at their top-level runtime boundary; test-internals is confined to test-only dependencies and the facade's opt-in testing-lab feature |
| Network Transports | The turnkey run_http* entry points provide a caller-owned dual-era HTTP listener and dispatch lifecycle. The experimental websocket-experimental facade profile also provides native async bind_websocket and serve_websocket listener lifecycles, plus caller-driven client connection. These surfaces do not establish aggregate conformance or complete lifecycle qualification |
| Client Transport Coverage | The fastmcp-client::Client type drives a subprocess over stdio. Its Client::http_with_cx and (exact-2024) Client::sse_with_cx constructors return a separate HttpClient, and WebSocketClient requires websocket-experimental. Public ClientHttpConnection and HttpClient provide modern HTTP and exact legacy SSE integration with typed list_tools/call_tool/read_resource/get_prompt verbs. Modern HTTP answers typed reverse sampling/createMessage, roots/list, and elicitation/create requests that arrive on a request-owned SSE body by POSTing the JSON-RPC response. Public HttpClient::call_tool and WebSocketClient::call_tool also follow modern server input_required by invoking those same installed handlers locally and retrying with inputResponses. Live bind_http JSON tools/call returns ctx.final_sampling and ctx.final_roots as input_required; a write-half EOF after the request is ordinary H1 completion and does not cancel that result. Public modern::Client stdio call_tool_result / read_resource_result / get_prompt_result keep the same live input_required branch. A Modern2026 stdio session stamps the same _meta protocol version and client capabilities on start_multiplexed_request that the typed verbs already send. Public stdio read_resource / get_prompt follow installed modern reverse handlers the same way call_tool does. Eligible stateless HTTP MRTR retries use framework-issued opaque, single-use requestState and may resume on a later POST only when the method, target, arguments, and admitted principal still match; forged or replayed state is rejected. Elicitation resumes the same way: the client's answer travels in inputResponses on the retry POST, bound to the original request by that single-use state. With websocket-experimental, the facade exposes WebSocketClient with incremental catalog listen, the same typed verbs, and the same modern reverse handlers: ModernOnly and LegacyOnly builders accept an owned async WebSocket transport, while Auto accepts a caller-owned factory that yields a fresh upgraded transport for initial modern discovery and its sole permitted exact-2024 retry |
| Two modules ship with tests but no consumer | fastmcp_transport::event_store (TTL retention, per-stream caps, replay_bounded cursor paging, 45 tests) has no consumer anywhere: its only references are its own pub mod declaration and the facade re-export. SSE resumption is deliberately not wired — exact 2024-11-05 reconnects start a fresh stream and Last-Event-ID is intentionally ignored, pinned by dual_era_endpoint_ignores_last_event_id_and_starts_a_fresh_legacy_stream. fastmcp_transport::http::HttpTransport is a complete synchronous HTTP/1.1 Read/Write adapter (request-line and token validation, obs-fold and duplicate-Host rejection, Content-Length/Transfer-Encoding conflict rejection, chunked decoding, 167 tests); the live listener does not use it, reaching the wire through asupersync::http::h1::Http1Codec instead, and its only out-of-crate consumer is one #[cfg(test)] fixture in fastmcp-server. Neither is an overclaim — this README promises no SSE replay — but 212 green tests exercise code no shipped request path reaches, so treat them as unclaimed library surface rather than as coverage of the HTTP or SSE paths |
| Experimental WebSocket framing | The frame codec that ships is asupersync's. fastmcp_transport::websocket compiles unconditionally, but its own RFC 6455 implementation — WsFrame, WsReader::read_frame, WsWriter::write_frame, WsClientWriter, generate_mask, EndpointRole::validate_peer_mask, WsTransport/WsClientTransport and their Transport impls — is #[cfg(test)] and is in no release binary. getrandom's WebSocket-masking use is likewise test-only. The shipping path (AsyncWsClientTransport, AsyncWsServerTransport, WebSocketListener, WebSocketUpgradeAdmission) uses asupersync::net::websocket for handshake and framing; FastMCP owns fragmentation assembly, opcode dispatch, size ceilings, pending-write bounds and close-code selection above it. Those production transports implement no Transport impl, unlike AsyncStdioTransport. Consequently any RFC 6455 invariant proven only against the cfg(test) codec — mask direction in particular — is not evidence about the shipped path |
| Experimental WebSocket TLS | The experimental async transport supports ws:// and wss://. wss:// can use the built-in WebPKI-rooted connector or a caller-supplied TLS connector for private roots, pinning, or client certificates; this connection support does not imply complete TLS, lifecycle, or MCP conformance qualification |
| HTTP Dispatch Qualification | Public run_http* binds and serves the caller-owned dual-era HTTP lifecycle. ModernOnly selects the exact MCP 2026-07-28 era and LegacyOnly selects the exact MCP 2024-11-05 era; MCP 2025-11-25 is not an adapter or supported policy. This executable surface does not establish aggregate MCP conformance or complete lifecycle qualification |
| Wire Cancellation | The modern-only split receive pump, including Unix stdio, admits bounded concurrent requests on the caller's dispatch runtime, including subscriptions/listen. It authenticates cancellation against the existing connection owner and serializes cancellation, response, and notification commits at the writer. Synchronous split runners use the bounded asupersync blocking bridge. Unsplit custom transports dispatch ordinary requests serially because receive and send share one handle; a subscriptions/listen runs off the receive loop, and output produced while recv blocks is queued and written as soon as recv returns. Transport reads and writes can still block. The dual-era Unix stdio pump retains its concurrent modern children and serialized exact MCP 2024-11-05 worker. A non-cooperative handler can exceed the bounded process-exit drain, and reliable awaitCleanup semantics remain unverified. "Transport reads and writes can still block" is a statement about the blocking stdio and custom adapters; a Unix serve_stdio_io server over the native process pipes does not block in its reader or writer, which removes that one residual without establishing any of the others |
| Silent stdio peers | On Unix, the public subprocess Client enforces configured idle/absolute deadlines at child-pipe readiness and decode boundaries, including silent and partial-frame peers. Generic blocking StdioTransport::recv and non-Unix child-pipe I/O retain their documented frame/I/O-boundary limitation. Unix client writes use a separate two-second queue-and-commit deadline, so response-wait deadlines are not an end-to-end request or process wall-clock guarantee. Those residuals remain FND-04 work |
| Stdio output backpressure | On Unix, primary server responses and notifications use serialized nonblocking writes with a two-second commit deadline for ordinary pipes/sockets; a timeout, lock poison, partial write, notification encoding failure, or descriptor-flag restoration failure is connection-fatal. The writer attempts to restore descriptor flags before releasing the local lock; on restoration failure the descriptor may remain nonblocking, and inherited duplicate descriptors can observe the temporary O_NONBLOCK setting. Regular files/devices and non-Unix stdout retain blocking-I/O limits. A handler that ignores cancellation may force unsuccessful process exit after the bounded drain; shutdown hooks are skipped unless all worker and modern-child quiescence is proven. This row describes the run_stdio_with_cx writer; a serve_stdio_io server over NativePipeWriter commits through the asynchronous transport instead, which has its own separate boundaries (see Non-blocking stdio) |
| Subprocess cleanup | Client::close(&mut self) -> McpResult<()> is the proof-bearing path; Drop is best effort. fastmcp test uses Unix-only anchored process-group ownership; successful connections report explicit final cleanup separately, and initialization-cleanup failures remain visible. Descendants can escape via a new group/session, host forks can copy the control descriptor, and SIGCHLD=SIG_IGN, SA_NOCLDWAIT, or competing global reapers can invalidate reap evidence. Windows Job Object support is not implemented |
| Development subprocess cleanup | On Unix, each fastmcp dev build/server group contains a signal-immune watchdog tied to a private owner-held control pipe, so ordinary shutdown, child-handle drop, and CLI owner death trigger bounded TERM-then-KILL cleanup. A host-side fork that copies the owner descriptor or a descendant that changes group/session remains outside this boundary; non-Unix dev remains fail-closed |
| Synchronous HTTP readers | Low-level HTTP parsing checkpoints before/after reads and retries EINTR, but a generic synchronous Read already blocked in the kernel cannot be preempted. A bounded host must supply readiness-aware/asynchronous I/O. Public turnkey run_http* uses its caller-owned asynchronous listener lifecycle, whose broader qualification boundaries remain documented here |
| Returning transport runners | run_transport_returning_with_cx and the split returning variants return fatal receive/send/close errors and preserve simultaneous run-plus-close failures. Clean EOF/cancellation is Ok(()). Each exact-2024 handler dispatch now opens and closes a budgeted child region of the caller's runtime, requiring a runtime-backed Cx. Blocking transport I/O and complete cancellation/cleanup guarantees remain unresolved |
| Request Cancellation Ownership | Unix modern stdio request work runs in independently owned bounded child contexts, but process-exiting shutdown does not wait unboundedly for a non-cooperative child; cancellation therefore is not yet a complete quiescence or awaitCleanup guarantee |
| Bidirectional Response Routing | On Unix, stdio continuously routes inbound responses while exact-2024 lifecycle work or modern request children are active. The WebSocket server and custom split transports use the same routing, proven live for exact-2024 reverse sampling and roots over bind_websocket. Non-Unix stdio, unsplit custom transports, and SSE do not provide the same split routing. Public HTTP has separate dual-era routing, while end-to-end bidirectional lifecycle qualification remains open |
| Response Cache Partitioning | Eligible entries are partitioned by committed authentication facts and opaque session identity/revision; ambiguous admission and state mutation fail closed. This does not promote OAuth/OIDC or establish protocol conformance |
| Authentication Admission | Native HTTP requires Authorization for protected requests and rejects recognized body/meta and query credential fields before provider invocation. Other adapters retain a stripped legacy fallback. Complete authorization, lease/revocation, and OAuth challenge qualification remain open |
| Tasks RPC | tasks/list and tasks/submit stay MethodNotFound. Official tasks/get, tasks/update, and tasks/cancel run by default on a process-local in-memory store; ServerBuilder::final_tasks replaces that store. ServerBuilder::task_supervisor(Arc::new(supervisor)) hosts the application's task service during each serve, waits for bounded readiness, and settles the service before returning. Without a ready service, task creation is refused |
MCP Apps (opt-in apps feature) |
Off by default. The facade apps feature adds the official MCP Apps extension: server ServerBuilder::mcp_apps (bilateral capability negotiation and server/discover metadata; Apps owns no client-to-server method), mcp_apps_ui_resource for final-only ui:// HTML documents and mcp_apps_tool for tools linked to one; client ClientBuilder::mcp_apps and the mcp_apps host bridge (McpAppsHost, McpAppsBridgeTransport). These are unit-tested (for example builder_mcp_apps_ui_resource_binds_a_final_only_ui_catalog_entry); Apps media rendering and Apps conformance are not claimed |
| Feature flags that gate nothing | fastmcp-server's enterprise-auth and jwt-resource-auth gate no server code; each only enables fastmcp-protocol's jose feature, and no inbound-JWT resource-server path exists for jwt-resource-auth to reach. fastmcp-server's websocket-experimental is also inert: it forwards only to fastmcp-transport's empty feature and is a different feature from fastmcp-server/websocket, which does gate code. The CLI's jwt-resource-auth adds no capability but is not dependency-graph inert — it carries dep:fastmcp-server, linking the server crate into the CLI. fastmcp-console's enterprise-auth, oauth-client-credentials, builtin-auth-server, jwt-resource-auth, proxy and websocket-experimental are empty, so its proxy-legacy and proxy-tasks reduce to legacy-2024-11-05 and tasks. fastmcp-transport's websocket-experimental is empty because fastmcp_transport::websocket is compiled unconditionally — but see Experimental WebSocket framing below: the always-compiled frame codec is not the one that ships. By contrast fastmcp-server's oauth-client-credentials is not inert: together with builtin-auth-server it gates 34 sites, including the client_credentials arm of the token endpoint and the advertised grant_types_supported list. The facade and client websocket-experimental features gate code: WebSocketClient, ClientBuilder::connect_websocket_with_cx, and (through fastmcp-server/websocket) bind_websocket. This list is complete as measured 2026-10-12 over all 72 declared features in the 8 crates that declare any (fastmcp-core declares none): the seven user-enableable features with zero cfg(feature = ...) sites in their own crate's src and an empty value list are exactly fastmcp-console's six above plus fastmcp-transport's websocket-experimental |
| HTTP as_proxy auto-follow | A gateway HTTP as_proxy does not auto-follow an upstream server input_required task across POSTs; per-request dispatch is stateless and upstream request state cannot resume. Callers resume such upstream tasks through an explicit matching tasks/update |
| OAuth/OIDC Promotion | Public source APIs exist, but production security and profile conformance remain unverified; they are quarantined from production-support claims |
| Early Development | API may change before 1.0 |
FAQ
Q: Why is Tokio unsupported?
A: FastMCP Rust is built around asupersync capability contexts, budgets, and cooperative-cancellation surfaces. Tokio and Tokio-based adapters are outside the supported runtime model.
Q: Can I use this with Claude Desktop?
A: Stdio integration exists, but compatibility must be checked against the client: the root compatibility PROTOCOL_VERSION is 2024-11-05, the modern facade's modern::PROTOCOL_VERSION is 2026-07-28, and MCP 2026-07-28 support is not yet verified.
Q: How do I add authentication?
A: Install an AuthProvider through the server builder. Native HTTP uses the
Authorization header and rejects recognized credentials in JSON-RPC params,
their _meta/headers containers, and query parameters with a fixed migration
diagnostic. Static tokens remain a non-OAuth deployment mode; applications own
TLS termination and token provisioning. Other transport adapters retain a
stripped legacy JSON-RPC credential fallback. OAuth/OIDC production security,
continuous authorization and profile conformance remain unverified.
Q: What's the performance overhead of checkpoints?
A: Checkpoints perform cancellation and budget checks. No project benchmark currently supports a universal per-call latency claim; measure them in the target workload if the cost matters.
Q: Can I use other async runtimes?
A: No. The current API and implementation require asupersync; other async runtimes are not supported.
Q: How do I test my handlers?
A: #[tool] keeps your function, so call it directly with an McpContext
built from a runtime's context and a request ID. (Cx::for_testing() needs
asupersync's test-internals feature; this form needs no extra features.)
use asupersync::runtime::RuntimeBuilder;
use fastmcp_rust::{Cx, McpContext, McpResult, tool};
#[tool]
fn my_tool(ctx: &McpContext, input: String) -> McpResult<String> {
ctx.checkpoint()?;
Ok(input)
}
#[test]
fn test_my_tool() {
let runtime = RuntimeBuilder::current_thread()
.build()
.expect("create test runtime");
runtime.block_on(async {
let ctx = McpContext::new(Cx::current().expect("test context"), 1);
let result = my_tool(&ctx, "input".to_string());
assert_eq!(result.unwrap(), "input");
});
}
About Contributions
Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via gh and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.
License
FastMCP Rust is distributed under the terms in LICENSE: the MIT
License with the included OpenAI/Anthropic rider. Every workspace crate uses
that file as its Cargo license-file. LICENSE-MIT is retained
as a reference copy of the underlying MIT text; it is not an alternative
license for this project.
README fetched from the repository 3 hours ago. The original is authoritative.