模型上下文协议服务器

一个基于Flask的模型上下文协议(MCP)实现,用于通过外部工具增强大型语言模型的能力。

  • by yisu201506
  • Python
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 yisu201506/mcp_server

使用说明

MCP服务器实现

基于Flask的模型上下文协议(MCP)的完整实现,用于使用外部工具增强大型语言模型的功能。

概述

此存储库演示了如何构建一个处理模型上下文协议(MCP)的服务器,MCP是一种通过在模型的文本输出中直接调用工具来扩展LLM功能的方法。与函数调用不同,MCP将工具定义直接放置在上下文窗口中,并解析模型的自然语言响应以识别工具使用情况。

特性

  • 🔧 完成MCP实施:完整的解析、执行和响应处理
  • 🌤️ 示例工具:带参数验证的天气和计算器工具
  • 🔄 对话流程:在多个交互中保持上下文
  • 🧩 基于正则表达式的解析:用于工具调用的灵活文本解析
  • 🚀 API弗拉斯克:用于聊天集成的REST API端点

项目结构

mcp_server/
├── app.py                  # Main Flask application
├── mcp_handler.py          # MCP parsing and execution
├── mcp_example.py          # Standalone MCP example
├── requirements.txt        # Dependencies
├── tools/                  # Tool implementations
│   ├── __init__.py
│   ├── weather.py          # Weather API tool
│   └── calculator.py       # Calculator tool
└── README.md               # This file

安装

  1. 克隆存储库:

    git clone https://github.com/yourusername/mcp-server.git
    cd mcp-server
    
  2. 创建虚拟环境:

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
    
  3. 安装依赖项:

    pip install -r requirements.txt
    
  4. 设置环境变量:

    # Create a .env file with:
    LLM_API_KEY=your_llm_api_key_here
    WEATHER_API_KEY=your_weather_api_key_here
    FLASK_APP=app.py
    FLASK_ENV=development
    

用法

运行服务器

启动Flask开发服务器:

flask run

生产:

gunicorn app:app

API终点

  • POST/聊天:使用MCP处理聊天消息
    curl -X POST http://localhost:5000/chat \
      -H "Content-Type: application/json" \
      -d '{
        "messages": [
          {
            "role": "user",
            "content": "What's the weather like in Boston?"
          }
        ]
      }'
    

独立示例

运行示例脚本以查看MCP的运行情况:

python mcp_example.py

运作原理

  1. 工具注册:工具已注册其参数和执行逻辑
  2. 工具定义注入:XML格式的工具描述将添加到提示中
  3. LLM响应处理:正则表达式模式标识LLM文本输出中的工具调用
  4. 工具执行:解析参数并将其传递给适当的工具处理程序
  5. 结果注射:将工具执行结果插入回响应中

MCP与函数调用

功能 MCP 函数调用
定义位置 提示文字中 API参数中
调用格式 自然语言 结构化JSON
实现 文本解析 API集成
可见性 响应中可见 可能隐藏
平台支持 任何基于文本的LLM 需要API支持

对话示例

用户波士顿的天气怎么样?

LLM:

I'll check the weather for you.

get_weather(location="Boston, MA", unit="fahrenheit")

处理后:

I'll check the weather for you.

get_weather(location="Boston, MA", unit="fahrenheit")

Result from get_weather:
{
  "location": "Boston, MA",
  "temperature": 72,
  "unit": "fahrenheit",
  "conditions": "Partly Cloudy",
  "humidity": 68,
  "wind_speed": 5.8
}

添加您自己的工具

  1. 创建一个继承自的新类 Tool
  2. 定义参数和执行逻辑
  3. 向MCP处理程序注册

例子:

class MyTool(Tool):
    def __init__(self):
        parameters = [
            {
                "name": "param1",
                "type": "string",
                "description": "Description of param1",
                "required": True
            }
        ]
        
        super().__init__(
            name="my_tool",
            description="Description of my tool",
            parameters=parameters
        )
    
    def execute(self, param1):
        # Tool logic here
        return {"result": "Processed " + param1}

MCP配置和调用流程

  1. 工具注册:

    • MCP工具已向处理程序注册
    • 每个工具都提供其名称、描述和参数定义
  2. 工具定义注入:

    • 工具定义已添加到系统消息中
    • 格式遵循MCP的XML结构
  3. LLM响应处理:

    • LLM生成的响应可能包括工具调用
    • 模式匹配识别文本中的工具调用
    • 工具参数被解析并传递给工具执行方法
  4. 工具执行:

    • 使用提供的参数执行工具
    • 结果被注入到对话中
  5. 会话管理:

    • 带有工具结果的已处理响应将添加到对话历史记录中
    • 未来的LLM请求包括此历史记录以供参考

对话示例

以下是一个对话的示例:

用户波士顿的天气怎么样?

系统: 向LLM发送带有MCP工具定义的提示

LLM响应:

I'll check the weather for you.

get_weather(location="Boston, MA", unit="fahrenheit")

MCP处理器: 解析响应,查找工具调用,并执行天气工具

工具执行结果:

Result from get_weather:
{
  "location": "Boston, MA",
  "temperature": 72,
  "unit": "fahrenheit",
  "conditions": "Partly Cloudy",
  "humidity": 68,
  "wind_speed": 5.8
}

已处理响应 (返回给用户):

I'll check the weather for you.

get_weather(location="Boston, MA", unit="fahrenheit")

Result from get_weather:
{
  "location": "Boston, MA",
  "temperature": 72,
  "unit": "fahrenheit",
  "conditions": "Partly Cloudy",
  "humidity": 68,
  "wind_speed": 5.8
}

用户你能算出144的平方根吗?

LLM响应:

I can calculate that for you.

calculator(expression="sqrt(144)")

MCP处理器: 解析响应,执行计算器工具

工具执行结果:

Result from calculator:
{
  "expression": "sqrt(144)",
  "result": 12.0
}

已处理响应 (返回给用户):

I can calculate that for you.

calculator(expression="sqrt(144)")

Result from calculator:
{
  "expression": "sqrt(144)",
  "result": 12.0
}

The square root of 144 is 12.

这演示了MCP工具使用的完整流程,从LLM的基于文本的调用到执行和响应处理。

许可证

麻省理工学院

贡献

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