Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756---title: contextsidebarTitle: context---
# `fastmcp.server.context`
## Functions
### `set_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L91" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_transport(transport: TransportType) -> Token[TransportType | None]```
Set the current transport type. Returns token for reset.
### `reset_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L98" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonreset_transport(token: Token[TransportType | None]) -> None```
Reset transport to previous value.
### `set_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L128" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_context(context: Context) -> Generator[Context, None, None]```
## Classes
### `LogData` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Data object for passing log arguments to client-side handlers.
This provides an interface to match the Python standard library logging,for compatibility with structured logging.
### `Context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L137" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Context object providing access to MCP capabilities.
This provides a cleaner interface to MCP's RequestContext functionality.It gets injected into tool and resource functions that request it via type hints.
To use context in a tool function, add a parameter with the Context type annotation:
```python@server.toolasync def my_tool(x: int, ctx: Context) -> str: # Log messages to the client await ctx.info(f"Processing {x}") await ctx.debug("Debug info") await ctx.warning("Warning message") await ctx.error("Error message")
# Report progress await ctx.report_progress(50, 100, "Processing")
# Access resources data = await ctx.read_resource("resource://data")
# Get request info request_id = ctx.request_id client_id = ctx.client_id
# Manage state across the session (persists across requests) await ctx.set_state("key", "value") value = await ctx.get_state("key")
# Store non-serializable values for the current request only await ctx.set_state("client", http_client, serializable=False)
return str(x)```
State Management:Context provides session-scoped state that persists across requests withinthe same MCP session. State is automatically keyed by session, ensuringisolation between different clients.
State set during `on_initialize` middleware will persist to subsequent toolcalls when using the same session object (STDIO, SSE, single-server HTTP).For distributed/serverless HTTP deployments where different machines handlethe init and tool calls, state is isolated by the mcp-session-id header.
The context parameter name can be anything as long as it's annotated with Context.The context is optional - tools that don't need it can omit the parameter.
**Methods:**
#### `is_background_task` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L210" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonis_background_task(self) -> bool```
True when this context is running in a background task (Docket worker).
When True, certain operations like elicit() and sample() will usetask-aware implementations that can pause the task and wait forclient input.
#### `task_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L229" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontask_id(self) -> str | None```
Get the background task ID if running in a background task.
Returns None if not running in a background task context.
#### `origin_request_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L237" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonorigin_request_id(self) -> str | None```
Get the request ID that originated this execution, if available.
In foreground request mode, this is the current request_id.In background task mode, this is the request_id captured when the taskwas submitted, if one was available.
#### `fastmcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L249" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonfastmcp(self) -> FastMCP```
Get the FastMCP instance.
#### `request_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L325" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrequest_context(self) -> RequestContext[ServerSession, Any, Request] | None```
Access to the underlying request context.
Returns None when the MCP session has not been established yet.Returns the full RequestContext once the MCP session is available.
For HTTP request access in middleware, use `get_http_request()` from fastmcp.server.dependencies,which works whether or not the MCP session is available.
Example in middleware:```pythonasync def on_request(self, context, call_next): ctx = context.fastmcp_context if ctx.request_context: # MCP session available - can access session_id, request_id, etc. session_id = ctx.session_id else: # MCP session not available yet - use HTTP helpers from fastmcp.server.dependencies import get_http_request request = get_http_request() return await call_next(context)```
#### `lifespan_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L354" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlifespan_context(self) -> dict[str, Any]```
Access the server's lifespan context.
Returns the context dict yielded by the server's lifespan function.Returns an empty dict if no lifespan was configured or if the MCPsession is not yet established.
In background tasks (Docket workers), where request_context is notavailable, falls back to reading from the FastMCP server's lifespanresult directly.
Example:```python@server.tooldef my_tool(ctx: Context) -> str: db = ctx.lifespan_context.get("db") if db: return db.query("SELECT 1") return "No database connection"```
#### `report_progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L385" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonreport_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None```
Report progress for the current operation.
Works in both foreground (MCP progress notifications) and background(Docket task execution) contexts.
**Args:**- `progress`: Current progress value e.g. 24- `total`: Optional total value e.g. 100- `message`: Optional status message describing current progress
#### `list_resources` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L478" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_resources(self) -> list[SDKResource]```
List all available resources from the server.
**Returns:**- List of Resource objects available on the server
#### `list_prompts` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L494" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_prompts(self) -> list[SDKPrompt]```
List all available prompts from the server.
**Returns:**- List of Prompt objects available on the server
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L510" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult```
Get a prompt by name with optional arguments.
**Args:**- `name`: The name of the prompt to get- `arguments`: Optional arguments to pass to the prompt
**Returns:**- The prompt result
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L529" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonread_resource(self, uri: str | AnyUrl) -> ResourceResult```
Read a resource by URI.
**Args:**- `uri`: Resource URI to read
**Returns:**- ResourceResult with contents
#### `log` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L545" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlog(self, message: str, level: LoggingLevel | None = None, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None```
Send a log message to the client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
**Args:**- `message`: Log message- `level`: Optional log level. One of "debug", "info", "notice", "warning", "error", "critical","alert", or "emergency". Default is "info".- `logger_name`: Optional logger name- `extra`: Optional mapping for additional arguments
#### `transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L575" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontransport(self) -> TransportType | None```
Get the current transport type.
Returns the transport type used to run this server: "stdio", "sse",or "streamable-http". Returns None if called outside of a server context.
#### `client_supports_extension` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L583" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonclient_supports_extension(self, extension_id: str) -> bool```
Check whether the connected client supports a given MCP extension.
Inspects the ``extensions`` extra field on ``ClientCapabilities``sent by the client during initialization.
Returns ``False`` when no session is available (e.g., outside arequest context) or when the client did not advertise the extension.
Example::
from fastmcp.apps.config import UI_EXTENSION_ID
@mcp.tool async def my_tool(ctx: Context) -> str: if ctx.client_supports_extension(UI_EXTENSION_ID): return "UI-capable client" return "text-only client"
#### `client_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L611" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonclient_id(self) -> str | None```
Get the client ID if available.
#### `request_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L620" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrequest_id(self) -> str```
Get the unique ID for this request.
Raises RuntimeError if MCP request context is not available.
#### `session_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L633" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsession_id(self) -> str```
Get the MCP session ID for ALL transports.
Returns the session ID that can be used as a key for session-baseddata storage (e.g., Redis) to share data between tool calls withinthe same client session.
**Returns:**- The session ID for StreamableHTTP transports, or a generated ID- for other transports.
#### `session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L690" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsession(self) -> ServerSession```
Access to the underlying session for advanced usage.
In request mode: Returns the session from the active request context.In background task mode: Returns the session stored at Context creation.
Raises RuntimeError if no session is available.
#### `debug` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L716" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythondebug(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None```
Send a `DEBUG`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L732" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoninfo(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None```
Send a `INFO`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `warning` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L748" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonwarning(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None```
Send a `WARNING`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L764" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonerror(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None```
Send a `ERROR`-level message to the connected MCP Client.
Messages sent to Clients are also logged to the `fastmcp.server.context.to_client` logger with a level of `DEBUG`.
#### `list_roots` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L780" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_roots(self) -> list[Root]```
List the roots available to the server, as indicated by the client.
#### `send_notification` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L785" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsend_notification(self, notification: mcp.types.ServerNotificationType) -> None```
Send a notification to the client immediately.
**Args:**- `notification`: An MCP notification instance (e.g., ToolListChangedNotification())
#### `close_sse_stream` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L795" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonclose_sse_stream(self) -> None```
Close the current response stream to trigger client reconnection.
When using StreamableHTTP transport with an EventStore configured, thismethod gracefully closes the HTTP connection for the current request.The client will automatically reconnect (after `retry_interval` milliseconds)and resume receiving events from where it left off via the EventStore.
This is useful for long-running operations to avoid load balancer timeouts.Instead of holding a connection open for minutes, you can periodically closeand let the client reconnect.
#### `sample_step` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L834" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsample_step(self, messages: str | Sequence[str | SamplingMessage]) -> SampleStep```
Make a single LLM sampling call.
This is a stateless function that makes exactly one LLM call and optionallyexecutes any requested tools. Use this for fine-grained control over thesampling loop.
**Args:**- `messages`: The message(s) to send. Can be a string, list of strings,or list of SamplingMessage objects.- `system_prompt`: Optional system prompt for the LLM.- `temperature`: Optional sampling temperature.- `max_tokens`: Maximum tokens to generate. Defaults to 512.- `model_preferences`: Optional model preferences.- `tools`: Optional list of tools the LLM can use.- `tool_choice`: Tool choice mode ("auto", "required", or "none").- `execute_tools`: If True (default), execute tool calls and append resultsto history. If False, return immediately with tool_calls availablein the step for manual execution.- `mask_error_details`: If True, mask detailed error messages from toolexecution. When None (default), uses the global settings value.Tools can raise ToolError to bypass masking.- `tool_concurrency`: Controls parallel execution of tools\:- None (default)\: Sequential execution (one at a time)- 0\: Unlimited parallel execution- N > 0\: Execute at most N tools concurrentlyIf any tool has sequential=True, all tools execute sequentiallyregardless of this setting.
**Returns:**- SampleStep containing:- - .response: The raw LLM response- - .history: Messages including input, assistant response, and tool results- - .is_tool_use: True if the LLM requested tool execution- - .tool_calls: List of tool calls (if any)- - .text: The text content (if any)
#### `sample` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L913" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT]```
Overload: With result_type, returns SamplingResult[ResultT].
#### `sample` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L929" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[str]```
Overload: Without result_type, returns SamplingResult[str].
#### `sample` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L944" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonsample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] | SamplingResult[str]```
Send a sampling request to the client and await the response.
This method runs to completion automatically. When tools are provided,it executes a tool loop: if the LLM returns a tool use request, the toolsare executed and the results are sent back to the LLM. This continuesuntil the LLM provides a final text response.
When result_type is specified, a synthetic `final_response` tool iscreated. The LLM calls this tool to provide the structured response,which is validated against the result_type and returned as `.result`.
For fine-grained control over the sampling loop, use sample_step() instead.
**Args:**- `messages`: The message(s) to send. Can be a string, list of strings,or list of SamplingMessage objects.- `system_prompt`: Optional system prompt for the LLM.- `temperature`: Optional sampling temperature.- `max_tokens`: Maximum tokens to generate. Defaults to 512.- `model_preferences`: Optional model preferences.- `tools`: Optional list of tools the LLM can use. Accepts plainfunctions or SamplingTools.- `result_type`: Optional type for structured output. When specified,a synthetic `final_response` tool is created and the LLM'sresponse is validated against this type.- `mask_error_details`: If True, mask detailed error messages from toolexecution. When None (default), uses the global settings value.Tools can raise ToolError to bypass masking.- `tool_concurrency`: Controls parallel execution of tools\:- None (default)\: Sequential execution (one at a time)- 0\: Unlimited parallel execution- N > 0\: Execute at most N tools concurrentlyIf any tool has sequential=True, all tools execute sequentiallyregardless of this setting.
**Returns:**- SamplingResult[T] containing:- - .text: The text representation (raw text or JSON for structured)- - .result: The typed result (str for text, parsed object for structured)- - .history: All messages exchanged during sampling
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1019" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: None) -> AcceptedElicitation[dict[str, Any]] | DeclinedElicitation | CancelledElicitation```
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1034" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: type[T]) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation```
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1047" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: list[str]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation```
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1060" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: dict[str, dict[str, str]]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation```
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1073" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: list[list[str]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation```
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1088" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: list[dict[str, dict[str, str]]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation```
#### `elicit` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1103" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonelicit(self, message: str, response_type: type[T] | list[str] | dict[str, dict[str, str]] | list[list[str]] | list[dict[str, dict[str, str]]] | None = None) -> AcceptedElicitation[T] | AcceptedElicitation[dict[str, Any]] | AcceptedElicitation[str] | AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation```
Send an elicitation request to the client and await the response.
Call this method at any time to request additional information fromthe user through the client. The client must support elicitation,or the request will error.
Note that the MCP protocol only supports simple object schemas withprimitive types. You can provide a dataclass, TypedDict, or BaseModel tocomply. If you provide a primitive type, an object schema with a single"value" field will be generated for the MCP interaction andautomatically deconstructed into the primitive type upon response.
Passing ``response_type=None`` (or omitting it) is deprecated and willbe removed in a future version. The resulting empty-schema form-moderequest is ambiguous and causes some clients (e.g. VS Code) to hang onan empty form. Pass an explicit ``response_type`` describing the datayou want back.
**Args:**- `message`: A human-readable message explaining what information is needed- `response_type`: The type of the response, which should be a primitivetype or dataclass or BaseModel. If it is a primitive type, anobject schema with a single "value" field will be generated.- `response_title`: Optional label to display for the wrapped ``value``field when ``response_type`` is a scalar, Literal, Enum, or oneof the dict/list shorthand forms. Overrides the auto-generated"Value" label. Raises ``TypeError`` if passed with a BaseModel,dataclass, or ``None`` response type (use ``Field(title=...)``on the model instead).- `response_description`: Optional description to attach to the wrapped``value`` field. Same scope rules as ``response_title``.
#### `set_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1245" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonset_state(self, key: str, value: Any) -> None```
Set a value in the state store.
By default, values are stored in the session-scoped state store andpersist across requests within the same MCP session. Values must beJSON-serializable (dicts, lists, strings, numbers, etc.).
For non-serializable values (e.g., HTTP clients, database connections),pass ``serializable=False``. These values are stored in a request-scopeddict and only live for the current MCP request (tool call, resourceread, or prompt render). They will not be available in subsequentrequests.
The key is automatically prefixed with the session identifier.
#### `get_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1287" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_state(self, key: str) -> Any```
Get a value from the state store.
Checks request-scoped state first (set with ``serializable=False``),then falls back to the session-scoped state store.
Returns None if the key is not found.
#### `delete_state` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1301" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythondelete_state(self, key: str) -> None```
Delete a value from the state store.
Removes from both request-scoped and session-scoped stores.
#### `enable_components` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1322" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonenable_components(self) -> None```
Enable components matching criteria for this session only.
Session rules override global transforms. Rules accumulate - each calladds a new rule to the session. Later marks override earlier ones(Visibility transform semantics).
Sends notifications to this session only: ToolListChangedNotification,ResourceListChangedNotification, and PromptListChangedNotification.
**Args:**- `names`: Component names or URIs to match.- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}).- `version`: Component version spec to match.- `tags`: Tags to match (component must have at least one).- `components`: Component types to match (e.g., {"tool", "prompt"}).- `match_all`: If True, matches all components regardless of other criteria.
#### `disable_components` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1360" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythondisable_components(self) -> None```
Disable components matching criteria for this session only.
Session rules override global transforms. Rules accumulate - each calladds a new rule to the session. Later marks override earlier ones(Visibility transform semantics).
Sends notifications to this session only: ToolListChangedNotification,ResourceListChangedNotification, and PromptListChangedNotification.
**Args:**- `names`: Component names or URIs to match.- `keys`: Component keys to match (e.g., {"tool\:my_tool@v1"}).- `version`: Component version spec to match.- `tags`: Tags to match (component must have at least one).- `components`: Component types to match (e.g., {"tool", "prompt"}).- `match_all`: If True, matches all components regardless of other criteria.
#### `reset_visibility` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/context.py#L1398" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonreset_visibility(self) -> None```
Clear all session visibility rules.
Use this to reset session visibility back to global defaults.
Sends notifications to this session only: ToolListChangedNotification,ResourceListChangedNotification, and PromptListChangedNotification.