可流式MCP示例
将模型上下文协议(MCP)与客户端-服务器架构一起使用的一个简单示例,演示了工具功能和流式通信。
特性
- 具有工具功能的MCP服务器
- 具有回退传输机制的客户端
- TypeScript实现
- Express.js服务器
- 工具执行示例(新增)
先决条件
- Node.js(v18或更高版本)
- pnpm(推荐)或npm
安装
- 克隆存储库:
git clone
cd streamable-mcp-example- 安装依赖项:
pnpm install发展
- 构建项目:
pnpm build- 启动服务器:
pnpm start:server- 在单独的终端中,运行客户端:
pnpm start:client项目结构
streamable-mcp-example/
├── client/ # Client implementation
│ └── index.ts # Client entry point
├── server/ # Server implementation
│ └── index.ts # Server entry point
├── package.json # Project configuration
├── tsconfig.json # TypeScript configuration
└── README.md # This file实现细节
服务器
服务器实现:
- MCP协议支持
- 工具能力注册
- 请求处理
- Express.js集成
- 错误处理
客户端
客户端实现:
- MCP协议支持
- 传输回退机制
- 工具发现
- 工具执行
- 错误处理
可用工具
添加工具
一个添加两个数字的简单工具:
{
name: "tools/addition",
description: "Add two numbers together",
parameters: {
type: "object",
properties: {
a: { type: "number" },
b: { type: "number" }
},
required: ["a", "b"]
}
}BTC价格工具
从雅虎财经检索BTC价格数据的工具:
{
name: "tools/getBTCPrices",
description: "Get BTC price data. Valid ranges: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max. Valid intervals: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo",
parameters: {
type: "object",
properties: {
timeFrame: {
type: "string",
enum: ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"]
},
interval: {
type: "string",
enum: ["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"]
}
},
required: ["timeFrame"]
}
}- 论据:
- timeFrame (必填):数据范围(例如,“1d”、“5d”、“1mo”等) - interval (可选):数据间隔(例如,“1m”、“5m”、“1h”等)
- 输出:
- 返回一个价格点数组(JSON),每个价格点包含 price, volume, high, low,以及 timestamp 领域。 - 输出示例:
[
{ "price": 109715.88, "volume": 123456, "high": 110000, "low": 109000, "timestamp": "2025-05-27T23:59:00.000Z" },
...
]- 请求范围的最新价格是数组中的最后一项。
MCP端点和协议
- MCP服务器在以下位置公开其端点:
http://localhost:3000/mcp - 仅支持POST请求。GET/DELETE将返回405错误。
- 服务器需要
Accept: application/json标题(或将其包含在列表中)。 - 该服务器符合JSON-RPC 2.0和模型上下文协议(MCP)。
- 工具调用和工具列表遵循MCP SDK和协议。
光标集成
使用此服务器 光标:
- 确保
.cursor/mcp.json存在以下内容:
{
"mcpServers": {
"streamable-mcp-example": {
"url": "http://localhost:3000/mcp"
}
}
}- 如果Cursor正在运行,请重新启动它。
- 服务器的输出格式与Cursor和MCP SDK兼容。
错误处理
该实现包括以下错误处理:
- 连接失败
- 运输回退
- 无效请求
- 服务器错误
贡献
- 分叉存储库
- 创建功能分支(
git checkout -b feature/amazing-feature) - 提交您的更改(
git commit -m 'Add some amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
许可证
此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。
