MCP服务器工具包

用于构建符合MCP协议的Python服务器工具包,提供同步实现、SSE支持及协议验证等功能,适用于需要集成MCP服务的Python应用开发。

  • by fulfilio
  • Python
  • 本地部署
  • 5 星标
  • 更新于
在 GitHub 查看 fulfilio/mcp-utils

使用说明

mcp 工具

用于构建模型上下文协议(MCP)服务器的Python实用程序包。

目录

概述

mcp-utils 提供了在Python中构建符合MCP的服务器的实用程序和帮助程序,重点是使用Flask的同步实现。此包专为希望在现有Python应用程序中实现MCP服务器而不需要异步代码复杂性的开发人员而设计。

主要特点

  • MCP服务器实现的基本实用程序
  • 服务器发送事件(SSE)支持
  • MCP端点的简单装饰器
  • 同步实施
  • HTTP协议支持
  • Redis响应队列
  • MCP模式的全面Pydantic模型
  • 内置验证和文档

安装

pip install mcp-utils

需求

  • Python 3.10+
  • Pydantic 2

可选依赖关系

  • Flask(用于web服务器)
  • Gunicorn(用于生产部署)
  • Redis(用于响应队列)

用法

基本MCP服务器

下面是一个创建MCP服务器的简单示例:

from mcp_utils.core import MCPServer
from mcp_utils.schema import GetPromptResult, Message, TextContent, CallToolResult

# Create a basic MCP server
mcp = MCPServer("example", "1.0")

@mcp.prompt()
def get_weather_prompt(city: str) -> GetPromptResult:
    return GetPromptResult(
        description="Weather prompt",
        messages=[
            Message(
                role="user",
                content=TextContent(
                    text=f"What is the weather like in {city}?",
                ),
            )
        ],
    )

@mcp.tool()
def get_weather(city: str) -> str:
    return "sunny"

烧瓶示例

对于生产使用,您可以将一个简单的Flask应用程序与mcp服务器一起使用 支持 流式HTTP 从版本2025-06-18开始。

from flask import Flask, Response, url_for, request

# Create Flask app and MCP server with Redis queue
app = Flask(__name__)
mcp = MCPServer(
    "example",
    "1.0",
)

@app.route("/mcp", methods=["POST"])
def mcp_route():
    response = mcp.handle_message(request.get_json())
    return jsonify(response.model_dump(exclude_none=True))


if __name__ == "__main__":
    app.run(debug=True)

SQLAlchemy事务处理示例

对于生产使用,您可以将MCP服务器与Flask、Redis和SQLAlchemy集成,以实现更好的消息处理和数据库事务管理:

from flask import Flask, request
from sqlalchemy.orm import Session
from sqlalchemy import create_engine

# Create engine for PostgreSQL database
engine = create_engine("postgresql://user:pass@localhost/dbname")

# Create Flask app and MCP server with Redis queue
app = Flask(__name__)
mcp = MCPServer(
    "example",
    "1.0",
)

@app.route("/mcp", methods=["POST"])
def mcp_route():
    with Session(engine) as session:
        try:
            response = mcp.handle_message(request.get_json())
            session.commit()
        except:
            session.rollback()
            raise
        else:
            return jsonify(response.model_dump(exclude_none=True))


if __name__ == "__main__":
    app.run(debug=True)

有关包括日志设置和会话管理在内的更全面的示例,请查看 Flask应用程序示例 在存储库中。

与Gunicorn一起跑步

Gunicorn是一种更好的跑步方式,即使是在当地。使用gunicon运行应用程序

from gunicorn.app.base import BaseApplication

class FlaskApplication(BaseApplication):
    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {
            key: value
            for key, value in self.options.items()
            if key in self.cfg.settings
        }
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application


if __name__ == "__main__":
    handler = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter("[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    options = {
        "bind": "0.0.0.0:9000",
        "workers": 1,
        "worker_class": "gevent",
        "loglevel": "debug",
    }
    FlaskApplication(app, options).run()

与MCP客户端连接

光标

  • 编辑MCP设置并添加到配置中
{
  "mcpServers": {
    "server-name": {
      "url": "http://localhost:9000/mcp"
    }
  }
}

克劳德桌面

在撰写本文时,Claude Desktop不支持通过SSE的MCP,只支持stdio。要将Claude Desktop与MCP服务器连接,您需要使用 mcp代理.

Claude Desktop的配置示例:

{
  "mcpServers": {
    "weather": {
      "command": "/Users/yourname/.local/bin/mcp-proxy",
      "args": ["http://127.0.0.1:9000/sse"]
    }
  }
}

通过Smithery安装

通过以下方式自动安装克劳德桌面的MCP代理 史密瑟里:

npx -y @smithery/cli install mcp-proxy --client claude

通过PyPI安装

该软件包的稳定版本可以在PyPI存储库中找到。您可以使用以下命令安装它:

# Option 1: With uv (recommended)
uv tool install mcp-proxy

# Option 2: With pipx (alternative)
pipx install mcp-proxy

安装后,您可以使用 mcp-proxy 命令。

贡献

欢迎投稿!请随时提交拉取请求。

相关项目

许可证

MIT许可证

MCP检验员测试

这 MCP检查员 是测试和调试MCP服务器的有用工具。它提供了一个web界面来检查和测试MCP服务器端点。

安装

使用npm安装MCP检查器:

npm install -g @modelcontextprotocol/inspector

用法

  1. 启动MCP服务器(例如,上面的Flask示例)
  2. 运行MCP检查器:
git clone git@github.com:modelcontextprotocol/inspector.git
cd inspector
npm run build
npm start
  1. 打开浏览器并导航到 http://127.0.0.1:6274/
  2. 输入您的MCP服务器URL(例如。, http://localhost:9000/sse)
  3. 使用检查器:
    • 将传输类型更改为SSE
    • 测试服务器连接
    • 监控SSE事件
    • 发送测试消息
    • 调试响应

此工具在开发过程中特别有用,可确保您的MCP服务器实现 工作正常,符合协议规范。