Repository navigation
Core Concepts
Jeffrie Budde edited this page Nov 25, 2025
·
1 revision
FastRMCP primitives you will touch in every server. See Tools/Resources/Prompts for macro details.
- Injected via
Contextparameter (optional) into tools/resources/prompts. - Carries
server_info, optionalclient_info,request_id, metadata map, and a notification sender. - Progress + logs:
ctx.report_progress(progress, total, Some("msg"))andctx.log_info(...)emit MCP notifications; falls back totracingif no transport hook. - Metadata:
ctx.set_metadata("key", json!(value)).awaitandctx.get_metadata("key").awaitfor middleware/handler sharing. Avoid blocking on metadata inside tight loops. - ID helper:
Context::generate_id()for unique tokens.
- Type-safe shared container (
fastrmcp::state::State) stored onFastMCPand clonable. - Insert at startup:
.with_state(|state| state.insert(DatabasePool::new()).unwrap()). - Access inside handlers by adding
Stateparam andstate.get::<T>()?returningArc<T>. - Lifetime nuance:
get()returnsArcclones that remain valid even afterremove()/clear()—plan for that if you hot-swap state.
- Auto-registration via inventory for
#[tool],#[resource],#[prompt]. - Tool/Prompt registries validate uniqueness; Resource registry also validates URI template collisions.
- Required order: FastMCP sets
server_infobeforeregister_from_inventoryso#[resource]fallback contexts have server metadata—don’t bypassFastMCP::new(...).run()with manual registration unless you callresource_registry.set_server_info(...)first; otherwise resources will error with “Server info not set before resource registration.” - Lookup helpers:
server.tool_registry().list(),.get(name), same for resources/prompts.
-
#[on_startup]and#[on_shutdown]macros register async hooks run before the main loop and during graceful shutdown. - Best for initializing stateful services, warming caches, or flushing telemetry.
- Hooks run sequentially; return
Result<()>to fail fast on critical setup errors.
- Built-in
SubscriptionManagerexposed from the handler; resources are subscribable out of the box when using#[resource]. - Protocol methods:
resources/subscribe,resources/unsubscribe,resources/list_subscriptions. - Notifications flow through transports; see Subscriptions & Notifications and Transports Guide for connectionId handling.
- Primary error:
fastrmcp_core::error::MCPErrorwith JSON-RPC-friendly codes. - Common variants:
InvalidParams,MethodNotFound,ResourceNotFound,PromptNotFound,TransportError,Custom { code, message, data }. - Return
Result<T>(alias toResult<T, MCPError>) from handlers; convert IO/serde errors via?(From implementations map toTransportError/ParseError/SerializationError). - For validation, prefer
InvalidParamsso clients get actionable feedback; useServerErrorwith specific codes (-32099..-32000) for server-specific faults.
Related: Tools/Resources/Prompts • Middleware Cookbook • Observability