Token导航 LogoToken导航TokenDH.com
Resty MCP Example logo
数据服务stdio官方级别未说明来源级核验

Resty MCP Example

MCP Server

一个基于FastAPI构建的REST API示例,模拟宠物领养系统,支持基本的CRUD操作、数据库集成和RESTful API设计。

工具数

12

提示词数

0

GitHub Stars

0

资源数

0
Python数据库集成API集成

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

amfred

提供方

amfred

最后核验

2026/5/17 20:20

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

pip install -r requirements.txt

详细介绍

Resty MCP示例-宠物收养API

一个有趣的REST API示例使用FastAPI构建,模拟宠物收养系统。该项目演示了基本的CRUD操作、数据库集成和RESTful API设计。

特性

  • 🐕 宠物管理:添加、查看、更新和删除宠物
  • 🔍 搜索和筛选:按物种、品种或可用性搜索宠物
  • 🏠 收养制度:将宠物标记为领养
  • 📊 SQLite数据库:持久数据存储
  • 🌐 CORS已启用:已准备好进行前端集成

快速开始

  1. 安装依赖项:
   pip install -r requirements.txt
  1. 运行应用程序:
   python app.py
  1. 访问API:

- API基本URL: http://localhost:5001 - 服务器将自动创建数据库并添加示例宠物

API终点

基本信息

  • GET / -API信息和可用端点

宠物操作

  • GET /pets -获取所有宠物
  • POST /pets -添加新宠物
  • GET /pets/ -养一只特定的宠物
  • PUT /pets//adopt -通过身份证领养宠物
  • PUT /pets/adopt?name= -按名字领养宠物
  • DELETE /pets/ -删除宠物
  • GET /pets/search -使用过滤器搜索宠物

搜索参数

  • species -按物种过滤(例如。, ?species=dog)
  • breed -按品种过滤(例如。, ?breed=golden)
  • available_only -仅显示可用的宠物(例如。, ?available_only=true)

示例用法

获取所有宠物

curl http://localhost:5001/pets

添加新宠物

curl -X POST http://localhost:5001/pets \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Fluffy",
    "species": "Cat",
    "breed": "Maine Coon",
    "age": 2,
    "description": "Very fluffy and friendly"
  }'

通过身份证领养宠物

curl -X PUT http://localhost:5001/pets/1/adopt

按名字领养宠物

curl -X PUT "http://localhost:5001/pets/adopt?name=Tweety"

搜索可用的狗

curl "http://localhost:5001/pets/search?species=dog&available_only=true"

新功能:按名称采用

API现在支持按名称收养宠物,这使得收养宠物变得更容易,而无需首先知道他们的身份证。

端点: PUT /pets/adopt?name=

参数:

  • name (必填):要收养的宠物的名称(不区分大小写的部分匹配)

响应示例:

成功(200):

{
  "message": "Tweety has been successfully adopted!",
  "pet": {
    "id": 3,
    "name": "Tweety",
    "species": "Bird",
    "breed": "Canary",
    "age": 1,
    "description": "Sings beautifully",
    "is_adopted": true,
    "created_at": "2024-01-15T10:30:00"
  }
}

错误案例:

  • 未找到宠物(404): {"error": "No pet found with name containing \"NonExistentPet\""}
  • 已通过(400): {"error": "Tweety is already adopted"}
  • 缺少名称(400): {"error": "Name parameter is required"}

使用示例:

# Adopt Tweety
curl -X PUT "http://localhost:5001/pets/adopt?name=Tweety"

# Adopt Buddy (partial name match works)
curl -X PUT "http://localhost:5001/pets/adopt?name=Bud"

# Try to adopt already adopted pet
curl -X PUT "http://localhost:5001/pets/adopt?name=Tweety"

测试

该项目包括全面的测试套件,涵盖所有API端点、完全符合MCP规范、错误处理和边缘案例。

测试覆盖率

该项目包括 两套全面的测试套件:

1.REST API测试套件(test_api.py) - 23种测试方法:

  • ✅ 所有REST API端点(14个端点)
  • ✅ MCP服务器的基本功能(JSON-RPC 2.0协议)
  • ✅ 验证和错误处理
  • ✅ CORS功能
  • ✅ 边缘案例和负面情景
  • ✅ 适当的测试隔离和清理

2.MCP合规性测试套件(test_mcp_compliance.py) - 30种测试方法:

  • 完全符合MCP协议 (2025年10月规范)
  • 扩展MCP功能:工具、资源、提示、日志记录
  • JSON-RPC 2.0协议验证:所有错误代码和边缘情况
  • 协议版本协商:版本兼容性测试
  • 结构化工具输出:工具响应格式的验证
  • 会话生命周期管理:完成工作流测试
  • 性能和可靠性:并发请求,大负载
  • 安全性测试:输入净化、限速意识
  • 边界测试:边缘情况,参数验证

先决条件

  1. 安装测试依赖项:
   pip install -r requirements-test.txt
  1. 启动API服务器 (集成测试所需):
   python app.py

服务器应在以下位置运行 http://127.0.0.1:5001 在运行测试之前。

运行测试

REST API测试

# Make the script executable (first time only)
chmod +x run_tests.sh

# Run REST API tests with different options:
./run_tests.sh                    # Default: pytest mode
./run_tests.sh pytest            # Pytest with verbose output (recommended)
./run_tests.sh coverage          # With coverage analysis
./run_tests.sh html              # Generate HTML test report
./run_tests.sh ci                # CI mode with JUnit XML output
./run_tests.sh quick             # Quick smoke tests only

MCP合规性测试⭐

# Make the script executable (first time only)
chmod +x run_mcp_compliance_tests.sh

# Run MCP compliance tests with different options:
./run_mcp_compliance_tests.sh                # Default: pytest mode
./run_mcp_compliance_tests.sh pytest        # Pytest with verbose output (recommended)
./run_mcp_compliance_tests.sh coverage      # With coverage analysis
./run_mcp_compliance_tests.sh html          # Generate HTML test report  
./run_mcp_compliance_tests.sh ci            # CI mode with JUnit XML output
./run_mcp_compliance_tests.sh quick         # Quick MCP smoke tests only
./run_mcp_compliance_tests.sh unittest      # Run with unittest

直接命令

REST API测试:

# Using pytest (recommended)
pytest test_api.py -v

# Using unittest
python test_api.py

# With coverage
coverage run -m pytest test_api.py
coverage report
coverage html  # Generates htmlcov/ directory

# Generate HTML test report
pytest test_api.py --html=test_report.html --self-contained-html

MCP合规性测试:

# Using pytest (recommended)
pytest test_mcp_compliance.py -v

# Using unittest
python test_mcp_compliance.py

# With coverage
coverage run -m pytest test_mcp_compliance.py
coverage report
coverage html --directory htmlcov_mcp  # Generates htmlcov_mcp/ directory

# Generate HTML test report
pytest test_mcp_compliance.py --html=mcp_compliance_report.html --self-contained-html

测试结构

REST API测试结构(test_api.py)

API核心测试(001-006):

  • API信息终结点
  • 获取所有宠物
  • 宠物统计摘要
  • 可用宠物筛选
  • 有效物种列表
  • 宠物搜索功能

原油操作(007-016):

  • 创建宠物(带验证)
  • 通过ID获取宠物
  • 更新宠物信息
  • 收养宠物(按身份证和姓名)
  • 删除宠物
  • 批量创建宠物

MCP服务器测试(017-021):

  • 工具定义端点
  • MCP初始化
  • JSON-RPC工具列表
  • 通过JSON-RPC执行工具
  • 错误处理

边缘案例和功能(022-023):

  • CORS标头验证
  • 已删除端点验证

MCP合规性测试结构(test_mcp_compliance.py) ⭐

核心协议合规性(001-007):

  • MCP初始化和协议版本协商
  • 服务器功能验证和增强
  • 工具列表全面验证
  • 具有结构化输出验证的工具调用
  • 工具调用错误处理

JSON-RPC协议合规性(008-010):

  • JSON-RPC 2.0格式验证
  • 标准JSON-RPC错误代码测试
  • 请求ID处理验证

高级MCP功能(011-013):

  • 结构化工具输出合规性(MCP 2025要求)
  • 客户端和服务器之间的能力协商
  • 完成会话生命周期测试

性能和可靠性(014-015):

  • 并发请求处理
  • 大载荷处理

安全与验证(016-017):

  • 输入净化和验证
  • 限速意识测试

边缘案例和边界(018-020):

  • 边界值测试
  • 方法名称区分大小写
  • 空和null参数处理

扩展MCP功能(021-030) - 2025年10月合规:

  • 资源: resources/listresources/read 方法
  • 鼓励: prompts/listprompts/get 方法
  • 日志记录: logging/setLevel 方法
  • 增强的功能验证
  • 完成MCP工作流程测试

持续集成

该项目包括GitHub Actions工作流,这些工作流:

  • 在多个Python版本(3.8、3.9、3.10、3.11)上运行测试
  • 生成测试报告和覆盖率分析
  • 将结果发布为工件
  • 将覆盖范围上传到Codecov

工作流触发器:

  • 推到 maindevelop 分支
  • 将请求拉到 main

测试特性

  • 独立测试:每个测试都是完全隔离的,可以独立运行
  • 自动清理:测试会清理它们创建的任何数据
  • 全面覆盖:测试所有端点、错误情况和边缘场景
  • 多种输出格式:JUnitXML、HTML报告、覆盖率分析
  • CI/CD就绪:完全集成GitHub Actions

测试输出示例

$ ./run_tests.sh pytest

🧪 Pet Adoption API Test Suite
================================
✅ API server is running
✅ Test dependencies installed
🏃 Running tests with pytest...

test_api.py::PetAdoptionAPITest::test_001_api_info PASSED
test_api.py::PetAdoptionAPITest::test_002_get_all_pets PASSED
test_api.py::PetAdoptionAPITest::test_003_get_pets_summary PASSED
...
test_api.py::PetAdoptionAPITest::test_023_removed_streaming_endpoints PASSED

========================= 23 passed in 2.34s =========================

✅ Test execution completed!

MCP(模型上下文协议)合规性⭐

该项目现在包括 完全符合 随着 2025年10月MCP规范,使其成为MCP服务器的优秀参考实现。

MCP功能已实现

🔧 核心MCP协议

  • JSON-RPC 2.0 具有适当错误处理的协议支持
  • 协议版本协商 (支持MCP 2025-06-18)
  • 完成会话生命周期 (初始化→ 已初始化→ 操作)
  • 结构化工具输出 通过适当的内容类型验证

🛠️ 工具能力

  • 7个优化工具 用于宠物收养业务
  • 动态工具执行 带参数验证
  • 全面的工具模式 具有输入/输出定义
  • 错误处理 带有正确的JSON-RPC错误代码

📁 资源能力

  • 3个样本资源:收养表格、护理指南、疫苗接种时间表
  • 资源列表 通过 resources/list 方法
  • 资源阅读 通过 resources/read 支持URI的方法
  • MIME类型支持 适用于不同的资源格式

💬 提示能力

  • 3个专业提示 对于宠物收养场景:

- 领养助理:帮助用户找到完美的宠物 - 宠物护理顾问:提供针对特定物种的护理建议 - 领养表格助手:通过收养过程提供指导

  • 动态提示生成 带参数插值
  • 结构化消息格式 基于角色的内容

📊 日志记录能力

  • 日志级别管理 通过 logging/setLevel 方法
  • 标准日志级别 (调试、信息、警告、错误等)
  • 级别验证 具有适当的错误响应

支持的MCP方法

方法描述状态
initialize使用功能初始化MCP会话✅ 满
initialized确认初始化完成✅ 满
tools/list列出可用工具✅ 满
tools/call执行工具✅ 满
resources/list列出可用资源✅ 满
resources/read阅读特定资源✅ 满
prompts/list列出可用的提示模板✅ 满
prompts/get获取特定提示✅ 满
logging/setLevel设置日志记录级别✅ 满

MCP合规性测试

全面的MCP合规性测试套件(test_mcp_compliance.py)验证:

  • 协议遵从:完全遵守JSON-RPC 2.0
  • 版本协商:协议版本兼容性
  • 能力声明:适当的服务器功能
  • 错误处理:所有JSON-RPC错误代码和边缘情况
  • 安全:输入净化和验证
  • 演出:并发请求和大负载
  • 边界测试:边缘情况和参数验证

MCP使用示例

# Initialize MCP session
curl -X POST http://localhost:5001/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "initialize", 
    "id": 1,
    "params": {
      "protocolVersion": "2025-06-18",
      "capabilities": {},
      "clientInfo": {"name": "my-client", "version": "1.0.0"}
    }
  }'

# List available resources
curl -X POST http://localhost:5001/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "resources/list",
    "id": 2,
    "params": {}
  }'

# Get a prompt template
curl -X POST http://localhost:5001/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "prompts/get",
    "id": 3,
    "params": {
      "name": "adoption_assistant",
      "arguments": {"user_preferences": "small dog, apartment-friendly"}
    }
  }'

为什么这一实施很重要

该项目作为 参考实现 用于:

  • 🏗️ MCP服务器开发:MCP合规性的完整工作示例
  • 📋 规范验证:MCP要求的全面测试覆盖率
  • 🔍 一致性测试:MCP验证的可重用测试模式
  • 📚 学习资源:记录良好的MCP集成示例
  • 🚀 生产就绪:经过全面错误处理和边缘案例的战斗测试

✅ 测试执行完成!


## Database Schema

The `Pet` model includes:
- `id` - Primary key
- `name` - Pet's name
- `species` - Type of animal (Dog, Cat, Bird, etc.)
- `breed` - Specific breed
- `age` - Age in years
- `description` - Additional details
- `is_adopted` - Adoption status
- `created_at` - Timestamp when added

## Sample Data

The application comes with 5 sample pets:
- Buddy (Golden Retriever)
- Whiskers (Persian Cat)
- Tweety (Canary)
- Max (Labrador)
- Luna (Siamese Cat)

## MCP Tools vs REST APIs Comparison

This project provides **dual interfaces** for different integration scenarios:

### 🔧 MCP Tools (12 total) - LLM Optimized

| Tool | Description | Use Case |
|------|-------------|----------|
| `list_all_pets` | Get complete list of all pets | Overview for AI assistants |
| `get_pet_by_id` | Get specific pet by ID | Direct pet lookup |
| `get_pet_by_name` | Find pet by name | Natural language queries |
| `create_pet` | Add new pet to system | Pet registration |
| `update_pet_info` | Update pet details | Information management |
| `delete_pet` | Remove pet by ID or name | Pet removal |
| `adopt_pet_by_name` | Adopt pet by searching name | Natural adoption process |
| `search_pets` | Search with filters | Advanced pet discovery |
| `get_available_pets` | Get adoptable pets only | Adoption-focused queries |
| `get_pets_summary` | Get comprehensive statistics | Data analysis |
| `get_valid_species` | Get valid pet species list | Form validation |
| `get_adoption_stats` | Get adoption statistics | Reporting and analytics |

### 🌐 REST API Endpoints (12 total) - Programmatic Integration

| Endpoint | Method | Description | Use Case |
|----------|--------|-------------|----------|
| `/api/v1/pets/` | GET | List all pets | Data retrieval |
| `/api/v1/pets/` | POST | Create new pet | Pet registration |
| `/api/v1/pets/{id}` | GET | Get pet by ID | Direct lookup |
| `/api/v1/pets/{id}` | PUT | Update pet | Information management |
| `/api/v1/pets/{id}` | DELETE | Delete pet | Pet removal |
| `/api/v1/pets/{id}/adopt` | PUT | Adopt pet by ID | Adoption process |
| `/api/v1/pets/adopt` | PUT | Adopt pet by name | Name-based adoption |
| `/api/v1/pets/search` | GET | Search with filters | Advanced queries |
| `/api/v1/pets/available` | GET | Get available pets | Adoption focus |
| `/api/v1/pets/summary` | GET | Get statistics | Data analysis |
| `/api/v1/pets/species` | GET | Get valid species | Form validation |
| `/api/v1/pets/batch` | POST | Create multiple pets | Bulk operations |

### 🎯 Design Rationale: Why the Lists Are Different

#### **MCP Tools Focus on LLM Interactions:**
- **Natural Language Operations**: Tools like `get_pet_by_name` and `adopt_pet_by_name` are optimized for conversational AI
- **High-Level Abstractions**: `get_pets_summary` and `get_adoption_stats` provide aggregated insights
- **Semantic Operations**: Focus on business logic rather than CRUD operations
- **Flexible Input**: Tools accept both ID and name parameters for maximum flexibility

#### **REST APIs Focus on Programmatic Integration:**
- **Standard HTTP Methods**: Proper use of GET, POST, PUT, DELETE following REST conventions
- **Resource-Based URLs**: Clear resource hierarchy (`/pets/{id}`, `/pets/{id}/adopt`)
- **HTTP Status Codes**: Appropriate status codes for different scenarios
- **Batch Operations**: `POST /batch` for bulk operations not available in MCP
- **Granular Control**: More specific endpoints for different use cases

#### **Complementary Coverage:**
- **No Redundancy**: Each interface serves its target audience effectively
- **Complete Coverage**: All major operations available through at least one interface
- **Appropriate Granularity**: MCP tools are higher-level, REST APIs are more granular
- **Different Strengths**: MCP excels at natural language, REST excels at programmatic control

### 📊 Coverage Analysis

| Functionality | MCP Tool | REST API | Coverage |
|---------------|----------|----------|----------|
| **List All Pets** | ✅ | ✅ | Both |
| **Get Pet by ID** | ✅ | ✅ | Both |
| **Get Pet by Name** | ✅ | ❌ | MCP only |
| **Create Pet** | ✅ | ✅ | Both |
| **Update Pet** | ✅ | ✅ | Both |
| **Delete Pet** | ✅ | ✅ | Both |
| **Adopt by ID** | ❌ | ✅ | REST only |
| **Adopt by Name** | ✅ | ✅ | Both |
| **Search Pets** | ✅ | ✅ | Both |
| **Get Available** | ✅ | ✅ | Both |
| **Get Summary** | ✅ | ✅ | Both |
| **Get Species** | ✅ | ✅ | Both |
| **Batch Create** | ❌ | ✅ | REST only |
| **Get Stats** | ✅ | ❌ | MCP only |

### 🏆 Result: Exemplary API Design

This implementation demonstrates **excellent API design principles**:
- **MCP tools** are optimized for AI/LLM interactions with natural language operations
- **REST APIs** provide comprehensive programmatic access with standard HTTP conventions
- **Both interfaces** serve their intended audiences without unnecessary overlap
- **The balance** is nearly perfect for a pet adoption system

This project shows how to properly design dual interfaces for different integration scenarios!

## Demo Scripts

This project includes comprehensive demo scripts that show how to integrate with LLMs using the MCP protocol:

### 🤖 `demo_mcp_flow.sh` - MCP Integration Flow Demo

A complete demonstration of the MCP server interaction flow:

./demo_mcp_flow.sh


**它展示了什么:**

- ✅ MCP会话初始化
- ✅ 从服务器检索可用工具
- ✅ 使用工具模式构建LLM请求
- ✅ 直接执行工具调用
- ✅ 格式化和显示结果

**特征:**

- 不需要API密钥(脱机工作)
- 显示LLM集成的完整curl命令
- 演示所有12个可用的MCP工具
- 提供不同查询的示例工具调用

### 🚀 `demo_llm_integration.sh` -完整的LLM集成演示

具有实际LLM集成的完整端到端演示:

export OPENAI_API_KEY='your-api-key' ./demo_llm_integration.sh


**它展示了什么:**

- ✅ 完成MCP到LLM的集成流程
- ✅ 向OpenAI GPT-4发送工具模式
- ✅ 接收和解析LLM工具调用
- ✅ 执行LLM请求的工具调用
- ✅ 格式化结果以供显示

**要求:**

- OpenAI API密钥
- `jq` 命令行JSON处理器
- 正在运行MCP服务器

### 📋 示例用法

**查询:“列出所有可供收养的宠物”**

1. **MCP服务器响应** (工具/列表):

{ "name": "get_available_pets", "description": "Get all pets that are currently available for adoption" }


1. **LLM请求** (OpenAI聊天完成):

curl -X POST https://api.openai.com/v1/chat/completions \ -H 'Authorization: Bearer $OPENAI_API_KEY' \ -d '{ "model": "gpt-4o", "messages": [{"role": "user", "content": "List available pets"}], "tools": [...tool_schemas...], "tool_choice": "auto" }'


1. **LLM响应** (工具调用):

{ "function": { "name": "get_available_pets", "arguments": "{}" } }


1. **MCP工具执行**:

curl -X POST http://127.0.0.1:5001/api/v1/mcp/ \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "get_available_pets", "arguments": {} } }'


1. **最终结果**:

{ "content": [{ "type": "text", "text": "[{\"name\": \"Fluffy\", \"species\": \"Cat\", \"is_adopted\": false}]" }] }


### 🎯 关键利益

- **完全集成**:显示完整的MCP到LLM工作流
- **真实案例**:使用实际的API调用和响应
- **教育的**:非常适合学习MCP协议实施
- **生产就绪**:演示正确的错误处理和验证
- **可扩展**:易于为不同的LLM提供商进行修改

## 发展

这是一个简单的FastAPI应用程序,非常适合:

- 学习REST API概念
- 了解数据库集成
- 练习CRUD操作
- 构建前端应用程序

您可以随时通过用户身份验证、照片上传或更复杂的关系等附加功能对其进行扩展!

## 许可证

此项目根据Apache许可证2.0获得许可-请参阅 [许可证](LICENSE) 文件以获取详细信息。

版权所有2025 Red Hat,股份有限公司。

根据Apache许可证2.0版(“许可证”)许可;
除非遵守许可证,否则您不得使用此文件。
您可以在以下网址获得许可证副本

http://www.apache.org/licenses/LICENSE-2.0


除非适用法律要求或书面同意,否则软件
根据许可证分发的内容按“原样”分发,
无任何明示或暗示的保证或条件。
请参阅许可证,了解管理权限和
许可证下的限制。

目录标签

目录标签

Python数据库集成API集成宠物管理本地部署RESTAPICRUD操作领养系统

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

token

工具数量(toolCount,工具数)

12

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdiotoken部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP