Token导航 LogoToken导航TokenDH.com
MCP Python SDK logo
AI代理stdio官方级别未说明来源级核验

MCP Python SDK

MCP Server

MCP Python SDK实现了模型上下文协议规范,用于标准化LLM应用的上下文交互,支持资源、工具和提示的创建与管理。

工具数

3

提示词数

0

GitHub Stars

0

资源数

0
上下文管理协议实现PythonClaudeClaude DesktopClaude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

imax09-wq

提供方

imax09-wq

最后核验

2026/5/17 20:20

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

pip install "mcp[cli]"

详细介绍

MCP Python SDK

模型上下文协议(MCP)的Python实现

![PyPI](https://pypi.org/project/mcp/) ![MIT licensed](https://github.com/modelcontextprotocol/python-sdk/blob/main/LICENSE) ](https://www.python.org/downloads/) ![Documentation](https://modelcontextprotocol.io) ![Specification](https://spec.modelcontextprotocol.io) ](https://github.com/modelcontextprotocol/python-sdk/discussions)

目录

- 概述 - 安装 - 将MCP添加到python项目中 - 运行独立的MCP开发工具 - 快速启动 - 什么是MCP? - 核心概念 - 服务器 - 资源 - 工具 - 鼓励 - 图像 - 上下文 - 运行服务器 - 发展模式 - Claude桌面集成 - 直接执行 - 安装到现有ASGI服务器 - 例子 - 回声服务器 - SQLite资源管理器 - 高级用法 - 低级服务器 - 编写MCP客户端 - MCP图元 - 服务器功能 - 文档 - 贡献 - 许可证

概述

模型上下文协议允许应用程序以标准化的方式为LLM提供上下文,将提供上下文的关注点与实际的LLM交互分开。此Python SDK实现了完整的MCP规范,使其易于:

  • 构建可以连接到任何MCP服务器的MCP客户端
  • 创建公开资源、提示和工具的MCP服务器
  • 使用标准传输方式,如stdio和SSE
  • 处理所有MCP协议消息和生命周期事件

安装

将MCP添加到python项目中

我们建议使用 紫外线 管理你的Python项目。

如果你还没有创建一个uv管理的项目,请创建一个:

uv init mcp-server-demo
cd mcp-server-demo

然后将MCP添加到您的项目依赖关系中:

uv add "mcp[cli]"

或者,对于使用pip作为依赖关系的项目:

pip install "mcp[cli]"

运行独立的MCP开发工具

要使用uv运行mcp命令:

uv run mcp

快速启动

让我们创建一个简单的MCP服务器,它公开了一个计算器工具和一些数据:

# server.py
from mcp.server.fastmcp import FastMCP

# Create an MCP server
mcp = FastMCP("Demo")

# Add an addition tool
@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two numbers"""
    return a + b

# Add a dynamic greeting resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
    """Get a personalized greeting"""
    return f"Hello, {name}!"

您可以在以下位置安装此服务器 克劳德桌面 并通过运行以下命令立即与之交互:

mcp install server.py

或者,您可以使用MCP检查器进行测试:

mcp dev server.py

什么是MCP?

模型上下文协议(MCP) 允许您构建以安全、标准化的方式向LLM应用程序公开数据和功能的服务器。将其视为一个web API,但它是专门为LLM交互而设计的。MCP服务器可以:

  • 通过以下方式公开数据 资源 (将这些类似于GET端点;它们用于将信息加载到LLM的上下文中)
  • 通过以下方式提供功能 工具 (有点像POST端点;它们用于执行代码或产生副作用)
  • 通过以下方式定义交互模式 鼓励 (LLM交互的可重用模板)
  • 还有更多!

核心概念

服务器

FastMCP服务器是MCP协议的核心接口。它处理连接管理、协议合规性和消息路由:

# Add lifespan support for startup/shutdown with strong typing
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from dataclasses import dataclass

from fake_database import Database  # Replace with your actual DB type

from mcp.server.fastmcp import Context, FastMCP

# Create a named server
mcp = FastMCP("My App")

# Specify dependencies for deployment and development
mcp = FastMCP("My App", dependencies=["pandas", "numpy"])

@dataclass
class AppContext:
    db: Database

@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
    """Manage application lifecycle with type-safe context"""
    # Initialize on startup
    db = await Database.connect()
    try:
        yield AppContext(db=db)
    finally:
        # Cleanup on shutdown
        await db.disconnect()

# Pass lifespan to server
mcp = FastMCP("My App", lifespan=app_lifespan)

# Access type-safe lifespan context in tools
@mcp.tool()
def query_db(ctx: Context) -> str:
    """Tool that uses initialized resources"""
    db = ctx.request_context.lifespan_context["db"]
    return db.query()

资源

资源是您向LLM公开数据的方式。它们类似于REST API中的GET端点-它们提供数据,但不应执行显著的计算或产生副作用:

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("My App")

@mcp.resource("config://app")
def get_config() -> str:
    """Static configuration data"""
    return "App configuration here"

@mcp.resource("users://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
    """Dynamic user data"""
    return f"Profile data for user {user_id}"

工具

工具允许LLM通过您的服务器执行操作。与资源不同,工具被期望执行计算并具有副作用:

import httpx
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("My App")

@mcp.tool()
def calculate_bmi(weight_kg: float, height_m: float) -> float:
    """Calculate BMI given weight in kg and height in meters"""
    return weight_kg / (height_m**2)

@mcp.tool()
async def fetch_weather(city: str) -> str:
    """Fetch current weather for a city"""
    async with httpx.AsyncClient() as client:
        response = await client.get(f"https://api.weather.com/{city}")
        return response.text

鼓励

提示是可重用的模板,可帮助LLM与您的服务器有效交互:

from mcp.server.fastmcp import FastMCP
from mcp.server.fastmcp.prompts import base

mcp = FastMCP("My App")

@mcp.prompt()
def review_code(code: str) -> str:
    return f"Please review this code:\n\n{code}"

@mcp.prompt()
def debug_error(error: str) -> list[base.Message]:
    return [
        base.UserMessage("I'm seeing this error:"),
        base.UserMessage(error),
        base.AssistantMessage("I'll help debug that. What have you tried so far?"),
    ]

图像

FastMCP提供 Image 自动处理图像数据的类:

from mcp.server.fastmcp import FastMCP, Image
from PIL import Image as PILImage

mcp = FastMCP("My App")

@mcp.tool()
def create_thumbnail(image_path: str) -> Image:
    """Create a thumbnail from an image"""
    img = PILImage.open(image_path)
    img.thumbnail((100, 100))
    return Image(data=img.tobytes(), format="png")

上下文

Context对象允许您的工具和资源访问MCP功能:

from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("My App")

@mcp.tool()
async def long_task(files: list[str], ctx: Context) -> str:
    """Process multiple files with progress tracking"""
    for i, file in enumerate(files):
        ctx.info(f"Processing {file}")
        await ctx.report_progress(i, len(files))
        data, mime_type = await ctx.read_resource(f"file://{file}")
    return "Processing complete"

运行服务器

发展模式

测试和调试服务器的最快方法是使用MCP检查器:

mcp dev server.py

# Add dependencies
mcp dev server.py --with pandas --with numpy

# Mount local code
mcp dev server.py --with-editable .

Claude桌面集成

服务器准备就绪后,将其安装在Claude Desktop中:

mcp install server.py

# Custom name
mcp install server.py --name "My Analytics Server"

# Environment variables
mcp install server.py -v API_KEY=abc123 -v DB_URL=postgres://...
mcp install server.py -f .env

直接执行

对于自定义部署等高级场景:

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("My App")

if __name__ == "__main__":
    mcp.run()

运行它:

python server.py
# or
mcp run server.py

安装到现有ASGI服务器

您可以使用以下命令将SSE服务器装载到现有的ASGI服务器 sse_app 方法。这允许您将SSE服务器与其他ASGI应用程序集成。

from starlette.applications import Starlette
from starlette.routing import Mount, Host
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("My App")

# Mount the SSE server to the existing ASGI server
app = Starlette(
    routes=[
        Mount('/', app=mcp.sse_app()),
    ]
)

# or dynamically mount as host
app.router.routes.append(Host('mcp.acme.corp', app=mcp.sse_app()))

有关在Starlette中安装应用程序的更多信息,请参阅 Starlette文档.

例子

回声服务器

一个简单的服务器,演示资源、工具和提示:

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Echo")

@mcp.resource("echo://{message}")
def echo_resource(message: str) -> str:
    """Echo a message as a resource"""
    return f"Resource echo: {message}"

@mcp.tool()
def echo_tool(message: str) -> str:
    """Echo a message as a tool"""
    return f"Tool echo: {message}"

@mcp.prompt()
def echo_prompt(message: str) -> str:
    """Create an echo prompt"""
    return f"Please process this message: {message}"

SQLite资源管理器

一个更复杂的数据库集成示例:

import sqlite3

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("SQLite Explorer")

@mcp.resource("schema://main")
def get_schema() -> str:
    """Provide the database schema as a resource"""
    conn = sqlite3.connect("database.db")
    schema = conn.execute("SELECT sql FROM sqlite_master WHERE type='table'").fetchall()
    return "\n".join(sql[0] for sql in schema if sql[0])

@mcp.tool()
def query_data(sql: str) -> str:
    """Execute SQL queries safely"""
    conn = sqlite3.connect("database.db")
    try:
        result = conn.execute(sql).fetchall()
        return "\n".join(str(row) for row in result)
    except Exception as e:
        return f"Error: {str(e)}"

高级用法

低级服务器

为了获得更多的控制,您可以直接使用低级服务器实现。这使您能够完全访问协议,并允许您自定义服务器的各个方面,包括整个生命周期的生命周期管理API:

from contextlib import asynccontextmanager
from collections.abc import AsyncIterator

from fake_database import Database  # Replace with your actual DB type

from mcp.server import Server

@asynccontextmanager
async def server_lifespan(server: Server) -> AsyncIterator[dict]:
    """Manage server startup and shutdown lifecycle."""
    # Initialize resources on startup
    db = await Database.connect()
    try:
        yield {"db": db}
    finally:
        # Clean up on shutdown
        await db.disconnect()

# Pass lifespan to server
server = Server("example-server", lifespan=server_lifespan)

# Access lifespan context in handlers
@server.call_tool()
async def query_db(name: str, arguments: dict) -> list:
    ctx = server.request_context
    db = ctx.lifespan_context["db"]
    return await db.query(arguments["query"])

API的使用寿命提供:

  • 一种在服务器启动时初始化资源并在停止时清理资源的方法
  • 通过处理程序中的请求上下文访问初始化的资源
  • 在生命周期和请求处理程序之间传递类型安全的上下文
import mcp.server.stdio
import mcp.types as types
from mcp.server.lowlevel import NotificationOptions, Server
from mcp.server.models import InitializationOptions

# Create a server instance
server = Server("example-server")

@server.list_prompts()
async def handle_list_prompts() -> list[types.Prompt]:
    return [
        types.Prompt(
            name="example-prompt",
            description="An example prompt template",
            arguments=[
                types.PromptArgument(
                    name="arg1", description="Example argument", required=True
                )
            ],
        )
    ]

@server.get_prompt()
async def handle_get_prompt(
    name: str, arguments: dict[str, str] | None
) -> types.GetPromptResult:
    if name != "example-prompt":
        raise ValueError(f"Unknown prompt: {name}")

    return types.GetPromptResult(
        description="Example prompt",
        messages=[
            types.PromptMessage(
                role="user",
                content=types.TextContent(type="text", text="Example prompt text"),
            )
        ],
    )

async def run():
    async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="example",
                server_version="0.1.0",
                capabilities=server.get_capabilities(
                    notification_options=NotificationOptions(),
                    experimental_capabilities={},
                ),
            ),
        )

if __name__ == "__main__":
    import asyncio

    asyncio.run(run())

编写MCP客户端

SDK提供了一个高级客户端接口,用于连接MCP服务器:

from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client

# Create server parameters for stdio connection
server_params = StdioServerParameters(
    command="python",  # Executable
    args=["example_server.py"],  # Optional command line arguments
    env=None,  # Optional environment variables
)

# Optional: create a sampling callback
async def handle_sampling_message(
    message: types.CreateMessageRequestParams,
) -> types.CreateMessageResult:
    return types.CreateMessageResult(
        role="assistant",
        content=types.TextContent(
            type="text",
            text="Hello, world! from model",
        ),
        model="gpt-3.5-turbo",
        stopReason="endTurn",
    )

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(
            read, write, sampling_callback=handle_sampling_message
        ) as session:
            # Initialize the connection
            await session.initialize()

            # List available prompts
            prompts = await session.list_prompts()

            # Get a prompt
            prompt = await session.get_prompt(
                "example-prompt", arguments={"arg1": "value"}
            )

            # List available resources
            resources = await session.list_resources()

            # List available tools
            tools = await session.list_tools()

            # Read a resource
            content, mime_type = await session.read_resource("file://some/path")

            # Call a tool
            result = await session.call_tool("tool-name", arguments={"arg1": "value"})

if __name__ == "__main__":
    import asyncio

    asyncio.run(run())

MCP图元

MCP协议定义了服务器可以实现的三个核心原语:

图元控件描述示例用法
提示用户控制用户选择调用的交互式模板Slash命令、菜单选项
资源应用程序控制客户端应用程序管理的上下文数据文件内容、API响应
工具模型控制向LLM公开以执行操作的函数API调用、数据更新

服务器功能

MCP服务器在初始化过程中声明功能:

功能功能标志描述
promptslistChanged快速模板管理
resourcessubscribe
listChanged资源暴露和更新
toolslistChanged工具发现和执行
logging-服务器日志记录配置
completion-论点完成建议

文档

贡献

我们热衷于支持各级经验的贡献者,并希望看到您参与该项目。请参阅 贡献指南 开始吧。

许可证

此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。

目录标签

目录标签

上下文管理协议实现PythonClaudeLLM集成本地部署PythonSDKAI工具开发

支持客户端

Claude DesktopClaude

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

session

工具数量(toolCount,工具数)

3

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdiosession部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP