import { createHash } from "crypto" import { createMcpHandler, withMcpAuth } from "mcp-handler" import { rateLimit } from "@/lib/rate-limit" import { verifyMcpToken } from "@/lib/mcp/auth" import { MCP_SERVER_NAME, MCP_SERVER_VERSION, mcpBaseUrl, } from "@/lib/mcp/config" import { registerTools } from "@/lib/mcp/server" /** * The MCP endpoint. * * Lives under /api deliberately: the middleware matcher in src/middleware.ts * excludes /api precisely because `authorized` answers with an HTML redirect to * /login, and an MCP client needs a JSON 401 with a WWW-Authenticate challenge. * Authentication here is a bearer token, never the session cookie. */ export const runtime = "nodejs" export const dynamic = "force-dynamic" const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource" const baseHandler = createMcpHandler(registerTools, { serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION }, verboseLogs: process.env.NODE_ENV !== "production", }) const authedHandler = withMcpAuth(baseHandler, verifyMcpToken, { required: true, resourceMetadataPath: RESOURCE_METADATA_PATH, // Pinned rather than derived from proxy headers. See src/lib/mcp/config.ts - // the app binds 0.0.0.0:3000 behind a reverse proxy, so a request-derived // origin sends clients to an unreachable metadata URL. resourceUrl: mcpBaseUrl(), }) /** * A wildcard origin is safe here only because this endpoint authenticates with an * Authorization header and never a cookie. Do not add Access-Control-Allow- * Credentials, and do not add session-cookie auth as a fallback: either one turns * this into a CSRF hole that any website could drive on a logged-in user's behalf. */ const CORS_HEADERS: Record = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS", "Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID", "Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate", "Access-Control-Max-Age": "86400", } function withCors(response: Response): Response { for (const [key, value] of Object.entries(CORS_HEADERS)) { response.headers.set(key, value) } return response } /** * Throttled on a hash of the presented credential, so it works before any * database lookup and a malformed token cannot be used to probe for free. * * Deliberately not enforced inside verifyMcpToken: returning undefined there * produces a 401, which tells the client to go and re-authenticate - the wrong * answer to "slow down", and one that would send Claude around the OAuth loop * repeatedly. Note src/lib/rate-limit.ts is a module-scope Map: per process and * reset by every deploy. Correct for the single systemd process this runs as; * under multiple workers the effective limit becomes N times looser. */ function throttle(request: Request): Response | null { const bearer = request.headers .get("authorization") ?.replace(/^Bearer\s+/i, "") .trim() const key = bearer ? `mcp:${createHash("sha256").update(bearer).digest("hex").slice(0, 16)}` : "mcp:anonymous" const { success } = rateLimit(key, 120, 60_000) if (success) return null return withCors( new Response( JSON.stringify({ error: "Too many requests. Please slow down." }), { status: 429, headers: { "content-type": "application/json", "retry-after": "60" }, } ) ) } async function handle(request: Request): Promise { const throttled = throttle(request) if (throttled) return throttled return withCors(await authedHandler(request)) } export const GET = handle export const POST = handle export const DELETE = handle export function OPTIONS(): Response { return withCors(new Response(null, { status: 204 })) }