[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-2342":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":23,"hasPages":25,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":27,"readmeContent":28,"aiSummary":29,"trendingCount":16,"starSnapshotCount":16,"syncStatus":30,"lastSyncTime":31,"discoverSource":32},2342,"python-sdk","modelcontextprotocol\u002Fpython-sdk","modelcontextprotocol","The official Python SDK for Model Context Protocol servers and clients","https:\u002F\u002Fmodelcontextprotocol.github.io\u002Fpython-sdk\u002F",null,"Python",23290,3530,172,267,0,7,55,329,37,114,"MIT License",false,"main",true,[],"2026-06-12 04:00:14","# MCP Python SDK\n\n\u003Cdiv align=\"center\">\n\n\u003Cstrong>Python implementation of the Model Context Protocol (MCP)\u003C\u002Fstrong>\n\n[![PyPI][pypi-badge]][pypi-url]\n[![MIT licensed][mit-badge]][mit-url]\n[![Python Version][python-badge]][python-url]\n[![Documentation][docs-badge]][docs-url]\n[![Protocol][protocol-badge]][protocol-url]\n[![Specification][spec-badge]][spec-url]\n\n\u003C\u002Fdiv>\n\n\u003C!-- TODO(v2): Replace this README with README.v2.md when v2 is released -->\n\n> [!NOTE]\n> **This README documents v1.x of the MCP Python SDK (the current stable release).**\n>\n> For v1.x code and documentation, see the [`v1.x` branch](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Ftree\u002Fv1.x).\n> For the upcoming v2 documentation (pre-alpha, in development on `main`), see [`README.v2.md`](README.v2.md).\n\n\u003C!-- omit in toc -->\n## Table of Contents\n\n- [MCP Python SDK](#mcp-python-sdk)\n  - [Overview](#overview)\n  - [Installation](#installation)\n    - [Adding MCP to your python project](#adding-mcp-to-your-python-project)\n    - [Running the standalone MCP development tools](#running-the-standalone-mcp-development-tools)\n  - [Quickstart](#quickstart)\n  - [What is MCP?](#what-is-mcp)\n  - [Core Concepts](#core-concepts)\n    - [Server](#server)\n    - [Resources](#resources)\n    - [Tools](#tools)\n      - [Structured Output](#structured-output)\n    - [Prompts](#prompts)\n    - [Images](#images)\n    - [Context](#context)\n      - [Getting Context in Functions](#getting-context-in-functions)\n      - [Context Properties and Methods](#context-properties-and-methods)\n    - [Completions](#completions)\n    - [Elicitation](#elicitation)\n    - [Sampling](#sampling)\n    - [Logging and Notifications](#logging-and-notifications)\n    - [Authentication](#authentication)\n    - [FastMCP Properties](#fastmcp-properties)\n    - [Session Properties and Methods](#session-properties-and-methods)\n    - [Request Context Properties](#request-context-properties)\n  - [Running Your Server](#running-your-server)\n    - [Development Mode](#development-mode)\n    - [Claude Desktop Integration](#claude-desktop-integration)\n    - [Direct Execution](#direct-execution)\n    - [Streamable HTTP Transport](#streamable-http-transport)\n      - [CORS Configuration for Browser-Based Clients](#cors-configuration-for-browser-based-clients)\n    - [Mounting to an Existing ASGI Server](#mounting-to-an-existing-asgi-server)\n      - [StreamableHTTP servers](#streamablehttp-servers)\n        - [Basic mounting](#basic-mounting)\n        - [Host-based routing](#host-based-routing)\n        - [Multiple servers with path configuration](#multiple-servers-with-path-configuration)\n        - [Path configuration at initialization](#path-configuration-at-initialization)\n      - [SSE servers](#sse-servers)\n  - [Advanced Usage](#advanced-usage)\n    - [Low-Level Server](#low-level-server)\n      - [Structured Output Support](#structured-output-support)\n    - [Pagination (Advanced)](#pagination-advanced)\n    - [Writing MCP Clients](#writing-mcp-clients)\n    - [Client Display Utilities](#client-display-utilities)\n    - [OAuth Authentication for Clients](#oauth-authentication-for-clients)\n    - [Parsing Tool Results](#parsing-tool-results)\n    - [MCP Primitives](#mcp-primitives)\n    - [Server Capabilities](#server-capabilities)\n  - [Documentation](#documentation)\n  - [Contributing](#contributing)\n  - [License](#license)\n\n[pypi-badge]: https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fv\u002Fmcp.svg\n[pypi-url]: https:\u002F\u002Fpypi.org\u002Fproject\u002Fmcp\u002F\n[mit-badge]: https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fl\u002Fmcp.svg\n[mit-url]: https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002FLICENSE\n[python-badge]: https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fpyversions\u002Fmcp.svg\n[python-url]: https:\u002F\u002Fwww.python.org\u002Fdownloads\u002F\n[docs-badge]: https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdocs-python--sdk-blue.svg\n[docs-url]: https:\u002F\u002Fmodelcontextprotocol.github.io\u002Fpython-sdk\u002F\n[protocol-badge]: https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fprotocol-modelcontextprotocol.io-blue.svg\n[protocol-url]: https:\u002F\u002Fmodelcontextprotocol.io\n[spec-badge]: https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fspec-spec.modelcontextprotocol.io-blue.svg\n[spec-url]: https:\u002F\u002Fmodelcontextprotocol.io\u002Fspecification\u002Flatest\n\n## Overview\n\nThe Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This Python SDK implements the full MCP specification, making it easy to:\n\n- Build MCP clients that can connect to any MCP server\n- Create MCP servers that expose resources, prompts and tools\n- Use standard transports like stdio, SSE, and Streamable HTTP\n- Handle all MCP protocol messages and lifecycle events\n\n## Installation\n\n### Adding MCP to your python project\n\nWe recommend using [uv](https:\u002F\u002Fdocs.astral.sh\u002Fuv\u002F) to manage your Python projects.\n\nIf you haven't created a uv-managed project yet, create one:\n\n   ```bash\n   uv init mcp-server-demo\n   cd mcp-server-demo\n   ```\n\n   Then add MCP to your project dependencies:\n\n   ```bash\n   uv add \"mcp[cli]\"\n   ```\n\nAlternatively, for projects using pip for dependencies:\n\n```bash\npip install \"mcp[cli]\"\n```\n\n### Running the standalone MCP development tools\n\nTo run the mcp command with uv:\n\n```bash\nuv run mcp\n```\n\n## Quickstart\n\nLet's create a simple MCP server that exposes a calculator tool and some data:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Ffastmcp_quickstart.py -->\n```python\n\"\"\"\nFastMCP quickstart example.\n\nRun from the repository root:\n    uv run examples\u002Fsnippets\u002Fservers\u002Ffastmcp_quickstart.py\n\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Create an MCP server\nmcp = FastMCP(\"Demo\", json_response=True)\n\n\n# Add an addition tool\n@mcp.tool()\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n\n\n# Add a dynamic greeting resource\n@mcp.resource(\"greeting:\u002F\u002F{name}\")\ndef get_greeting(name: str) -> str:\n    \"\"\"Get a personalized greeting\"\"\"\n    return f\"Hello, {name}!\"\n\n\n# Add a prompt\n@mcp.prompt()\ndef greet_user(name: str, style: str = \"friendly\") -> str:\n    \"\"\"Generate a greeting prompt\"\"\"\n    styles = {\n        \"friendly\": \"Please write a warm, friendly greeting\",\n        \"formal\": \"Please write a formal, professional greeting\",\n        \"casual\": \"Please write a casual, relaxed greeting\",\n    }\n\n    return f\"{styles.get(style, styles['friendly'])} for someone named {name}.\"\n\n\n# Run with streamable HTTP transport\nif __name__ == \"__main__\":\n    mcp.run(transport=\"streamable-http\")\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Ffastmcp_quickstart.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Ffastmcp_quickstart.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nYou can install this server in [Claude Code](https:\u002F\u002Fdocs.claude.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fmcp) and interact with it right away. First, run the server:\n\n```bash\nuv run --with mcp examples\u002Fsnippets\u002Fservers\u002Ffastmcp_quickstart.py\n```\n\nThen add it to Claude Code:\n\n```bash\nclaude mcp add --transport http my-server http:\u002F\u002Flocalhost:8000\u002Fmcp\n```\n\nAlternatively, you can test it with the MCP Inspector. Start the server as above, then in a separate terminal:\n\n```bash\nnpx -y @modelcontextprotocol\u002Finspector\n```\n\nIn the inspector UI, connect to `http:\u002F\u002Flocalhost:8000\u002Fmcp`.\n\n## What is MCP?\n\nThe [Model Context Protocol (MCP)](https:\u002F\u002Fmodelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can:\n\n- Expose data through **Resources** (think of these sort of like GET endpoints; they are used to load information into the LLM's context)\n- Provide functionality through **Tools** (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect)\n- Define interaction patterns through **Prompts** (reusable templates for LLM interactions)\n- And more!\n\n## Core Concepts\n\n### Server\n\nThe FastMCP server is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Flifespan_example.py -->\n```python\n\"\"\"Example showing lifespan support for startup\u002Fshutdown with strong typing.\"\"\"\n\nfrom collections.abc import AsyncIterator\nfrom contextlib import asynccontextmanager\nfrom dataclasses import dataclass\n\nfrom mcp.server.fastmcp import Context, FastMCP\nfrom mcp.server.session import ServerSession\n\n\n# Mock database class for example\nclass Database:\n    \"\"\"Mock database class for example.\"\"\"\n\n    @classmethod\n    async def connect(cls) -> \"Database\":\n        \"\"\"Connect to database.\"\"\"\n        return cls()\n\n    async def disconnect(self) -> None:\n        \"\"\"Disconnect from database.\"\"\"\n        pass\n\n    def query(self) -> str:\n        \"\"\"Execute a query.\"\"\"\n        return \"Query result\"\n\n\n@dataclass\nclass AppContext:\n    \"\"\"Application context with typed dependencies.\"\"\"\n\n    db: Database\n\n\n@asynccontextmanager\nasync def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:\n    \"\"\"Manage application lifecycle with type-safe context.\"\"\"\n    # Initialize on startup\n    db = await Database.connect()\n    try:\n        yield AppContext(db=db)\n    finally:\n        # Cleanup on shutdown\n        await db.disconnect()\n\n\n# Pass lifespan to server\nmcp = FastMCP(\"My App\", lifespan=app_lifespan)\n\n\n# Access type-safe lifespan context in tools\n@mcp.tool()\ndef query_db(ctx: Context[ServerSession, AppContext]) -> str:\n    \"\"\"Tool that uses initialized resources.\"\"\"\n    db = ctx.request_context.lifespan_context.db\n    return db.query()\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Flifespan_example.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Flifespan_example.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Resources\n\nResources are how you expose data to LLMs. They're similar to GET endpoints in a REST API - they provide data but shouldn't perform significant computation or have side effects:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fbasic_resource.py -->\n```python\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(name=\"Resource Example\")\n\n\n@mcp.resource(\"file:\u002F\u002Fdocuments\u002F{name}\")\ndef read_document(name: str) -> str:\n    \"\"\"Read a document by name.\"\"\"\n    # This would normally read from disk\n    return f\"Content of {name}\"\n\n\n@mcp.resource(\"config:\u002F\u002Fsettings\")\ndef get_settings() -> str:\n    \"\"\"Get application settings.\"\"\"\n    return \"\"\"{\n  \"theme\": \"dark\",\n  \"language\": \"en\",\n  \"debug\": false\n}\"\"\"\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fbasic_resource.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fbasic_resource.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Tools\n\nTools let LLMs take actions through your server. Unlike resources, tools are expected to perform computation and have side effects:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fbasic_tool.py -->\n```python\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(name=\"Tool Example\")\n\n\n@mcp.tool()\ndef sum(a: int, b: int) -> int:\n    \"\"\"Add two numbers together.\"\"\"\n    return a + b\n\n\n@mcp.tool()\ndef get_weather(city: str, unit: str = \"celsius\") -> str:\n    \"\"\"Get weather for a city.\"\"\"\n    # This would normally call a weather API\n    return f\"Weather in {city}: 22degrees{unit[0].upper()}\"\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fbasic_tool.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fbasic_tool.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nTools can optionally receive a Context object by including a parameter with the `Context` type annotation. This context is automatically injected by the FastMCP framework and provides access to MCP capabilities:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Ftool_progress.py -->\n```python\nfrom mcp.server.fastmcp import Context, FastMCP\nfrom mcp.server.session import ServerSession\n\nmcp = FastMCP(name=\"Progress Example\")\n\n\n@mcp.tool()\nasync def long_running_task(task_name: str, ctx: Context[ServerSession, None], steps: int = 5) -> str:\n    \"\"\"Execute a task with progress updates.\"\"\"\n    await ctx.info(f\"Starting: {task_name}\")\n\n    for i in range(steps):\n        progress = (i + 1) \u002F steps\n        await ctx.report_progress(\n            progress=progress,\n            total=1.0,\n            message=f\"Step {i + 1}\u002F{steps}\",\n        )\n        await ctx.debug(f\"Completed step {i + 1}\")\n\n    return f\"Task '{task_name}' completed\"\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Ftool_progress.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Ftool_progress.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n#### Structured Output\n\nTools will return structured results by default, if their return type\nannotation is compatible. Otherwise, they will return unstructured results.\n\nStructured output supports these return types:\n\n- Pydantic models (BaseModel subclasses)\n- TypedDicts\n- Dataclasses and other classes with type hints\n- `dict[str, T]` (where T is any JSON-serializable type)\n- Primitive types (str, int, float, bool, bytes, None) - wrapped in `{\"result\": value}`\n- Generic types (list, tuple, Union, Optional, etc.) - wrapped in `{\"result\": value}`\n\nClasses without type hints cannot be serialized for structured output. Only\nclasses with properly annotated attributes will be converted to Pydantic models\nfor schema generation and validation.\n\nStructured results are automatically validated against the output schema\ngenerated from the annotation. This ensures the tool returns well-typed,\nvalidated data that clients can easily process.\n\n**Note:** For backward compatibility, unstructured results are also\nreturned. Unstructured results are provided for backward compatibility\nwith previous versions of the MCP specification, and are quirks-compatible\nwith previous versions of FastMCP in the current version of the SDK.\n\n**Note:** In cases where a tool function's return type annotation\ncauses the tool to be classified as structured _and this is undesirable_,\nthe  classification can be suppressed by passing `structured_output=False`\nto the `@tool` decorator.\n\n##### Advanced: Direct CallToolResult\n\nFor full control over tool responses including the `_meta` field (for passing data to client applications without exposing it to the model), you can return `CallToolResult` directly:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fdirect_call_tool_result.py -->\n```python\n\"\"\"Example showing direct CallToolResult return for advanced control.\"\"\"\n\nfrom typing import Annotated\n\nfrom pydantic import BaseModel\n\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp.types import CallToolResult, TextContent\n\nmcp = FastMCP(\"CallToolResult Example\")\n\n\nclass ValidationModel(BaseModel):\n    \"\"\"Model for validating structured output.\"\"\"\n\n    status: str\n    data: dict[str, int]\n\n\n@mcp.tool()\ndef advanced_tool() -> CallToolResult:\n    \"\"\"Return CallToolResult directly for full control including _meta field.\"\"\"\n    return CallToolResult(\n        content=[TextContent(type=\"text\", text=\"Response visible to the model\")],\n        _meta={\"hidden\": \"data for client applications only\"},\n    )\n\n\n@mcp.tool()\ndef validated_tool() -> Annotated[CallToolResult, ValidationModel]:\n    \"\"\"Return CallToolResult with structured output validation.\"\"\"\n    return CallToolResult(\n        content=[TextContent(type=\"text\", text=\"Validated response\")],\n        structuredContent={\"status\": \"success\", \"data\": {\"result\": 42}},\n        _meta={\"internal\": \"metadata\"},\n    )\n\n\n@mcp.tool()\ndef empty_result_tool() -> CallToolResult:\n    \"\"\"For empty results, return CallToolResult with empty content.\"\"\"\n    return CallToolResult(content=[])\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fdirect_call_tool_result.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fdirect_call_tool_result.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n**Important:** `CallToolResult` must always be returned (no `Optional` or `Union`). For empty results, use `CallToolResult(content=[])`. For optional simple types, use `str | None` without `CallToolResult`.\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstructured_output.py -->\n```python\n\"\"\"Example showing structured output with tools.\"\"\"\n\nfrom typing import TypedDict\n\nfrom pydantic import BaseModel, Field\n\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Structured Output Example\")\n\n\n# Using Pydantic models for rich structured data\nclass WeatherData(BaseModel):\n    \"\"\"Weather information structure.\"\"\"\n\n    temperature: float = Field(description=\"Temperature in Celsius\")\n    humidity: float = Field(description=\"Humidity percentage\")\n    condition: str\n    wind_speed: float\n\n\n@mcp.tool()\ndef get_weather(city: str) -> WeatherData:\n    \"\"\"Get weather for a city - returns structured data.\"\"\"\n    # Simulated weather data\n    return WeatherData(\n        temperature=22.5,\n        humidity=45.0,\n        condition=\"sunny\",\n        wind_speed=5.2,\n    )\n\n\n# Using TypedDict for simpler structures\nclass LocationInfo(TypedDict):\n    latitude: float\n    longitude: float\n    name: str\n\n\n@mcp.tool()\ndef get_location(address: str) -> LocationInfo:\n    \"\"\"Get location coordinates\"\"\"\n    return LocationInfo(latitude=51.5074, longitude=-0.1278, name=\"London, UK\")\n\n\n# Using dict[str, Any] for flexible schemas\n@mcp.tool()\ndef get_statistics(data_type: str) -> dict[str, float]:\n    \"\"\"Get various statistics\"\"\"\n    return {\"mean\": 42.5, \"median\": 40.0, \"std_dev\": 5.2}\n\n\n# Ordinary classes with type hints work for structured output\nclass UserProfile:\n    name: str\n    age: int\n    email: str | None = None\n\n    def __init__(self, name: str, age: int, email: str | None = None):\n        self.name = name\n        self.age = age\n        self.email = email\n\n\n@mcp.tool()\ndef get_user(user_id: str) -> UserProfile:\n    \"\"\"Get user profile - returns structured data\"\"\"\n    return UserProfile(name=\"Alice\", age=30, email=\"alice@example.com\")\n\n\n# Classes WITHOUT type hints cannot be used for structured output\nclass UntypedConfig:\n    def __init__(self, setting1, setting2):  # type: ignore[reportMissingParameterType]\n        self.setting1 = setting1\n        self.setting2 = setting2\n\n\n@mcp.tool()\ndef get_config() -> UntypedConfig:\n    \"\"\"This returns unstructured output - no schema generated\"\"\"\n    return UntypedConfig(\"value1\", \"value2\")\n\n\n# Lists and other types are wrapped automatically\n@mcp.tool()\ndef list_cities() -> list[str]:\n    \"\"\"Get a list of cities\"\"\"\n    return [\"London\", \"Paris\", \"Tokyo\"]\n    # Returns: {\"result\": [\"London\", \"Paris\", \"Tokyo\"]}\n\n\n@mcp.tool()\ndef get_temperature(city: str) -> float:\n    \"\"\"Get temperature as a simple float\"\"\"\n    return 22.5\n    # Returns: {\"result\": 22.5}\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstructured_output.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstructured_output.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Prompts\n\nPrompts are reusable templates that help LLMs interact with your server effectively:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fbasic_prompt.py -->\n```python\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp.server.fastmcp.prompts import base\n\nmcp = FastMCP(name=\"Prompt Example\")\n\n\n@mcp.prompt(title=\"Code Review\")\ndef review_code(code: str) -> str:\n    return f\"Please review this code:\\n\\n{code}\"\n\n\n@mcp.prompt(title=\"Debug Assistant\")\ndef debug_error(error: str) -> list[base.Message]:\n    return [\n        base.UserMessage(\"I'm seeing this error:\"),\n        base.UserMessage(error),\n        base.AssistantMessage(\"I'll help debug that. What have you tried so far?\"),\n    ]\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fbasic_prompt.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fbasic_prompt.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Icons\n\nMCP servers can provide icons for UI display. Icons can be added to the server implementation, tools, resources, and prompts:\n\n```python\nfrom mcp.server.fastmcp import FastMCP, Icon\n\n# Create an icon from a file path or URL\nicon = Icon(\n    src=\"icon.png\",\n    mimeType=\"image\u002Fpng\",\n    sizes=\"64x64\"\n)\n\n# Add icons to server\nmcp = FastMCP(\n    \"My Server\",\n    website_url=\"https:\u002F\u002Fexample.com\",\n    icons=[icon]\n)\n\n# Add icons to tools, resources, and prompts\n@mcp.tool(icons=[icon])\ndef my_tool():\n    \"\"\"Tool with an icon.\"\"\"\n    return \"result\"\n\n@mcp.resource(\"demo:\u002F\u002Fresource\", icons=[icon])\ndef my_resource():\n    \"\"\"Resource with an icon.\"\"\"\n    return \"content\"\n```\n\n_Full example: [examples\u002Ffastmcp\u002Ficons_demo.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Ffastmcp\u002Ficons_demo.py)_\n\n### Images\n\nFastMCP provides an `Image` class that automatically handles image data:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fimages.py -->\n```python\n\"\"\"Example showing image handling with FastMCP.\"\"\"\n\nfrom PIL import Image as PILImage\n\nfrom mcp.server.fastmcp import FastMCP, Image\n\nmcp = FastMCP(\"Image Example\")\n\n\n@mcp.tool()\ndef create_thumbnail(image_path: str) -> Image:\n    \"\"\"Create a thumbnail from an image\"\"\"\n    img = PILImage.open(image_path)\n    img.thumbnail((100, 100))\n    return Image(data=img.tobytes(), format=\"png\")\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fimages.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fimages.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Context\n\nThe Context object is automatically injected into tool and resource functions that request it via type hints. It provides access to MCP capabilities like logging, progress reporting, resource reading, user interaction, and request metadata.\n\n#### Getting Context in Functions\n\nTo use context in a tool or resource function, add a parameter with the `Context` type annotation:\n\n```python\nfrom mcp.server.fastmcp import Context, FastMCP\n\nmcp = FastMCP(name=\"Context Example\")\n\n\n@mcp.tool()\nasync def my_tool(x: int, ctx: Context) -> str:\n    \"\"\"Tool that uses context capabilities.\"\"\"\n    # The context parameter can have any name as long as it's type-annotated\n    return await process_with_context(x, ctx)\n```\n\n#### Context Properties and Methods\n\nThe Context object provides the following capabilities:\n\n- `ctx.request_id` - Unique ID for the current request\n- `ctx.client_id` - Client ID if available\n- `ctx.fastmcp` - Access to the FastMCP server instance (see [FastMCP Properties](#fastmcp-properties))\n- `ctx.session` - Access to the underlying session for advanced communication (see [Session Properties and Methods](#session-properties-and-methods))\n- `ctx.request_context` - Access to request-specific data and lifespan resources (see [Request Context Properties](#request-context-properties))\n- `await ctx.debug(message)` - Send debug log message\n- `await ctx.info(message)` - Send info log message  \n- `await ctx.warning(message)` - Send warning log message\n- `await ctx.error(message)` - Send error log message\n- `await ctx.log(level, message, logger_name=None)` - Send log with custom level\n- `await ctx.report_progress(progress, total=None, message=None)` - Report operation progress\n- `await ctx.read_resource(uri)` - Read a resource by URI\n- `await ctx.elicit(message, schema)` - Request additional information from user with validation\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Ftool_progress.py -->\n```python\nfrom mcp.server.fastmcp import Context, FastMCP\nfrom mcp.server.session import ServerSession\n\nmcp = FastMCP(name=\"Progress Example\")\n\n\n@mcp.tool()\nasync def long_running_task(task_name: str, ctx: Context[ServerSession, None], steps: int = 5) -> str:\n    \"\"\"Execute a task with progress updates.\"\"\"\n    await ctx.info(f\"Starting: {task_name}\")\n\n    for i in range(steps):\n        progress = (i + 1) \u002F steps\n        await ctx.report_progress(\n            progress=progress,\n            total=1.0,\n            message=f\"Step {i + 1}\u002F{steps}\",\n        )\n        await ctx.debug(f\"Completed step {i + 1}\")\n\n    return f\"Task '{task_name}' completed\"\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Ftool_progress.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Ftool_progress.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Completions\n\nMCP supports providing completion suggestions for prompt arguments and resource template parameters. With the context parameter, servers can provide completions based on previously resolved values:\n\nClient usage:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fclients\u002Fcompletion_client.py -->\n```python\n\"\"\"\ncd to the `examples\u002Fsnippets` directory and run:\n    uv run completion-client\n\"\"\"\n\nimport asyncio\nimport os\n\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\nfrom mcp.types import PromptReference, ResourceTemplateReference\n\n# Create server parameters for stdio connection\nserver_params = StdioServerParameters(\n    command=\"uv\",  # Using uv to run the server\n    args=[\"run\", \"server\", \"completion\", \"stdio\"],  # Server with completion support\n    env={\"UV_INDEX\": os.environ.get(\"UV_INDEX\", \"\")},\n)\n\n\nasync def run():\n    \"\"\"Run the completion client example.\"\"\"\n    async with stdio_client(server_params) as (read, write):\n        async with ClientSession(read, write) as session:\n            # Initialize the connection\n            await session.initialize()\n\n            # List available resource templates\n            templates = await session.list_resource_templates()\n            print(\"Available resource templates:\")\n            for template in templates.resourceTemplates:\n                print(f\"  - {template.uriTemplate}\")\n\n            # List available prompts\n            prompts = await session.list_prompts()\n            print(\"\\nAvailable prompts:\")\n            for prompt in prompts.prompts:\n                print(f\"  - {prompt.name}\")\n\n            # Complete resource template arguments\n            if templates.resourceTemplates:\n                template = templates.resourceTemplates[0]\n                print(f\"\\nCompleting arguments for resource template: {template.uriTemplate}\")\n\n                # Complete without context\n                result = await session.complete(\n                    ref=ResourceTemplateReference(type=\"ref\u002Fresource\", uri=template.uriTemplate),\n                    argument={\"name\": \"owner\", \"value\": \"model\"},\n                )\n                print(f\"Completions for 'owner' starting with 'model': {result.completion.values}\")\n\n                # Complete with context - repo suggestions based on owner\n                result = await session.complete(\n                    ref=ResourceTemplateReference(type=\"ref\u002Fresource\", uri=template.uriTemplate),\n                    argument={\"name\": \"repo\", \"value\": \"\"},\n                    context_arguments={\"owner\": \"modelcontextprotocol\"},\n                )\n                print(f\"Completions for 'repo' with owner='modelcontextprotocol': {result.completion.values}\")\n\n            # Complete prompt arguments\n            if prompts.prompts:\n                prompt_name = prompts.prompts[0].name\n                print(f\"\\nCompleting arguments for prompt: {prompt_name}\")\n\n                result = await session.complete(\n                    ref=PromptReference(type=\"ref\u002Fprompt\", name=prompt_name),\n                    argument={\"name\": \"style\", \"value\": \"\"},\n                )\n                print(f\"Completions for 'style' argument: {result.completion.values}\")\n\n\ndef main():\n    \"\"\"Entry point for the completion client.\"\"\"\n    asyncio.run(run())\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n_Full example: [examples\u002Fsnippets\u002Fclients\u002Fcompletion_client.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fclients\u002Fcompletion_client.py)_\n\u003C!-- \u002Fsnippet-source -->\n### Elicitation\n\nRequest additional information from users. This example shows an Elicitation during a Tool Call:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Felicitation.py -->\n```python\n\"\"\"Elicitation examples demonstrating form and URL mode elicitation.\n\nForm mode elicitation collects structured, non-sensitive data through a schema.\nURL mode elicitation directs users to external URLs for sensitive operations\nlike OAuth flows, credential collection, or payment processing.\n\"\"\"\n\nimport uuid\n\nfrom pydantic import BaseModel, Field\n\nfrom mcp.server.fastmcp import Context, FastMCP\nfrom mcp.server.session import ServerSession\nfrom mcp.shared.exceptions import UrlElicitationRequiredError\nfrom mcp.types import ElicitRequestURLParams\n\nmcp = FastMCP(name=\"Elicitation Example\")\n\n\nclass BookingPreferences(BaseModel):\n    \"\"\"Schema for collecting user preferences.\"\"\"\n\n    checkAlternative: bool = Field(description=\"Would you like to check another date?\")\n    alternativeDate: str = Field(\n        default=\"2024-12-26\",\n        description=\"Alternative date (YYYY-MM-DD)\",\n    )\n\n\n@mcp.tool()\nasync def book_table(date: str, time: str, party_size: int, ctx: Context[ServerSession, None]) -> str:\n    \"\"\"Book a table with date availability check.\n\n    This demonstrates form mode elicitation for collecting non-sensitive user input.\n    \"\"\"\n    # Check if date is available\n    if date == \"2024-12-25\":\n        # Date unavailable - ask user for alternative\n        result = await ctx.elicit(\n            message=(f\"No tables available for {party_size} on {date}. Would you like to try another date?\"),\n            schema=BookingPreferences,\n        )\n\n        if result.action == \"accept\" and result.data:\n            if result.data.checkAlternative:\n                return f\"[SUCCESS] Booked for {result.data.alternativeDate}\"\n            return \"[CANCELLED] No booking made\"\n        return \"[CANCELLED] Booking cancelled\"\n\n    # Date available\n    return f\"[SUCCESS] Booked for {date} at {time}\"\n\n\n@mcp.tool()\nasync def secure_payment(amount: float, ctx: Context[ServerSession, None]) -> str:\n    \"\"\"Process a secure payment requiring URL confirmation.\n\n    This demonstrates URL mode elicitation using ctx.elicit_url() for\n    operations that require out-of-band user interaction.\n    \"\"\"\n    elicitation_id = str(uuid.uuid4())\n\n    result = await ctx.elicit_url(\n        message=f\"Please confirm payment of ${amount:.2f}\",\n        url=f\"https:\u002F\u002Fpayments.example.com\u002Fconfirm?amount={amount}&id={elicitation_id}\",\n        elicitation_id=elicitation_id,\n    )\n\n    if result.action == \"accept\":\n        # In a real app, the payment confirmation would happen out-of-band\n        # and you'd verify the payment status from your backend\n        return f\"Payment of ${amount:.2f} initiated - check your browser to complete\"\n    elif result.action == \"decline\":\n        return \"Payment declined by user\"\n    return \"Payment cancelled\"\n\n\n@mcp.tool()\nasync def connect_service(service_name: str, ctx: Context[ServerSession, None]) -> str:\n    \"\"\"Connect to a third-party service requiring OAuth authorization.\n\n    This demonstrates the \"throw error\" pattern using UrlElicitationRequiredError.\n    Use this pattern when the tool cannot proceed without user authorization.\n    \"\"\"\n    elicitation_id = str(uuid.uuid4())\n\n    # Raise UrlElicitationRequiredError to signal that the client must complete\n    # a URL elicitation before this request can be processed.\n    # The MCP framework will convert this to a -32042 error response.\n    raise UrlElicitationRequiredError(\n        [\n            ElicitRequestURLParams(\n                mode=\"url\",\n                message=f\"Authorization required to connect to {service_name}\",\n                url=f\"https:\u002F\u002F{service_name}.example.com\u002Foauth\u002Fauthorize?elicit={elicitation_id}\",\n                elicitationId=elicitation_id,\n            )\n        ]\n    )\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Felicitation.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Felicitation.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nElicitation schemas support default values for all field types. Default values are automatically included in the JSON schema sent to clients, allowing them to pre-populate forms.\n\nThe `elicit()` method returns an `ElicitationResult` with:\n\n- `action`: \"accept\", \"decline\", or \"cancel\"\n- `data`: The validated response (only when accepted)\n- `validation_error`: Any validation error message\n\n### Sampling\n\nTools can interact with LLMs through sampling (generating text):\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fsampling.py -->\n```python\nfrom mcp.server.fastmcp import Context, FastMCP\nfrom mcp.server.session import ServerSession\nfrom mcp.types import SamplingMessage, TextContent\n\nmcp = FastMCP(name=\"Sampling Example\")\n\n\n@mcp.tool()\nasync def generate_poem(topic: str, ctx: Context[ServerSession, None]) -> str:\n    \"\"\"Generate a poem using LLM sampling.\"\"\"\n    prompt = f\"Write a short poem about {topic}\"\n\n    result = await ctx.session.create_message(\n        messages=[\n            SamplingMessage(\n                role=\"user\",\n                content=TextContent(type=\"text\", text=prompt),\n            )\n        ],\n        max_tokens=100,\n    )\n\n    # Since we're not passing tools param, result.content is single content\n    if result.content.type == \"text\":\n        return result.content.text\n    return str(result.content)\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fsampling.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fsampling.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Logging and Notifications\n\nTools can send logs and notifications through the context:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fnotifications.py -->\n```python\nfrom mcp.server.fastmcp import Context, FastMCP\nfrom mcp.server.session import ServerSession\n\nmcp = FastMCP(name=\"Notifications Example\")\n\n\n@mcp.tool()\nasync def process_data(data: str, ctx: Context[ServerSession, None]) -> str:\n    \"\"\"Process data with logging.\"\"\"\n    # Different log levels\n    await ctx.debug(f\"Debug: Processing '{data}'\")\n    await ctx.info(\"Info: Starting processing\")\n    await ctx.warning(\"Warning: This is experimental\")\n    await ctx.error(\"Error: (This is just a demo)\")\n\n    # Notify about resource changes\n    await ctx.session.send_resource_list_changed()\n\n    return f\"Processed: {data}\"\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fnotifications.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fnotifications.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n### Authentication\n\nAuthentication can be used by servers that want to expose tools accessing protected resources.\n\n`mcp.server.auth` implements OAuth 2.1 resource server functionality, where MCP servers act as Resource Servers (RS) that validate tokens issued by separate Authorization Servers (AS). This follows the [MCP authorization specification](https:\u002F\u002Fmodelcontextprotocol.io\u002Fspecification\u002F2025-06-18\u002Fbasic\u002Fauthorization) and implements RFC 9728 (Protected Resource Metadata) for AS discovery.\n\nMCP servers can use authentication by providing an implementation of the `TokenVerifier` protocol:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Foauth_server.py -->\n```python\n\"\"\"\nRun from the repository root:\n    uv run examples\u002Fsnippets\u002Fservers\u002Foauth_server.py\n\"\"\"\n\nfrom pydantic import AnyHttpUrl\n\nfrom mcp.server.auth.provider import AccessToken, TokenVerifier\nfrom mcp.server.auth.settings import AuthSettings\nfrom mcp.server.fastmcp import FastMCP\n\n\nclass SimpleTokenVerifier(TokenVerifier):\n    \"\"\"Simple token verifier for demonstration.\"\"\"\n\n    async def verify_token(self, token: str) -> AccessToken | None:\n        pass  # This is where you would implement actual token validation\n\n\n# Create FastMCP instance as a Resource Server\nmcp = FastMCP(\n    \"Weather Service\",\n    json_response=True,\n    # Token verifier for authentication\n    token_verifier=SimpleTokenVerifier(),\n    # Auth settings for RFC 9728 Protected Resource Metadata\n    auth=AuthSettings(\n        issuer_url=AnyHttpUrl(\"https:\u002F\u002Fauth.example.com\"),  # Authorization Server URL\n        resource_server_url=AnyHttpUrl(\"http:\u002F\u002Flocalhost:3001\"),  # This server's URL\n        required_scopes=[\"user\"],\n    ),\n)\n\n\n@mcp.tool()\nasync def get_weather(city: str = \"London\") -> dict[str, str]:\n    \"\"\"Get weather data for a city\"\"\"\n    return {\n        \"city\": city,\n        \"temperature\": \"22\",\n        \"condition\": \"Partly cloudy\",\n        \"humidity\": \"65%\",\n    }\n\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"streamable-http\")\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Foauth_server.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Foauth_server.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nFor a complete example with separate Authorization Server and Resource Server implementations, see [`examples\u002Fservers\u002Fsimple-auth\u002F`](examples\u002Fservers\u002Fsimple-auth\u002F).\n\n**Architecture:**\n\n- **Authorization Server (AS)**: Handles OAuth flows, user authentication, and token issuance\n- **Resource Server (RS)**: Your MCP server that validates tokens and serves protected resources\n- **Client**: Discovers AS through RFC 9728, obtains tokens, and uses them with the MCP server\n\nSee [TokenVerifier](src\u002Fmcp\u002Fserver\u002Fauth\u002Fprovider.py) for more details on implementing token validation.\n\n### FastMCP Properties\n\nThe FastMCP server instance accessible via `ctx.fastmcp` provides access to server configuration and metadata:\n\n- `ctx.fastmcp.name` - The server's name as defined during initialization\n- `ctx.fastmcp.instructions` - Server instructions\u002Fdescription provided to clients\n- `ctx.fastmcp.website_url` - Optional website URL for the server\n- `ctx.fastmcp.icons` - Optional list of icons for UI display\n- `ctx.fastmcp.settings` - Complete server configuration object containing:\n  - `debug` - Debug mode flag\n  - `log_level` - Current logging level\n  - `host` and `port` - Server network configuration\n  - `mount_path`, `sse_path`, `streamable_http_path` - Transport paths\n  - `stateless_http` - Whether the server operates in stateless mode\n  - And other configuration options\n\n```python\n@mcp.tool()\ndef server_info(ctx: Context) -> dict:\n    \"\"\"Get information about the current server.\"\"\"\n    return {\n        \"name\": ctx.fastmcp.name,\n        \"instructions\": ctx.fastmcp.instructions,\n        \"debug_mode\": ctx.fastmcp.settings.debug,\n        \"log_level\": ctx.fastmcp.settings.log_level,\n        \"host\": ctx.fastmcp.settings.host,\n        \"port\": ctx.fastmcp.settings.port,\n    }\n```\n\n### Session Properties and Methods\n\nThe session object accessible via `ctx.session` provides advanced control over client communication:\n\n- `ctx.session.client_params` - Client initialization parameters and declared capabilities\n- `await ctx.session.send_log_message(level, data, logger)` - Send log messages with full control\n- `await ctx.session.create_message(messages, max_tokens)` - Request LLM sampling\u002Fcompletion\n- `await ctx.session.send_progress_notification(token, progress, total, message)` - Direct progress updates\n- `await ctx.session.send_resource_updated(uri)` - Notify clients that a specific resource changed\n- `await ctx.session.send_resource_list_changed()` - Notify clients that the resource list changed\n- `await ctx.session.send_tool_list_changed()` - Notify clients that the tool list changed\n- `await ctx.session.send_prompt_list_changed()` - Notify clients that the prompt list changed\n\n```python\n@mcp.tool()\nasync def notify_data_update(resource_uri: str, ctx: Context) -> str:\n    \"\"\"Update data and notify clients of the change.\"\"\"\n    # Perform data update logic here\n    \n    # Notify clients that this specific resource changed\n    await ctx.session.send_resource_updated(AnyUrl(resource_uri))\n    \n    # If this affects the overall resource list, notify about that too\n    await ctx.session.send_resource_list_changed()\n    \n    return f\"Updated {resource_uri} and notified clients\"\n```\n\n### Request Context Properties\n\nThe request context accessible via `ctx.request_context` contains request-specific information and resources:\n\n- `ctx.request_context.lifespan_context` - Access to resources initialized during server startup\n  - Database connections, configuration objects, shared services\n  - Type-safe access to resources defined in your server's lifespan function\n- `ctx.request_context.meta` - Request metadata from the client including:\n  - `progressToken` - Token for progress notifications\n  - Other client-provided metadata\n- `ctx.request_context.request` - The original MCP request object for advanced processing\n- `ctx.request_context.request_id` - Unique identifier for this request\n\n```python\n# Example with typed lifespan context\n@dataclass\nclass AppContext:\n    db: Database\n    config: AppConfig\n\n@mcp.tool()\ndef query_with_config(query: str, ctx: Context) -> str:\n    \"\"\"Execute a query using shared database and configuration.\"\"\"\n    # Access typed lifespan context\n    app_ctx: AppContext = ctx.request_context.lifespan_context\n    \n    # Use shared resources\n    connection = app_ctx.db\n    settings = app_ctx.config\n    \n    # Execute query with configuration\n    result = connection.execute(query, timeout=settings.query_timeout)\n    return str(result)\n```\n\n_Full lifespan example: [examples\u002Fsnippets\u002Fservers\u002Flifespan_example.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Flifespan_example.py)_\n\n## Running Your Server\n\n### Development Mode\n\nThe fastest way to test and debug your server is with the MCP Inspector:\n\n```bash\nuv run mcp dev server.py\n\n# Add dependencies\nuv run mcp dev server.py --with pandas --with numpy\n\n# Mount local code\nuv run mcp dev server.py --with-editable .\n```\n\n### Claude Desktop Integration\n\nOnce your server is ready, install it in Claude Desktop:\n\n```bash\nuv run mcp install server.py\n\n# Custom name\nuv run mcp install server.py --name \"My Analytics Server\"\n\n# Environment variables\nuv run mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres:\u002F\u002F...\nuv run mcp install server.py -f .env\n```\n\n### Direct Execution\n\nFor advanced scenarios like custom deployments:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fdirect_execution.py -->\n```python\n\"\"\"Example showing direct execution of an MCP server.\n\nThis is the simplest way to run an MCP server directly.\ncd to the `examples\u002Fsnippets` directory and run:\n    uv run direct-execution-server\n    or\n    python servers\u002Fdirect_execution.py\n\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"My App\")\n\n\n@mcp.tool()\ndef hello(name: str = \"World\") -> str:\n    \"\"\"Say hello to someone.\"\"\"\n    return f\"Hello, {name}!\"\n\n\ndef main():\n    \"\"\"Entry point for the direct execution server.\"\"\"\n    mcp.run()\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fdirect_execution.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fdirect_execution.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nRun it with:\n\n```bash\npython servers\u002Fdirect_execution.py\n# or\nuv run mcp run servers\u002Fdirect_execution.py\n```\n\nNote that `uv run mcp run` or `uv run mcp dev` only supports server using FastMCP and not the low-level server variant.\n\n### Streamable HTTP Transport\n\n> **Note**: Streamable HTTP transport is the recommended transport for production deployments. Use `stateless_http=True` and `json_response=True` for optimal scalability.\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstreamable_config.py -->\n```python\n\"\"\"\nRun from the repository root:\n    uv run examples\u002Fsnippets\u002Fservers\u002Fstreamable_config.py\n\"\"\"\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Stateless server with JSON responses (recommended)\nmcp = FastMCP(\"StatelessServer\", stateless_http=True, json_response=True)\n\n# Other configuration options:\n# Stateless server with SSE streaming responses\n# mcp = FastMCP(\"StatelessServer\", stateless_http=True)\n\n# Stateful server with session persistence\n# mcp = FastMCP(\"StatefulServer\")\n\n\n# Add a simple tool to demonstrate the server\n@mcp.tool()\ndef greet(name: str = \"World\") -> str:\n    \"\"\"Greet someone by name.\"\"\"\n    return f\"Hello, {name}!\"\n\n\n# Run server with streamable_http transport\nif __name__ == \"__main__\":\n    mcp.run(transport=\"streamable-http\")\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstreamable_config.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstreamable_config.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nYou can mount multiple FastMCP servers in a Starlette application:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstreamable_starlette_mount.py -->\n```python\n\"\"\"\nRun from the repository root:\n    uvicorn examples.snippets.servers.streamable_starlette_mount:app --reload\n\"\"\"\n\nimport contextlib\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Create the Echo server\necho_mcp = FastMCP(name=\"EchoServer\", stateless_http=True, json_response=True)\n\n\n@echo_mcp.tool()\ndef echo(message: str) -> str:\n    \"\"\"A simple echo tool\"\"\"\n    return f\"Echo: {message}\"\n\n\n# Create the Math server\nmath_mcp = FastMCP(name=\"MathServer\", stateless_http=True, json_response=True)\n\n\n@math_mcp.tool()\ndef add_two(n: int) -> int:\n    \"\"\"Tool to add two to the input\"\"\"\n    return n + 2\n\n\n# Create a combined lifespan to manage both session managers\n@contextlib.asynccontextmanager\nasync def lifespan(app: Starlette):\n    async with contextlib.AsyncExitStack() as stack:\n        await stack.enter_async_context(echo_mcp.session_manager.run())\n        await stack.enter_async_context(math_mcp.session_manager.run())\n        yield\n\n\n# Create the Starlette app and mount the MCP servers\napp = Starlette(\n    routes=[\n        Mount(\"\u002Fecho\", echo_mcp.streamable_http_app()),\n        Mount(\"\u002Fmath\", math_mcp.streamable_http_app()),\n    ],\n    lifespan=lifespan,\n)\n\n# Note: Clients connect to http:\u002F\u002Flocalhost:8000\u002Fecho\u002Fmcp and http:\u002F\u002Flocalhost:8000\u002Fmath\u002Fmcp\n# To mount at the root of each path (e.g., \u002Fecho instead of \u002Fecho\u002Fmcp):\n# echo_mcp.settings.streamable_http_path = \"\u002F\"\n# math_mcp.settings.streamable_http_path = \"\u002F\"\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstreamable_starlette_mount.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstreamable_starlette_mount.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nFor low level server with Streamable HTTP implementations, see:\n\n- Stateful server: [`examples\u002Fservers\u002Fsimple-streamablehttp\u002F`](examples\u002Fservers\u002Fsimple-streamablehttp\u002F)\n- Stateless server: [`examples\u002Fservers\u002Fsimple-streamablehttp-stateless\u002F`](examples\u002Fservers\u002Fsimple-streamablehttp-stateless\u002F)\n\nThe streamable HTTP transport supports:\n\n- Stateful and stateless operation modes\n- Resumability with event stores\n- JSON or SSE response formats\n- Better scalability for multi-node deployments\n\n#### CORS Configuration for Browser-Based Clients\n\nIf you'd like your server to be accessible by browser-based MCP clients, you'll need to configure CORS headers. The `Mcp-Session-Id` header must be exposed for browser clients to access it:\n\n```python\nfrom starlette.applications import Starlette\nfrom starlette.middleware.cors import CORSMiddleware\n\n# Create your Starlette app first\nstarlette_app = Starlette(routes=[...])\n\n# Then wrap it with CORS middleware\nstarlette_app = CORSMiddleware(\n    starlette_app,\n    allow_origins=[\"*\"],  # Configure appropriately for production\n    allow_methods=[\"GET\", \"POST\", \"DELETE\"],  # MCP streamable HTTP methods\n    expose_headers=[\"Mcp-Session-Id\"],\n)\n```\n\nThis configuration is necessary because:\n\n- The MCP streamable HTTP transport uses the `Mcp-Session-Id` header for session management\n- Browsers restrict access to response headers unless explicitly exposed via CORS\n- Without this configuration, browser-based clients won't be able to read the session ID from initialization responses\n\n### Mounting to an Existing ASGI Server\n\nBy default, SSE servers are mounted at `\u002Fsse` and Streamable HTTP servers are mounted at `\u002Fmcp`. You can customize these paths using the methods described below.\n\nFor more information on mounting applications in Starlette, see the [Starlette documentation](https:\u002F\u002Fwww.starlette.io\u002Frouting\u002F#submounting-routes).\n\n#### StreamableHTTP servers\n\nYou can mount the StreamableHTTP server to an existing ASGI server using the `streamable_http_app` method. This allows you to integrate the StreamableHTTP server with other ASGI applications.\n\n##### Basic mounting\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_basic_mounting.py -->\n```python\n\"\"\"\nBasic example showing how to mount StreamableHTTP server in Starlette.\n\nRun from the repository root:\n    uvicorn examples.snippets.servers.streamable_http_basic_mounting:app --reload\n\"\"\"\n\nimport contextlib\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Create MCP server\nmcp = FastMCP(\"My App\", json_response=True)\n\n\n@mcp.tool()\ndef hello() -> str:\n    \"\"\"A simple hello tool\"\"\"\n    return \"Hello from MCP!\"\n\n\n# Create a lifespan context manager to run the session manager\n@contextlib.asynccontextmanager\nasync def lifespan(app: Starlette):\n    async with mcp.session_manager.run():\n        yield\n\n\n# Mount the StreamableHTTP server to the existing ASGI server\napp = Starlette(\n    routes=[\n        Mount(\"\u002F\", app=mcp.streamable_http_app()),\n    ],\n    lifespan=lifespan,\n)\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_basic_mounting.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstreamable_http_basic_mounting.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n##### Host-based routing\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_host_mounting.py -->\n```python\n\"\"\"\nExample showing how to mount StreamableHTTP server using Host-based routing.\n\nRun from the repository root:\n    uvicorn examples.snippets.servers.streamable_http_host_mounting:app --reload\n\"\"\"\n\nimport contextlib\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Host\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Create MCP server\nmcp = FastMCP(\"MCP Host App\", json_response=True)\n\n\n@mcp.tool()\ndef domain_info() -> str:\n    \"\"\"Get domain-specific information\"\"\"\n    return \"This is served from mcp.acme.corp\"\n\n\n# Create a lifespan context manager to run the session manager\n@contextlib.asynccontextmanager\nasync def lifespan(app: Starlette):\n    async with mcp.session_manager.run():\n        yield\n\n\n# Mount using Host-based routing\napp = Starlette(\n    routes=[\n        Host(\"mcp.acme.corp\", app=mcp.streamable_http_app()),\n    ],\n    lifespan=lifespan,\n)\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_host_mounting.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstreamable_http_host_mounting.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n##### Multiple servers with path configuration\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_multiple_servers.py -->\n```python\n\"\"\"\nExample showing how to mount multiple StreamableHTTP servers with path configuration.\n\nRun from the repository root:\n    uvicorn examples.snippets.servers.streamable_http_multiple_servers:app --reload\n\"\"\"\n\nimport contextlib\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Create multiple MCP servers\napi_mcp = FastMCP(\"API Server\", json_response=True)\nchat_mcp = FastMCP(\"Chat Server\", json_response=True)\n\n\n@api_mcp.tool()\ndef api_status() -> str:\n    \"\"\"Get API status\"\"\"\n    return \"API is running\"\n\n\n@chat_mcp.tool()\ndef send_message(message: str) -> str:\n    \"\"\"Send a chat message\"\"\"\n    return f\"Message sent: {message}\"\n\n\n# Configure servers to mount at the root of each path\n# This means endpoints will be at \u002Fapi and \u002Fchat instead of \u002Fapi\u002Fmcp and \u002Fchat\u002Fmcp\napi_mcp.settings.streamable_http_path = \"\u002F\"\nchat_mcp.settings.streamable_http_path = \"\u002F\"\n\n\n# Create a combined lifespan to manage both session managers\n@contextlib.asynccontextmanager\nasync def lifespan(app: Starlette):\n    async with contextlib.AsyncExitStack() as stack:\n        await stack.enter_async_context(api_mcp.session_manager.run())\n        await stack.enter_async_context(chat_mcp.session_manager.run())\n        yield\n\n\n# Mount the servers\napp = Starlette(\n    routes=[\n        Mount(\"\u002Fapi\", app=api_mcp.streamable_http_app()),\n        Mount(\"\u002Fchat\", app=chat_mcp.streamable_http_app()),\n    ],\n    lifespan=lifespan,\n)\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_multiple_servers.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstreamable_http_multiple_servers.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n##### Path configuration at initialization\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_path_config.py -->\n```python\n\"\"\"\nExample showing path configuration during FastMCP initialization.\n\nRun from the repository root:\n    uvicorn examples.snippets.servers.streamable_http_path_config:app --reload\n\"\"\"\n\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\n\nfrom mcp.server.fastmcp import FastMCP\n\n# Configure streamable_http_path during initialization\n# This server will mount at the root of wherever it's mounted\nmcp_at_root = FastMCP(\n    \"My Server\",\n    json_response=True,\n    streamable_http_path=\"\u002F\",\n)\n\n\n@mcp_at_root.tool()\ndef process_data(data: str) -> str:\n    \"\"\"Process some data\"\"\"\n    return f\"Processed: {data}\"\n\n\n# Mount at \u002Fprocess - endpoints will be at \u002Fprocess instead of \u002Fprocess\u002Fmcp\napp = Starlette(\n    routes=[\n        Mount(\"\u002Fprocess\", app=mcp_at_root.streamable_http_app()),\n    ]\n)\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Fstreamable_http_path_config.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Fstreamable_http_path_config.py)_\n\u003C!-- \u002Fsnippet-source -->\n\n#### SSE servers\n\n> **Note**: SSE transport is being superseded by [Streamable HTTP transport](https:\u002F\u002Fmodelcontextprotocol.io\u002Fspecification\u002F2025-03-26\u002Fbasic\u002Ftransports#streamable-http).\n\nYou can mount the SSE server to an existing ASGI server using the `sse_app` method. This allows you to integrate the SSE server with other ASGI applications.\n\n```python\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount, Host\nfrom mcp.server.fastmcp import FastMCP\n\n\nmcp = FastMCP(\"My App\")\n\n# Mount the SSE server to the existing ASGI server\napp = Starlette(\n    routes=[\n        Mount('\u002F', app=mcp.sse_app()),\n    ]\n)\n\n# or dynamically mount as host\napp.router.routes.append(Host('mcp.acme.corp', app=mcp.sse_app()))\n```\n\nWhen mounting multiple MCP servers under different paths, you can configure the mount path in several ways:\n\n```python\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\nfrom mcp.server.fastmcp import FastMCP\n\n# Create multiple MCP servers\ngithub_mcp = FastMCP(\"GitHub API\")\nbrowser_mcp = FastMCP(\"Browser\")\ncurl_mcp = FastMCP(\"Curl\")\nsearch_mcp = FastMCP(\"Search\")\n\n# Method 1: Configure mount paths via settings (recommended for persistent configuration)\ngithub_mcp.settings.mount_path = \"\u002Fgithub\"\nbrowser_mcp.settings.mount_path = \"\u002Fbrowser\"\n\n# Method 2: Pass mount path directly to sse_app (preferred for ad-hoc mounting)\n# This approach doesn't modify the server's settings permanently\n\n# Create Starlette app with multiple mounted servers\napp = Starlette(\n    routes=[\n        # Using settings-based configuration\n        Mount(\"\u002Fgithub\", app=github_mcp.sse_app()),\n        Mount(\"\u002Fbrowser\", app=browser_mcp.sse_app()),\n        # Using direct mount path parameter\n        Mount(\"\u002Fcurl\", app=curl_mcp.sse_app(\"\u002Fcurl\")),\n        Mount(\"\u002Fsearch\", app=search_mcp.sse_app(\"\u002Fsearch\")),\n    ]\n)\n\n# Method 3: For direct execution, you can also pass the mount path to run()\nif __name__ == \"__main__\":\n    search_mcp.run(transport=\"sse\", mount_path=\"\u002Fsearch\")\n```\n\nFor more information on mounting applications in Starlette, see the [Starlette documentation](https:\u002F\u002Fwww.starlette.io\u002Frouting\u002F#submounting-routes).\n\n## Advanced Usage\n\n### Low-Level Server\n\nFor more control, you can use the low-level server implementation directly. This gives you full access to the protocol and allows you to customize every aspect of your server, including lifecycle management through the lifespan API:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Flifespan.py -->\n```python\n\"\"\"\nRun from the repository root:\n    uv run examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Flifespan.py\n\"\"\"\n\nfrom collections.abc import AsyncIterator\nfrom contextlib import asynccontextmanager\nfrom typing import Any\n\nimport mcp.server.stdio\nimport mcp.types as types\nfrom mcp.server.lowlevel import NotificationOptions, Server\nfrom mcp.server.models import InitializationOptions\n\n\n# Mock database class for example\nclass Database:\n    \"\"\"Mock database class for example.\"\"\"\n\n    @classmethod\n    async def connect(cls) -> \"Database\":\n        \"\"\"Connect to database.\"\"\"\n        print(\"Database connected\")\n        return cls()\n\n    async def disconnect(self) -> None:\n        \"\"\"Disconnect from database.\"\"\"\n        print(\"Database disconnected\")\n\n    async def query(self, query_str: str) -> list[dict[str, str]]:\n        \"\"\"Execute a query.\"\"\"\n        # Simulate database query\n        return [{\"id\": \"1\", \"name\": \"Example\", \"query\": query_str}]\n\n\n@asynccontextmanager\nasync def server_lifespan(_server: Server) -> AsyncIterator[dict[str, Any]]:\n    \"\"\"Manage server startup and shutdown lifecycle.\"\"\"\n    # Initialize resources on startup\n    db = await Database.connect()\n    try:\n        yield {\"db\": db}\n    finally:\n        # Clean up on shutdown\n        await db.disconnect()\n\n\n# Pass lifespan to server\nserver = Server(\"example-server\", lifespan=server_lifespan)\n\n\n@server.list_tools()\nasync def handle_list_tools() -> list[types.Tool]:\n    \"\"\"List available tools.\"\"\"\n    return [\n        types.Tool(\n            name=\"query_db\",\n            description=\"Query the database\",\n            inputSchema={\n                \"type\": \"object\",\n                \"properties\": {\"query\": {\"type\": \"string\", \"description\": \"SQL query to execute\"}},\n                \"required\": [\"query\"],\n            },\n        )\n    ]\n\n\n@server.call_tool()\nasync def query_db(name: str, arguments: dict[str, Any]) -> list[types.TextContent]:\n    \"\"\"Handle database query tool call.\"\"\"\n    if name != \"query_db\":\n        raise ValueError(f\"Unknown tool: {name}\")\n\n    # Access lifespan context\n    ctx = server.request_context\n    db = ctx.lifespan_context[\"db\"]\n\n    # Execute query\n    results = await db.query(arguments[\"query\"])\n\n    return [types.TextContent(type=\"text\", text=f\"Query results: {results}\")]\n\n\nasync def run():\n    \"\"\"Run the server with lifespan management.\"\"\"\n    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            InitializationOptions(\n                server_name=\"example-server\",\n                server_version=\"0.1.0\",\n                capabilities=server.get_capabilities(\n                    notification_options=NotificationOptions(),\n                    experimental_capabilities={},\n                ),\n            ),\n        )\n\n\nif __name__ == \"__main__\":\n    import asyncio\n\n    asyncio.run(run())\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Flifespan.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Flifespan.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nThe lifespan API provides:\n\n- A way to initialize resources when the server starts and clean them up when it stops\n- Access to initialized resources through the request context in handlers\n- Type-safe context passing between lifespan and request handlers\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fbasic.py -->\n```python\n\"\"\"\nRun from the repository root:\nuv run examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fbasic.py\n\"\"\"\n\nimport asyncio\n\nimport mcp.server.stdio\nimport mcp.types as types\nfrom mcp.server.lowlevel import NotificationOptions, Server\nfrom mcp.server.models import InitializationOptions\n\n# Create a server instance\nserver = Server(\"example-server\")\n\n\n@server.list_prompts()\nasync def handle_list_prompts() -> list[types.Prompt]:\n    \"\"\"List available prompts.\"\"\"\n    return [\n        types.Prompt(\n            name=\"example-prompt\",\n            description=\"An example prompt template\",\n            arguments=[types.PromptArgument(name=\"arg1\", description=\"Example argument\", required=True)],\n        )\n    ]\n\n\n@server.get_prompt()\nasync def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> types.GetPromptResult:\n    \"\"\"Get a specific prompt by name.\"\"\"\n    if name != \"example-prompt\":\n        raise ValueError(f\"Unknown prompt: {name}\")\n\n    arg1_value = (arguments or {}).get(\"arg1\", \"default\")\n\n    return types.GetPromptResult(\n        description=\"Example prompt\",\n        messages=[\n            types.PromptMessage(\n                role=\"user\",\n                content=types.TextContent(type=\"text\", text=f\"Example prompt text with argument: {arg1_value}\"),\n            )\n        ],\n    )\n\n\nasync def run():\n    \"\"\"Run the basic low-level server.\"\"\"\n    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            InitializationOptions(\n                server_name=\"example\",\n                server_version=\"0.1.0\",\n                capabilities=server.get_capabilities(\n                    notification_options=NotificationOptions(),\n                    experimental_capabilities={},\n                ),\n            ),\n        )\n\n\nif __name__ == \"__main__\":\n    asyncio.run(run())\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fbasic.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fbasic.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nCaution: The `uv run mcp run` and `uv run mcp dev` tool doesn't support low-level server.\n\n#### Structured Output Support\n\nThe low-level server supports structured output for tools, allowing you to return both human-readable content and machine-readable structured data. Tools can define an `outputSchema` to validate their structured output:\n\n\u003C!-- snippet-source examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fstructured_output.py -->\n```python\n\"\"\"\nRun from the repository root:\n    uv run examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fstructured_output.py\n\"\"\"\n\nimport asyncio\nfrom typing import Any\n\nimport mcp.server.stdio\nimport mcp.types as types\nfrom mcp.server.lowlevel import NotificationOptions, Server\nfrom mcp.server.models import InitializationOptions\n\nserver = Server(\"example-server\")\n\n\n@server.list_tools()\nasync def list_tools() -> list[types.Tool]:\n    \"\"\"List available tools with structured output schemas.\"\"\"\n    return [\n        types.Tool(\n            name=\"get_weather\",\n            description=\"Get current weather for a city\",\n            inputSchema={\n                \"type\": \"object\",\n                \"properties\": {\"city\": {\"type\": \"string\", \"description\": \"City name\"}},\n                \"required\": [\"city\"],\n            },\n            outputSchema={\n                \"type\": \"object\",\n                \"properties\": {\n                    \"temperature\": {\"type\": \"number\", \"description\": \"Temperature in Celsius\"},\n                    \"condition\": {\"type\": \"string\", \"description\": \"Weather condition\"},\n                    \"humidity\": {\"type\": \"number\", \"description\": \"Humidity percentage\"},\n                    \"city\": {\"type\": \"string\", \"description\": \"City name\"},\n                },\n                \"required\": [\"temperature\", \"condition\", \"humidity\", \"city\"],\n            },\n        )\n    ]\n\n\n@server.call_tool()\nasync def call_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Handle tool calls with structured output.\"\"\"\n    if name == \"get_weather\":\n        city = arguments[\"city\"]\n\n        # Simulated weather data - in production, call a weather API\n        weather_data = {\n            \"temperature\": 22.5,\n            \"condition\": \"partly cloudy\",\n            \"humidity\": 65,\n            \"city\": city,  # Include the requested city\n        }\n\n        # low-level server will validate structured output against the tool's\n        # output schema, and additionally serialize it into a TextContent block\n        # for backwards compatibility with pre-2025-06-18 clients.\n        return weather_data\n    else:\n        raise ValueError(f\"Unknown tool: {name}\")\n\n\nasync def run():\n    \"\"\"Run the structured output server.\"\"\"\n    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):\n        await server.run(\n            read_stream,\n            write_stream,\n            InitializationOptions(\n                server_name=\"structured-output-example\",\n                server_version=\"0.1.0\",\n                capabilities=server.get_capabilities(\n                    notification_options=NotificationOptions(),\n                    experimental_capabilities={},\n                ),\n            ),\n        )\n\n\nif __name__ == \"__main__\":\n    asyncio.run(run())\n```\n\n_Full example: [examples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fstructured_output.py](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fblob\u002Fmain\u002Fexamples\u002Fsnippets\u002Fservers\u002Flowlevel\u002Fstructured_output.py)_\n\u003C!-- \u002Fsnippet-source -->\n\nTools can return data in four ways:\n\n1. **Content only**: Return a list of content blocks (default behavior before spec revision 2025-06-18)\n2. **Structured data only**: Return a dictionary that will be serialized to JSON (Introduced in spec revision 2025-06-18)\n3. **Both**: Return a tuple of (content, structured_data) preferred option to use for backwards compatibility\n4. **Direct CallToolResult**: Return `CallToolResult` directly for full control (inc","MCP Python SDK 是Model Context Protocol的官方Python软件开发工具包，用于构建和管理MCP服务器与客户端。该项目支持创建、管理和交互模型上下文环境，具备结构化输出、资源管理、认证机制等核心功能，并通过提供丰富的API来简化开发过程。其设计特别适合需要在Python环境中实现高效、安全的数据处理及模型服务部署的应用场景，如机器学习工程、自然语言处理项目等。采用MIT许可证发布，确保了广泛的使用自由度。",2,"2026-06-11 02:49:32","top_language"]