honoWebStandardStreamableHttp.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport
  3. *
  4. * This example demonstrates using the Web Standard transport directly with Hono,
  5. * which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc.
  6. *
  7. * Run with: npx tsx src/examples/server/honoWebStandardStreamableHttp.ts
  8. */
  9. import { Hono } from 'hono';
  10. import { cors } from 'hono/cors';
  11. import { serve } from '@hono/node-server';
  12. import * as z from 'zod/v4';
  13. import { McpServer } from '../../server/mcp.js';
  14. import { WebStandardStreamableHTTPServerTransport } from '../../server/webStandardStreamableHttp.js';
  15. // Factory function to create a new MCP server per request (stateless mode)
  16. const getServer = () => {
  17. const server = new McpServer({
  18. name: 'hono-webstandard-mcp-server',
  19. version: '1.0.0'
  20. });
  21. // Register a simple greeting tool
  22. server.registerTool('greet', {
  23. title: 'Greeting Tool',
  24. description: 'A simple greeting tool',
  25. inputSchema: { name: z.string().describe('Name to greet') }
  26. }, async ({ name }) => {
  27. return {
  28. content: [{ type: 'text', text: `Hello, ${name}! (from Hono + WebStandard transport)` }]
  29. };
  30. });
  31. return server;
  32. };
  33. // Create the Hono app
  34. const app = new Hono();
  35. // Enable CORS for all origins
  36. app.use('*', cors({
  37. origin: '*',
  38. allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
  39. allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'],
  40. exposeHeaders: ['mcp-session-id', 'mcp-protocol-version']
  41. }));
  42. // Health check endpoint
  43. app.get('/health', c => c.json({ status: 'ok' }));
  44. // MCP endpoint - create a fresh transport and server per request (stateless)
  45. app.all('/mcp', async (c) => {
  46. const transport = new WebStandardStreamableHTTPServerTransport();
  47. const server = getServer();
  48. await server.connect(transport);
  49. return transport.handleRequest(c.req.raw);
  50. });
  51. // Start the server
  52. const PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000;
  53. console.log(`Starting Hono MCP server on port ${PORT}`);
  54. console.log(`Health check: http://localhost:${PORT}/health`);
  55. console.log(`MCP endpoint: http://localhost:${PORT}/mcp`);
  56. serve({
  57. fetch: app.fetch,
  58. port: PORT
  59. });
  60. //# sourceMappingURL=honoWebStandardStreamableHttp.js.map