Spaces:
Running
Running
File size: 6,246 Bytes
6f5f15e 12bb291 6f5f15e 12bb291 6f5f15e 12bb291 6f5f15e 12bb291 6f5f15e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | import { getConnInfo } from '@hono/node-server/conninfo';
import {
PROTOCOL_VERSION_META_KEY,
createMcpHandler,
isJsonContentType,
isLegacyRequest,
readRequestBody,
type McpServerFactory,
} from '@modelcontextprotocol/server';
import type { Context, Hono } from 'hono';
import type { RoomRegistryApi } from '../contracts.js';
import { EVENTS_ERR } from '../events/protocol.js';
import { logger } from '../logger.js';
import { setRequestRemoteAddress } from '../mcp/identity.js';
import { resolveUser } from './userParam.js';
const MCP_MAX_BODY = 4 * 1024 * 1024; // 4 MiB
const MODERN_PROTOCOL = '2026-07-28';
const BASE64_SENTINEL_RE = /^=\?base64\?([^?]+)\?=$/i;
export interface McpRouteDeps {
rooms: RoomRegistryApi;
serverFactory: McpServerFactory;
}
function decodeMcpNameHeader(raw: string): string {
const trimmed = raw.trim();
const match = BASE64_SENTINEL_RE.exec(trimmed);
if (match) {
try {
return Buffer.from(match[1], 'base64').toString('utf8');
} catch {
return trimmed;
}
}
return trimmed;
}
export function checkEventsMcpName(req: Request, parsed: unknown): Response | null {
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return null;
}
const msg = parsed as { id?: unknown; method?: unknown; params?: unknown };
if (msg.method !== 'events/poll' && msg.method !== 'events/stream') {
return null;
}
const params = msg.params && typeof msg.params === 'object' && !Array.isArray(msg.params)
? (msg.params as Record<string, unknown>)
: undefined;
const meta = params?._meta && typeof params._meta === 'object' && !Array.isArray(params._meta)
? (params._meta as Record<string, unknown>)
: undefined;
const isModern = req.headers.get('mcp-protocol-version') === MODERN_PROTOCOL
|| meta?.[PROTOCOL_VERSION_META_KEY] === MODERN_PROTOCOL;
if (!isModern) {
return null;
}
const headerVal = req.headers.get('mcp-name');
if (headerVal === null || headerVal.trim() === '') {
logger.debug('Missing Mcp-Name header on modern events request', { method: msg.method });
return null;
}
const decoded = decodeMcpNameHeader(headerVal);
const paramName = typeof params?.name === 'string' ? params.name : undefined;
if (paramName !== undefined && decoded !== paramName) {
return new Response(
JSON.stringify({
jsonrpc: '2.0',
id: msg.id ?? null,
error: {
code: EVENTS_ERR.HeaderMismatch,
message: 'HeaderMismatch',
},
}),
{
status: 400,
headers: { 'content-type': 'application/json' },
},
);
}
return null;
}
function safeRemoteAddress(c: Context): string | undefined {
try {
return getConnInfo(c).remote.address;
} catch {
return undefined;
}
}
function applyCorsHeaders(res: Response, origin: string | null): Response {
if (!origin) return res;
const headers = new Headers(res.headers);
headers.set('Access-Control-Allow-Origin', origin);
headers.set('Vary', 'Origin');
headers.set('Access-Control-Expose-Headers', 'Mcp-Session-Id, MCP-Protocol-Version');
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers,
});
}
export interface MountedMcpRoute {
close(): Promise<void>;
}
export function mountMcpRoute(app: Hono, deps: McpRouteDeps): MountedMcpRoute {
const handler = createMcpHandler(deps.serverFactory, {
onerror: (err) => {
logger.error('MCP handler error', err);
},
});
const handleOptions = (c: Context): Response => {
const origin = c.req.header('origin');
const headers: Record<string, string> = {
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers':
'Content-Type, Accept, MCP-Protocol-Version, Mcp-Method, Mcp-Name, Mcp-Session-Id, Last-Event-ID, X-User-ID',
'Access-Control-Expose-Headers': 'Mcp-Session-Id, MCP-Protocol-Version',
'Access-Control-Max-Age': '600',
};
if (origin) {
headers['Access-Control-Allow-Origin'] = origin;
headers['Vary'] = 'Origin';
}
return new Response(null, { status: 204, headers });
};
const handleMcp = async (c: Context): Promise<Response> => {
const req = c.req.raw;
const origin = req.headers.get('origin');
const user = resolveUser(req);
let parsed: unknown;
if (req.method === 'POST' && isJsonContentType(req.headers.get('content-type'))) {
const body = await readRequestBody(req.clone(), MCP_MAX_BODY);
if (body.tooLarge) {
return applyCorsHeaders(
c.json(
{ jsonrpc: '2.0', error: { code: -32000, message: 'Payload Too Large' }, id: null },
413,
),
origin,
);
}
try {
parsed = JSON.parse(body.text);
} catch {
// let the SDK answer the JSON parse error
}
}
const mismatch = checkEventsMcpName(req, parsed);
if (mismatch) {
return applyCorsHeaders(mismatch, origin);
}
const legacy = parsed !== undefined ? await isLegacyRequest(req, parsed) : true;
const remote = safeRemoteAddress(c);
setRequestRemoteAddress(req, remote);
const room = deps.rooms.get(user);
if (Array.isArray(parsed)) {
for (const item of parsed) {
room.activity.observeHttp({ message: item, legacy, req, remote });
}
} else if (parsed !== undefined) {
room.activity.observeHttp({ message: parsed, legacy, req, remote });
}
const res = await handler.fetch(req, parsed !== undefined ? { parsedBody: parsed } : undefined);
if (parsed !== undefined) {
room.activity.observeHttpResponse(parsed, res.status, res.headers.get('content-type'), req);
}
return applyCorsHeaders(res, origin);
};
app.options('/mcp', handleOptions);
app.all('/mcp', handleMcp);
// Also accept MCP POST/DELETE/OPTIONS at `/` so pasting the browser URL
// (e.g. https://webcam.fast-agent.ai/?user=room-xxx) into a client just works,
// while GET `/` continues to serve the web UI.
app.options('/', handleOptions);
app.post('/', handleMcp);
app.delete('/', handleMcp);
return {
close: () => handler.close(),
};
}
|