Petstore MCP服务器和客户端
Swagger Petstore API的全面模型上下文协议(MCP)实现。该项目包括一个完整的MCP服务器和一个用于无缝代理集成的复杂客户端系统。
概述
该项目提供:
- MCP服务器:完整实现所有Petstore API端点
- MCP客户端:具有代理友好界面的高级客户端
- 代理集成:AI代理的即用型组件
- 配置管理:灵活的配置系统
- 提示模板:针对不同场景的预构建提示
项目结构
petstore/
├── openapi.yaml # OpenAPI 3.0 specification
├── petstore-mcp-server.py # MCP server implementation
├── petstore_mcp_client.py # Comprehensive MCP client
├── agent_interface.py # High-level agent interface
├── transport.py # MCP transport layer
├── prompt_manager.py # Prompt template management
├── sampling.py # AI model sampling configurations
├── client_config.py # Configuration management
├── requirements.txt # Server dependencies
├── client_requirements.txt # Client dependencies
├── mcp-server-config.json # MCP server configuration
├── example_usage.py # Usage examples
├── test_server.py # Server testing script
├── setup.sh # Setup script
└── README.md # This documentation______________________________________________________________________
MCP服务器
特性
MCP服务器提供了对Petstore API的全面访问,提供了三类19种工具:
宠物管理(8个工具)
- add_pet:将新宠物添加到商店
- update_pet:更新现有宠物
- get_pet_by_id:通过ID查找宠物
- find_pets_by_status:按状态查找宠物(可用、待定、已售出)
- find_pets_by_tags:通过标签查找宠物
- update_pet_with_form:使用表单数据更新宠物
- delete_pet:删除宠物
- upload_pet_image:上传宠物图片
店铺运营(4个工具)
- get_investory:按状态获取宠物库存
- 下单:订购宠物
- get_order_by_id:按ID查找采购订单
- 删除订单:按ID删除采购订单
用户管理(7个工具)
- create_user:创建新用户
- create_users_with_list:从列表中创建多个用户
- 登录用户:用户登录系统
- 登录用户:注销当前用户会话
- get_user_by_name:按用户名获取用户
- update_user:更新用户信息
- 删除用户:删除用户
服务器安装
- 安装服务器依赖项:
pip3 install -r requirements.txt- 使服务器可执行:
chmod +x petstore-mcp-server.py- 或者运行安装脚本:
bash setup.sh服务器配置
适用于Amazon Q CLI
将服务器添加到MCP配置中:
{
"mcpServers": {
"petstore": {
"command": "python3",
"args": ["petstore-mcp-server.py"],
"cwd": "/path/to/petstore",
"env": {}
}
}
}运行服务器
# Direct execution
python3 petstore-mcp-server.py
# With Amazon Q CLI
q chat --mcp-server petstore服务器API示例
宠物管理
添加新宠物:
{
"pet": {
"name": "Buddy",
"photoUrls": ["https://example.com/buddy.jpg"],
"category": {
"id": 1,
"name": "Dogs"
},
"tags": [
{
"id": 1,
"name": "friendly"
}
],
"status": "available"
}
}按状态查找宠物:
{
"status": "available"
}门店运营
下订单:
{
"order": {
"petId": 123,
"quantity": 1,
"shipDate": "2024-12-01T10:00:00Z",
"status": "placed",
"complete": false
}
}用户管理
创建用户:
{
"user": {
"username": "johndoe",
"firstName": "John",
"lastName": "Doe",
"email": "john@example.com",
"password": "password123",
"phone": "555-1234",
"userStatus": 1
}
}______________________________________________________________________
MCP客户端
客户端体系结构
MCP客户端系统由多层组成,以实现最大的灵活性和易用性:
核心组件
- 传输层 (
transport.py)
- 处理MCP服务器通信 - 使用异步上下文管理器进行连接管理 - 错误处理和日志
- 配置管理 (
client_config.py)
- 集中配置系统 - 服务器连接设置 - 重试策略和缓存选项
- 及时管理 (
prompt_manager.py)
- 基于模板的提示生成 - 不同操作的不同模板 - 可扩展的提示系统
- 采样配置 (
sampling.py)
- 多种AI模型采样预设 - 不同用例的可配置参数 - 易于配置管理
- 代理接口 (
agent_interface.py)
- 高级任务执行 - 所有组件的无缝集成 - 代理友好型API
客户端安装
- 安装客户端依赖项:
pip3 install -r client_requirements.txt- 确保服务器可用:
# Make sure the MCP server is in the same directory
ls petstore-mcp-server.py客户端使用情况
基本客户端使用
from petstore_mcp_client import PetstoreClient
async def main():
client = PetstoreClient()
async with client.connect():
# Find available pets
pets = await client.find_pets_by_status("available")
# Add a new pet
new_pet = await client.add_pet(
name="Buddy",
photo_urls=["https://example.com/buddy.jpg"],
status="available"
)
# Get inventory
inventory = await client.get_inventory()代理接口使用
from agent_interface import PetstoreAgent
from client_config import ClientConfig
async def main():
# Initialize agent with configuration
config = ClientConfig.default()
agent = PetstoreAgent(config)
# Execute high-level tasks
result = await agent.execute_task("find_pets", status="available")
# Get prompts for AI models
prompt = agent.get_prompt("pet_search", status="available", tags=["friendly"])
# Get sampling configuration
sampling_config = agent.get_sampling_config("balanced")高级客户端功能
from petstore_mcp_client import PetstoreAgent
async def main():
agent = PetstoreAgent()
# Execute complex workflows
workflow_result = await agent.execute_pet_workflow(
"create_pet",
name="Max",
category="Dogs",
tags=["friendly", "large"]
)
# Get store summary
summary = await agent.client.get_store_summary()配置选项
客户端配置
from client_config import ClientConfig, ServerConfig
# Custom configuration
config = ClientConfig(
server=ServerConfig(
command="python3",
args=["./petstore-mcp-server.py"],
timeout=30
),
retry_attempts=3,
retry_delay=1.0,
log_level="INFO",
enable_caching=True,
cache_ttl=300
)采样配置
可用采样预设:
- 保守的:低温,集中反应
- 平衡的:适度的创造力和专注力(默认)
- 创造性的:温度越高,反应越有创意
- 精确的:零温度,确定性响应
from sampling import SamplingManager
sampling = SamplingManager()
# Get different configurations
conservative = sampling.get_config_dict("conservative")
creative = sampling.get_config_dict("creative")提示模板
可用提示模板:
- pet_search:用于查找和过滤宠物
- 宠物管理:用于宠物库存操作
- 订单处理:用于处理客户订单
- 用户管理:用于用户帐户操作
from prompt_manager import PromptManager
prompts = PromptManager()
# Get prompt for pet search
prompt = prompts.get_prompt(
"pet_search",
status="available",
tags=["friendly", "small"]
)代理集成
基于任务的操作
代理界面提供了AI代理可以轻松使用的高级任务:
# Find pets
await agent.execute_task("find_pets", status="available", tags=["friendly"])
# Manage pets
await agent.execute_task("manage_pet", action="add", name="Buddy", photoUrls=["url"])
# Process orders
await agent.execute_task("process_order", action="place", petId=123, quantity=1)
# Manage users
await agent.execute_task("manage_user", action="create", username="john", email="john@example.com")工作流执行
# Pet management workflow
result = await agent.execute_pet_workflow(
"create_pet",
name="Luna",
category="Cats",
tags=["indoor", "quiet"],
photo_urls=["https://example.com/luna.jpg"]
)
# Inventory management workflow
inventory = await agent.execute_pet_workflow("manage_inventory")错误处理
客户端系统包括全面的错误处理:
- 网络错误:使用指数回退自动重试
- API错误:有意义的错误消息和建议
- 验证错误:输入验证和有用的反馈
- 连接错误:优雅的退化和恢复
测试
服务器测试
# Test server functionality
python3 test_server.py客户端测试
# Test client functionality
python3 example_usage.pyapi参考
基本URL
- 生产:
https://petstore3.swagger.io/api/v3
认证
- API特定终结点的密钥身份验证
- OAuth2支持宠物操作
速率限制
- 可配置的重试策略
- 失败请求的指数回退
发展
扩展服务器
- 使用添加新工具功能
@server.call_tool()装饰器 - 更新中的工具定义
handle_list_tools() - 添加适当的错误处理和验证
- 更新文档
扩展客户端
- 添加新方法
PetstoreClient类 - 创建相应的代理工作流
- 为新操作添加提示模板
- 更新配置选项
添加新提示
from prompt_manager import PromptTemplate
# Create new template
template = PromptTemplate(
system="You are a pet care specialist.",
user_template="Provide care advice for {pet_type} with {condition}",
examples={"basic": "Care for a sick dog"}
)
# Add to manager
prompt_manager.add_template("pet_care", template)安全考虑
- API密钥处理安全
- 密码不会被记录或缓存
- 所有API调用的HTTPS连接
- 输入验证和净化
- 错误消息不会暴露敏感信息
演出
- 非阻塞操作始终异步/等待
- HTTP请求的连接池
- 可配置的TTL缓存
- 高效的JSON解析和序列化
贡献
- 分叉存储库
- 创建要素分支
- 添加新功能的测试
- 更新文档
- 提交拉取请求
许可证
该项目遵循与Swagger Petstore API(Apache 2.0)相同的许可证。
支持
对于问题和疑问:
- 检查示例使用脚本
- 查看测试文件
- 检查配置选项
- 用详细信息创建问题
