模型上下文协议工具箱

一个全面的学习资源库,用于构建MCP服务器、客户端和主机,实现AI模型与外部工具和服务的标准化交互。

  • by rajkundalia
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 rajkundalia/mcp-toolbox

使用说明

MCP工具箱

一个全面的学习库 模型上下文协议(MCP),演示如何使用实际工具构建MCP服务器、客户端和主机。

目录

什么是MCP?

这 模型上下文协议(MCP) 是一个开放协议,规范了应用程序如何向LLM提供上下文。它允许AI模型与外部工具和服务进行一致的交互。

优点:

  • 标准化工具集成
  • 混合搭配来自不同供应商的工具
  • 在隔离的服务器中安全执行工具
  • LLM和工具逻辑之间的明确分离

架构:

flowchart TB
    User[User] -->|Request| Host[Host]
    Host -->|Prompt| LLM[Ollama LLM]
    LLM -->|Tool Call| Host
    Host -->|JSON-RPC| Server[MCP Server]
    Server -->|Execute| Tools[Tools]
    Tools -->|Result| Server
    Server -->|Response| Host
    Host -->|Format| LLM
    LLM -->|Answer| User

安装

git clone https://github.com/rajkundalia/mcp-toolbox.git
cd mcp-toolbox
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate
pip install -r requirements.txt

先决条件: Python 3.10+,Ollama(可选),Node.js(可选)

快速开始

1.使用MCP检验员进行测试

npx @modelcontextprotocol/inspector python server/stdio_server.py

打开web UI以交互方式测试工具。

2.运行示例客户端

python client/example_usage.py

演示:

  • 连接到STDIO服务器
  • 列出并调用所有工具
  • 错误处理

3.与Ollama聊天

ollama pull llama3
python host/run_ollama.py

交互式聊天,自动使用工具。

建筑

运输

STDIO服务器 (server/stdio_server.py):

  • 通过stdin/stdout进行子进程通信
  • 简单的本地工具执行
  • 大多数MCP客户端使用

执行流程

sequenceDiagram
    User->>Host: Question
    Host->>Ollama: Prompt + tools
    Ollama->>Host: Tool request
    Host->>MCP Server: call_tool
    MCP Server->>Tool: Execute
    Tool->>MCP Server: Result
    MCP Server->>Host: Response
    Host->>Ollama: Tool result
    Ollama->>User: Final answer

可用工具

工具 输入 输出 目的
yaml_to_json yaml: string json: string 将YAML转换为JSON
json_to_yaml json: string yaml: string 将JSON转换为YAML
base64_encode text: string encoded: string Base64编码
sha256_hash text: string hash: string SHA256哈希
is_port_open host: string, port: number open: boolean 检查TCP端口
validate_url url: string valid: boolean, reason?: string 验证URL格式

示例:

yaml_to_json(yaml="name: John\nage: 30")
# {"json": "{\n  \"name\": \"John\",\n  \"age\": 30\n}"}

base64_encode(text="Hello!")
# {"encoded": "SGVsbG8h"}

sha256_hash(text="test")
# {"hash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"}

await is_port_open(host="google.com", port=80)
# {"open": true}

validate_url(url="https://example.com")
# {"valid": true}

测试

与MCP检查员一起

# STDIO transport
npx @modelcontextprotocol/inspector python server/stdio_server.py

使用pytest

pytest tests/ -v

测试包括:

  • 格式工具(YAML/JSON转换)
  • 文本工具(编码、哈希)
  • 网络工具(端口检查、URL验证)
  • 错误处理
  • 边缘案例

开发指南

添加新工具

第一步: 在适当的模块中实施工具

# server/tools/my_tools.py
def my_tool(param: str) -> dict:
    """Tool documentation."""
    result = do_something(param)
    return {"output": result}

第二步: 注册 server/registry.py

AVAILABLE_TOOLS["my_tool"] = {
    "name": "my_tool",
    "description": "What this tool does",
    "inputSchema": {
        "type": "object",
        "properties": {
            "param": {"type": "string", "description": "Parameter description"}
        },
        "required": ["param"]
    }
}

TOOL_FUNCTIONS["my_tool"] = my_tool

步骤3: 添加测试

# tests/test_my_tools.py
def test_my_tool():
    result = my_tool("test input")
    assert "output" in result

步骤4: 检验员测试

npx @modelcontextprotocol/inspector python server/stdio_server.py

项目组织机构

  • 服务器/工具/:工具实施
  • 服务器/注册表.py:工具元数据和注册
  • 服务器/stdio_server.py:STDIO传输
  • 客户/:客户和指南示例
  • 主持人/:Olama集成
  • 测试/:测试套件

故障排除

服务器无法启动

问题: ModuleNotFoundError: No module named 'mcp'

解决方案:

pip install -r requirements.txt

Ollama连接失败

问题: Error: Cannot connect to Ollama

解决方案:

# Check if Ollama is running
ollama list

# Start Ollama
ollama serve

# Pull required model
ollama pull llama3

检查员无法连接

问题: web UI连接失败

解决方案:

# Check server path is correct
python server/stdio_server.py  # Should run without errors

# Check Python version
python --version  # Must be 3.10+

工具未出现

问题: list_tools 返回空值

解决方案:

  • 检查 server/registry.py 导入
  • 验证在中注册的所有工具 AVAILABLE_TOOLS
  • 检查服务器日志中的导入错误

项目结构

mcp-toolbox/
├── server/
│   ├── tools/
│   │   ├── __init__.py           # Tool exports
│   │   ├── format_tools.py       # YAML/JSON conversion
│   │   ├── text_tools.py         # Base64, SHA256
│   │   └── network_tools.py      # Port check, URL validation
│   ├── registry.py               # Tool registration
│   ├── stdio_server.py           # STDIO transport
│
├── client/
│   ├── example_usage.py          # Client examples
│   └── inspector_integration.md  # Inspector guide
│
├── host/
│   ├── run_ollama.py            # Ollama integration
│   └── config.yaml              # Host configuration
│
├── tests/
│   ├── test_format_tools.py     # Format tool tests
│   ├── test_text_tools.py       # Text tool tests
│   └── test_network_tools.py    # Network tool tests
│
├── diagrams/
│   ├── architecture.mmd         # System architecture
│   └── lifecycle.mmd            # Request/response flow
│
├── requirements.txt             # Python dependencies
├── .env.example                 # Environment template
├── .gitignore                   # Git ignore rules
└── README.md                    # This file

资源

  • MCP规范: https://spec.modelcontextprotocol.io
  • MCP Python SDK: https://github.com/modelcontextprotocol/python-sdk
  • MCP检查员: https://github.com/modelcontextprotocol/inspector
  • 奥拉马: https://ollama.ai
  • FastAPI: https://fastapi.tiangolo.com

许可证

麻省理工学院许可证-您可以自由地将其用作您自己的MCP服务器的学习资源或起点。

贡献

这是一个学习库。请随意:

  • 添加新工具作为示例
  • 改进文档
  • 修复bug
  • 分享你的实验