import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js' import { timingSafeEqual } from 'node:crypto' import { createServer, type ServerOptions } from './server' /** * `@basementstudio/qa-mcp` over HTTP — the same fourteen tools, reachable at a URL. * * The stdio server (`index.ts`) spawns as a child process of the client, and **a browser cannot * reach that**: it cannot spawn a process, and no amount of granting permissions in a page * bridges a tab to a subprocess. A remote MCP server is a different transport, not a different * permission — an HTTPS endpoint speaking Streamable HTTP, which a client connects to as a * configured connector. * * Built on the SDK's **Web-standard** transport (`Request` → `Response`) rather than the * Node/Express wrapper, because that is what serverless hosts hand you and it needs no `node:http`. * * ## Stateless, and not by preference * * `sessionIdGenerator` is left undefined and `enableJsonResponse` is on. The SDK's stateful mode * keeps sessions, streams and message history **in memory**, and a serverless invocation does not * share memory with the next one: a session id minted by one would be unrecognised by whichever * instance answered the follow-up, so every second request 404s. That failure is intermittent and * load-dependent, which is the worst kind to debug — so the constraint is encoded here rather * than left to be discovered. A fresh server and transport per request is the correct shape, and * cheap: `createServer` registers tool schemas and touches no disk. * * Resumability (`eventStore`) is deliberately not wired up for the same reason — it needs shared * storage to mean anything, and an in-memory one would silently drop replays. */ export interface HttpServerOptions extends ServerOptions { /** * The bearer token a client must present. * * **Required, with no open default.** stdio needed no auth because owning the process *was* the * authorisation; an endpoint on the public internet has no equivalent property, and four of the * fifteen tools write — `qa_issue_write`, `qa_issue_delete`, `qa_waive`, `qa_set_finished`. * An unset token therefore refuses every request instead of allowing them: a server that is * accidentally wide open looks exactly like a working one until somebody else writes to your * run store, whereas one that refuses everything is noticed within a minute. */ token?: string } /** Where the JSON-RPC endpoint lives. Clients are given this path, so it is part of the contract. */ export const MCP_ENDPOINT = '/mcp' function jsonRpcError(status: number, code: number, message: string, extraHeaders: HeadersInit = {}): Response { // Shaped as JSON-RPC rather than bare text: the caller is an MCP client, and an error it can // parse tells the model what went wrong instead of surfacing as a transport failure. return new Response(JSON.stringify({ jsonrpc: '2.0', error: { code, message }, id: null }), { status, headers: { 'content-type': 'application/json', ...extraHeaders }, }) } /** * Constant-time bearer check. * * `timingSafeEqual` throws on length mismatch, so length is compared first — that leaks the * token's length and nothing else, which is not a secret worth protecting. A plain `===` would * leak the token's *prefix* one request at a time, and this endpoint is reachable by anyone. * * Exported because `/mcp` is no longer the only machine endpoint on the dashboard, and the second * one must not get its own comparison. A hand-rolled `===` in a new route would be indistinguishable * from this at review and wrong in exactly the way this comment exists to prevent. */ export function tokenMatches(presented: string, expected: string): boolean { const a = Buffer.from(presented, 'utf8') const b = Buffer.from(expected, 'utf8') if (a.length !== b.length) return false return timingSafeEqual(a, b) } /** * A `fetch`-style handler for the MCP endpoint. * * Runtime-agnostic on purpose: a Vercel function, a Bun server, a Cloudflare Worker and a test * all call it the same way, so the transport is exercised in tests by the same code path that * serves production rather than by a mock of it. */ export function createHttpHandler(opts: HttpServerOptions = {}): (req: Request) => Promise { const { token, ...serverOptions } = opts return async function handle(req: Request): Promise { if (!token) { /** * Refusing rather than allowing. Reported as a server fault because that is what it is — * a deployment missing its configuration — and saying so plainly is what stops somebody * concluding the endpoint is broken and "fixing" it by removing the check. */ return jsonRpcError(500, -32603, 'Server is missing its QA_MCP_TOKEN configuration; refusing all requests.') } const presented = req.headers.get('authorization')?.replace(/^Bearer /i, '') ?? '' if (!tokenMatches(presented, token)) { // `WWW-Authenticate` is what tells a client this is an auth problem it can fix, rather than // a server that is simply broken. return jsonRpcError(401, -32001, 'Unauthorized.', { 'www-authenticate': 'Bearer realm="qa-mcp"' }) } const server = createServer(serverOptions) const transport = new WebStandardStreamableHTTPServerTransport({ // Stateless — see the header. Not a tuning choice. sessionIdGenerator: undefined, enableJsonResponse: true, }) try { await server.connect(transport) return await transport.handleRequest(req) } finally { // Per-request lifecycle: nothing here outlives the invocation, so leaving the transport // open would leak a connection per request on a long-lived host. await transport.close().catch(() => {}) await server.close().catch(() => {}) } } }