使用说明
MCP沙盒-Claude+MCP服务器集成
一个可用于生产的Python应用程序,演示了使用Claude API和模块化架构实现的适当MCP(模型上下文协议)。
🚀 这是什么
该项目展示 生产就绪的MCP集成 与:
- 模块化架构:为清楚起见,将客户端和服务器包分开
- MCP协议:使用单独的服务器进程进行正确的stdio传输
- 真实MCP服务器:使用官方
mcp使用FastMCP的库 - SQLite数据库:真实数据持久性和操作
- 生产特点:错误处理、监控、度量和重试逻辑
- 综合测试:涵盖所有功能的45项测试
非常适合学习MCP概念和构建生产就绪的MCP集成。
📁 项目结构
mcp-sandbox/
├── main.py # 🚀 MAIN ENTRY POINT
├── pyproject.toml # Poetry dependencies & config
├── Makefile # Development commands
├── data/ # SQLite database files
├── logs/ # Application logs
├── config/ # MCP server configuration
├── docs/ # Documentation
│ ├── ARCHITECTURE.md # Module architecture details
│ └── PRODUCTION.md # Production deployment guide
├── tests/ # Test suite (45 tests)
│ ├── test_main.py # Main entry point tests
│ ├── test_client.py # Client tests
│ └── test_server.py # Server tests
└── src/
└── mcp_sandbox/ # Main package
├── __init__.py # Package exports
├── client/ # MCP Client (connects to Claude)
│ ├── __init__.py # Client exports
│ ├── app.py # MCPClient - main orchestration
│ ├── session.py # MCPSessionManager - server connections
│ ├── metrics.py # Request metrics collection
│ └── chat.py # MCPChat - interactive interface
└── server/ # MCP Server (provides tools)
├── __init__.py # Server exports
├── __main__.py # Module entry point (python -m)
├── app.py # FastMCP server setup
├── database.py # SQLite operations
└── tools.py # MCP tool definitions (5 tools)
🔧 关键组件
1. 主要入口点(main.py)
- 演示模式,包含6个示例查询
- 与Claude互动聊天
- 简单的命令行界面
2. 客户端包(client/)
app.py-MCPClient用于Claude API集成的类- 通过重试逻辑和指数回退增强错误处理
- 请求指标跟踪
- 会话管理
session.py-MCPSessionManager用于MCP服务器连接- 基于JSON的配置管理
- 健康监测和自动恢复
- 工具执行路线
metrics.py-请求度量和报告chat.py-MCPChat交互界面- 命令:
/help,/clear,/metrics,/quit - 自然语言数据库交互
- 命令:
3. 服务器包(server/)
app.py-FastMCP服务器设置和初始化database.py-SQLite连接和模式管理tools.py-5 MCP工具实现:execute_sql_query-参数化SQL查询get_database_schema-完整的数据库结构get_table_info-详细表格分析insert_user-安全的用户插入和验证search_users-使用过滤器进行灵活的用户搜索
__main__.py-模块入口点(python -m mcp_sandbox.server)
🎯 特性
✅ 模块化架构 -单独的客户端和服务器包
✅ 生产准备就绪 -错误处理、监控、度量、重试逻辑
✅ 真实MCP服务器 -官方 mcp 使用FastMCP的库
✅ 综合测试 -45次测试,通过率100%
✅ 结构化日志记录 -具有stderr分隔的基于文件的日志
✅ 健康监测 -自动服务器健康检查
✅ 配置管理 -基于JSON的服务器配置
✅ 交互式聊天 -自然语言数据库交互
✅ 工具调用 -Claude可以使用所有5个数据库工具
✅ SQLite后端 -真实数据持久性
✅ 诗歌管理 -现代依赖关系管理
✅ 代码质量 -Ruff、isort和综合棉绒
🚀 快速开始
1. 设置环境
# Clone and setup
cd mcp-sandbox
poetry install
# Set up your Claude API key
echo "export ANTHROPIC_API_KEY=your_key_here" > .envrc
source .envrc # or use direnv
2. 运行演示
使用生成命令(推荐):
# Run demo with 6 example queries
make demo
# Interactive chat with Claude
make chat
# Run test suite (45 tests)
make test
# Format and check code
make check
# Complete development setup
make dev-setup
# See all available commands
make help
使用诗歌脚本:
# Run demo
poetry run demo
# Interactive chat
poetry run chat
# Run test suite
poetry run pytest
手动执行:
# Demo mode
poetry run python main.py
# Interactive chat mode
poetry run python main.py --chat
3. 获得帮助
poetry run python main.py --help
💬 交互示例
🧑💻 You: What tables are in my database?
🤖 Claude: Based on the schema, there is currently 1 table:
1. `users` table with columns:
- id (INTEGER, Primary Key, Auto-incrementing)
- name (TEXT, Not Null)
- email (TEXT, Unique)
- age (INTEGER)
- created_at (DATETIME, Default: current timestamp)
🧑💻 You: Show me all users over 30 years old
🤖 Claude: [Executes search_users tool with min_age filter]
Found 2 users over 30:
1. Bob Smith (34 years old, bob@test.com)
2. Alice Johnson (32 years old, alice@test.com)
🧑💻 You: Add a new user named Sarah with email sarah@test.com and age 28
🤖 Claude: [Uses insert_user tool with validation]
✅ Successfully added Sarah to the database!
- Name: Sarah, Email: sarah@test.com, Age: 28, ID: 8
🧪 测试
该项目包括涵盖所有组件的全面测试:
运行测试
# Run all tests (recommended)
make test
# Alternative syntax
poetry run pytest
# Run with verbose output
poetry run pytest -v
# Run specific test file
poetry run pytest tests/test_client.py
# Run specific test
poetry run pytest tests/test_main.py::TestMainEntryPoints::test_run_demo
测试覆盖率(45次测试)
- 主要入口点 (10个测试)-CLI、演示模式、聊天模式、错误处理
- 客户端程序包 (16个测试)-指标收集、会话管理、配置
- 服务器包 (19项测试)-数据库操作、工具执行、验证
测试结构
tests/
├── conftest.py # Test configuration and fixtures
├── test_main.py # Main entry point tests (10 tests)
├── test_client.py # Client package tests (16 tests)
└── test_server.py # Server package tests (19 tests)
主要特点:
- ✅ 100%测试通过率,无警告
- ✅ 使用pytest-asyncio支持异步测试
- ✅ 协程的正确模拟配置
- ✅ 全面覆盖错误场景
🛠️ 建筑
系统架构
main.py
↓
MCPClient (client/app.py)
↓
MCPSessionManager (client/session.py)
↓
[stdio transport / JSON-RPC]
↓
FastMCP Server (server/app.py)
↓
Tools (server/tools.py)
↓
SQLite Database (server/database.py)
关键设计原则
- ✅ 模块化 -客户端和服务器的单独包
- ✅ MCP协议 -行业标准标准标准传输
- ✅ 进程隔离 -服务器作为独立进程运行
- ✅ JSON-RPC通信 -正确的MCP消息处理
- ✅ 生产就绪 -错误处理、监控、指标
- ✅ 可测试性 -全面的测试覆盖率
模块职责
- 客户端程序包:Claude API集成、会话管理、指标
- 服务器包:MCP工具实施、数据库操作
- 主条目:CLI界面、演示和聊天模式
🧪 使用模式
演示模式
- 运行6个示例查询,展示所有工具
- 非常适合测试和演示
- 显示正在运行的MCP协议
make demo
# or
poetry run demo
交互式聊天
- 数据库的自然语言界面
- 使用工具与Claude进行全面对话
- 命令:
/help,/clear,/metrics,/quit
make chat
# or
poetry run chat
🔍 学习领域
1.MCP协议实施
- 标准传输设置和通信(
client/session.py) - JSON-RPC消息处理
- 工具定义和执行(
server/tools.py) - 使用重试逻辑进行错误处理和恢复
2.FastMCP服务器开发
- 向装饰师注册工具(
server/tools.py) - 输入验证和模式定义
- 具有安全性的数据库操作(
server/database.py) - 基于模块的服务器执行(
server/__main__.py)
3.Claude API集成
- 具有适当格式的工具调用(
client/app.py) - 会话管理
- 工具结果处理
- 请求指标收集(
client/metrics.py) - 速率限制的指数回退
4.模块化架构
- 包装结构和组织
- 关注点分离(客户端与服务器)
- 配置管理(
client/session.py) - 使用stdout/stderr分隔进行日志记录
📊 数据库模式
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE,
age INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
🔧 依赖项
核心:
mcp^1.0.0-官方模型上下文协议库anthropic^0.34.0-Claude API客户python-dotenv^1.0.0-环境变量管理httpx<0.28-HTTP客户端(版本固定以兼容)
内置:
sqlite3-数据库操作asyncio-异步支持pathlib-文件路径处理
🛠️ 开发工作流程
该项目包括一个全面的Makefile,用于简化开发:
开发命令
# Complete development setup
make dev-setup # Install deps, check code, run tests
# Code quality and formatting
make lint # Check code quality (no fixes)
make format # Format code with ruff and isort
make check # Check and auto-fix all issues
# Testing and demos
make test # Run test suite
make demo # Quick demo (direct mode)
make chat # Interactive chat (direct mode)
make demo-mcp # Demo with MCP protocol
make chat-mcp # Chat with MCP protocol
# Maintenance
make clean # Clean cache files
make install # Install dependencies
make all # Complete CI pipeline
代码质量工具
- 拉夫:现代Python linter和格式化程序
- isort:进口排序和组织
- pytest:综合测试框架
- 诗歌:依赖关系管理和虚拟环境
所有工具均已配置 pyproject.toml 使用特定于项目的设置,在保持可读性的同时实现最佳代码质量。
🏆 主要成就
该项目展示了:
- 真正的MCP实施 -使用官方MCP库和FastMCP
- 生产模式 -错误处理、重试逻辑、监控、指标
- 模块化架构 -客户端和服务器问题的清晰分离
- 综合测试 -45次测试,100%通过率,零警告
- 现代工具 -诗歌、拉夫、伊索、适当的包装结构
- 代码质量 -严格的剪裁、格式化和类型检查
- 教育价值 -记录良好、代码组织清晰
🤝 后续步骤
学习:
- 探索模块化架构
src/mcp_sandbox/ - 阅读代码——它有很好的文档记录和组织
- 尝试交互式聊天功能
- 添加新工具
server/tools.py - 修改和扩展客户端功能
生产:
- 查看中的生产部署指南
docs/PRODUCTION.md - 添加身份验证和授权
- 实施限速和资源管理
- 连接到真实的数据源和API
- 部署为微服务或容器
- 设置监控和警报
📚 资源
快乐学习与建设! 🎉
这个沙箱为现实世界的MCP应用程序提供了实用的模式。从演示开始,探索代码,构建自己的MCP集成!