|
| 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 | + |
| 10 | +import { Hono } from 'hono'; |
| 11 | +import { cors } from 'hono/cors'; |
| 12 | +import { serve } from '@hono/node-server'; |
| 13 | +import * as z from 'zod/v4'; |
| 14 | +import { McpServer } from '../../server/mcp.js'; |
| 15 | +import { WebStandardStreamableHTTPServerTransport } from '../../server/webStandardStreamableHttp.js'; |
| 16 | +import { CallToolResult } from '../../types.js'; |
| 17 | + |
| 18 | +// Create the MCP server |
| 19 | +const server = new McpServer({ |
| 20 | + name: 'hono-webstandard-mcp-server', |
| 21 | + version: '1.0.0' |
| 22 | +}); |
| 23 | + |
| 24 | +// Register a simple greeting tool |
| 25 | +server.registerTool( |
| 26 | + 'greet', |
| 27 | + { |
| 28 | + title: 'Greeting Tool', |
| 29 | + description: 'A simple greeting tool', |
| 30 | + inputSchema: { name: z.string().describe('Name to greet') } |
| 31 | + }, |
| 32 | + async ({ name }): Promise<CallToolResult> => { |
| 33 | + return { |
| 34 | + content: [{ type: 'text', text: `Hello, ${name}! (from Hono + WebStandard transport)` }] |
| 35 | + }; |
| 36 | + } |
| 37 | +); |
| 38 | + |
| 39 | +// Create a stateless transport (no options = no session management) |
| 40 | +const transport = new WebStandardStreamableHTTPServerTransport(); |
| 41 | + |
| 42 | +// Create the Hono app |
| 43 | +const app = new Hono(); |
| 44 | + |
| 45 | +// Enable CORS for all origins |
| 46 | +app.use( |
| 47 | + '*', |
| 48 | + cors({ |
| 49 | + origin: '*', |
| 50 | + allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'], |
| 51 | + allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'], |
| 52 | + exposeHeaders: ['mcp-session-id', 'mcp-protocol-version'] |
| 53 | + }) |
| 54 | +); |
| 55 | + |
| 56 | +// Health check endpoint |
| 57 | +app.get('/health', c => c.json({ status: 'ok' })); |
| 58 | + |
| 59 | +// MCP endpoint |
| 60 | +app.all('/mcp', c => transport.handleRequest(c.req.raw)); |
| 61 | + |
| 62 | +// Start the server |
| 63 | +const PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; |
| 64 | + |
| 65 | +server.connect(transport).then(() => { |
| 66 | + console.log(`Starting Hono MCP server on port ${PORT}`); |
| 67 | + console.log(`Health check: http://localhost:${PORT}/health`); |
| 68 | + console.log(`MCP endpoint: http://localhost:${PORT}/mcp`); |
| 69 | + |
| 70 | + serve({ |
| 71 | + fetch: app.fetch, |
| 72 | + port: PORT |
| 73 | + }); |
| 74 | +}); |
0 commit comments