======================== CODE SNIPPETS ======================== TITLE: Install MCP Python SDK Simple Auth Client DESCRIPTION: Instructions to navigate to the client directory and install its dependencies using the `uv sync` command, ensuring a clean installation. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md#_snippet_0 LANGUAGE: bash CODE: ``` cd examples/clients/simple-auth-client uv sync --reinstall ``` ---------------------------------------- TITLE: Start MCP StreamableHttp Server DESCRIPTION: This snippet provides command-line examples for starting the MCP StreamableHttp server. It illustrates how to configure the server's port, set the logging verbosity, and switch between Server-Sent Events (SSE) and JSON response formats for client interactions. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-streamablehttp/README.md#_snippet_0 LANGUAGE: bash CODE: ``` # Using custom port uv run mcp-simple-streamablehttp --port 3000 # Custom logging level uv run mcp-simple-streamablehttp --log-level DEBUG # Enable JSON responses instead of SSE streams uv run mcp-simple-streamablehttp --json-response ``` ---------------------------------------- TITLE: Start MCP Simple StreamableHttp Stateless Server DESCRIPTION: Commands to start the MCP Simple StreamableHttp Stateless Server using `uv run`, with options for default port, custom port, custom logging level, and enabling JSON responses instead of SSE streams. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-streamablehttp-stateless/README.md#_snippet_0 LANGUAGE: bash CODE: ``` # Using default port 3000 uv run mcp-simple-streamablehttp-stateless # Using custom port uv run mcp-simple-streamablehttp-stateless --port 3000 # Custom logging level uv run mcp-simple-streamablehttp-stateless --log-level DEBUG # Enable JSON responses instead of SSE streams uv run mcp-simple-streamablehttp-stateless --json-response ``` ---------------------------------------- TITLE: Start MCP Server with OAuth Support DESCRIPTION: Command to run an MCP server instance, specifically `mcp-simple-auth`, configured for streamable HTTP transport on port 3001. This server acts as a prerequisite for the client to connect and perform OAuth authentication. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md#_snippet_1 LANGUAGE: bash CODE: ``` cd path/to/mcp-simple-auth uv run mcp-simple-auth --transport streamable-http --port 3001 ``` ---------------------------------------- TITLE: Start MCP Server with Website Fetching Tool DESCRIPTION: These commands demonstrate how to start the simple MCP server. It can be run using either the default stdio transport or configured for SSE transport on a specified port, enabling the 'fetch' tool. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-tool/README.md#_snippet_0 LANGUAGE: bash CODE: ``` # Using stdio transport (default) uv run mcp-simple-tool ``` LANGUAGE: bash CODE: ``` # Using SSE transport on custom port uv run mcp-simple-tool --transport sse --port 8000 ``` ---------------------------------------- TITLE: Start MCP Simple Resource Server DESCRIPTION: Demonstrates how to start the MCP simple resource server using either the default stdio transport or the SSE transport on a custom port. This requires the `uv` tool to run the `mcp-simple-resource` application. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-resource/README.md#_snippet_0 LANGUAGE: bash CODE: ``` # Using stdio transport (default) uv run mcp-simple-resource # Using SSE transport on custom port uv run mcp-simple-resource --transport sse --port 8000 ``` ---------------------------------------- TITLE: Example MCP Client Interaction and OAuth Flow DESCRIPTION: Illustrates an interactive command-line session with the MCP client, demonstrating the OAuth authorization process, successful server connection, listing available tools, calling a tool with JSON arguments, and gracefully exiting the client application. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md#_snippet_3 LANGUAGE: markdown CODE: ``` 🔐 Simple MCP Auth Client Connecting to: http://localhost:3001 Please visit the following URL to authorize the application: http://localhost:3001/authorize?response_type=code&client_id=... ✅ Connected to MCP server at http://localhost:3001 mcp> list 📋 Available tools: 1. echo - Echo back the input text mcp> call echo {"text": "Hello, world!"} 🔧 Tool 'echo' result: Hello, world! mcp> quit 👋 Goodbye! ``` ---------------------------------------- TITLE: Start MCP Simple Prompt Server DESCRIPTION: Commands to start the MCP simple prompt server using `uv run`. Demonstrates both default stdio transport and SSE transport with a custom port. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/README.md#_snippet_0 LANGUAGE: bash CODE: ``` # Using stdio transport (default) uv run mcp-simple-prompt # Using SSE transport on custom port uv run mcp-simple-prompt --transport sse --port 8000 ``` ---------------------------------------- TITLE: Setup Pre-commit Hooks DESCRIPTION: Installs and configures pre-commit hooks for the project using uv, ensuring code quality checks are performed automatically. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md#_snippet_1 LANGUAGE: bash CODE: ``` uv tool install pre-commit --with pre-commit-uv --force-reinstall ``` ---------------------------------------- TITLE: MCP Python SDK: Stdio Client Example DESCRIPTION: Demonstrates connecting to an MCP server using the stdio_client. It covers session initialization, listing prompts, retrieving a prompt with arguments, listing resources, reading resource content, and calling a tool with structured and unstructured results. Includes an example of a sampling callback. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_31 LANGUAGE: python CODE: ``` import asyncio from mcp import ClientSession, RequestContext, types from mcp.client.stdio import stdio_client from mcp.shared.url import AnyUrl # Optional: create a sampling callback async def handle_sampling_message( context: RequestContext, params: types.CreateMessageRequestParams ) -> types.CreateMessageResult: print(f"Sampling request: {params.messages}") return types.CreateMessageResult( role="assistant", content=types.TextContent( type="text", text="Hello, world! from model", ), model="gpt-3.5-turbo", stopReason="endTurn", ) async def run(): # Replace with your server parameters server_params = {} # Example: StdioServerParameters(path="/path/to/server") async with stdio_client(server_params) as (read, write): async with ClientSession(read, write, sampling_callback=handle_sampling_message) as session: # Initialize the connection await session.initialize() # List available prompts prompts = await session.list_prompts() print(f"Available prompts: {[p.name for p in prompts.prompts]}") # Get a prompt (greet_user prompt from fastmcp_quickstart) if prompts.prompts: prompt = await session.get_prompt("greet_user", arguments={"name": "Alice", "style": "friendly"}) print(f"Prompt result: {prompt.messages[0].content}") # List available resources resources = await session.list_resources() print(f"Available resources: {[r.uri for r in resources.resources]}") # List available tools tools = await session.list_tools() print(f"Available tools: {[t.name for t in tools.tools]}") # Read a resource (greeting resource from fastmcp_quickstart) resource_content = await session.read_resource(AnyUrl("greeting://World")) content_block = resource_content.contents[0] if isinstance(content_block, types.TextContent): print(f"Resource content: {content_block.text}") # Call a tool (add tool from fastmcp_quickstart) result = await session.call_tool("add", arguments={"a": 5, "b": 3}) result_unstructured = result.content[0] if isinstance(result_unstructured, types.TextContent): print(f"Tool result: {result_unstructured.text}") result_structured = result.structuredContent print(f"Structured tool result: {result_structured}") def main(): """Entry point for the client script.""" asyncio.run(run()) if __name__ == "__main__": main() ``` ---------------------------------------- TITLE: Install Project Dependencies DESCRIPTION: Installs project dependencies using uv, ensuring all extras and development dependencies are included for a frozen environment. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md#_snippet_0 LANGUAGE: bash CODE: ``` uv sync --frozen --all-extras --dev ``` ---------------------------------------- TITLE: Install MCP Server in Claude Desktop DESCRIPTION: Commands to install an MCP server into Claude Desktop using the `uv run mcp install` command. Supports custom server names and loading environment variables from files or direct arguments. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_21 LANGUAGE: bash CODE: ``` uv run mcp install server.py # Custom name uv run mcp install server.py --name "My Analytics Server" # Environment variables uv run mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://... uv run mcp install server.py -f .env ``` ---------------------------------------- TITLE: Python SDK: Run Basic Low-Level Server DESCRIPTION: Illustrates running a basic low-level server using the Python SDK. This example shows how to define and handle prompts, and how to set up the server for communication. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_28 LANGUAGE: python CODE: ``` """ Run from the repository root: uv run examples/snippets/servers/lowlevel/basic.py """ import asyncio import mcp.server.stdio import mcp.types as types from mcp.server.lowlevel import NotificationOptions, Server from mcp.server.models import InitializationOptions # Create a server instance server = Server("example-server") @server.list_prompts() async def handle_list_prompts() -> list[types.Prompt]: """List available prompts.""" return [ types.Prompt( name="example-prompt", description="An example prompt template", arguments=[types.PromptArgument(name="arg1", description="Example argument", required=True)], ) ] @server.get_prompt() async def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> types.GetPromptResult: """Get a specific prompt by name.""" if name != "example-prompt": raise ValueError(f"Unknown prompt: {name}") arg1_value = (arguments or {}).get("arg1", "default") return types.GetPromptResult( description="Example prompt", messages=[ types.PromptMessage( role="user", content=types.TextContent(type="text", text=f"Example prompt text with argument: {arg1_value}"), ) ], ) async def run(): """Run the basic low-level server.""" async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="example", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=NotificationOptions(), experimental_capabilities={}, ), ), ) if __name__ == "__main__": asyncio.run(run()) ``` ---------------------------------------- TITLE: Start MCP Authorization Server (AS) for OAuth 2.0 DESCRIPTION: This command initiates the Authorization Server component of the MCP OAuth 2.0 setup. It handles OAuth flows, credential-based authentication, and provides a token introspection endpoint for Resource Servers. The server is configured to run on port 9000. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-auth/README.md#_snippet_0 LANGUAGE: bash CODE: ``` cd examples/servers/simple-auth uv run mcp-simple-auth-as --port=9000 ``` ---------------------------------------- TITLE: MCP Client Stdio Connection Example DESCRIPTION: Shows how to set up server parameters for an MCP client to connect to a server using the stdio transport. It specifies the command and arguments to run the server. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_30 LANGUAGE: python CODE: ``` """ cd to the `examples/snippets/clients` directory and run: uv run client """ import asyncio import os from pydantic import AnyUrl from mcp import ClientSession, StdioServerParameters, types from mcp.client.stdio import stdio_client from mcp.shared.context import RequestContext # Create server parameters for stdio connection server_params = StdioServerParameters( command="uv", # Using uv to run the server args=["run", "server", "fastmcp_quickstart", "stdio"], # We're already in snippets dir env={"UV_INDEX": os.environ.get("UV_INDEX", "")}, ) ``` ---------------------------------------- TITLE: Python Client Interaction with MCP Fetch Tool DESCRIPTION: This Python example illustrates how to connect to the MCP server using the `mcp.client` SDK. It shows how to initialize a client session, list available tools, and call the 'fetch' tool with a URL argument to retrieve website content. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-tool/README.md#_snippet_2 LANGUAGE: python CODE: ``` import asyncio from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client async def main(): async with stdio_client( StdioServerParameters(command="uv", args=["run", "mcp-simple-tool"]) ) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available tools tools = await session.list_tools() print(tools) # Call the fetch tool result = await session.call_tool("fetch", {"url": "https://example.com"}) print(result) asyncio.run(main()) ``` ---------------------------------------- TITLE: Install and Run FastMCP Server DESCRIPTION: Provides bash commands to install and run a FastMCP server. It includes commands for both development mode and production deployment. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_5 LANGUAGE: bash CODE: ``` uv run mcp install server.py # Or for development: uv run mcp dev server.py ``` ---------------------------------------- TITLE: Python Completion Client Example DESCRIPTION: Demonstrates how to use the completion client to connect to a server, list available resource templates and prompts, and perform argument completion. It covers both completing arguments without context and with context-based suggestions. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_15 LANGUAGE: python CODE: ``` import asyncio import os from aiohttp import ClientSession from modelcontextprotocol.client.completion import stdio_client from modelcontextprotocol.client.completion.types import ResourceTemplateReference, PromptReference from modelcontextprotocol.server.parameters import StdioServerParameters # Create server parameters for stdio connection server_params = StdioServerParameters( command="uv", # Using uv to run the server args=["run", "server", "completion", "stdio"], # Server with completion support env={"UV_INDEX": os.environ.get("UV_INDEX", "")}, ) async def run(): """Run the completion client example.""" async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: # Initialize the connection await session.initialize() # List available resource templates templates = await session.list_resource_templates() print("Available resource templates:") for template in templates.resourceTemplates: print(f" - {template.uriTemplate}") # List available prompts prompts = await session.list_prompts() print("\nAvailable prompts:") for prompt in prompts.prompts: print(f" - {prompt.name}") # Complete resource template arguments if templates.resourceTemplates: template = templates.resourceTemplates[0] print(f"\nCompleting arguments for resource template: {template.uriTemplate}") # Complete without context result = await session.complete( ref=ResourceTemplateReference(type="ref/resource", uri=template.uriTemplate), argument={"name": "owner", "value": "model"}, ) print(f"Completions for 'owner' starting with 'model': {result.completion.values}") # Complete with context - repo suggestions based on owner result = await session.complete( ref=ResourceTemplateReference(type="ref/resource", uri=template.uriTemplate), argument={"name": "repo", "value": ""}, context_arguments={"owner": "modelcontextprotocol"}, ) print(f"Completions for 'repo' with owner='modelcontextprotocol': {result.completion.values}") # Complete prompt arguments if prompts.prompts: prompt_name = prompts.prompts[0].name print(f"\nCompleting arguments for prompt: {prompt_name}") result = await session.complete( ref=PromptReference(type="ref/prompt", name=prompt_name), argument={"name": "style", "value": ""}, ) print(f"Completions for 'style' argument: {result.completion.values}") def main(): """Entry point for the completion client.""" asyncio.run(run()) if __name__ == "__main__": main() ``` ---------------------------------------- TITLE: MCP Python SDK: Streamable HTTP Client Example DESCRIPTION: Demonstrates connecting to an MCP server using the streamable HTTP transport. This snippet shows how to establish a client connection, create a session, initialize it, and list available tools. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_32 LANGUAGE: python CODE: ``` """ Run from the repository root: uv run examples/snippets/clients/streamable_basic.py """ import asyncio from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client async def main(): # Connect to a streamable HTTP server # Replace with your server URL async with streamablehttp_client("http://localhost:8000/mcp") as ( read_stream, write_stream, _, ): # Create a session using the client streams async with ClientSession(read_stream, write_stream) as session: # Initialize the connection await session.initialize() # List available tools tools = await session.list_tools() print(f"Available tools: {[tool.name for tool in tools.tools]}") if __name__ == "__main__": asyncio.run(main()) ``` ---------------------------------------- TITLE: Retrieve Prompt with MCP Python Client DESCRIPTION: Asynchronous Python example demonstrating how to connect to the MCP server using the `mcp.client` library, list available prompts, and retrieve a specific prompt ('simple') with context and topic arguments. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-prompt/README.md#_snippet_1 LANGUAGE: python CODE: ``` import asyncio from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client async def main(): async with stdio_client( StdioServerParameters(command="uv", args=["run", "mcp-simple-prompt"]) ) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available prompts prompts = await session.list_prompts() print(prompts) # Get the prompt with arguments prompt = await session.get_prompt( "simple", { "context": "User is a software developer", "topic": "Python async programming", }, ) print(prompt) asyncio.run(main()) ``` ---------------------------------------- TITLE: Python Server Elicitation Example DESCRIPTION: Illustrates how to use the `elicit` method within a server context to request additional information from the user. This example shows prompting for an alternative date when a booking is unavailable, using a Pydantic schema for structured input. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_16 LANGUAGE: python CODE: ``` from pydantic import BaseModel, Field from mcp.server.fastmcp import Context, FastMCP mcp = FastMCP(name="Elicitation Example") class BookingPreferences(BaseModel): """Schema for collecting user preferences.""" checkAlternative: bool = Field(description="Would you like to check another date?") alternativeDate: str = Field( default="2024-12-26", description="Alternative date (YYYY-MM-DD)", ) @mcp.tool() async def book_table( date: str, time: str, party_size: int, ctx: Context, ) -> str: """Book a table with date availability check.""" # Check if date is available if date == "2024-12-25": # Date unavailable - ask user for alternative result = await ctx.elicit( message=(f"No tables available for {party_size} on {date}. Would you like to try another date?"), schema=BookingPreferences, ) if result.action == "accept" and result.data: if result.data.checkAlternative: return f"[SUCCESS] Booked for {result.data.alternativeDate}" return "[CANCELLED] No booking made" return "[CANCELLED] Booking cancelled" # Date available return f"[SUCCESS] Booked for {date} at {time}" ``` ---------------------------------------- TITLE: Direct Execution of MCP Server DESCRIPTION: Example demonstrating the direct execution of an MCP server using `FastMCP`. This snippet shows how to define a simple tool and run the server, suitable for advanced scenarios and custom deployments. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_22 LANGUAGE: python CODE: ``` """Example showing direct execution of an MCP server. This is the simplest way to run an MCP server directly. cd to the `examples/snippets` directory and run: uv run direct-execution-server or python servers/direct_execution.py """ from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") @mcp.tool() def hello(name: str = "World") -> str: """Say hello to someone.""" return f"Hello, {name}!" def main(): """Entry point for the direct execution server.""" mcp.run() if __name__ == "__main__": main() ``` ---------------------------------------- TITLE: Run MCP Simple Auth Client DESCRIPTION: Commands to execute the simple authentication client. This includes options for running with default settings, specifying a custom server URL using `MCP_SERVER_PORT`, and choosing between `streamable_http` (default) or `sse` transport types via `MCP_TRANSPORT_TYPE` environment variables. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md#_snippet_2 LANGUAGE: bash CODE: ``` uv run mcp-simple-auth-client # Or with custom server URL MCP_SERVER_PORT=3001 uv run mcp-simple-auth-client # Use SSE transport MCP_TRANSPORT_TYPE=sse uv run mcp-simple-auth-client ``` ---------------------------------------- TITLE: Retrieve Resources with MCP Python Client DESCRIPTION: Illustrates how to use the MCP Python client to connect to the simple resource server via stdio. The example initializes a client session, lists available resources, and then reads a specific resource (e.g., 'file:///greeting.txt') using asynchronous operations. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-resource/README.md#_snippet_1 LANGUAGE: python CODE: ``` import asyncio from mcp.types import AnyUrl from mcp.client.session import ClientSession from mcp.client.stdio import StdioServerParameters, stdio_client async def main(): async with stdio_client( StdioServerParameters(command="uv", args=["run", "mcp-simple-resource"]) ) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available resources resources = await session.list_resources() print(resources) # Get a specific resource resource = await session.read_resource(AnyUrl("file:///greeting.txt")) print(resource) asyncio.run(main()) ``` ---------------------------------------- TITLE: Start Legacy MCP Server as Authorization Server DESCRIPTION: This command starts a legacy MCP server that functions as both an MCP server and an Authorization Server, adhering to older specifications. It provides backward compatibility for existing MCP implementations where the server handles its own OAuth. The server is configured to run on port 8002. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-auth/README.md#_snippet_4 LANGUAGE: bash CODE: ``` uv run mcp-simple-auth-legacy --port=8002 ``` ---------------------------------------- TITLE: MCP Client for Completion Suggestions DESCRIPTION: Provides a client-side example for utilizing MCP's completion suggestions. This allows clients to request context-aware suggestions for prompt arguments or resource parameters, enhancing user interaction and data input. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_14 LANGUAGE: python CODE: ``` """ cd to the `examples/snippets` directory and run: uv run completion-client """ import asyncio import os from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from mcp.types import PromptReference, ResourceTemplateReference ``` ---------------------------------------- TITLE: MCP Client Configuration Variables DESCRIPTION: Environment variables used to configure the MCP client's connection parameters. These variables allow users to specify the server's port and the desired transport type for communication. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/clients/simple-auth-client/README.md#_snippet_4 LANGUAGE: APIDOC CODE: ``` MCP_SERVER_PORT - Server URL (default: 8000) MCP_TRANSPORT_TYPE - Transport type: streamable_http (default) or sse ``` ---------------------------------------- TITLE: Handle Images with FastMCP in Python DESCRIPTION: Shows how to integrate image handling within the FastMCP framework using the `Image` class. This example demonstrates creating a thumbnail from an image file, converting it to bytes, and specifying the format for transmission. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_12 LANGUAGE: python CODE: ``` """Example showing image handling with FastMCP.""" from PIL import Image as PILImage from mcp.server.fastmcp import FastMCP, Image mcp = FastMCP("Image Example") @mcp.tool() def create_thumbnail(image_path: str) -> Image: """Create a thumbnail from an image""" img = PILImage.open(image_path) img.thumbnail((100, 100)) return Image(data=img.tobytes(), format="png") ``` ---------------------------------------- TITLE: MCP Server Structured Output Example DESCRIPTION: Demonstrates how an MCP server can define `outputSchema` for tools to enable structured data validation and serialization. It includes a `get_weather` tool with input and output schemas, and a handler for tool calls. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_29 LANGUAGE: python CODE: ``` """ Run from the repository root: uv run examples/snippets/servers/lowlevel/structured_output.py """ import asyncio from typing import Any import mcp.server.stdio import mcp.types as types from mcp.server.lowlevel import NotificationOptions, Server from mcp.server.models import InitializationOptions server = Server("example-server") @server.list_tools() async def list_tools() -> list[types.Tool]: """List available tools with structured output schemas.""" return [ types.Tool( name="get_weather", description="Get current weather for a city", inputSchema={ "type": "object", "properties": {"city": {"type": "string", "description": "City name"}}, "required": ["city"], }, outputSchema={ "type": "object", "properties": { "temperature": {"type": "number", "description": "Temperature in Celsius"}, "condition": {"type": "string", "description": "Weather condition"}, "humidity": {"type": "number", "description": "Humidity percentage"}, "city": {"type": "string", "description": "City name"}, }, "required": ["temperature", "condition", "humidity", "city"], }, ) ] @server.call_tool() async def call_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]: """Handle tool calls with structured output.""" if name == "get_weather": city = arguments["city"] # Simulated weather data - in production, call a weather API weather_data = { "temperature": 22.5, "condition": "partly cloudy", "humidity": 65, "city": city, # Include the requested city } # low-level server will validate structured output against the tool's # output schema, and additionally serialize it into a TextContent block # for backwards compatibility with pre-2025-06-18 clients. return weather_data else: raise ValueError(f"Unknown tool: {name}") async def run(): """Run the structured output server.""" async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="structured-output-example", server_version="0.1.0", capabilities=server.get_capabilities( notification_options=NotificationOptions(), experimental_capabilities={}, ), ), ) if __name__ == "__main__": asyncio.run(run()) ``` ---------------------------------------- TITLE: Define Basic Tools DESCRIPTION: Demonstrates how to define tools for LLMs using the `@mcp.tool()` decorator from the `fastmcp` module. It shows simple examples of tools that perform computations, like adding numbers or fetching weather data, highlighting function signatures and return types. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_8 LANGUAGE: python CODE: ``` from mcp.server.fastmcp import FastMCP mcp = FastMCP(name="Tool Example") @mcp.tool() def sum(a: int, b: int) -> int: """Add two numbers together.""" return a + b @mcp.tool() def get_weather(city: str, unit: str = "celsius") -> str: """Get weather for a city.""" # This would normally call a weather API return f"Weather in {city}: 22degrees{unit[0].upper()}" ``` ---------------------------------------- TITLE: Python OAuth Client Example DESCRIPTION: This Python script demonstrates OAuth authentication for connecting to protected MCP servers using the SDK. It includes a custom in-memory token storage and handles the OAuth redirect and callback flow, culminating in listing available tools and resources via an authenticated client session. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_35 LANGUAGE: python CODE: ``` """ Before running, specify running MCP RS server URL. To spin up RS server locally, see examples/servers/simple-auth/README.md cd to the `examples/snippets` directory and run: uv run oauth-client """ import asyncio from urllib.parse import parse_qs, urlparse from pydantic import AnyUrl from mcp import ClientSession from mcp.client.auth import OAuthClientProvider, TokenStorage from mcp.client.streamable_http import streamablehttp_client from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken class InMemoryTokenStorage(TokenStorage): """Demo In-memory token storage implementation.""" def __init__(self): self.tokens: OAuthToken | None = None self.client_info: OAuthClientInformationFull | None = None async def get_tokens(self) -> OAuthToken | None: """Get stored tokens.""" return self.tokens async def set_tokens(self, tokens: OAuthToken) -> None: """Store tokens.""" self.tokens = tokens async def get_client_info(self) -> OAuthClientInformationFull | None: """Get stored client information.""" return self.client_info async def set_client_info(self, client_info: OAuthClientInformationFull) -> None: """Store client information.""" self.client_info = client_info async def handle_redirect(auth_url: str) -> None: print(f"Visit: {auth_url}") async def handle_callback() -> tuple[str, str | None]: callback_url = input("Paste callback URL: ") params = parse_qs(urlparse(callback_url).query) return params["code"][0], params.get("state", [None])[0] async def main(): """Run the OAuth client example.""" oauth_auth = OAuthClientProvider( server_url="http://localhost:8001", client_metadata=OAuthClientMetadata( client_name="Example MCP Client", redirect_uris=[AnyUrl("http://localhost:3000/callback")], grant_types=["authorization_code", "refresh_token"], response_types=["code"], scope="user", ), storage=InMemoryTokenStorage(), redirect_handler=handle_redirect, callback_handler=handle_callback, ) async with streamablehttp_client("http://localhost:8001/mcp", auth=oauth_auth) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() tools = await session.list_tools() print(f"Available tools: {[tool.name for tool in tools.tools]}") resources = await session.list_resources() print(f"Available resources: {[r.uri for r in resources.resources]}") def run(): asyncio.run(main()) if __name__ == "__main__": run() ``` ---------------------------------------- TITLE: Install MCP Python SDK with pip DESCRIPTION: Installs the MCP Python SDK and its CLI tools using pip. This command adds the 'mcp[cli]' package to your project's dependencies. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_1 LANGUAGE: bash CODE: ``` pip install "mcp[cli]" ``` ---------------------------------------- TITLE: Install MCP Python SDK with uv DESCRIPTION: Installs the MCP Python SDK and its CLI tools using the uv package manager. This command adds the 'mcp[cli]' package to your project's dependencies. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_0 LANGUAGE: bash CODE: ``` uv add "mcp[cli]" ``` ---------------------------------------- TITLE: MCP Development Server Commands DESCRIPTION: Provides commands for running the MCP development server using `uv` and the `mcp dev` utility. It covers basic server startup, adding dependencies, and mounting local code for development. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_20 LANGUAGE: bash CODE: ``` uv run mcp dev server.py # Add dependencies uv run mcp dev server.py --with pandas --with numpy # Mount local code uv run mcp dev server.py --with-editable . ``` ---------------------------------------- TITLE: Start MCP Resource Server (RS) with OAuth 2.0 Integration DESCRIPTION: These commands launch the Resource Server (MCP Server) which connects to the Authorization Server for token validation. It can be started with or without strict RFC 8707 resource validation, which is recommended for production environments. The server operates on port 8001. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-auth/README.md#_snippet_1 LANGUAGE: bash CODE: ``` cd examples/servers/simple-auth uv run mcp-simple-auth-rs --port=8001 --auth-server=http://localhost:9000 --transport=streamable-http ``` LANGUAGE: bash CODE: ``` cd examples/servers/simple-auth uv run mcp-simple-auth-rs --port=8001 --auth-server=http://localhost:9000 --transport=streamable-http --oauth-strict ``` ---------------------------------------- TITLE: Update README Snippets DESCRIPTION: Runs a script to update code snippets embedded within the README file, ensuring examples are current. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md#_snippet_5 LANGUAGE: bash CODE: ``` uv run scripts/update_readme_snippets.py ``` ---------------------------------------- TITLE: MCP Fetch Tool API Reference DESCRIPTION: Reference for the 'fetch' tool exposed by the MCP server, detailing its parameters and functionality. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-tool/README.md#_snippet_1 LANGUAGE: APIDOC CODE: ``` Tool: fetch Description: Fetches the content of a given URL. Parameters: url (string, required): The URL of the website to fetch. Returns: The content of the fetched URL (type depends on implementation, likely string or bytes). ``` ---------------------------------------- TITLE: Run MCP Development Tools with uv DESCRIPTION: Executes the MCP command-line interface tools using uv for development. This command is used to run the MCP CLI after installation. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_2 LANGUAGE: bash CODE: ``` uv run mcp ``` ---------------------------------------- TITLE: Create a FastMCP Server with Tools and Resources DESCRIPTION: Demonstrates building a simple MCP server using FastMCP. It includes an addition tool and a dynamic greeting resource, showcasing basic server functionality and resource definition. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_3 LANGUAGE: python CODE: ``` """ FastMCP quickstart example. cd to the `examples/snippets/clients` directory and run: uv run server fastmcp_quickstart stdio """ from mcp.server.fastmcp import FastMCP # Create an MCP server mcp = FastMCP("Demo") # Add an addition tool @mcp.tool() def add(a: int, b: int) -> int: """Add two numbers""" return a + b # Add a dynamic greeting resource @mcp.resource("greeting://{name}") def get_greeting(name: str) -> str: """Get a personalized greeting""" return f"Hello, {name}!" ``` ---------------------------------------- TITLE: uv Package Management Commands DESCRIPTION: These commands demonstrate how to manage Python packages using `uv`, the recommended package manager for this project. They cover adding new packages, running project-specific tools, and upgrading existing packages, while explicitly forbidding `pip` usage and `@latest` syntax. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/CLAUDE.md#_snippet_0 LANGUAGE: bash CODE: ``` uv add package ``` LANGUAGE: bash CODE: ``` uv run tool ``` LANGUAGE: bash CODE: ``` uv add --dev package --upgrade-package package ``` ---------------------------------------- TITLE: Expose Data with MCP Resources DESCRIPTION: Shows how to expose data to LLM applications using MCP Resources. Resources are defined with decorators and can be accessed via specific URIs, similar to GET endpoints. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_7 LANGUAGE: python CODE: ``` from mcp.server.fastmcp import FastMCP mcp = FastMCP(name="Resource Example") @mcp.resource("file://documents/{name}") def read_document(name: str) -> str: """Read a document by name.""" # This would normally read from disk return f"Content of {name}" @mcp.resource("config://settings") def get_settings() -> str: """Get application settings.""" return """{ "theme": "dark", "language": "en", "debug": false }""" ``` ---------------------------------------- TITLE: Mount SSE Servers to ASGI Applications DESCRIPTION: Demonstrates mounting SSE servers to existing ASGI applications using Starlette. Covers default mounting, dynamic mounting via Host, and configuring mount paths via settings or directly to the `sse_app` method for integrating multiple MCP servers. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/README.md#_snippet_25 LANGUAGE: python CODE: ``` from starlette.applications import Starlette from starlette.routing import Mount, Host from mcp.server.fastmcp import FastMCP mcp = FastMCP("My App") # Mount the SSE server to the existing ASGI server app = Starlette( routes=[ Mount('/', app=mcp.sse_app()), ] ) # or dynamically mount as host app.router.routes.append(Host('mcp.acme.corp', app=mcp.sse_app())) ``` LANGUAGE: python CODE: ``` from starlette.applications import Starlette from starlette.routing import Mount from mcp.server.fastmcp import FastMCP # Create multiple MCP servers github_mcp = FastMCP("GitHub API") browser_mcp = FastMCP("Browser") curl_mcp = FastMCP("Curl") search_mcp = FastMCP("Search") # Method 1: Configure mount paths via settings (recommended for persistent configuration) github_mcp.settings.mount_path = "/github" browser_mcp.settings.mount_path = "/browser" # Method 2: Pass mount path directly to sse_app (preferred for ad-hoc mounting) # This approach doesn't modify the server's settings permanently # Create Starlette app with multiple mounted servers app = Starlette( routes=[ # Using settings-based configuration Mount("/github", app=github_mcp.sse_app()), Mount("/browser", app=browser_mcp.sse_app()), # Using direct mount path parameter Mount("/curl", app=curl_mcp.sse_app("/curl")), Mount("/search", app=search_mcp.sse_app("/search")), ] ) # Method 3: For direct execution, you can also pass the mount path to run() if __name__ == "__main__": search_mcp.run(transport="sse", mount_path="/search") ``` ---------------------------------------- TITLE: Test Client with Legacy MCP Server DESCRIPTION: This command runs the client against the legacy MCP server. The client is designed to first attempt RFC 9728 discovery, and upon failure (as legacy servers don't support it), it falls back to direct OAuth discovery with the legacy server acting as its own Authorization Server, ensuring compatibility. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/servers/simple-auth/README.md#_snippet_5 LANGUAGE: bash CODE: ``` cd examples/clients/simple-auth-client MCP_SERVER_PORT=8002 MCP_TRANSPORT_TYPE=streamable_http uv run mcp-simple-auth-client ``` ---------------------------------------- TITLE: Run All Pre-commit Hooks DESCRIPTION: Manually runs all configured pre-commit hooks across all files in the repository for a comprehensive check. SOURCE: https://github.com/modelcontextprotocol/python-sdk/blob/main/CONTRIBUTING.md#_snippet_6 LANGUAGE: bash CODE: ``` pre-commit run --all-files ```