diff --git a/docs/python-sdk/fastmcp-server-context.mdx b/docs/python-sdk/fastmcp-server-context.mdx index 5dcd64893..85688d54f 100644 --- a/docs/python-sdk/fastmcp-server-context.mdx +++ b/docs/python-sdk/fastmcp-server-context.mdx @@ -7,7 +7,7 @@ sidebarTitle: context ## Functions -### `set_transport` +### `set_transport` ```python set_transport(transport: TransportType) -> Token[TransportType | None] @@ -17,7 +17,7 @@ set_transport(transport: TransportType) -> Token[TransportType | None] Set the current transport type. Returns token for reset. -### `reset_transport` +### `reset_transport` ```python reset_transport(token: Token[TransportType | None]) -> None @@ -27,35 +27,15 @@ reset_transport(token: Token[TransportType | None]) -> None Reset transport to previous value. -### `set_context` +### `set_context` ```python set_context(context: Context) -> Generator[Context, None, None] ``` -### `apply_session_transforms` - -```python -apply_session_transforms(components: Sequence[ComponentT]) -> Sequence[ComponentT] -``` - - -Apply session-specific visibility transforms to components. - -This helper applies session-level enable/disable rules by marking -components with their enabled state. Session transforms override -global transforms due to mark-based semantics (later marks win). - -**Args:** -- `components`: The components to apply session transforms to. - -**Returns:** -- The components with session transforms applied. - - ## Classes -### `LogData` +### `LogData` Data object for passing log arguments to client-side handlers. @@ -64,7 +44,7 @@ This provides an interface to match the Python standard library logging, for compatibility with structured logging. -### `Context` +### `Context` Context object providing access to MCP capabilities. @@ -116,7 +96,7 @@ The context is optional - tools that don't need it can omit the parameter. **Methods:** -#### `fastmcp` +#### `fastmcp` ```python fastmcp(self) -> FastMCP @@ -125,7 +105,7 @@ fastmcp(self) -> FastMCP Get the FastMCP instance. -#### `request_context` +#### `request_context` ```python request_context(self) -> RequestContext[ServerSession, Any, Request] | None @@ -154,7 +134,7 @@ async def on_request(self, context, call_next): ``` -#### `lifespan_context` +#### `lifespan_context` ```python lifespan_context(self) -> dict[str, Any] @@ -177,7 +157,7 @@ def my_tool(ctx: Context) -> str: ``` -#### `report_progress` +#### `report_progress` ```python report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None @@ -190,7 +170,7 @@ Report progress for the current operation. - `total`: Optional total value e.g. 100 -#### `list_resources` +#### `list_resources` ```python list_resources(self) -> list[SDKResource] @@ -202,7 +182,7 @@ List all available resources from the server. - List of Resource objects available on the server -#### `list_prompts` +#### `list_prompts` ```python list_prompts(self) -> list[SDKPrompt] @@ -214,7 +194,7 @@ List all available prompts from the server. - List of Prompt objects available on the server -#### `get_prompt` +#### `get_prompt` ```python get_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult @@ -230,7 +210,7 @@ Get a prompt by name with optional arguments. - The prompt result -#### `read_resource` +#### `read_resource` ```python read_resource(self, uri: str | AnyUrl) -> ResourceResult @@ -245,7 +225,7 @@ Read a resource by URI. - ResourceResult with contents -#### `log` +#### `log` ```python log(self, message: str, level: LoggingLevel | None = None, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None @@ -263,7 +243,7 @@ Messages sent to Clients are also logged to the `fastmcp.server.context.to_clien - `extra`: Optional mapping for additional arguments -#### `transport` +#### `transport` ```python transport(self) -> TransportType | None @@ -275,7 +255,7 @@ Returns the transport type used to run this server: "stdio", "sse", or "streamable-http". Returns None if called outside of a server context. -#### `client_id` +#### `client_id` ```python client_id(self) -> str | None @@ -284,7 +264,7 @@ client_id(self) -> str | None Get the client ID if available. -#### `request_id` +#### `request_id` ```python request_id(self) -> str @@ -295,7 +275,7 @@ Get the unique ID for this request. Raises RuntimeError if MCP request context is not available. -#### `session_id` +#### `session_id` ```python session_id(self) -> str @@ -312,7 +292,7 @@ the same client session. - for other transports. -#### `session` +#### `session` ```python session(self) -> ServerSession @@ -323,7 +303,7 @@ Access to the underlying session for advanced usage. Raises RuntimeError if MCP request context is not available. -#### `debug` +#### `debug` ```python debug(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None @@ -334,7 +314,7 @@ 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` +#### `info` ```python info(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None @@ -345,7 +325,7 @@ 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` +#### `warning` ```python warning(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None @@ -356,7 +336,7 @@ 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` +#### `error` ```python error(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None @@ -367,7 +347,7 @@ 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` +#### `list_roots` ```python list_roots(self) -> list[Root] @@ -376,7 +356,7 @@ list_roots(self) -> list[Root] List the roots available to the server, as indicated by the client. -#### `send_notification` +#### `send_notification` ```python send_notification(self, notification: mcp.types.ServerNotificationType) -> None @@ -388,7 +368,7 @@ Send a notification to the client immediately. - `notification`: An MCP notification instance (e.g., ToolListChangedNotification()) -#### `close_sse_stream` +#### `close_sse_stream` ```python close_sse_stream(self) -> None @@ -406,7 +386,7 @@ Instead of holding a connection open for minutes, you can periodically close and let the client reconnect. -#### `sample_step` +#### `sample_step` ```python sample_step(self, messages: str | Sequence[str | SamplingMessage]) -> SampleStep @@ -443,7 +423,7 @@ Tools can raise ToolError to bypass masking. - - .text: The text content (if any) -#### `sample` +#### `sample` ```python sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] @@ -452,7 +432,7 @@ sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ Overload: With result_type, returns SamplingResult[ResultT]. -#### `sample` +#### `sample` ```python sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[str] @@ -461,7 +441,7 @@ sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ Overload: Without result_type, returns SamplingResult[str]. -#### `sample` +#### `sample` ```python sample(self, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] | SamplingResult[str] @@ -503,43 +483,43 @@ Tools can raise ToolError to bypass masking. - - .history: All messages exchanged during sampling -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: None) -> AcceptedElicitation[dict[str, Any]] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: type[T]) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: list[str]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: dict[str, dict[str, str]]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: list[list[str]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: list[dict[str, dict[str, str]]]) -> AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: type[T] | list[str] | dict[str, dict[str, str]] | list[list[str]] | list[dict[str, dict[str, str]]] | None = None) -> AcceptedElicitation[T] | AcceptedElicitation[dict[str, Any]] | AcceptedElicitation[str] | AcceptedElicitation[list[str]] | DeclinedElicitation | CancelledElicitation @@ -568,7 +548,7 @@ type or dataclass or BaseModel. If it is a primitive type, an object schema with a single "value" field will be generated. -#### `set_state` +#### `set_state` ```python set_state(self, key: str, value: Any) -> None @@ -581,7 +561,7 @@ The key is automatically prefixed with the session identifier. State expires after 1 day to prevent unbounded memory growth. -#### `get_state` +#### `get_state` ```python get_state(self, key: str) -> Any @@ -592,7 +572,7 @@ Get a value from the session-scoped state store. Returns None if the key is not found. -#### `delete_state` +#### `delete_state` ```python delete_state(self, key: str) -> None @@ -601,7 +581,7 @@ delete_state(self, key: str) -> None Delete a value from the session-scoped state store. -#### `enable_components` +#### `enable_components` ```python enable_components(self) -> None @@ -625,7 +605,7 @@ ResourceListChangedNotification, and PromptListChangedNotification. - `match_all`: If True, matches all components regardless of other criteria. -#### `disable_components` +#### `disable_components` ```python disable_components(self) -> None @@ -649,7 +629,7 @@ ResourceListChangedNotification, and PromptListChangedNotification. - `match_all`: If True, matches all components regardless of other criteria. -#### `reset_components` +#### `reset_components` ```python reset_components(self) -> None diff --git a/docs/python-sdk/fastmcp-server-sampling-run.mdx b/docs/python-sdk/fastmcp-server-sampling-run.mdx index 16ea08a8f..a251946ff 100644 --- a/docs/python-sdk/fastmcp-server-sampling-run.mdx +++ b/docs/python-sdk/fastmcp-server-sampling-run.mdx @@ -10,7 +10,7 @@ Sampling types and helper functions for FastMCP servers. ## Functions -### `determine_handler_mode` +### `determine_handler_mode` ```python determine_handler_mode(context: Context, needs_tools: bool) -> bool @@ -30,7 +30,7 @@ Determine whether to use fallback handler or client for sampling. - `ValueError`: If client lacks required capability and no fallback configured. -### `call_sampling_handler` +### `call_sampling_handler` ```python call_sampling_handler(context: Context, messages: list[SamplingMessage]) -> CreateMessageResult | CreateMessageResultWithTools @@ -44,7 +44,7 @@ sampling_handler is set via determine_handler_mode(). The checks below are safeguards against internal misuse. -### `execute_tools` +### `execute_tools` ```python execute_tools(tool_calls: list[ToolUseContent], tool_map: dict[str, SamplingTool], mask_error_details: bool = False) -> list[ToolResultContent] @@ -65,9 +65,79 @@ to provide specific error messages to the LLM. - List of tool result content blocks. +### `prepare_messages` + +```python +prepare_messages(messages: str | Sequence[str | SamplingMessage]) -> list[SamplingMessage] +``` + + +Convert various message formats to a list of SamplingMessage objects. + + +### `prepare_tools` + +```python +prepare_tools(tools: Sequence[SamplingTool | Callable[..., Any]] | None) -> list[SamplingTool] | None +``` + + +Convert tools to SamplingTool objects. + + +### `extract_tool_calls` + +```python +extract_tool_calls(response: CreateMessageResult | CreateMessageResultWithTools) -> list[ToolUseContent] +``` + + +Extract tool calls from a response. + + +### `create_final_response_tool` + +```python +create_final_response_tool(result_type: type) -> SamplingTool +``` + + +Create a synthetic 'final_response' tool for structured output. + +This tool is used to capture structured responses from the LLM. +The tool's schema is derived from the result_type. + + +### `sample_step_impl` + +```python +sample_step_impl(context: Context, messages: str | Sequence[str | SamplingMessage]) -> SampleStep +``` + + +Implementation of Context.sample_step(). + +Make a single LLM sampling call. This is a stateless function that makes +exactly one LLM call and optionally executes any requested tools. + + +### `sample_impl` + +```python +sample_impl(context: Context, messages: str | Sequence[str | SamplingMessage]) -> SamplingResult[ResultT] +``` + + +Implementation of Context.sample(). + +Send a sampling request to the client and await the response. This method +runs to completion automatically, executing a tool loop until the LLM +provides a final text response. + + ## Classes -### `SamplingResult` +### `SamplingResult` Result of a sampling operation. @@ -78,7 +148,7 @@ Result of a sampling operation. - `history`: All messages exchanged during sampling. -### `SampleStep` +### `SampleStep` Result of a single sampling call. @@ -88,7 +158,7 @@ Represents what the LLM returned in this step plus the message history. **Methods:** -#### `is_tool_use` +#### `is_tool_use` ```python is_tool_use(self) -> bool @@ -97,7 +167,7 @@ is_tool_use(self) -> bool True if the LLM is requesting tool execution. -#### `text` +#### `text` ```python text(self) -> str | None @@ -106,7 +176,7 @@ text(self) -> str | None Extract text from the response, if available. -#### `tool_calls` +#### `tool_calls` ```python tool_calls(self) -> list[ToolUseContent] diff --git a/docs/python-sdk/fastmcp-server-server.mdx b/docs/python-sdk/fastmcp-server-server.mdx index db0290264..6f101ab75 100644 --- a/docs/python-sdk/fastmcp-server-server.mdx +++ b/docs/python-sdk/fastmcp-server-server.mdx @@ -26,7 +26,7 @@ Default lifespan context manager that does nothing. - An empty dictionary as the lifespan result. -### `create_proxy` +### `create_proxy` ```python create_proxy(target: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy @@ -235,7 +235,7 @@ and middleware execution. Returns all versions (no deduplication). Protocol handlers deduplicate for MCP wire format. -#### `get_tool` +#### `get_tool` ```python get_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None @@ -255,7 +255,7 @@ session transforms can override provider-level disables. - The tool if found and enabled, None otherwise. -#### `list_resources` +#### `list_resources` ```python list_resources(self) -> Sequence[Resource] @@ -268,7 +268,7 @@ and middleware execution. Returns all versions (no deduplication). Protocol handlers deduplicate for MCP wire format. -#### `get_resource` +#### `get_resource` ```python get_resource(self, uri: str, version: VersionSpec | None = None) -> Resource | None @@ -287,7 +287,7 @@ transforms (including session-level) have been applied. - The resource if found and enabled, None otherwise. -#### `list_resource_templates` +#### `list_resource_templates` ```python list_resource_templates(self) -> Sequence[ResourceTemplate] @@ -300,7 +300,7 @@ auth filtering, and middleware execution. Returns all versions (no deduplication Protocol handlers deduplicate for MCP wire format. -#### `get_resource_template` +#### `get_resource_template` ```python get_resource_template(self, uri: str, version: VersionSpec | None = None) -> ResourceTemplate | None @@ -319,7 +319,7 @@ all transforms (including session-level) have been applied. - The template if found and enabled, None otherwise. -#### `list_prompts` +#### `list_prompts` ```python list_prompts(self) -> Sequence[Prompt] @@ -332,7 +332,7 @@ and middleware execution. Returns all versions (no deduplication). Protocol handlers deduplicate for MCP wire format. -#### `get_prompt` +#### `get_prompt` ```python get_prompt(self, name: str, version: VersionSpec | None = None) -> Prompt | None @@ -351,19 +351,19 @@ transforms (including session-level) have been applied. - The prompt if found and enabled, None otherwise. -#### `call_tool` +#### `call_tool` ```python call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult ``` -#### `call_tool` +#### `call_tool` ```python call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.CreateTaskResult ``` -#### `call_tool` +#### `call_tool` ```python call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult | mcp.types.CreateTaskResult @@ -393,19 +393,19 @@ return ToolResult. - `ValidationError`: If arguments fail validation -#### `read_resource` +#### `read_resource` ```python read_resource(self, uri: str) -> ResourceResult ``` -#### `read_resource` +#### `read_resource` ```python read_resource(self, uri: str) -> mcp.types.CreateTaskResult ``` -#### `read_resource` +#### `read_resource` ```python read_resource(self, uri: str) -> ResourceResult | mcp.types.CreateTaskResult @@ -434,19 +434,19 @@ return ResourceResult. - `ResourceError`: If resource read fails -#### `render_prompt` +#### `render_prompt` ```python render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> PromptResult ``` -#### `render_prompt` +#### `render_prompt` ```python render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.CreateTaskResult ``` -#### `render_prompt` +#### `render_prompt` ```python render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> PromptResult | mcp.types.CreateTaskResult @@ -476,7 +476,7 @@ return PromptResult. - `PromptError`: If prompt rendering fails -#### `custom_route` +#### `custom_route` ```python custom_route(self, path: str, methods: list[str], name: str | None = None, include_in_schema: bool = True) -> Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]] @@ -497,7 +497,7 @@ Starlette's reverse URL lookup feature) - `include_in_schema`: Whether to include in OpenAPI schema, defaults to True -#### `add_tool` +#### `add_tool` ```python add_tool(self, tool: Tool | Callable[..., Any]) -> Tool @@ -515,7 +515,7 @@ with the Context type annotation. See the @tool decorator for examples. - The tool instance that was added to the server. -#### `remove_tool` +#### `remove_tool` ```python remove_tool(self, name: str, version: str | None = None) -> None @@ -531,19 +531,19 @@ Remove tool(s) from the server. - `NotFoundError`: If no matching tool is found. -#### `tool` +#### `tool` ```python tool(self, name_or_fn: AnyFunction) -> FunctionTool ``` -#### `tool` +#### `tool` ```python tool(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionTool] ``` -#### `tool` +#### `tool` ```python tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool] @@ -599,7 +599,7 @@ server.tool(my_function, name="custom_name") ``` -#### `add_resource` +#### `add_resource` ```python add_resource(self, resource: Resource | Callable[..., Any]) -> Resource | ResourceTemplate @@ -614,7 +614,7 @@ Add a resource to the server. - The resource instance that was added to the server. -#### `add_template` +#### `add_template` ```python add_template(self, template: ResourceTemplate) -> ResourceTemplate @@ -629,7 +629,7 @@ Add a resource template to the server. - The template instance that was added to the server. -#### `resource` +#### `resource` ```python resource(self, uri: str) -> Callable[[AnyFunction], Resource | ResourceTemplate | AnyFunction] @@ -688,7 +688,7 @@ async def get_weather(city: str) -> str: ``` -#### `add_prompt` +#### `add_prompt` ```python add_prompt(self, prompt: Prompt | Callable[..., Any]) -> Prompt @@ -703,19 +703,19 @@ Add a prompt to the server. - The prompt instance that was added to the server. -#### `prompt` +#### `prompt` ```python prompt(self, name_or_fn: AnyFunction) -> FunctionPrompt ``` -#### `prompt` +#### `prompt` ```python prompt(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionPrompt] ``` -#### `prompt` +#### `prompt` ```python prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt] @@ -792,7 +792,7 @@ Decorator to register a prompt. ``` -#### `run_stdio_async` +#### `run_stdio_async` ```python run_stdio_async(self, show_banner: bool = True, log_level: str | None = None, stateless: bool = False) -> None @@ -806,7 +806,7 @@ Run the server using stdio transport. - `stateless`: Whether to run in stateless mode (no session initialization) -#### `run_http_async` +#### `run_http_async` ```python run_http_async(self, show_banner: bool = True, transport: Literal['http', 'streamable-http', 'sse'] = 'http', host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, stateless: bool | None = None) -> None @@ -827,7 +827,7 @@ Run the server using HTTP transport. - `stateless`: Alias for stateless_http for CLI consistency -#### `http_app` +#### `http_app` ```python http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http', event_store: EventStore | None = None, retry_interval: int | None = None) -> StarletteWithLifespan @@ -853,7 +853,7 @@ streamable-http transport. - A Starlette application configured with the specified transport -#### `mount` +#### `mount` ```python mount(self, server: FastMCP[LifespanResultT], namespace: str | None = None, as_proxy: bool | None = None, tool_names: dict[str, str] | None = None, prefix: str | None = None) -> None @@ -900,7 +900,7 @@ mounted server. - `prefix`: Deprecated. Use namespace instead. -#### `import_server` +#### `import_server` ```python import_server(self, server: FastMCP[LifespanResultT], prefix: str | None = None) -> None @@ -941,7 +941,7 @@ templates, and prompts are imported with their original names. objects are imported with their original names. -#### `from_openapi` +#### `from_openapi` ```python from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, name: str = 'OpenAPI Server', route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, timeout: float | None = None, **settings: Any) -> Self @@ -965,7 +965,7 @@ Create a FastMCP server from an OpenAPI specification. - A FastMCP server with an OpenAPIProvider attached. -#### `from_fastapi` +#### `from_fastapi` ```python from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, httpx_client_kwargs: dict[str, Any] | None = None, tags: set[str] | None = None, timeout: float | None = None, **settings: Any) -> Self @@ -989,7 +989,7 @@ Create a FastMCP server from a FastAPI application. - A FastMCP server with an OpenAPIProvider attached. -#### `as_proxy` +#### `as_proxy` ```python as_proxy(cls, backend: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy @@ -1007,7 +1007,7 @@ instance or any value accepted as the `transport` argument of `fastmcp.client.Client` constructor. -#### `generate_name` +#### `generate_name` ```python generate_name(cls, name: str | None = None) -> str diff --git a/docs/python-sdk/fastmcp-server-transforms-enabled.mdx b/docs/python-sdk/fastmcp-server-transforms-enabled.mdx index 58fb33009..ebf95d5b1 100644 --- a/docs/python-sdk/fastmcp-server-transforms-enabled.mdx +++ b/docs/python-sdk/fastmcp-server-transforms-enabled.mdx @@ -15,7 +15,7 @@ Final filtering happens at the Provider level. ## Functions -### `is_enabled` +### `is_enabled` ```python is_enabled(component: FastMCPComponent) -> bool @@ -37,9 +37,146 @@ Returns False if enabled mark is False. - True if component should be enabled/visible to clients. +### `get_visibility_rules` + +```python +get_visibility_rules(context: Context) -> list[dict[str, Any]] +``` + + +Load visibility rule dicts from session state. + + +### `save_visibility_rules` + +```python +save_visibility_rules(context: Context, rules: list[dict[str, Any]]) -> None +``` + + +Save visibility rule dicts to session state and send notifications. + +**Args:** +- `context`: The context to save rules for. +- `rules`: The visibility rules to save. +- `components`: Optional hint about which component types are affected. +If None, sends notifications for all types (safe default). +If provided, only sends notifications for specified types. + + +### `create_enabled_transforms` + +```python +create_enabled_transforms(rules: list[dict[str, Any]]) -> list[Enabled] +``` + + +Convert rule dicts to Enabled transforms. + + +### `get_session_transforms` + +```python +get_session_transforms(context: Context) -> list[Enabled] +``` + + +Get session-specific Enabled transforms from state store. + + +### `enable_components` + +```python +enable_components(context: Context) -> None +``` + + +Enable components matching criteria for this session only. + +Session rules override global transforms. Rules accumulate - each call +adds a new rule to the session. Later marks override earlier ones +(Enabled transform semantics). + +Sends notifications to this session only: ToolListChangedNotification, +ResourceListChangedNotification, and PromptListChangedNotification. + +**Args:** +- `context`: The context for this session. +- `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` + +```python +disable_components(context: Context) -> None +``` + + +Disable components matching criteria for this session only. + +Session rules override global transforms. Rules accumulate - each call +adds a new rule to the session. Later marks override earlier ones +(Enabled transform semantics). + +Sends notifications to this session only: ToolListChangedNotification, +ResourceListChangedNotification, and PromptListChangedNotification. + +**Args:** +- `context`: The context for this session. +- `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_components` + +```python +reset_components(context: Context) -> 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. + +**Args:** +- `context`: The context for this session. + + +### `apply_session_transforms` + +```python +apply_session_transforms(components: Sequence[ComponentT]) -> Sequence[ComponentT] +``` + + +Apply session-specific visibility transforms to components. + +This helper applies session-level enable/disable rules by marking +components with their enabled state. Session transforms override +global transforms due to mark-based semantics (later marks win). + +**Args:** +- `components`: The components to apply session transforms to. + +**Returns:** +- The components with session transforms applied. + + ## Classes -### `Enabled` +### `Enabled` Sets enabled state on matching components. @@ -51,7 +188,7 @@ Final filtering happens at the Provider level after all transforms run. **Methods:** -#### `list_tools` +#### `list_tools` ```python list_tools(self, call_next: ListToolsNext) -> Sequence[Tool] @@ -60,7 +197,7 @@ list_tools(self, call_next: ListToolsNext) -> Sequence[Tool] Mark tools by enabled state. -#### `get_tool` +#### `get_tool` ```python get_tool(self, name: str, call_next: GetToolNext) -> Tool | None @@ -69,7 +206,7 @@ get_tool(self, name: str, call_next: GetToolNext) -> Tool | None Mark tool if found. -#### `list_resources` +#### `list_resources` ```python list_resources(self, call_next: ListResourcesNext) -> Sequence[Resource] @@ -78,7 +215,7 @@ list_resources(self, call_next: ListResourcesNext) -> Sequence[Resource] Mark resources by enabled state. -#### `get_resource` +#### `get_resource` ```python get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None @@ -87,7 +224,7 @@ get_resource(self, uri: str, call_next: GetResourceNext) -> Resource | None Mark resource if found. -#### `list_resource_templates` +#### `list_resource_templates` ```python list_resource_templates(self, call_next: ListResourceTemplatesNext) -> Sequence[ResourceTemplate] @@ -96,7 +233,7 @@ list_resource_templates(self, call_next: ListResourceTemplatesNext) -> Sequence[ Mark resource templates by enabled state. -#### `get_resource_template` +#### `get_resource_template` ```python get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> ResourceTemplate | None @@ -105,7 +242,7 @@ get_resource_template(self, uri: str, call_next: GetResourceTemplateNext) -> Res Mark resource template if found. -#### `list_prompts` +#### `list_prompts` ```python list_prompts(self, call_next: ListPromptsNext) -> Sequence[Prompt] @@ -114,7 +251,7 @@ list_prompts(self, call_next: ListPromptsNext) -> Sequence[Prompt] Mark prompts by enabled state. -#### `get_prompt` +#### `get_prompt` ```python get_prompt(self, name: str, call_next: GetPromptNext) -> Prompt | None