这是一个使用可流式传输HTTP的 Hono MCP 服务器示例,基于官方的 Express 示例 the official Express example,使用 fetch-to-node 进行转换,可以部署到 Cloudflare Workers(以及任何其他运行 Hono 的地方)。
与 Express 示例相比,唯一的实际改动如下:
- import express, { Request, Response } from 'express';
+ import { Hono } from 'hono';
+ import { toFetchResponse, toReqRes } from 'fetch-to-node';
// ...
- const app = express();
- app.use(express.json());
+ const app = new Hono();
- app.post('/mcp', async (req: Request, res: Response) => {
+ app.post('/mcp', async (c) => {
+ const { req, res } = toReqRes(c.req.raw);
const server = getServer();
try {
const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
});
await server.connect(transport);
- await transport.handleRequest(req, res, req.body);
+ await transport.handleRequest(req, res, await c.req.json());
res.on('close', () => {
console.log('请求已关闭');
transport.close();
server.close();
});
+ return toFetchResponse(res);
} catch (error) {
在一个终端中:
npm start
在另一个终端中:
node node_modules/@modelcontextprotocol/sdk/dist/esm/examples/client/simpleStreamableHttp.js
这将尝试连接到运行在 3000 端口上的 MCP 服务器。你可以使用 connect <url>/mcp 来连接到不同的主机或端口。
然后你可以运行如 list-prompts 或 list-tools 命令来验证你的 MCP 服务器是否正常工作。
npm run deploy
以下是一个针对部署在 Cloudflare Workers 上的 Hono MCP 服务器的示例会话:
> connect https://mcp-hono-stateless.michael.workers.dev/mcp
正在连接到 https://mcp-hono-stateless.michael.workers.dev/mcp...
创建了具有会话ID:undefined 的传输
已连接到 MCP 服务器
> list-tools
可用工具:
- start-notification-stream: 开始发送周期性通知以测试可恢复性
> list-prompts
可用提示:
- greeting-template: 一个简单的问候提示模板
> call-tool start-notification-stream
调用工具 'start-notification-stream',参数:{}
通知 #1: info - 第 1 个周期性通知于 2025-04-22T16:20:50.178Z
>
通知 #2: info - 第 2 个周期性通知于 2025-04-22T16:20:50.278Z
>
通知 #3: info - 第 3 个周期性通知于 2025-04-22T16:20:50.378Z
>
通知 #4: info - 第 4 个周期性通知于 2025-04-22T16:20:50.478Z
>
通知 #5: info - 第 5 个周期性通知于 2025-04-22T16:20:50.578Z
>
通知 #6: info - 第 6 个周期性通知于 2025-04-22T16:20:50.678Z
>
通知 #7: info - 第 7 个周期性通知于 2025-04-22T16:20:50.778Z
>
通知 #8: info - 第 8 个周期性通知于 2025-04-22T16:20:50.878Z
>
通知 #9: info - 第 9 个周期性通知于 2025-04-22T16:20:50.978Z
>
通知 #10: info - 第 10 个周期性通知于 2025-04-22T16:20:51.078Z
> 工具结果:
每 100 毫秒开始发送周期性通知