import { randomUUID, createHash } from 'node:crypto'; import { serve } from '@hono/node-server'; import { Pool } from 'pg'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'; import { z } from 'zod'; import { loadConfig } from './config.mjs'; import { boundedBody, failure } from './http.mjs'; import { createPrincipalVerifier } from './auth.mjs'; const config = loadConfig(); const pool = new Pool({ connectionString: config.databaseUrl, max: 8, statement_timeout: 5000 }); const hash = value => createHash('sha256').update(value).digest('hex'); const verifyPrincipal = createPrincipalVerifier(config); const schema = `CREATE TABLE IF NOT EXISTS mcp_template_drafts ( tenant text NOT NULL, account text NOT NULL, version integer NOT NULL, value text NOT NULL, PRIMARY KEY(tenant, account)); CREATE TABLE IF NOT EXISTS mcp_template_operations ( tenant text NOT NULL, account text NOT NULL, request_id uuid NOT NULL, hash char(64) NOT NULL, result jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(tenant, account, request_id)); CREATE TABLE IF NOT EXISTS mcp_template_limits (key char(64) NOT NULL, bucket bigint NOT NULL, count integer NOT NULL, PRIMARY KEY(key,bucket));`; const migration = await pool.connect(); try { await migration.query('BEGIN'); await migration.query("SELECT pg_advisory_xact_lock(hashtext('mcp-template-schema-v1'))"); await migration.query(schema); await migration.query('COMMIT'); } catch { await migration.query('ROLLBACK'); throw new Error('MCP template schema initialization failed'); } finally { migration.release(); } async function limited(key, budget) { const result = await pool.query( `INSERT INTO mcp_template_limits VALUES ($1,floor(extract(epoch FROM now())/60),1) ON CONFLICT(key,bucket) DO UPDATE SET count=mcp_template_limits.count+1 WHERE mcp_template_limits.count<$2 RETURNING count`, [hash(key), budget], ); if (!result.rowCount) throw failure('rate_limited', 429); } async function principal(request, write = false) { return verifyPrincipal(request.headers.get('authorization'), write); } async function save(p, args) { const db = await pool.connect(); try { await db.query('BEGIN'); await db.query("SET LOCAL transaction_timeout='10s'"); await db.query('SELECT pg_advisory_xact_lock(hashtext($1))', [p.tenant + ':' + p.account]); const old = await db.query( 'SELECT hash,result FROM mcp_template_operations WHERE tenant=$1 AND account=$2 AND request_id=$3', [p.tenant, p.account, args.requestId], ); const inputHash = hash(JSON.stringify(args)); if (old.rowCount) { if (old.rows[0].hash !== inputHash) throw failure('idempotency_key_reused', 409); await db.query('COMMIT'); return old.rows[0].result; } const values = [p.tenant, p.account, args.value, args.expectedVersion]; const row = args.expectedVersion === 0 ? await db.query( 'INSERT INTO mcp_template_drafts VALUES ($1,$2,1,$3) ON CONFLICT DO NOTHING RETURNING version,value', values.slice(0, 3), ) : await db.query( 'UPDATE mcp_template_drafts SET version=version+1,value=$3 WHERE tenant=$1 AND account=$2 AND version=$4 RETURNING version,value', values, ); if (!row.rowCount) throw failure('draft_version_conflict', 409); await db.query( 'INSERT INTO mcp_template_operations(tenant,account,request_id,hash,result) VALUES ($1,$2,$3,$4,$5)', [p.tenant, p.account, args.requestId, inputHash, JSON.stringify(row.rows[0])], ); await db.query('COMMIT'); return row.rows[0]; } catch (error) { await db.query('ROLLBACK'); throw error; } finally { db.release(); } } const cleanup = setInterval(() => { void pool .query( `DELETE FROM mcp_template_limits WHERE ctid IN (SELECT ctid FROM mcp_template_limits WHERE bucket console.warn('MCP maintenance unavailable')); }, 60000).unref(); let active = 0; const server = serve({ port: config.port, hostname: process.env.NODE_ENV === 'test' ? '127.0.0.1' : '0.0.0.0', fetch: async (request, env) => { const correlationId = randomUUID(); let mcp; let admitted = false; const headers = { 'Cache-Control': 'no-store', 'X-Request-Id': correlationId, 'Content-Type': 'application/json' }; try { const path = new URL(request.url).pathname; if (request.method === 'GET' && path === '/health') return Response.json({ status: 'ok' }); if (request.method === 'GET' && path === '/ready') { await pool.query('SELECT 1 FROM mcp_template_drafts LIMIT 0'); return Response.json({ status: 'ready' }); } const origin = request.headers.get('origin'); if (origin && !config.origins.includes(origin)) throw failure('untrusted_origin'); await limited('ip:' + (env.incoming.socket.remoteAddress ?? 'unknown'), config.anonymous); if (path === '/.well-known/oauth-protected-resource/mcp' && request.method === 'GET') return Response.json( { resource: config.resource, authorization_servers: [config.issuer], scopes_supported: [config.readScope, config.writeScope], bearer_methods_supported: ['header'], }, { headers }, ); if (path !== '/mcp') throw failure('not_found', 404); const p = await principal(request); await limited('account:' + p.tenant + ':' + p.account, config.reads); await limited('tenant:' + p.tenant, config.reads * 2); if (request.method !== 'POST') throw failure('method_not_allowed', 405); if (request.headers.get('content-type')?.split(';')[0] !== 'application/json') throw failure('json_required', 415); const body = JSON.parse(await boundedBody(request)); if (!body || Array.isArray(body) || typeof body !== 'object') throw failure('invalid_request', 400); if (active >= config.concurrency) throw failure('concurrency_limit', 429); active++; admitted = true; mcp = new McpServer({ name: 'bounded-draft-sample', version: '0.1.0' }); const draft = z.object({ version: z.number().int(), value: z.string().max(2000) }).strict(); const add = (name, input, output, write, action) => mcp.registerTool( name, { description: write ? 'Save a private reversible text draft only when requested; no deployment or external effects.' : 'Read your authenticated context or private saved draft.', inputSchema: input, outputSchema: z.object({ result: output }).strict(), annotations: { readOnlyHint: !write, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, async args => { try { const current = await principal(request, write); if (write) { await limited('write-account:' + current.tenant + ':' + current.account, config.writes); await limited('write-tenant:' + current.tenant, config.writes * 2); } const result = await action(current, args); console.info( JSON.stringify({ correlationId, principal: hash(current.account), tenant: hash(current.tenant), tool: name, outcome: 'ok', }), ); return { content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: { result } }; } catch (error) { return { isError: true, content: [ { type: 'text', text: JSON.stringify({ error: error.status ? error.message : 'temporarily_unavailable', correlationId, }), }, ], }; } }, ); add( 'identity', z.object({}).strict(), z.object({ account: z.string(), tenant: z.string(), scopes: z.array(z.string()) }).strict(), false, async p => p, ); add( 'read_draft', z.object({}).strict(), draft.nullable(), false, async p => ( await pool.query('SELECT version,value FROM mcp_template_drafts WHERE tenant=$1 AND account=$2', [ p.tenant, p.account, ]) ).rows[0] ?? null, ); add( 'save_draft', z .object({ expectedVersion: z.number().int().min(0).max(2147483646), requestId: z.string().uuid(), value: z.string().max(2000), }) .strict(), draft, true, save, ); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true, }); await mcp.connect(transport); const response = await transport.handleRequest( new Request(request.url, { method: 'POST', headers: request.headers, body: JSON.stringify(body) }), { parsedBody: body }, ); const responseHeaders = new Headers(response.headers); for (const [key, value] of Object.entries(headers)) responseHeaders.set(key, value); return new Response(await response.arrayBuffer(), { status: response.status, headers: responseHeaders, }); } catch (error) { const status = error instanceof SyntaxError ? 400 : (error.status ?? 503); return Response.json( { error: status === 503 ? 'temporarily_unavailable' : error instanceof SyntaxError ? 'invalid_json' : error.message, correlationId, }, { status, headers: { ...headers, ...(status === 401 || status === 403 ? { 'WWW-Authenticate': `Bearer resource_metadata="${new URL('/.well-known/oauth-protected-resource/mcp', config.resource)}", scope="${config.readScope}"`, } : {}), ...(status === 429 ? { 'Retry-After': '60' } : {}), }, }, ); } finally { await mcp?.close(); if (admitted) active--; } }, }); for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { clearInterval(cleanup); server.close(() => { void pool.end().then(() => process.exit(0)); }); setTimeout(() => process.exit(1), 10000).unref(); });