TITLE: Create FastMCP Server from OpenAPI Spec and Get Tools DESCRIPTION: Shows how to initialize a FastMCP server from an OpenAPI specification and retrieve the tools created by the server. This process involves loading the API definition and setting up components for execution. SOURCE: https://github.com/jlowin/fastmcp/blob/main/README_OPENAPI.md#_snippet_4 LANGUAGE: python CODE: ``` # Check component creation server = FastMCP.from_openapi(openapi_spec, client) tools = await server.get_tools() print(f"Created {len(tools)} tools: {list(tools.keys())}") ``` ---------------------------------------- TITLE: Enable Tool via Curl DESCRIPTION: Demonstrates how to enable a tool using a cURL command. This example includes setting the Authorization header and Content-Type for a typical API request. SOURCE: https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/contrib/component_manager/README.md#_snippet_4 LANGUAGE: bash CODE: ``` curl -X POST \ -H "Authorization: Bearer YOUR_TOKEN_HERE" \ -H "Content-Type: application/json" \ http://localhost:8001/tools/example_tool/enable ``` ---------------------------------------- TITLE: Generate Example from Schema DESCRIPTION: Generates a simple example value from a JSON schema dictionary. This is a basic implementation focused on deriving examples based on schema types. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-utilities-openapi.mdx#_snippet_2 LANGUAGE: python CODE: ``` generate_example_from_schema(schema: JsonSchema | None) -> Any ``` ---------------------------------------- TITLE: MCPMixin Usage Example DESCRIPTION: Demonstrates how to inherit from MCPMixin and use decorators to register methods as tools, resources, and prompts. Includes examples for enabling/disabling, excluding arguments, and applying annotations. SOURCE: https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/contrib/mcp_mixin/README.md#_snippet_0 LANGUAGE: python CODE: ``` from mcp.types import ToolAnnotations from fastmcp import FastMCP from fastmcp.contrib.mcp_mixin import MCPMixin, mcp_tool, mcp_resource, mcp_prompt class MyComponent(MCPMixin): @mcp_tool(name="my_tool", description="Does something cool.") def tool_method(self): return "Tool executed!" # example of disabled tool @mcp_tool(name="my_tool", description="Does something cool.", enabled=False) def disabled_tool_method(self): # This function can't be called by client because it's disabled return "You'll never get here!" # example of excluded parameter tool @mcp_tool( name="my_tool", description="Does something cool.", enabled=False, exclude_args=['delete_everything'], ) def excluded_param_tool_method(self, delete_everything=False): # MCP tool calls can't pass the "delete_everything" argument if delete_everything: return "Nothing to delete, I bet you're not a tool :)" return "You might be a tool if..." # example tool w/annotations @mcp_tool( name="my_tool", description="Does something cool.", annotations=ToolAnnotations( title="Attn LLM, use this tool first!", readOnlyHint=False, destructiveHint=False, idempotentHint=False, ) ) def tool_method_with_annotations(self): return "Tool executed!" # example tool w/everything @mcp_tool( name="my_tool", description="Does something cool.", enabled=True, exclude_args=['delete_all'], annotations=ToolAnnotations( title="Attn LLM, use this tool first!", readOnlyHint=False, destructiveHint=False, idempotentHint=False, ) ) def tool_method_with_all_options(self, delete_all=False): if delete_all: return "99 records deleted. I bet you're not a tool :)" return "Tool executed, but you might be a tool!" @mcp_resource(uri="component://data") def resource_method(self): return {"data": "some data"} # Disabled resource @mcp_resource(uri="component://data", enabled=False) def disabled_resource_method(self): return {"data": "some data"} # prompt @mcp_prompt(name="A prompt") def prompt_method(self, name): return f"Whats up {name}?" # disabled prompt @mcp_prompt(name="A prompt", enabled=False) def disabled_prompt_method(self, name): return f"Whats up {name}?" mcp_server = FastMCP() component = MyComponent() # Register all decorated methods with a prefix # Useful if you will have multiple instantiated objects of the same class # and want to avoid name collisions. component.register_all(mcp_server, prefix="my_comp") # Register without a prefix # component.register_all(mcp_server) # Now 'my_comp_my_tool' tool and 'my_comp+component://data' resource are registered (if prefix used) # Or 'my_tool' and 'component://data' are registered (if no prefix used) ``` ---------------------------------------- TITLE: FastMCP Client Class API DESCRIPTION: API documentation for the methods available on the Client class. This includes managing sessions, retrieving initialization results, setting root configurations, defining sampling callbacks, and checking the connection status. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-client-client.mdx#_snippet_1 LANGUAGE: APIDOC CODE: ``` Client: __init__(transport: ClientTransport | FastMCP | AnyUrl | str | Path | MCPConfig | dict, roots: RootsList | RootsHandler | None = None, sampling_handler: SamplingHandler | None = None, log_handler: LogHandler | None = None, message_handler: MessageHandler | None = None, progress_handler: ProgressHandler | None = None, timeout: float | timedelta | None = None, init_timeout: float | timedelta | None = None) Initializes the MCP client, delegating connection management to a Transport instance. Args: transport: Specifies the connection source, which can be a ClientTransport instance, an in-process FastMCP server, a URL, a local socket path, MCPConfig, or a transport configuration dictionary. roots: Optional handler for filesystem access. sampling_handler: Optional handler for sampling requests. log_handler: Optional handler for log messages. message_handler: Optional handler for protocol messages. progress_handler: Optional handler for progress notifications. timeout: Optional timeout for requests. init_timeout: Optional timeout for initial connection. Set to 0 to disable. session(self) -> ClientSession Retrieves the current active session. Raises RuntimeError if not connected. initialize_result(self) -> mcp.types.InitializeResult Returns the result of the initialization request made by the client. set_roots(self, roots: RootsList | RootsHandler) -> None Sets the roots for the client. This method does not automatically trigger a `send_roots_list_changed` notification. set_sampling_callback(self, sampling_callback: SamplingHandler) -> None Sets the callback function to be used for handling sampling requests. is_connected(self) -> bool Checks and returns a boolean indicating whether the client is currently connected to the transport. ``` ---------------------------------------- TITLE: Custom Route Map Example for GET Requests DESCRIPTION: Provides an example of custom route mapping to restore behavior where GET requests were mapped to Resource and ResourceTemplate components based on path parameters. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/openapi.mdx#_snippet_3 LANGUAGE: python CODE: ``` from fastmcp import FastMCP from fastmcp.server.openapi import RouteMap, MCPType # Example custom route maps (specific implementation details omitted as per input text) # custom_route_maps = [ # RouteMap(methods=["GET"], pattern=r"^/users/.*", mcp_type=MCPType.RESOURCE), # RouteMap(methods=["GET"], pattern=r"^/items/.*", mcp_type=MCPType.RESOURCE_TEMPLATE), # RouteMap(mcp_type=MCPType.TOOL) # Fallback # ] # mcp = FastMCP.from_openapi( # openapi_spec=spec, # client=client, # route_maps=custom_route_maps # ) ``` ---------------------------------------- TITLE: TransformedTool.from_tool API DESCRIPTION: API for creating a TransformedTool from an existing Tool, supporting argument transformations, custom logic functions, and metadata overrides. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-tools-tool_transform.mdx#_snippet_1 LANGUAGE: APIDOC CODE: ``` TransformedTool.from_tool(cls, tool: Tool, name: str | None = None, description: str | None = None, tags: set[str] | None = None, transform_fn: Callable[..., Any] | None = None, transform_args: dict[str, ArgTransform] | None = None, annotations: ToolAnnotations | None = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> TransformedTool Creates a transformed tool from a parent tool. Args: tool: The parent tool to transform. transform_fn: Optional custom function. Can use forward() and forward_raw() to call the parent tool. Functions with **kwargs receive transformed argument names. name: New name for the tool. Defaults to parent tool's name. transform_args: Optional transformations for parent tool arguments. Only specified arguments are transformed, others pass through unchanged. Can be a simple rename (str) or complex transformation (ArgTransform). description: New description. Defaults to parent's description. tags: New tags. Defaults to parent's tags. annotations: New annotations. Defaults to parent's annotations. serializer: New serializer. Defaults to parent's serializer. enabled: Whether the tool is enabled. Defaults to parent's enabled status. Returns: TransformedTool with the specified transformations. Examples: # Transform specific arguments only Tool.from_tool(parent, transform_args={"old": "new"}) # Others unchanged # Custom function with partial transforms async def custom(x: int, y: int) -> str: result = await forward(x=x, y=y) return f"Custom: {result}" Tool.from_tool(parent, transform_fn=custom, transform_args={"a": "x", "b": "y"}) # Using **kwargs (gets all args, transformed and untransformed) async def flexible(**kwargs) -> str: result = await forward(**kwargs) return f"Got: {kwargs}" Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"}) ``` ---------------------------------------- TITLE: ToolManager API Documentation DESCRIPTION: API reference for the ToolManager class, covering methods for adding, removing, and managing tools within the FastMCP server. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-tools-tool_manager.mdx#_snippet_0 LANGUAGE: APIDOC CODE: ``` ToolManager: __init__(self) Initializes the ToolManager. mount(self, server: MountedServer) -> None Adds a mounted server as a source for tools. Parameters: server: The MountedServer instance to add. add_tool_from_fn(self, fn: Callable[..., Any], name: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, serializer: Callable[[Any], str] | None = None, exclude_args: list[str] | None = None) -> Tool Add a tool to the server from a function. Parameters: fn: The function to wrap as a tool. name: Optional name for the tool. description: Optional description for the tool. tags: Optional set of tags for the tool. annotations: Optional tool annotations. serializer: Optional serializer for tool arguments. exclude_args: Optional list of arguments to exclude. Returns: The created Tool object. add_tool(self, tool: Tool) -> Tool Register a tool with the server. Parameters: tool: The Tool object to register. Returns: The registered Tool object. remove_tool(self, key: str) -> None Remove a tool from the server. Parameters: key: The key of the tool to remove. Raises: NotFoundError: If the tool is not found. ``` ---------------------------------------- TITLE: FastMCPComponent Class API DESCRIPTION: API documentation for the FastMCPComponent base class, detailing its methods for managing component identity and state. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-utilities-components.mdx#_snippet_0 LANGUAGE: APIDOC CODE: ``` FastMCPComponent: key() -> str The key of the component. This is used for internal bookkeeping and may reflect e.g. prefixes or other identifiers. You should not depend on keys having a certain value, as the same tool loaded from different hierarchies of servers may have different keys. with_key(key: str) -> Self enable() -> None Enable the component. disable() -> None Disable the component. ``` ---------------------------------------- TITLE: Complete Server Example with Bearer Auth DESCRIPTION: A full Python example for a FastMCP server implementing bearer token authentication. It includes key generation, provider setup, a sample tool, and running the server. Note: Printing tokens to console is for development only. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/anthropic.mdx#_snippet_5 LANGUAGE: python CODE: ``` from fastmcp import FastMCP from fastmcp.server.auth import BearerAuthProvider from fastmcp.server.auth.providers.bearer import RSAKeyPair import random key_pair = RSAKeyPair.generate() access_token = key_pair.create_token(audience="dice-server") auth = BearerAuthProvider( public_key=key_pair.public_key, audience="dice-server", ) mcp = FastMCP(name="Dice Roller", auth=auth) @mcp.tool def roll_dice(n_dice: int) -> list[int]: """Roll `n_dice` 6-sided dice and return the results.""" return [random.randint(1, 6) for _ in range(n_dice)] if __name__ == "__main__": print(f"\n---\n\n๐Ÿ”‘ Dice Roller access token:\n\n{access_token}\n\n---\n") mcp.run(transport="http", port=8000) ``` ---------------------------------------- TITLE: Serialization Examples for Complex Data DESCRIPTION: Provides further examples of how complex data structures like dictionaries and lists are automatically serialized into JSON strings when passed as arguments to prompts. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/clients/prompts.mdx#_snippet_4 LANGUAGE: python CODE: ``` async with client: result = await client.get_prompt("data_analysis", { # These will be automatically serialized to JSON strings: "config": { "format": "csv", "include_headers": True, "delimiter": "," }, "filters": [ {"field": "age", "operator": ">", "value": 18}, {"field": "status", "operator": "==", "value": "active"} ], # This remains a string: "report_title": "Monthly Analytics Report" }) ``` ---------------------------------------- TITLE: Complete FastMCP Server with Bearer Auth DESCRIPTION: A full example of a FastMCP server implementing bearer token authentication. It includes key generation, auth provider setup, a sample tool, and running the server. Prints the token for demonstration. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/openai.mdx#_snippet_6 LANGUAGE: python CODE: ``` from fastmcp import FastMCP from fastmcp.server.auth import BearerAuthProvider from fastmcp.server.auth.providers.bearer import RSAKeyPair import random key_pair = RSAKeyPair.generate() access_token = key_pair.create_token(audience="dice-server") auth = BearerAuthProvider( public_key=key_pair.public_key, audience="dice-server", ) mcp = FastMCP(name="Dice Roller", auth=auth) @mcp.tool def roll_dice(n_dice: int) -> list[int]: """Roll `n_dice` 6-sided dice and return the results.""" return [random.randint(1, 6) for _ in range(n_dice)] if __name__ == "__main__": print(f"\n---\n\n๐Ÿ”‘ Dice Roller access token:\n\n{access_token}\n\n---\n") mcp.run(transport="http", port=8000) ``` ---------------------------------------- TITLE: ATProto MCP Server API Tools DESCRIPTION: Tools for performing actions on the AT Protocol. These include creating posts, managing threads, searching content, and social interactions like following and liking. SOURCE: https://github.com/jlowin/fastmcp/blob/main/examples/atproto_mcp/README.md#_snippet_5 LANGUAGE: APIDOC CODE: ``` Tools (Actions): post - Description: Create posts with rich features (text, images, quotes, replies, links, mentions). - Parameters: - text (str, required): The content of the post. - images (list[str], optional): URLs for images (max 4). - image_alts (list[str], optional): Alt text for each image. - links (list[RichTextLink], optional): Embedded links with text and URL. - mentions (list[RichTextMention], optional): User mentions with handle and display text. - reply_to (str, optional): URI of the post to reply to. - reply_root (str, optional): URI of the thread root for replies. - quote (str, optional): URI of the post to quote. - Example: await client.call_tool("post", {"text": "Hello!", "images": ["url"]}) create_thread - Description: Post multi-part threads with automatic linking. - Parameters: - posts (list[dict], required): A list of post objects, each with a 'text' field and optional 'images'. - Example: await client.call_tool("create_thread", {"posts": [{"text": "Part 1"}, {"text": "Part 2"}]}) search - Description: Search for posts by query. - Parameters: query (str, required): The search term. - Returns: List of matching posts. follow - Description: Follow users by handle. - Parameters: handle (str, required): The user's handle to follow. like - Description: Like posts by URI. - Parameters: uri (str, required): The URI of the post to like. repost - Description: Share posts by URI. - Parameters: uri (str, required): The URI of the post to repost. ``` ---------------------------------------- TITLE: OpenAI Responses API with MCP Integration DESCRIPTION: Documentation for using OpenAI's Responses API to integrate with MCP servers. This API allows AI agents to call custom functions exposed by MCP servers. It details the structure for defining MCP tools within the API request. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/openai.mdx#_snippet_3 LANGUAGE: APIDOC CODE: ``` OpenAI Responses API Integration with MCP: This API allows AI agents to interact with custom functions hosted on FastMCP servers. Method: POST /v1/responses Parameters: model: string The model to use for generating the response (e.g., "gpt-4.1"). tools: array of tool objects Defines the tools available to the AI agent. Each tool object can have: type: string Must be "mcp" for MCP server integration. server_label: string A unique identifier for the MCP server. server_url: string The public URL of the MCP server, including the endpoint (e.g., "https://your-server-url.com/mcp/"). require_approval: "never" | "user" | "auto" Specifies when user approval is needed for tool execution. input: string The user's prompt or query. Returns: An object containing the AI's response, which may include output from called MCP tools. output_text: string The text output from the AI. Example Usage: client.responses.create( model="gpt-4.1", tools=[ { "type": "mcp", "server_label": "dice_server", "server_url": "https://your-server-url.com/mcp/", "require_approval": "never", }, ], input="Roll a few dice!", ) Note: The Responses API is distinct from OpenAI's Completions or Assistants APIs. Currently, it only supports tools from MCP servers. ``` ---------------------------------------- TITLE: Create MCP Server from OpenAPI Spec DESCRIPTION: Creates an MCP server that exposes a REST API as LLM tools. It uses `FastMCP.from_openapi`, taking an OpenAPI specification and an httpx client to automatically generate callable tools for each API endpoint. The server is then run on a specified port. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/tutorials/rest-api.mdx#_snippet_1 LANGUAGE: python CODE: ``` import httpx from fastmcp import FastMCP # Create an HTTP client for the target API client = httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com") # Define a simplified OpenAPI spec for JSONPlaceholder openapi_spec = { "openapi": "3.0.0", "info": {"title": "JSONPlaceholder API", "version": "1.0"}, "paths": { "/users": { "get": { "summary": "Get all users", "operationId": "get_users", "responses": {"200": {"description": "A list of users."}} } }, "/users/{id}": { "get": { "summary": "Get a user by ID", "operationId": "get_user_by_id", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "A single user."}} } } } } # Create the MCP server from the OpenAPI spec mcp = FastMCP.from_openapi( openapi_spec=openapi_spec, client=client, name="JSONPlaceholder MCP Server" ) if __name__ == "__main__": mcp.run(transport="http", port=8000) ``` ---------------------------------------- TITLE: Generate Code Example with System Prompt and Parameters DESCRIPTION: Illustrates advanced usage of `ctx.sample()` by providing a specific prompt, a system prompt to guide behavior, and parameters like `temperature` and `max_tokens` for controlled LLM output. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/servers/sampling.mdx#_snippet_2 LANGUAGE: python CODE: ``` @mcp.tool async def generate_code_example(concept: str, ctx: Context) -> str: """Generate a Python code example for a given concept.""" response = await ctx.sample( messages=f"Write a simple Python code example demonstrating '{concept}'.", system_prompt="You are an expert Python programmer. Provide concise, working code examples without explanations.", temperature=0.7, max_tokens=300 ) code_example = response.text return f"```python\n{code_example}\n```" ``` ---------------------------------------- TITLE: ATProto MCP Server API Resources DESCRIPTION: Provides access to read-only data from the AT Protocol. These endpoints allow fetching connection status, profile information, and timeline feeds. SOURCE: https://github.com/jlowin/fastmcp/blob/main/examples/atproto_mcp/README.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` Resources (Read-only): atproto://profile/status - Description: Get connection status and profile information. - Method: GET - Parameters: None - Returns: Profile status and connection details. atproto://timeline - Description: Retrieve your timeline feed. - Method: GET - Parameters: None - Returns: List of posts in the user's timeline. atproto://notifications - Description: Get recent notifications. - Method: GET - Parameters: None - Returns: List of recent notifications. ``` ---------------------------------------- TITLE: FastMCP Constructor API DESCRIPTION: Details the parameters available for the FastMCP server constructor, including server naming, instructions, lifespan management, tagging, and tool/resource integration. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/servers/server.mdx#_snippet_7 LANGUAGE: apidoc CODE: ``` FastMCP(name: str = "FastMCP", instructions: str | None = None, lifespan: AsyncContextManager | None = None, tags: set[str] | None = None, tools: list[Tool | Callable] | None = None, **settings: Any) - Creates and configures a FastMCP server instance. - Parameters: - name: A human-readable name for your server. Defaults to "FastMCP". - instructions: Description of how to interact with this server. Helps clients understand purpose and functionality. - lifespan: An async context manager function for server startup and shutdown logic. - tags: A set of strings to tag the server itself. - tools: A list of tools (or functions to convert to tools) to add to the server programmatically. - **settings: Keyword arguments corresponding to additional ServerSettings configuration. ``` ---------------------------------------- TITLE: Basic Sampling Handler Example DESCRIPTION: Provides a basic implementation of a sampling handler that formats conversation history and returns a placeholder response. It demonstrates extracting text content and using the system prompt. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/clients/sampling.mdx#_snippet_2 LANGUAGE: python CODE: ``` from fastmcp import Client from fastmcp.client.sampling import SamplingMessage, SamplingParams, RequestContext async def basic_sampling_handler( messages: list[SamplingMessage], params: SamplingParams, context: RequestContext ) -> str: # Extract message content conversation = [] for message in messages: content = message.content.text if hasattr(message.content, 'text') else str(message.content) conversation.append(f"{message.role}: {content}") # Use the system prompt if provided system_prompt = params.systemPrompt or "You are a helpful assistant." # Here you would integrate with your preferred LLM service # This is just a placeholder response return f"Response based on conversation: {' | '.join(conversation)}" client = Client( "my_mcp_server.py", sampling_handler=basic_sampling_handler ) ``` ---------------------------------------- TITLE: PromptManager API DESCRIPTION: API documentation for the PromptManager class, detailing methods for adding and managing prompts within the fastmcp framework. Includes function-based prompts and direct prompt additions. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-prompts-prompt_manager.mdx#_snippet_0 LANGUAGE: APIDOC CODE: ``` PromptManager API: mount(self, server: MountedServer) -> None Adds a mounted server as a source for prompts. Parameters: self: The PromptManager instance. server: The MountedServer instance to add. Returns: None add_prompt_from_fn(self, fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, description: str | None = None, tags: set[str] | None = None) -> FunctionPrompt Create a prompt from a function. Parameters: fn: The callable function that generates a PromptResult or Awaitable[PromptResult]. name: An optional name for the prompt. description: An optional description for the prompt. tags: An optional set of tags for categorizing the prompt. Returns: The created FunctionPrompt object. add_prompt(self, prompt: Prompt) -> Prompt Add a prompt to the manager. Parameters: prompt: The Prompt object to add. Returns: The added Prompt object. ``` ---------------------------------------- TITLE: Generate Summary with ctx.sample DESCRIPTION: Shows a basic example of using `ctx.sample()` with a simple string prompt to generate a concise summary of provided content. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/servers/sampling.mdx#_snippet_1 LANGUAGE: python CODE: ``` @mcp.tool async def generate_summary(content: str, ctx: Context) -> str: """Generate a summary of the provided content.""" prompt = f"Please provide a concise summary of the following content:\n\n{content}" response = await ctx.sample(prompt) return response.text ``` ---------------------------------------- TITLE: FastMCP Server with Custom Route Maps DESCRIPTION: This Python snippet demonstrates how to create a FastMCP server with custom route maps. It configures the server to map API routes to specific MCP types, such as ResourceTemplate for routes with path parameters and Resource for other GET requests, using the RouteMap class. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/tutorials/rest-api.mdx#_snippet_3 LANGUAGE: python CODE: ``` import httpx from fastmcp import FastMCP from fastmcp.server.openapi import RouteMap, MCPType # Create an HTTP client for the target API client = httpx.AsyncClient(base_url="https://jsonplaceholder.typicode.com") # Define a simplified OpenAPI spec for JSONPlaceholder openapi_spec = { "openapi": "3.0.0", "info": {"title": "JSONPlaceholder API", "version": "1.0"}, "paths": { "/users": { "get": { "summary": "Get all users", "operationId": "get_users", "responses": {"200": {"description": "A list of users."}} } }, "/users/{id}": { "get": { "summary": "Get a user by ID", "operationId": "get_user_by_id", "parameters": [{"name": "id", "in": "path", "required": True, "schema": {"type": "integer"}}], "responses": {"200": {"description": "A single user."}} } } } } # Create the MCP server with custom route mapping mcp = FastMCP.from_openapi( openapi_spec=openapi_spec, client=client, name="JSONPlaceholder MCP Server", route_maps=[ # Map GET requests with path parameters (e.g., /users/{id}) to ResourceTemplate RouteMap(methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE), # Map all other GET requests to Resource RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE), ] ) if __name__ == "__main__": mcp.run(transport="http", port=8000) ``` ---------------------------------------- TITLE: FastMCP ATProto MCP Server Usage Examples DESCRIPTION: Demonstrates various ways to use the ATProto MCP Server's tools, including simple posts, posts with images, replies, quotes, rich text formatting, and creating multi-part threads. SOURCE: https://github.com/jlowin/fastmcp/blob/main/examples/atproto_mcp/README.md#_snippet_2 LANGUAGE: python CODE: ``` from fastmcp import Client from atproto_mcp.server import atproto_mcp async def demo(): async with Client(atproto_mcp) as client: # Simple post await client.call_tool("post", { "text": "Hello from FastMCP!" }) # Post with image await client.call_tool("post", { "text": "Beautiful sunset! ๐ŸŒ…", "images": ["https://example.com/sunset.jpg"], "image_alts": ["Sunset over the ocean"] }) # Reply to a post await client.call_tool("post", { "text": "Great point!", "reply_to": "at://did:plc:xxx/app.bsky.feed.post/yyy" }) # Quote post await client.call_tool("post", { "text": "This is important:", "quote": "at://did:plc:xxx/app.bsky.feed.post/yyy" }) # Rich text with links and mentions await client.call_tool("post", { "text": "Check out FastMCP by @alternatebuild.dev", "links": [{"text": "FastMCP", "url": "https://github.com/jlowin/fastmcp"}], "mentions": [{"handle": "alternatebuild.dev", "display_text": "@alternatebuild.dev"}] }) # Advanced: Quote with image await client.call_tool("post", { "text": "Adding visual context:", "quote": "at://did:plc:xxx/app.bsky.feed.post/yyy", "images": ["https://example.com/chart.png"] }) # Advanced: Reply with rich text await client.call_tool("post", { "text": "I agree! See this article for more info", "reply_to": "at://did:plc:xxx/app.bsky.feed.post/yyy", "links": [{"text": "this article", "url": "https://example.com/article"}] }) # Create a thread await client.call_tool("create_thread", { "posts": [ {"text": "Starting a thread about Python ๐Ÿงต"}, {"text": "Python is great for rapid prototyping"}, {"text": "And the ecosystem is amazing!", "images": ["https://example.com/python.jpg"]} ] }) ``` ---------------------------------------- TITLE: Custom Route Mapping Function for FastMCP DESCRIPTION: Illustrates how to define a custom route mapping function to control how OpenAPI routes are processed by FastMCP. This example excludes routes starting with '/admin'. SOURCE: https://github.com/jlowin/fastmcp/blob/main/README_OPENAPI.md#_snippet_5 LANGUAGE: python CODE: ``` def custom_mapper(route: HTTPRoute, current_type: MCPType) -> MCPType: if route.path.startswith("/admin"): return MCPType.EXCLUDE return current_type server = FastMCP.from_openapi(spec, client, route_map_fn=custom_mapper) ``` ---------------------------------------- TITLE: Basic Semantic Mapping for GET Requests DESCRIPTION: Demonstrates initial route mapping for GET requests. It converts GET requests with path parameters to ResourceTemplates and all other GET requests to Resources, using a list of RouteMap objects. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/openapi.mdx#_snippet_4 LANGUAGE: python CODE: ``` from fastmcp import FastMCP from fastmcp.server.openapi import RouteMap, MCPType # Define semantic mapping rules semantic_maps = [ # GET requests with path parameters become ResourceTemplates RouteMap(methods=["GET"], pattern=r".*\{.*\}.*", mcp_type=MCPType.RESOURCE_TEMPLATE), # All other GET requests become Resources RouteMap(methods=["GET"], pattern=r".*", mcp_type=MCPType.RESOURCE), ] # Initialize FastMCP with custom route maps mcp = FastMCP.from_openapi( openapi_spec=spec, client=client, route_maps=semantic_maps, ) ``` ---------------------------------------- TITLE: Call FastMCP Server from Anthropic API DESCRIPTION: An example using the Anthropic Python SDK to call a deployed FastMCP server. It demonstrates setting up the client, making a messages API call, specifying the MCP server URL, and including the required 'anthropic-beta' header. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/anthropic.mdx#_snippet_2 LANGUAGE: python CODE: ``` import anthropic from rich import print # Your server URL (replace with your actual URL) url = 'https://your-server-url.com' client = anthropic.Anthropic() response = client.beta.messages.create( model="claude-sonnet-4-20250514", max_tokens=1000, messages=[{"role": "user", "content": "Roll a few dice!"}], mcp_servers=[ { "type": "url", "url": f"{url}/mcp/", "name": "dice-server", } ], extra_headers={ "anthropic-beta": "mcp-client-2025-04-04" } ) print(response.content) ``` ---------------------------------------- TITLE: Example Test Pattern for Parameter Style Verification DESCRIPTION: Provides a template for unit testing parameter parsing and serialization logic within FastMCP. It involves creating a specific OpenAPI spec, initializing a tool, executing it, and asserting the generated request parameters. SOURCE: https://github.com/jlowin/fastmcp/blob/main/README_OPENAPI.md#_snippet_6 LANGUAGE: python CODE: ``` async def test_parameter_style(): # 1. Create OpenAPI spec with specific parameter configuration spec = {"openapi": "3.1.0", ...} # 2. Parse and create components routes = parse_openapi_to_http_routes(spec) tool = OpenAPITool(mock_client, routes[0], ...) # 3. Execute and verify request parameters await tool.run({"param": "value"}) actual_params = mock_client.request.call_args.kwargs["params"] assert actual_params == expected_params ``` ---------------------------------------- TITLE: FastMCP OpenAPI and FastAPI Integration DESCRIPTION: Explains how to automatically generate FastMCP servers from existing OpenAPI specifications or FastAPI applications. This allows web APIs to be seamlessly integrated into the MCP ecosystem. SOURCE: https://github.com/jlowin/fastmcp/blob/main/README.md#_snippet_13 LANGUAGE: APIDOC CODE: ``` FastMCP.from_openapi(openapi_spec) - Generates a FastMCP server from an OpenAPI specification. - Automatically converts OpenAPI definitions into MCP tools and endpoints. - Parameters: - openapi_spec: The OpenAPI specification (e.g., a dictionary or file path). FastMCP.from_fastapi(fastapi_app) - Generates a FastMCP server from a FastAPI application instance. - Wraps existing FastAPI routes and models for MCP compatibility. - Parameters: - fastapi_app: The FastAPI application instance. ``` ---------------------------------------- TITLE: FastMCP Server Composition API DESCRIPTION: Details the primary methods for composing FastMCP servers: import_server for static composition and mount for dynamic composition. It outlines their parameters, behavior, and how components are handled. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/servers/composition.mdx#_snippet_1 LANGUAGE: apidoc CODE: ``` FastMCP.import_server(server, prefix=None) - Copies components (tools, resources, prompts) from a subserver to the main server. - Parameters: - server: The FastMCP subserver instance to import. - prefix (str, optional): A string to prepend to component names and resource URIs. If None, components are imported without modification. - Behavior: - Tools are prefixed: `subserver.tool(name='my_tool')` becomes `main_mcp.tool(name='{prefix}_my_tool')`. - Resources are prefixed: `subserver.resource(uri='data://info')` becomes `main_mcp.resource(uri='data://{prefix}/info')`. - Prompts are prefixed: `subserver.prompt(name='my_prompt')` becomes `main_mcp.prompt(name='{prefix}_my_prompt')`. - Performs a one-time copy; changes to the subserver after import are not reflected. - The subserver's lifespan context is not executed by the main server. FastMCP.mount(server, prefix=None) - Creates a live link, delegating requests to the subserver (dynamic composition). - Parameters: - server: The FastMCP subserver instance to mount. - prefix (str, optional): A string to prepend to component names and resource URIs. If None, components are mounted without modification. - Behavior: - Changes to the subserver are immediately reflected in the main server. - Similar prefixing rules apply to tools, resources, and prompts as with `import_server`. Comparison: | Feature | Importing (import_server) | Mounting (mount) | |---------------------|-----------------------------|------------------| | Composition Type | One-time copy (static) | Live link (dynamic) | | Updates | Not reflected | Immediately reflected | | Lifespan Context | Not executed by main server | Executed by main server (if applicable) | | Best For | Bundling finalized components | Modular runtime composition | ``` ---------------------------------------- TITLE: Example: Handling Tool Changes with Python Class DESCRIPTION: Provides a practical example of using a `MessageHandler` subclass to specifically handle `on_tool_list_changed` notifications, demonstrating cache invalidation. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/clients/messages.mdx#_snippet_3 LANGUAGE: python CODE: ``` from fastmcp.client.messages import MessageHandler import mcp.types class ToolCacheHandler(MessageHandler): def __init__(self): self.cached_tools = [] async def on_tool_list_changed( self, notification: mcp.types.ToolListChangedNotification ) -> None: """Clear tool cache when tools change.""" print("Tools changed - clearing cache") self.cached_tools = [] # Force refresh on next access client = Client("server.py", message_handler=ToolCacheHandler()) ``` ---------------------------------------- TITLE: Format Description with Responses and Parameters DESCRIPTION: Formats a base description string by incorporating response, parameter, and request body information. This enhances API documentation clarity by embedding structured details. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/python-sdk/fastmcp-utilities-openapi.mdx#_snippet_4 LANGUAGE: python CODE: ``` format_description_with_responses(base_description: str, responses: dict[str, Any], parameters: list[ParameterInfo] | None = None, request_body: RequestBodyInfo | None = None) -> str ``` ---------------------------------------- TITLE: Basic FastMCP Server Example DESCRIPTION: Demonstrates how to create a simple MCP server using the FastMCP framework, defining a basic tool for adding two numbers. SOURCE: https://github.com/jlowin/fastmcp/blob/main/README.md#_snippet_0 LANGUAGE: python CODE: ``` # server.py from fastmcp import FastMCP mcp = FastMCP("Demo ๐Ÿš€") @mcp.tool def add(a: int, b: int) -> int: """Add two numbers""" return a + b if __name__ == "__main__": mcp.run() ``` ---------------------------------------- TITLE: Running FastMCP Server with Python DESCRIPTION: Demonstrates how to start a FastMCP server using `mcp.run()` within a Python script. It shows the default STDIO transport and an example of configuring HTTP transport with host and port. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/servers/fastmcp.mdx#_snippet_7 LANGUAGE: python CODE: ``` # my_server.py from fastmcp import FastMCP mcp = FastMCP(name="MyServer") @mcp.tool def greet(name: str) -> str: """Greet a user by name.""" return f"Hello, {name}!" if __name__ == "__main__": # This runs the server, defaulting to STDIO transport mcp.run() # To use a different transport, e.g., HTTP: # mcp.run(transport="streamable-http", host="127.0.0.1", port=9000) ``` ---------------------------------------- TITLE: Parse OpenAPI to HTTP Routes and Inspect Parameters DESCRIPTION: Demonstrates how to parse an OpenAPI specification into HTTP routes and inspect route parameters, including their name, location, style, and explode attributes. This is useful for understanding the intermediate representation of API definitions. SOURCE: https://github.com/jlowin/fastmcp/blob/main/README_OPENAPI.md#_snippet_3 LANGUAGE: python CODE: ``` # Parse routes to inspect intermediate representation routes = parse_openapi_to_http_routes(openapi_spec) for route in routes: print(f"{route.method} {route.path}") for param in route.parameters: print(f" {param.name} ({param.location}): style={param.style}, explode={param.explode}") ``` ---------------------------------------- TITLE: Authenticate Anthropic Client with FastMCP Server DESCRIPTION: This example demonstrates how to authenticate an Anthropic client when making requests to an authenticated FastMCP server. It shows how to pass the `authorization_token` within the `mcp_servers` configuration, allowing the client to successfully interact with the server. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/anthropic.mdx#_snippet_10 LANGUAGE: Python CODE: ``` import anthropic from rich import print # Your server URL (replace with your actual URL) url = 'https://your-server-url.com' # Your access token (replace with your actual token) access_token = 'your-access-token' client = anthropic.Anthropic() response = client.beta.messages.create( model="claude-sonnet-4-20250514", max_tokens=1000, messages=[{"role": "user", "content": "Roll a few dice!"}], mcp_servers=[ { "type": "url", "url": f"{url}/sse", "name": "dice-server", "authorization_token": access_token } ], extra_headers={ "anthropic-beta": "mcp-client-2025-04-04" } ) print(response.content) ``` ---------------------------------------- TITLE: Call FastMCP Server via OpenAI API (Python) DESCRIPTION: Shows how to call a deployed FastMCP server from Python using the OpenAI SDK. It requires the `openai` library and an OpenAI API key. The code configures the tool integration, specifying the server URL and label. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/openai.mdx#_snippet_2 LANGUAGE: python CODE: ``` from openai import OpenAI # Your server URL (replace with your actual URL) url = 'https://your-server-url.com' client = OpenAI() resp = client.responses.create( model="gpt-4.1", tools=[ { "type": "mcp", "server_label": "dice_server", "server_url": f"{url}/mcp/", "require_approval": "never", }, ], input="Roll a few dice!", ) print(resp.output_text) ``` ---------------------------------------- TITLE: Test MCP Server with FastMCP Client DESCRIPTION: Connects to a running MCP server using the `fastmcp.Client` to list available tools and call a specific tool. This verifies that the server correctly exposes the API endpoints as callable functions for an LLM. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/tutorials/rest-api.mdx#_snippet_2 LANGUAGE: python CODE: ``` import asyncio from fastmcp import Client async def main(): # Connect to the MCP server we just created async with Client("http://127.0.0.1:8000/mcp/") as client: # List the tools that were automatically generated tools = await client.list_tools() print("Generated Tools:") for tool in tools: print(f"- {tool.name}") # Call one of the generated tools print("\n\nCalling tool 'get_user_by_id'...") user = await client.call_tool("get_user_by_id", {"id": 1}) print(f"Result:\n{user.data}") if __name__ == "__main__": asyncio.run(main()) ``` ---------------------------------------- TITLE: FastMCP Dev Server Example DESCRIPTION: An example command demonstrating how to run a FastMCP development server with editable mode and additional packages installed. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/patterns/cli.mdx#_snippet_7 LANGUAGE: bash CODE: ``` # Run dev server with editable mode and additional packages fastmcp dev server.py -e . --with pandas --with matplotlib ``` ---------------------------------------- TITLE: Custom Route Maps for Analytics, Admin, and Internal Routes DESCRIPTION: Provides a comprehensive example of custom route mapping. It configures GET endpoints under '/analytics/' as Tools, excludes all '/admin/' routes, and excludes routes tagged as 'internal'. SOURCE: https://github.com/jlowin/fastmcp/blob/main/docs/integrations/openapi.mdx#_snippet_5 LANGUAGE: python CODE: ``` from fastmcp import FastMCP from fastmcp.server.openapi import RouteMap, MCPType mcp = FastMCP.from_openapi( openapi_spec=spec, client=client, route_maps=[ # Analytics `GET` endpoints are tools RouteMap( methods=["GET"], pattern=r"^/analytics/.*", mcp_type=MCPType.TOOL, ), # Exclude all admin endpoints RouteMap( pattern=r"^/admin/.*", mcp_type=MCPType.EXCLUDE, ), # Exclude all routes tagged "internal" RouteMap( tags={"internal"}, mcp_type=MCPType.EXCLUDE, ), ], ) ```