使用说明
MCP API转换器
使用简单、可扩展的TypeScript框架将REST API转换为模型上下文协议(MCP)工具。
概述
MCP API转换器提供了一个框架,用于将REST API包装为MCP工具,使人工智能助手和其他MCP客户端可以访问它们。该系统使用可扩展的基于类的体系结构,其中每个API实现扩展一个基类以自动与MCP服务器集成。
特性
- 可扩展工具框架:用于创建新API工具的简单基类
- HTTP传输:通过HTTP公开支持MCP协议的工具
- 多级日志记录:具有可配置级别的全面日志记录
- 类型安全:使用TypeScript构建,用于健壮的类型检查
- 天气API示例:包括工作天气API工具实现
建筑
MCP API转换器采用分层架构:
┌─────────────────────────────────────────┐
│ HTTP Client (MCP Client) │
└──────────────────┬──────────────────────┘
│ MCP Protocol
┌──────────────────▼──────────────────────┐
│ HTTP Transport Layer │
└──────────────────┬──────────────────────┘
│
┌──────────────────▼──────────────────────┐
│ MCP Server │
│ ┌────────────────────────────────┐ │
│ │ Tool Registry │ │
│ └────────────────────────────────┘ │
└──────────────────┬──────────────────────┘
│
┌──────────────────▼──────────────────────┐
│ Base Tool Class │
└──────────────────┬──────────────────────┘
│
┌──────────┴──────────┐
│ │
┌───────▼────────┐ ┌────────▼─────────┐
│ Weather API │ │ Your Custom │
│ Tool │ │ API Tools │
└────────────────┘ └──────────────────┘
组件层:
- 传输层:处理MCP协议消息的HTTP服务器
- MCP服务器层:核心服务器管理工具注册和执行
- 工具框架层:API工具的基类和注册表
- 实现层:具体的API工具实现
跨领域问题:
- 记录系统:监控跨层的所有操作
- 文档生成器:自动创建任务文档
安装
先决条件
- Node.js 18+
- npm或纱线
设置
- 克隆存储库:
git clone <repository-url>
cd mcp-api-converter
- 安装依赖项:
npm install
- 创建环境配置:
cp .env.example .env
-
编辑
.env并配置您的环境变量(请参阅下面的配置部分) -
构建项目:
npm run build
配置
所需的环境变量
创建一个 .env 项目根目录中的文件,包含以下变量:
服务器配置
- 端口 (可选,默认值:3000)
- HTTP服务器端口号
- 必须介于1和65535之间
- 例子:
PORT=3000
日志记录配置
- LOG_LEVEL (可选,默认值:info)
- 控制日志的详细程度
- 有效值:
debug,info,warning,error - 例子:
LOG_LEVEL=info
天气API配置
-
WEATHER_API_键 (气象工具需要)
- WeatherAPI.com的API密钥
- 获取您的免费API密钥:https://www.weatherapi.com/signup.aspx
- 例子:
WEATHER_API_KEY=your_api_key_here
-
天气_API_URL (可选)
- 天气API的基本URL
- 违约:
http://api.weatherapi.com/v1/current.json - 例子:
WEATHER_API_URL=http://api.weatherapi.com/v1/current.json
示例.env文件
PORT=3000
LOG_LEVEL=info
WEATHER_API_KEY=abc123def456
WEATHER_API_URL=http://api.weatherapi.com/v1/current.json
用法
启动服务器
开发模式(自动重新加载):
npm run dev
生产方式:
npm run build
npm start
服务器将启动并显示:
[2024-11-16T10:30:45.123Z] [INFO] MCP API Converter started successfully {"serverUrl":"http://localhost:3000","port":3000,"registeredTools":["get-weather"],"toolCount":1}
连接MCP客户端
服务器公开了一个HTTP端点,该端点通过POST请求接受MCP协议消息。
健康检查
您可以通过GET请求验证服务器是否正在运行:
curl http://localhost:3000
答复:
{
"status": "ok",
"service": "MCP API Converter",
"timestamp": "2024-11-16T10:30:45.123Z",
"toolCount": 1
}
列出可用工具
curl -X POST http://localhost:3000 \
-H "Content-Type: application/json" \
-d '{"method": "tools/list"}'
答复:
{
"result": {
"tools": [
{
"name": "get-weather",
"description": "Get current weather information for a specified location",
"inputSchema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name (e.g., \"London\", \"New York\") or city with country code (e.g., \"London,UK\")"
}
},
"required": ["location"]
}
}
]
}
}
调用工具
curl -X POST http://localhost:3000 \
-H "Content-Type: application/json" \
-d '{
"method": "tools/call",
"params": {
"name": "get-weather",
"arguments": {
"location": "London"
}
}
}'
答复:
{
"result": {
"location": "London",
"temperature": 15.3,
"temperatureUnit": "celsius",
"conditions": "partly cloudy",
"humidity": 72,
"windSpeed": 5.2,
"timestamp": "2024-11-16T10:30:45.123Z"
}
}
错误响应
当发生错误时,服务器会返回错误响应:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid parameters: location is required"
}
}
常见错误代码:
VALIDATION_ERROR:提供的参数无效TOOL_NOT_FOUND:请求的工具不存在EXECUTION_ERROR:工具执行失败EXTERNAL_API_ERROR:外部API请求失败
天气工具示例
附带的天气工具支持各种位置格式:
城市名称:
curl -X POST http://localhost:3000 \
-H "Content-Type: application/json" \
-d '{"method":"tools/call","params":{"name":"get-weather","arguments":{"location":"Paris"}}}'
国家代码所在城市:
curl -X POST http://localhost:3000 \
-H "Content-Type: application/json" \
-d '{"method":"tools/call","params":{"name":"get-weather","arguments":{"location":"Tokyo,JP"}}}'
多个单词的城市名称:
curl -X POST http://localhost:3000 \
-H "Content-Type: application/json" \
-d '{"method":"tools/call","params":{"name":"get-weather","arguments":{"location":"New York"}}}'
使用新的API工具扩展
添加新的API工具:
- 创建一个扩展的新类
BaseTool在src/tools/:
import { BaseTool } from '../core/BaseTool';
export class MyAPITool extends BaseTool {
readonly name = 'my-api-tool';
readonly description = 'Description of what this tool does';
readonly inputSchema = {
type: 'object' as const,
properties: {
param1: {
type: 'string',
description: 'Description of parameter'
}
},
required: ['param1']
};
async execute(params: { param1: string }): Promise<any> {
// Implement your API logic here
return { result: 'success' };
}
}
- 在中注册该工具
src/index.ts:
import { MyAPITool } from './tools/MyAPITool';
// In the main() function:
const myTool = new MyAPITool();
mcpServer.registerTool(myTool);
- 重建并重新启动服务器
项目结构
mcp-api-converter/
├── src/
│ ├── core/ # Core framework components
│ │ ├── BaseTool.ts # Abstract base class for tools
│ │ ├── MCPServer.ts # MCP server implementation
│ │ └── HTTPTransport.ts # HTTP transport layer
│ ├── tools/ # API tool implementations
│ │ └── WeatherAPITool.ts
│ ├── utils/ # Utility classes
│ │ ├── Logger.ts # Logging system
│ │ └── DocumentationGenerator.ts
│ ├── types/ # TypeScript type definitions
│ │ └── index.ts
│ └── index.ts # Main entry point
├── docs/ # Generated documentation
├── tests/ # Test files
├── .env # Environment configuration (create from .env.example)
├── .env.example # Example environment configuration
├── package.json
├── tsconfig.json
└── README.md
发展
运行测试
npm test
建筑
npm run build
输出将在 dist/ 目录。
日志记录
该应用程序使用多级日志记录系统。集 LOG_LEVEL 在你的 .env 文件:
- 调试:详细记录发展情况
- 信息:常规操作消息(默认)
- 警告:潜在问题的警告信息
- 错误:仅显示错误消息
故障排除
服务器无法启动
问题: Error: WEATHER_API_KEY is required
- 解决方案:确保您已创建
.env文件并添加您的OpenWeatherMap API密钥
问题: Error: Port 3000 is already in use
- 解决方案:更改
PORT在你的.env使用端口3000归档或停止进程
天气工具返回错误
问题: External API error: 401 Unauthorized
- 解决方案:验证您的
WEATHER_API_KEY有效且有效
问题: External API error: 404 Not Found
- 解决方案:检查位置拼写或尝试使用“城市,国家代码”格式(例如“英国伦敦”)
连接问题
问题:无法连接到服务器
- 解决方案:验证服务器是否正在运行,并检查请求中的端口是否与
PORT在.env
问题: Invalid MCP protocol message
- 解决方案:确保您的请求包括正确的
method字段,并遵循MCP协议格式
日志记录
调试时,设置 LOG_LEVEL=debug 在你的 .env 文件以查看详细日志:
LOG_LEVEL=debug
这将显示:
- 所有HTTP请求和响应
- 工具注册事件
- 参数验证详细信息
- 外部API调用和响应
贡献
欢迎投稿!请随时提交拉取请求。
许可证
麻省理工学院
