使用说明
MCP服务器发送事件(SSE)-示例
一种参考实现,用于使用服务器发送事件(SSE)作为传输层将模型上下文协议(MCP)功能集成到web应用程序中。
概述
本项目演示了如何创建一个使用SSE传输协议与客户端通信的MCP服务器。它使web应用程序能够访问强大的MCP功能,同时保持与AI模型实时通信的持久连接。
主要特点:
- 使用服务器发送事件实现MCP服务器以实现web兼容性
- 创建可从web客户端访问的自定义MCP工具
- 将任何兼容MCP的客户端连接到基于SSE的服务器
- 通过标准化协议扩展基于网络的AI助手功能
什么是MCP SSE?
模型上下文协议(MCP)支持多种传输机制,SSE是web应用程序的理想选择:
- 服务器发送事件(SSE):用于建立单向连接的web标准,服务器可以向客户端推送更新
- MCP通过SSE:使用SSE作为传输层实现MCP协议,使web客户端能够与MCP服务器交互
- 实时AI交互:允许持续流式传输AI响应,同时保持工具执行能力
入门指南
先决条件
- Node.js(v18或更高版本)
- NPM或纱线
- 示例搜索工具的勇敢搜索API密钥
安装
# Clone the repository
git clone https://github.com/yourusername/mcp-sse-example.git
cd mcp-sse-example
# Install backend dependencies
cd backend
npm install
配置
创建一个 .env 使用API凭据在后端目录中的文件:
BRAVE_API_KEY=your_api_key_here
用法
启动服务器
# Build and start the server
npm run build
npm run start
MCP SSE服务器将在 http://localhost:3001.
Docker部署
# From the project root
docker-compose up -d
运作原理
此实现使用:
- Express.js 作为web服务器
- SSE服务器传输 从MCP SDK处理SSE协议
- McpServer 注册和管理工具
服务器公开了两个主要端点:
/sse-用于建立SSE连接/messages-用于接收来自客户端的消息
示例实现
核心服务器实现:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import express from "express";
const server = new McpServer({
name: "Example SSE Server",
version: "1.0.0",
});
// Register tools
server.tool("example_tool", { param: z.string() }, async ({ param }) => ({
content: [{ type: "text", text: `Processed: ${param}` }],
}));
const app = express();
let transport: SSEServerTransport;
app.get("/sse", async (req, res) => {
transport = new SSEServerTransport("/messages", res);
await server.connect(transport);
});
app.post("/messages", async (req, res) => {
await transport.handlePostMessage(req, res);
});
app.listen(3001);
兼容客户端
许多MCP客户端支持SSE传输协议,包括:
调试
调试MCP SSE实现时:
# Follow logs in real-time (for MacOS)
tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
有关更详细的调试说明,请参阅 MCP调试指南.
贡献
欢迎投稿!请随时提交拉取请求。
许可证
此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。
相关资源
- 模型上下文协议 -MCP官方文件
- MCP TypeScript SDK -TypeScript官方实现
- MCP检查员 -用于测试MCP服务器的交互式工具