REST API和MCP服务器

一个在Cloudflare Workers上同时提供REST API和MCP(Model Context Protocol)接口的服务。

  • by HeyGarrison
  • TypeScript
  • 本地部署
  • 6 星标
  • 更新于
在 GitHub 查看 HeyGarrison/cf-mcp

使用说明

CF-MCP:Cloudflare Workers上的REST API+MCP服务器

一个单一的Cloudflare Worker,同时为REST API和MCP(模型上下文协议)接口提供服务。

建筑

┌─────────────────────────────────────┐
│   Cloudflare Worker (Edge)          │
│                                      │
│  ┌────────────────────────────────┐ │
│  │  Hono Router                   │ │
│  │                                │ │
│  │  /api/*  ─── REST API          │ │
│  │                                │ │
│  │  /mcp    ─── MCP Protocol      │ │
│  │               (wraps REST)     │ │
│  └────────────────────────────────┘ │
└─────────────────────────────────────┘

特性

REST API端点

  • GET /api/products -列出所有产品(带筛选)
  • GET /api/products/:id -获取单一产品
  • POST /api/products -创建新产品
  • PUT /api/products/:id -更新产品
  • DELETE /api/products/:id -删除产品

MCP工具

MCP端点将所有REST操作打包为工具:

  • list_products -使用筛选器查询产品
  • get_product -检索产品详细信息
  • create_product -添加新产品
  • update_product -修改现有产品
  • delete_product -删除产品

入门指南

再进行

npm install

在本地运行

npm run dev

服务器将在以下时间启动 http://localhost:8787

测试REST API

# List all products
curl http://localhost:8787/api/products

# Get a specific product
curl http://localhost:8787/api/products/1

# Filter by category
curl http://localhost:8787/api/products?category=Electronics

# Create a product
curl -X POST http://localhost:8787/api/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Laptop","price":999,"description":"Powerful laptop","category":"Electronics"}'

测试MCP端点

# List available tools
curl -X POST http://localhost:8787/mcp \
  -H "Content-Type: application/json" \
  -d '{"method":"tools/list","params":{}}'

# Call a tool
curl -X POST http://localhost:8787/mcp \
  -H "Content-Type: application/json" \
  -d '{"method":"tools/call","params":{"name":"list_products","arguments":{"category":"Electronics"}}}'

部署到Cloudflare

npm run deploy

部署后,您的API将在Cloudflare的边缘网络上全球可用!

展示的关键模式

1.REST到MCP的转换

每个REST端点都映射到MCP工具:

  • REST参数→ MCP工具参数
  • REST响应→ MCP工具结果
  • REST身份验证→ MCP工具上下文

2.边缘部署

  • 单个工作人员同时服务于两个接口
  • 通过Cloudflare网络进行全球分发
  • REST和MCP调用的低延迟

3.统一代码库

  • 在REST和MCP之间共享业务逻辑
  • DRY原则:定义一次操作
  • 易于维护和扩展

项目结构

cf-mcp/
├── src/
│   ├── index.ts      # Main Hono app + routing
│   ├── api.ts        # REST API endpoints
│   └── mcp.ts        # MCP protocol handler
├── wrangler.toml     # Cloudflare config
├── package.json
└── tsconfig.json

后续步骤

  1. 添加身份验证(API密钥、OAuth)
  2. 实施速率限制
  3. 使用Cloudflare KV添加缓存
  4. 连接到Cloudflare D1进行持久存储
  5. 添加流媒体响应
  6. 实现分页

了解更多

课程名称

“从边缘和背面:将任何REST API转换为MCP服务器”

一个实用的代码重会话,展示了如何使用模型上下文协议包装任何REST API,并将其部署到Cloudflare Workers以实现轻量级、全局分布式访问。