|
| 1 | +// Redpanda Docs MCP Server on Netlify Edge Functions |
| 2 | +// --------------------------------------------------- |
| 3 | +// This Edge Function implements an authless MCP (Model Context Protocol) server |
| 4 | +// that proxies requests to Kapa AI’s chat and search APIs for Redpanda documentation. |
| 5 | +// It uses the official MCP SDK plus the Netlify adapter (modelfetch) to support |
| 6 | +// JSON-RPC over HTTP and SSE streaming. |
| 7 | +// |
| 8 | +// For background and reference implementations, see: |
| 9 | +// - Kapa AI blog: Build an MCP Server with Kapa AI |
| 10 | +// https://www.kapa.ai/blog/build-an-mcp-server-with-kapa-ai |
| 11 | +// - Netlify guide: Writing MCPs on Netlify |
| 12 | +// https://developers.netlify.com/guides/write-mcps-on-netlify/ |
| 13 | +// |
| 14 | +// Key challenges on Netlify Edge: |
| 15 | +// 1. ESM-only runtime: import via https://esm.sh for all modules (no local npm installs). |
| 16 | +// 2. Edge transport: leverage the `streamingHttp` protocol via the `@modelfetch/netlify` adapter, which under the hood uses `StreamableHTTPServerTransport` to handle SSE streams in Edge environments. Adapter docs: |
| 17 | +// - Modelfetch npm: https://www.npmjs.com/package/@modelfetch/netlify |
| 18 | +// - Modelfetch GitHub: https://github.com/modelcontextprotocol/modelfetch |
| 19 | +// 3. Header requirements: MCP expects both application/json and text/event-stream in Accept, |
| 20 | +// and requires Content-Type: application/json on incoming JSON-RPC messages. |
| 21 | + |
| 22 | +import { McpServer } from 'https://esm.sh/@modelcontextprotocol/[email protected]/server/mcp.js' |
| 23 | +import { z } from 'https://esm.sh/[email protected]' |
| 24 | +import handle from "https://esm.sh/@modelfetch/[email protected]"; |
| 25 | +import rateLimiter from 'https://esm.sh/[email protected]'; |
| 26 | + |
| 27 | +const API_BASE = "https://api.kapa.ai"; |
| 28 | +// Fetch Netlify env vars |
| 29 | +const KAPA_API_KEY = Netlify.env.get('KAPA_API_KEY'); |
| 30 | +const KAPA_PROJECT_ID = Netlify.env.get('KAPA_PROJECT_ID'); |
| 31 | +const KAPA_INTEGRATION_ID = Netlify.env.get('KAPA_INTEGRATION_ID'); |
| 32 | + |
| 33 | +// Initialize MCP Server and register tools |
| 34 | +const server = new McpServer({ |
| 35 | + name: "Redpanda Docs MCP", // Display name visible for inspectors |
| 36 | + version: "0.1.0", |
| 37 | +}); |
| 38 | + |
| 39 | +server.registerTool( |
| 40 | + "ask_redpanda_question", |
| 41 | + { |
| 42 | + title: "Ask Redpanda Question", |
| 43 | + description: "Ask a question about Redpanda documentation", |
| 44 | + inputSchema: { question: z.string() }, |
| 45 | + }, |
| 46 | + async ({ question }) => { |
| 47 | + try { |
| 48 | + const response = await fetch( |
| 49 | + `${API_BASE}/query/v1/projects/${KAPA_PROJECT_ID}/chat/`, |
| 50 | + { |
| 51 | + method: "POST", |
| 52 | + headers: { |
| 53 | + "Content-Type": "application/json", |
| 54 | + "X-API-KEY": KAPA_API_KEY, |
| 55 | + }, |
| 56 | + body: JSON.stringify({ |
| 57 | + integration_id: KAPA_INTEGRATION_ID, |
| 58 | + query: question, |
| 59 | + }), |
| 60 | + } |
| 61 | + ); |
| 62 | + // Always handle as JSON (Kapa API returns JSON) |
| 63 | + if (!response.ok) { |
| 64 | + return { |
| 65 | + content: [ |
| 66 | + { |
| 67 | + type: "text", |
| 68 | + text: `Redpanda Docs MCP error: ${response.status} - ${response.statusText}`, |
| 69 | + }, |
| 70 | + ], |
| 71 | + }; |
| 72 | + } |
| 73 | + const chatData = await response.json(); |
| 74 | + return { |
| 75 | + content: [ |
| 76 | + { |
| 77 | + type: "text", |
| 78 | + text: (chatData.answer || "No answer received"), |
| 79 | + }, |
| 80 | + ], |
| 81 | + }; |
| 82 | + } catch (error) { |
| 83 | + console.log(`[ask_redpanda_question] Exception:`, error); |
| 84 | + return { |
| 85 | + content: [ |
| 86 | + { |
| 87 | + type: "text", |
| 88 | + text: `Error: Failed to call kapa.ai API - ${error instanceof Error ? error.message : String(error)}`, |
| 89 | + }, |
| 90 | + ], |
| 91 | + }; |
| 92 | + } |
| 93 | + } |
| 94 | +); |
| 95 | + |
| 96 | +// Wrap the server with the Netlify Edge handler |
| 97 | +// --------------------------------------------- |
| 98 | +// The `handle` function from `@modelfetch/netlify` does several things: |
| 99 | +// 1. Adapts the Edge `fetch` Request/Response to the Node-style HTTP transport |
| 100 | +// that the MCP SDK expects (using streamingHttp under the hood). |
| 101 | +// 2. Parses incoming JSON-RPC payloads from the request body. |
| 102 | +// 3. Routes `initialize`, `tool:discover`, and `tool:invoke` JSON-RPC methods |
| 103 | +// to the registered tools on our `server` instance. |
| 104 | +// 4. Manages Server-Sent Events (SSE) streaming: it takes ReadableStreams |
| 105 | +// returned by streaming tools and writes them as |
| 106 | +// text/event-stream chunks back through the Edge Function response. |
| 107 | +// 5. Handles error formatting according to JSON-RPC (wrapping exceptions in |
| 108 | +// appropriate error objects). |
| 109 | +const baseHandler = handle({ |
| 110 | + server: server, |
| 111 | + pre: (app) => { |
| 112 | + app.use( |
| 113 | + "/mcp", |
| 114 | + rateLimiter.rateLimiter({ |
| 115 | + windowMs: 15 * 60 * 1000, // 15 minutes |
| 116 | + limit: 30, // 30 requests per window |
| 117 | + keyGenerator: (c) => c.ip, |
| 118 | + }), |
| 119 | + ); |
| 120 | + }, |
| 121 | +}); |
| 122 | + |
| 123 | +// Wrapper to handle both browser requests (show docs) and MCP client requests |
| 124 | +export default async (request, context) => { |
| 125 | + // Check if this is a browser request (not an MCP client) |
| 126 | + const userAgent = request.headers.get('user-agent') || ''; |
| 127 | + const accept = request.headers.get('accept') || ''; |
| 128 | + const contentType = request.headers.get('content-type') || ''; |
| 129 | + |
| 130 | + // Detect browser requests: |
| 131 | + // - User-Agent contains browser identifiers |
| 132 | + // - Accept header includes text/html |
| 133 | + // - NOT a JSON-RPC POST request |
| 134 | + const isBrowserRequest = ( |
| 135 | + request.method === 'GET' && |
| 136 | + (userAgent.includes('Mozilla') || userAgent.includes('Chrome') || userAgent.includes('Safari') || userAgent.includes('Edge')) && |
| 137 | + accept.includes('text/html') && |
| 138 | + !contentType.includes('application/json') |
| 139 | + ); |
| 140 | + |
| 141 | + // If it's a browser request, redirect to the documentation page |
| 142 | + if (isBrowserRequest) { |
| 143 | + return new Response(null, { |
| 144 | + status: 302, |
| 145 | + headers: { |
| 146 | + 'Location': '/home/mcp-setup', // Redirect to the built docs page |
| 147 | + }, |
| 148 | + }); |
| 149 | + } |
| 150 | + |
| 151 | + // Otherwise, handle as MCP client request |
| 152 | + const patchedHeaders = new Headers(request.headers); |
| 153 | + patchedHeaders.set('accept', 'application/json, text/event-stream'); |
| 154 | + patchedHeaders.set('content-type', 'application/json'); |
| 155 | + |
| 156 | + const patchedRequest = new Request(request, { headers: patchedHeaders }); |
| 157 | + return baseHandler(patchedRequest, context); |
| 158 | +}; |
| 159 | + |
| 160 | +export const config = { path: "/mcp" }; |
| 161 | + |
0 commit comments