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

MCP Typed Prompts

MCP Server

一个实现模型上下文协议(MCP)的Python SDK,用于构建与LLM交互的标准化服务端和客户端。

工具数

4

提示词数

0

GitHub Stars

3

资源数

0
模型集成PythonClaudeClaude DesktopClaude DesktopClaude

安装说明

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

作者 / 组织

wanderingnature

提供方

wanderingnature

最后核验

2026/5/17 20:20

快速接入

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

命令预览

pip install mcp

详细介绍

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)

目录

- 服务器 - 资源 - 工具 - 提示 - 图像 - 上下文

- 发展模式 - Claude桌面集成 - 直接执行

- 回声服务器 - SQLite资源管理器

- 低级服务器 - 编写MCP客户端 - MCP图元 - 服务器功能

概述

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

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

安装

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

uv add "mcp[cli]"

或者:

pip install 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协议的核心接口。它处理连接管理、协议合规性和消息路由:

from mcp.server.fastmcp import FastMCP

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

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

资源

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

@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通过您的服务器执行操作。与资源不同,工具被期望执行计算并具有副作用:

@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与您的服务器有效交互:

@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[Message]:
    return [
        UserMessage("I'm seeing this error:"),
        UserMessage(error),
        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.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.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 = 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

例子

回声服务器

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

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资源管理器

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

from mcp.server.fastmcp import FastMCP
import sqlite3

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)}"

高级用法

低级服务器

为了获得更多的控制,您可以直接使用低级服务器实现。这使您可以完全访问协议,并允许您自定义服务器的各个方面:

from mcp.server.lowlevel import Server, NotificationOptions
from mcp.server.models import InitializationOptions
import mcp.server.stdio
import mcp.types as types

# 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, Any] | 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
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
)

async def run():
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) 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
            resource = 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许可证获得许可-有关详细信息,请参阅许可证文件。

目录标签

目录标签

模型集成PythonClaudeClaude DesktopLLM集成本地部署Python开发API协议AI工具

支持客户端

Claude DesktopClaude

接入字段

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

stdio

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

session

工具数量(toolCount,工具数)

4

资源数量(resourceCount,资源数)

0

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

0

权限和风险

stdiosession部署方式未说明

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

安装前确认

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

来源信息

继续浏览同类 MCP