{"id":21999925,"url":"https://github.com/modelcontextprotocol/python-sdk","last_synced_at":"2025-05-12T16:27:14.623Z","repository":{"id":264668147,"uuid":"862584018","full_name":"modelcontextprotocol/python-sdk","owner":"modelcontextprotocol","description":"The official Python SDK for Model Context Protocol servers and clients","archived":false,"fork":false,"pushed_at":"2025-05-04T17:59:31.000Z","size":1614,"stargazers_count":11392,"open_issues_count":282,"forks_count":1251,"subscribers_count":98,"default_branch":"main","last_synced_at":"2025-05-05T14:25:08.691Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://modelcontextprotocol.io","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/modelcontextprotocol.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-09-24T21:01:35.000Z","updated_at":"2025-05-05T14:11:34.000Z","dependencies_parsed_at":"2024-11-25T17:31:22.609Z","dependency_job_id":"f1b65138-5ad7-4638-989c-e320f60d990f","html_url":"https://github.com/modelcontextprotocol/python-sdk","commit_stats":null,"previous_names":["modelcontextprotocol/python-sdk"],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/modelcontextprotocol%2Fpython-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/modelcontextprotocol%2Fpython-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/modelcontextprotocol%2Fpython-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/modelcontextprotocol%2Fpython-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/modelcontextprotocol","download_url":"https://codeload.github.com/modelcontextprotocol/python-sdk/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253692554,"owners_count":21948320,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-29T23:08:59.673Z","updated_at":"2025-05-12T16:27:14.616Z","avatar_url":"https://github.com/modelcontextprotocol.png","language":"Python","readme":"# MCP Python SDK\n\n\u003cdiv align=\"center\"\u003e\n\n\u003cstrong\u003ePython implementation of the Model Context Protocol (MCP)\u003c/strong\u003e\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[![Specification][spec-badge]][spec-url]\n[![GitHub Discussions][discussions-badge]][discussions-url]\n\n\u003c/div\u003e\n\n\u003c!-- omit in toc --\u003e\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    - [Prompts](#prompts)\n    - [Images](#images)\n    - [Context](#context)\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    - [Mounting to an Existing ASGI Server](#mounting-to-an-existing-asgi-server)\n  - [Examples](#examples)\n    - [Echo Server](#echo-server)\n    - [SQLite Explorer](#sqlite-explorer)\n  - [Advanced Usage](#advanced-usage)\n    - [Low-Level Server](#low-level-server)\n    - [Writing MCP Clients](#writing-mcp-clients)\n    - [MCP Primitives](#mcp-primitives)\n    - [Server Capabilities](#server-capabilities)\n  - [Documentation](#documentation)\n  - [Contributing](#contributing)\n  - [License](#license)\n\n[pypi-badge]: https://img.shields.io/pypi/v/mcp.svg\n[pypi-url]: https://pypi.org/project/mcp/\n[mit-badge]: https://img.shields.io/pypi/l/mcp.svg\n[mit-url]: https://github.com/modelcontextprotocol/python-sdk/blob/main/LICENSE\n[python-badge]: https://img.shields.io/pypi/pyversions/mcp.svg\n[python-url]: https://www.python.org/downloads/\n[docs-badge]: https://img.shields.io/badge/docs-modelcontextprotocol.io-blue.svg\n[docs-url]: https://modelcontextprotocol.io\n[spec-badge]: https://img.shields.io/badge/spec-spec.modelcontextprotocol.io-blue.svg\n[spec-url]: https://spec.modelcontextprotocol.io\n[discussions-badge]: https://img.shields.io/github/discussions/modelcontextprotocol/python-sdk\n[discussions-url]: https://github.com/modelcontextprotocol/python-sdk/discussions\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://docs.astral.sh/uv/) 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```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```python\n# server.py\nfrom mcp.server.fastmcp import FastMCP\n\n# Create an MCP server\nmcp = FastMCP(\"Demo\")\n\n\n# Add an addition tool\n@mcp.tool()\ndef add(a: int, b: int) -\u003e int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n\n\n# Add a dynamic greeting resource\n@mcp.resource(\"greeting://{name}\")\ndef get_greeting(name: str) -\u003e str:\n    \"\"\"Get a personalized greeting\"\"\"\n    return f\"Hello, {name}!\"\n```\n\nYou can install this server in [Claude Desktop](https://claude.ai/download) and interact with it right away by running:\n```bash\nmcp install server.py\n```\n\nAlternatively, you can test it with the MCP Inspector:\n```bash\nmcp dev server.py\n```\n\n## What is MCP?\n\nThe [Model Context Protocol (MCP)](https://modelcontextprotocol.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```python\n# Add lifespan support for startup/shutdown with strong typing\nfrom contextlib import asynccontextmanager\nfrom collections.abc import AsyncIterator\nfrom dataclasses import dataclass\n\nfrom fake_database import Database  # Replace with your actual DB type\n\nfrom mcp.server.fastmcp import Context, FastMCP\n\n# Create a named server\nmcp = FastMCP(\"My App\")\n\n# Specify dependencies for deployment and development\nmcp = FastMCP(\"My App\", dependencies=[\"pandas\", \"numpy\"])\n\n\n@dataclass\nclass AppContext:\n    db: Database\n\n\n@asynccontextmanager\nasync def app_lifespan(server: FastMCP) -\u003e 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) -\u003e str:\n    \"\"\"Tool that uses initialized resources\"\"\"\n    db = ctx.request_context.lifespan_context.db\n    return db.query()\n```\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```python\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"My App\")\n\n\n@mcp.resource(\"config://app\")\ndef get_config() -\u003e str:\n    \"\"\"Static configuration data\"\"\"\n    return \"App configuration here\"\n\n\n@mcp.resource(\"users://{user_id}/profile\")\ndef get_user_profile(user_id: str) -\u003e str:\n    \"\"\"Dynamic user data\"\"\"\n    return f\"Profile data for user {user_id}\"\n```\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```python\nimport httpx\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"My App\")\n\n\n@mcp.tool()\ndef calculate_bmi(weight_kg: float, height_m: float) -\u003e float:\n    \"\"\"Calculate BMI given weight in kg and height in meters\"\"\"\n    return weight_kg / (height_m**2)\n\n\n@mcp.tool()\nasync def fetch_weather(city: str) -\u003e str:\n    \"\"\"Fetch current weather for a city\"\"\"\n    async with httpx.AsyncClient() as client:\n        response = await client.get(f\"https://api.weather.com/{city}\")\n        return response.text\n```\n\n### Prompts\n\nPrompts are reusable templates that help LLMs interact with your server effectively:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\nfrom mcp.server.fastmcp.prompts import base\n\nmcp = FastMCP(\"My App\")\n\n\n@mcp.prompt()\ndef review_code(code: str) -\u003e str:\n    return f\"Please review this code:\\n\\n{code}\"\n\n\n@mcp.prompt()\ndef debug_error(error: str) -\u003e 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### Images\n\nFastMCP provides an `Image` class that automatically handles image data:\n\n```python\nfrom mcp.server.fastmcp import FastMCP, Image\nfrom PIL import Image as PILImage\n\nmcp = FastMCP(\"My App\")\n\n\n@mcp.tool()\ndef create_thumbnail(image_path: str) -\u003e 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### Context\n\nThe Context object gives your tools and resources access to MCP capabilities:\n\n```python\nfrom mcp.server.fastmcp import FastMCP, Context\n\nmcp = FastMCP(\"My App\")\n\n\n@mcp.tool()\nasync def long_task(files: list[str], ctx: Context) -\u003e str:\n    \"\"\"Process multiple files with progress tracking\"\"\"\n    for i, file in enumerate(files):\n        ctx.info(f\"Processing {file}\")\n        await ctx.report_progress(i, len(files))\n        data, mime_type = await ctx.read_resource(f\"file://{file}\")\n    return \"Processing complete\"\n```\n\n### Authentication\n\nAuthentication can be used by servers that want to expose tools accessing protected resources.\n\n`mcp.server.auth` implements an OAuth 2.0 server interface, which servers can use by\nproviding an implementation of the `OAuthServerProvider` protocol.\n\n```\nmcp = FastMCP(\"My App\",\n        auth_provider=MyOAuthServerProvider(),\n        auth=AuthSettings(\n            issuer_url=\"https://myapp.com\",\n            revocation_options=RevocationOptions(\n                enabled=True,\n            ),\n            client_registration_options=ClientRegistrationOptions(\n                enabled=True,\n                valid_scopes=[\"myscope\", \"myotherscope\"],\n                default_scopes=[\"myscope\"],\n            ),\n            required_scopes=[\"myscope\"],\n        ),\n)\n```\n\nSee [OAuthServerProvider](src/mcp/server/auth/provider.py) for more details.\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\nmcp dev server.py\n\n# Add dependencies\nmcp dev server.py --with pandas --with numpy\n\n# Mount local code\nmcp 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\nmcp install server.py\n\n# Custom name\nmcp install server.py --name \"My Analytics Server\"\n\n# Environment variables\nmcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://...\nmcp install server.py -f .env\n```\n\n### Direct Execution\n\nFor advanced scenarios like custom deployments:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"My App\")\n\nif __name__ == \"__main__\":\n    mcp.run()\n```\n\nRun it with:\n```bash\npython server.py\n# or\nmcp run server.py\n```\n\n### Streamable HTTP Transport\n\n\u003e **Note**: Streamable HTTP transport is superseding SSE transport for production deployments.\n\n```python\nfrom mcp.server.fastmcp import FastMCP\n\n# Stateful server (maintains session state)\nmcp = FastMCP(\"StatefulServer\")\n\n# Stateless server (no session persistence)\nmcp = FastMCP(\"StatelessServer\", stateless_http=True)\n\n# Run server with streamable_http transport\nmcp.run(transport=\"streamable-http\")\n```\n\nYou can mount multiple FastMCP servers in a FastAPI application:\n\n```python\n# echo.py\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(name=\"EchoServer\", stateless_http=True)\n\n\n@mcp.tool(description=\"A simple echo tool\")\ndef echo(message: str) -\u003e str:\n    return f\"Echo: {message}\"\n```\n\n```python\n# math.py\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(name=\"MathServer\", stateless_http=True)\n\n\n@mcp.tool(description=\"A simple add tool\")\ndef add_two(n: int) -\u003e str:\n    return n + 2\n```\n\n```python\n# main.py\nfrom fastapi import FastAPI\nfrom mcp.echo import echo\nfrom mcp.math import math\n\n\napp = FastAPI()\n\n# Use the session manager's lifespan\napp = FastAPI(lifespan=lambda app: echo.mcp.session_manager.run())\napp.mount(\"/echo\", echo.mcp.streamable_http_app())\napp.mount(\"/math\", math.mcp.streamable_http_app())\n```\n\nFor low level server with Streamable HTTP implementations, see:\n- Stateful server: [`examples/servers/simple-streamablehttp/`](examples/servers/simple-streamablehttp/)\n- Stateless server: [`examples/servers/simple-streamablehttp-stateless/`](examples/servers/simple-streamablehttp-stateless/)\n\n\n\nThe streamable HTTP transport supports:\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\n### Mounting to an Existing ASGI Server\n\n\u003e **Note**: SSE transport is being superseded by [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#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('/', 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 = \"/github\"\nbrowser_mcp.settings.mount_path = \"/browser\"\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(\"/github\", app=github_mcp.sse_app()),\n        Mount(\"/browser\", app=browser_mcp.sse_app()),\n        # Using direct mount path parameter\n        Mount(\"/curl\", app=curl_mcp.sse_app(\"/curl\")),\n        Mount(\"/search\", app=search_mcp.sse_app(\"/search\")),\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=\"/search\")\n```\n\nFor more information on mounting applications in Starlette, see the [Starlette documentation](https://www.starlette.io/routing/#submounting-routes).\n\n## Examples\n\n### Echo Server\n\nA simple server demonstrating resources, tools, and prompts:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"Echo\")\n\n\n@mcp.resource(\"echo://{message}\")\ndef echo_resource(message: str) -\u003e str:\n    \"\"\"Echo a message as a resource\"\"\"\n    return f\"Resource echo: {message}\"\n\n\n@mcp.tool()\ndef echo_tool(message: str) -\u003e str:\n    \"\"\"Echo a message as a tool\"\"\"\n    return f\"Tool echo: {message}\"\n\n\n@mcp.prompt()\ndef echo_prompt(message: str) -\u003e str:\n    \"\"\"Create an echo prompt\"\"\"\n    return f\"Please process this message: {message}\"\n```\n\n### SQLite Explorer\n\nA more complex example showing database integration:\n\n```python\nimport sqlite3\n\nfrom mcp.server.fastmcp import FastMCP\n\nmcp = FastMCP(\"SQLite Explorer\")\n\n\n@mcp.resource(\"schema://main\")\ndef get_schema() -\u003e str:\n    \"\"\"Provide the database schema as a resource\"\"\"\n    conn = sqlite3.connect(\"database.db\")\n    schema = conn.execute(\"SELECT sql FROM sqlite_master WHERE type='table'\").fetchall()\n    return \"\\n\".join(sql[0] for sql in schema if sql[0])\n\n\n@mcp.tool()\ndef query_data(sql: str) -\u003e str:\n    \"\"\"Execute SQL queries safely\"\"\"\n    conn = sqlite3.connect(\"database.db\")\n    try:\n        result = conn.execute(sql).fetchall()\n        return \"\\n\".join(str(row) for row in result)\n    except Exception as e:\n        return f\"Error: {str(e)}\"\n```\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```python\nfrom contextlib import asynccontextmanager\nfrom collections.abc import AsyncIterator\n\nfrom fake_database import Database  # Replace with your actual DB type\n\nfrom mcp.server import Server\n\n\n@asynccontextmanager\nasync def server_lifespan(server: Server) -\u003e AsyncIterator[dict]:\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# Access lifespan context in handlers\n@server.call_tool()\nasync def query_db(name: str, arguments: dict) -\u003e list:\n    ctx = server.request_context\n    db = ctx.lifespan_context[\"db\"]\n    return await db.query(arguments[\"query\"])\n```\n\nThe lifespan API provides:\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```python\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() -\u003e list[types.Prompt]:\n    return [\n        types.Prompt(\n            name=\"example-prompt\",\n            description=\"An example prompt template\",\n            arguments=[\n                types.PromptArgument(\n                    name=\"arg1\", description=\"Example argument\", required=True\n                )\n            ],\n        )\n    ]\n\n\n@server.get_prompt()\nasync def handle_get_prompt(\n    name: str, arguments: dict[str, str] | None\n) -\u003e types.GetPromptResult:\n    if name != \"example-prompt\":\n        raise ValueError(f\"Unknown prompt: {name}\")\n\n    return types.GetPromptResult(\n        description=\"Example prompt\",\n        messages=[\n            types.PromptMessage(\n                role=\"user\",\n                content=types.TextContent(type=\"text\", text=\"Example prompt text\"),\n            )\n        ],\n    )\n\n\nasync def run():\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    import asyncio\n\n    asyncio.run(run())\n```\n\n### Writing MCP Clients\n\nThe SDK provides a high-level client interface for connecting to MCP servers using various [transports](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports):\n\n```python\nfrom mcp import ClientSession, StdioServerParameters, types\nfrom mcp.client.stdio import stdio_client\n\n# Create server parameters for stdio connection\nserver_params = StdioServerParameters(\n    command=\"python\",  # Executable\n    args=[\"example_server.py\"],  # Optional command line arguments\n    env=None,  # Optional environment variables\n)\n\n\n# Optional: create a sampling callback\nasync def handle_sampling_message(\n    message: types.CreateMessageRequestParams,\n) -\u003e types.CreateMessageResult:\n    return types.CreateMessageResult(\n        role=\"assistant\",\n        content=types.TextContent(\n            type=\"text\",\n            text=\"Hello, world! from model\",\n        ),\n        model=\"gpt-3.5-turbo\",\n        stopReason=\"endTurn\",\n    )\n\n\nasync def run():\n    async with stdio_client(server_params) as (read, write):\n        async with ClientSession(\n            read, write, sampling_callback=handle_sampling_message\n        ) as session:\n            # Initialize the connection\n            await session.initialize()\n\n            # List available prompts\n            prompts = await session.list_prompts()\n\n            # Get a prompt\n            prompt = await session.get_prompt(\n                \"example-prompt\", arguments={\"arg1\": \"value\"}\n            )\n\n            # List available resources\n            resources = await session.list_resources()\n\n            # List available tools\n            tools = await session.list_tools()\n\n            # Read a resource\n            content, mime_type = await session.read_resource(\"file://some/path\")\n\n            # Call a tool\n            result = await session.call_tool(\"tool-name\", arguments={\"arg1\": \"value\"})\n\n\nif __name__ == \"__main__\":\n    import asyncio\n\n    asyncio.run(run())\n```\n\nClients can also connect using [Streamable HTTP transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http):\n\n```python\nfrom mcp.client.streamable_http import streamablehttp_client\nfrom mcp import ClientSession\n\n\nasync def main():\n    # Connect to a streamable HTTP server\n    async with streamablehttp_client(\"example/mcp\") as (\n        read_stream,\n        write_stream,\n        _,\n    ):\n        # Create a session using the client streams\n        async with ClientSession(read_stream, write_stream) as session:\n            # Initialize the connection\n            await session.initialize()\n            # Call a tool\n            tool_result = await session.call_tool(\"echo\", {\"message\": \"hello\"})\n```\n\n### MCP Primitives\n\nThe MCP protocol defines three core primitives that servers can implement:\n\n| Primitive | Control               | Description                                         | Example Use                  |\n|-----------|-----------------------|-----------------------------------------------------|------------------------------|\n| Prompts   | User-controlled       | Interactive templates invoked by user choice        | Slash commands, menu options |\n| Resources | Application-controlled| Contextual data managed by the client application   | File contents, API responses |\n| Tools     | Model-controlled      | Functions exposed to the LLM to take actions        | API calls, data updates      |\n\n### Server Capabilities\n\nMCP servers declare capabilities during initialization:\n\n| Capability  | Feature Flag                 | Description                        |\n|-------------|------------------------------|------------------------------------|\n| `prompts`   | `listChanged`                | Prompt template management         |\n| `resources` | `subscribe`\u003cbr/\u003e`listChanged`| Resource exposure and updates      |\n| `tools`     | `listChanged`                | Tool discovery and execution       |\n| `logging`   | -                            | Server logging configuration       |\n| `completion`| -                            | Argument completion suggestions    |\n\n## Documentation\n\n- [Model Context Protocol documentation](https://modelcontextprotocol.io)\n- [Model Context Protocol specification](https://spec.modelcontextprotocol.io)\n- [Officially supported servers](https://github.com/modelcontextprotocol/servers)\n\n## Contributing\n\nWe are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project. See the [contributing guide](CONTRIBUTING.md) to get started.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n","funding_links":[],"categories":["MCP Servers \u0026 Execution Sandboxes","Python","HarmonyOS","🔩 MCP SDKs \u0026 Building Blocks","Tools \u0026 Integrations","📚 Projects (1974 total)","SDKs","🧰 Development Tools","A01_文本生成_文本对话","🔎 Select Context","Table of Contents","Mcp Server Directories \u0026 Lists","Official Resources","📦 Other","MCP Ecosystem","MCP Frameworks and libraries","📚 참조 링크","MCP \u0026 Model Context Protocol","📚 学习资源","🔌 MCP (Model Context Protocol)"],"sub_categories":["Windows Manager","MCP Ecosystem","MCP Servers","Offcial","Official SDKs","大语言对话模型及数据","MCP Frameworks","Developer Tools","Core \u0026 Frameworks","Python","공식 저장소","Official MCP Resources","官方资源","Codex Resources","Core MCP Resources"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmodelcontextprotocol%2Fpython-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmodelcontextprotocol%2Fpython-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmodelcontextprotocol%2Fpython-sdk/lists"}