(fastify)
| 9 | export const mcpSessionManager = new SessionManager(); |
| 10 | |
| 11 | const mcpRouter: FastifyPluginAsync = async (fastify) => { |
| 12 | await activateRateLimiter({ fastify, max: 60, timeWindow: '1 minute' }); |
| 13 | |
| 14 | /** |
| 15 | * POST /mcp |
| 16 | * |
| 17 | * Handles both session initialization (no Mcp-Session-Id header) and |
| 18 | * subsequent JSON-RPC messages within an existing session. |
| 19 | * |
| 20 | * First request: authenticate via ?token= query param or Authorization: Bearer. |
| 21 | * Subsequent requests: route by Mcp-Session-Id header. |
| 22 | */ |
| 23 | await fastify.post('/', async (req, reply) => { |
| 24 | // Hand off full response control to the MCP transport |
| 25 | reply.hijack(); |
| 26 | await handleMcpPost( |
| 27 | mcpSessionManager, |
| 28 | req.raw, |
| 29 | reply.raw, |
| 30 | req.body, |
| 31 | req.query as Record<string, unknown>, |
| 32 | ); |
| 33 | }); |
| 34 | |
| 35 | /** |
| 36 | * GET /mcp |
| 37 | * |
| 38 | * Establishes an SSE stream for server-to-client notifications. |
| 39 | * Requires Mcp-Session-Id header from a previously initialized session. |
| 40 | */ |
| 41 | await fastify.get('/', async (req, reply) => { |
| 42 | reply.hijack(); |
| 43 | await handleMcpGet(mcpSessionManager, req.raw, reply.raw); |
| 44 | }); |
| 45 | |
| 46 | /** |
| 47 | * DELETE /mcp |
| 48 | * |
| 49 | * Explicitly close an MCP session and free its resources. |
| 50 | * Requires the same auth token used to create the session — verified against |
| 51 | * the session's organizationId to prevent one client closing another's session. |
| 52 | */ |
| 53 | await fastify.delete('/', async (req, reply) => { |
| 54 | const sessionId = req.headers['mcp-session-id'] as string | undefined; |
| 55 | if (!sessionId) { |
| 56 | return reply.status(400).send({ error: 'Mcp-Session-Id header is required' }); |
| 57 | } |
| 58 | |
| 59 | const token = extractToken(req.query as Record<string, unknown>, req.headers.authorization); |
| 60 | let callerContext; |
| 61 | try { |
| 62 | callerContext = await authenticateToken(token); |
| 63 | } catch (err) { |
| 64 | return reply.status(401).send({ error: err instanceof McpAuthError ? err.message : 'Unauthorized' }); |
| 65 | } |
| 66 | |
| 67 | const context = await mcpSessionManager.getContext(sessionId); |
| 68 | if (!context) { |
nothing calls this directly
no test coverage detected