Repository navigation
Expand file tree
/
Copy pathmcp.ts
More file actions
790 lines (709 loc) · 23.9 KB
/
Copy pathmcp.ts
File metadata and controls
790 lines (709 loc) · 23.9 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
/**
* Vercel Serverless Function for Terminal49 MCP Server
* Uses StreamableHTTPServerTransport for MCP protocol
*
* Endpoint: POST /api/mcp
*/
import '../packages/mcp/src/instrument.js';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { randomUUID, timingSafeEqual } from 'node:crypto';
import {
createMcpHandler,
type McpHttpHandler,
} from '@modelcontextprotocol/server';
import { toNodeHandler } from '@modelcontextprotocol/node';
import * as Sentry from '@sentry/node';
import { createTerminal49McpServer } from '../packages/mcp/src/server.js';
import { CALL_BUDGET_MS } from '../packages/mcp/src/tools/record-writes.js';
import { flushPostHogEvents } from '../packages/mcp/src/posthog.js';
import { captureMcpException } from '../packages/mcp/src/sentry.js';
import { protectedResourceMetadataUrl } from '../packages/mcp/src/resource.js';
import { logMcpEvent } from '../packages/mcp/src/logging.js';
import type { McpCredentialType } from '../packages/mcp/src/tools/context.js';
import type { ToolSelection } from '../packages/mcp/src/tools/registry.js';
import {
READ_ONLY_HEADER,
resolveToolSelection,
ToolSelectionRequestError,
TOOLSETS_HEADER,
} from '../packages/mcp/src/toolsets.js';
type RequestLike = {
method?: string;
headers: IncomingMessage['headers'];
body?: unknown;
} & IncomingMessage;
type JsonResponse = {
error: string | { code: number; message: string };
message?: string;
jsonrpc?: string;
id?: string | number | null;
};
type ResponseLike = {
headersSent: boolean;
status(code: number): ResponseLike;
json(payload: JsonResponse): void;
setHeader(name: string, value: string): void;
end(): void;
on(event: 'close' | 'finish', listener: () => void): void;
} & ServerResponse;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function setCorsHeaders(res: ResponseLike): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader(
'Access-Control-Allow-Headers',
`Content-Type, Authorization, X-Account-ID, X-T49-Credential-Type, ${TOOLSETS_HEADER}, ${READ_ONLY_HEADER}, MCP-Protocol-Version, Mcp-Method, Mcp-Name, Mcp-Session-Id`,
);
}
function getHeaderValue(
value: string | string[] | undefined,
): string | undefined {
if (Array.isArray(value)) {
return value[0];
}
return value;
}
type AuthorizationToken = {
scheme?: 'Bearer' | 'Token';
token?: string;
source?: 'authorization';
};
function extractAuthorizationToken(
authorizationHeader: string | undefined,
): AuthorizationToken {
if (authorizationHeader?.trim()) {
const trimmed = authorizationHeader.trim();
const authMatch = trimmed.match(/^(bearer|token)\s+(.+)$/i);
if (authMatch?.[2]) {
const token = authMatch[2].trim();
if (token.length > 0) {
const scheme =
authMatch[1].toLowerCase() === 'bearer' ? 'Bearer' : 'Token';
return { scheme, token, source: 'authorization' };
}
}
}
return {};
}
type ResolvedTerminal49Auth = {
apiToken: string;
accountId?: string;
authSource: 'authorization' | 'environment' | 'workos_mcp';
credentialType: McpCredentialType;
};
type ConnectedClientResolutionResponse = {
data?: {
attributes?: {
access_token?: string;
account_id?: string;
};
};
error?: string;
};
type UnauthorizedReason = 'missing_credentials' | 'invalid_token';
function oauthConfigured(): boolean {
return Boolean(
process.env.WORKOS_AUTHORIZATION_SERVER_URL?.trim() ||
process.env.WORKOS_ISSUER?.trim(),
);
}
function wwwAuthenticateHeader(
req: RequestLike,
reason: UnauthorizedReason,
): string {
const parts = ['Bearer realm="mcp"'];
// RFC 6750 §3.1: include an error code only when a token was actually
// presented and rejected; omit it when the client sent no credentials.
if (reason === 'invalid_token') {
parts.push('error="invalid_token"');
parts.push('error_description="The access token is invalid or expired"');
}
// Only advertise OAuth discovery when the WorkOS resolver path is actually
// active: AuthKit enabled AND the authorization server configured. If AuthKit
// is off, a Bearer token isn't resolved (it's treated as a passthrough key), so
// an OAuth-aware client would complete the WorkOS flow and then loop with a
// token the handler won't honor. The PRM endpoint also 500s without WORKOS_*.
if (authKitMcpEnabled() && oauthConfigured()) {
parts.push(`resource_metadata="${protectedResourceMetadataUrl(req)}"`);
}
return parts.join(', ');
}
function setUnauthorizedChallenge(
res: ResponseLike,
req: RequestLike,
reason: UnauthorizedReason,
): void {
res.setHeader('WWW-Authenticate', wwwAuthenticateHeader(req, reason));
}
function authKitMcpEnabled(): boolean {
return process.env.T49_MCP_AUTHKIT_ENABLED === 'true';
}
function resolveEndpointUrl(): string {
const apiBaseUrl =
process.env.T49_API_BASE_URL?.trim() || 'https://api.terminal49.com/v2';
return `${apiBaseUrl.replace(/\/+$/, '')}/connected-clients/resolve`;
}
type ResolveFailureKind = 'config' | 'invalid_token' | 'forbidden' | 'upstream';
class ConnectedClientResolveError extends Error {
readonly kind: ResolveFailureKind;
readonly upstreamStatus?: number;
constructor(
message: string,
kind: ResolveFailureKind,
upstreamStatus?: number,
) {
super(message);
this.name = 'ConnectedClientResolveError';
this.kind = kind;
this.upstreamStatus = upstreamStatus;
}
}
/** Rejects with an upstream error if `signal` aborts before `work` settles. */
function untilDeadline<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
return new Promise<T>((resolve, reject) => {
const onAbort = () =>
reject(
new ConnectedClientResolveError(
'Terminal49 connected client resolve ran past the request deadline.',
'upstream',
),
);
if (signal.aborted) {
onAbort();
return;
}
signal.addEventListener('abort', onAbort, { once: true });
work
.then(resolve, reject)
.finally(() => signal.removeEventListener('abort', onAbort));
});
}
async function resolveConnectedClientToken(
token: string,
requestId: string,
deadlineAt: number,
): Promise<{ apiToken: string; accountId: string }> {
const resolveSecret =
process.env.T49_CONNECTED_CLIENTS_RESOLVE_SECRET?.trim() ||
process.env.T49_MCP_RESOLVE_SECRET?.trim();
if (!resolveSecret) {
throw new ConnectedClientResolveError(
'T49_CONNECTED_CLIENTS_RESOLVE_SECRET must be set when AuthKit MCP auth is enabled.',
'config',
);
}
// Sign-in counts against the same deadline as the tool call, so a slow
// resolver cannot push the request past the function limit.
const deadline = new AbortController();
const timer = setTimeout(
() => deadline.abort(),
Math.max(deadlineAt - Date.now(), 0),
);
let response: Response;
let payload: ConnectedClientResolutionResponse = {};
try {
try {
response = await untilDeadline(
fetch(resolveEndpointUrl(), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-T49-Connected-Clients-Resolve-Secret': resolveSecret,
'X-Request-Id': requestId,
},
body: JSON.stringify({ access_token: token }),
signal: deadline.signal,
}),
deadline.signal,
);
} catch (error) {
if (error instanceof ConnectedClientResolveError) throw error;
const err = asError(error);
throw new ConnectedClientResolveError(
`Terminal49 connected client resolve request failed: ${err.message}`,
'upstream',
);
}
try {
// SAFETY: The fields read below are optional and validated before use.
payload = (await untilDeadline(
response.json(),
deadline.signal,
)) as ConnectedClientResolutionResponse;
} catch (error) {
if (error instanceof ConnectedClientResolveError) throw error;
payload = {};
}
} finally {
clearTimeout(timer);
}
if (!response.ok) {
// A 401 means the credential itself is invalid. A 403 means WorkOS auth
// succeeded but Terminal49 denied account access (for example, a rollout
// gate); converting that to 401 makes clients discard a valid grant and
// loop through OAuth. Other failures are retryable upstream errors.
const kind: ResolveFailureKind =
response.status === 401
? 'invalid_token'
: response.status === 403
? 'forbidden'
: 'upstream';
throw new ConnectedClientResolveError(
payload.error ||
`Terminal49 connected client resolve failed with ${response.status}`,
kind,
response.status,
);
}
const accessToken = payload.data?.attributes?.access_token;
const accountId = payload.data?.attributes?.account_id;
if (!accessToken || !accountId) {
throw new ConnectedClientResolveError(
'Terminal49 connected client resolve response is missing access_token or account_id.',
'upstream',
);
}
return { apiToken: `Bearer ${accessToken}`, accountId };
}
function isMatchingClientSecret(
providedToken: string,
expectedSecret: string,
): boolean {
const providedBuffer = Buffer.from(providedToken);
const expectedBuffer = Buffer.from(expectedSecret);
if (providedBuffer.length !== expectedBuffer.length) {
return false;
}
return timingSafeEqual(providedBuffer, expectedBuffer);
}
function buildRequestId(): string {
// Caller-controlled request IDs can contain tokens or customer identifiers.
// Generate an internal correlation ID so the safe request_id log exemption
// never forwards arbitrary header content.
return randomUUID();
}
function asError(cause: unknown): Error {
return cause instanceof Error ? cause : new Error(String(cause));
}
type LifecycleDetail = string | number | string[] | undefined;
function logLifecycle(
event: string,
requestId: string,
details: Record<string, LifecycleDetail> = {},
): void {
logMcpEvent({
event,
request_id: requestId,
timestamp: new Date().toISOString(),
...details,
});
}
function parseAllowList(value: string | undefined): Set<string> {
if (!value) {
return new Set();
}
return new Set(
value
.split(',')
.map((item) => item.trim())
.filter((item) => item.length > 0),
);
}
function isAllowedHost(
hostHeader: string | undefined,
allowList: Set<string>,
): boolean {
if (allowList.size === 0) {
return true;
}
if (!hostHeader) {
return false;
}
const hostname = hostHeader.split(':')[0];
return allowList.has(hostHeader) || allowList.has(hostname);
}
function isAllowedOrigin(
originHeader: string | undefined,
hostHeader: string | undefined,
allowList: Set<string>,
): boolean {
if (!originHeader) {
// Non-browser clients commonly omit Origin.
return true;
}
let origin: URL;
try {
origin = new URL(originHeader);
} catch {
return false;
}
if (allowList.size > 0) {
return allowList.has(origin.origin) || allowList.has(origin.hostname);
}
const localHosts = new Set(['localhost', '127.0.0.1', '::1']);
if (localHosts.has(origin.hostname)) {
return true;
}
if (!hostHeader) {
return false;
}
const requestHost = hostHeader.split(':')[0];
return origin.hostname === requestHost;
}
function validateRequestSecurity(req: RequestLike, res: ResponseLike): boolean {
const hostHeader = getHeaderValue(req.headers.host);
const originHeader = getHeaderValue(req.headers.origin);
const allowedHosts = parseAllowList(process.env.T49_MCP_ALLOWED_HOSTS);
const allowedOrigins = parseAllowList(process.env.T49_MCP_ALLOWED_ORIGINS);
if (!isAllowedHost(hostHeader, allowedHosts)) {
setCorsHeaders(res);
res.status(403).json({
error: 'Forbidden',
message: `Invalid Host header: ${hostHeader ?? '(missing)'}`,
});
return false;
}
if (!isAllowedOrigin(originHeader, hostHeader, allowedOrigins)) {
setCorsHeaders(res);
res.status(403).json({
error: 'Forbidden',
message: `Invalid Origin header: ${originHeader ?? '(missing)'}`,
});
return false;
}
return true;
}
/**
* Main handler for Vercel serverless function
*/
export default async function handler(
req: RequestLike,
res: ResponseLike,
): Promise<void> {
const requestId = buildRequestId();
// vercel.json caps this function at 30s from the request, auth included.
const deadlineAt = Date.now() + CALL_BUDGET_MS;
setCorsHeaders(res);
logLifecycle('mcp.request.start', requestId, {
method: req.method ?? 'UNKNOWN',
});
if (!validateRequestSecurity(req, res)) {
logLifecycle('mcp.request.rejected', requestId, {
reason: 'request_security_validation_failed',
});
return;
}
// Handle CORS preflight
if (req.method === 'OPTIONS') {
res.status(200).end();
logLifecycle('mcp.request.complete', requestId, { reason: 'preflight' });
return;
}
// Only accept POST requests
if (req.method !== 'POST') {
setCorsHeaders(res);
res.status(405).json({
error: 'Method not allowed',
message: 'Only POST requests are accepted',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'method_not_allowed',
method: req.method,
});
return;
}
let mcpHandler: McpHttpHandler | undefined;
let cleanupPromise: Promise<void> | null = null;
let shouldFlushSentry = false;
const runCleanup = (reason: string): Promise<void> => {
if (cleanupPromise) {
return cleanupPromise;
}
cleanupPromise = (async () => {
const cleanupErrors: string[] = [];
logLifecycle('mcp.request.cleanup.start', requestId, { reason });
if (mcpHandler) {
try {
await mcpHandler.close();
} catch (error) {
const err = asError(error);
cleanupErrors.push(`handler.close: ${err.message}`);
}
}
if (cleanupErrors.length > 0) {
logLifecycle('mcp.request.cleanup.error', requestId, {
reason,
errors: cleanupErrors,
});
return;
}
logLifecycle('mcp.request.cleanup.complete', requestId, { reason });
})();
return cleanupPromise;
};
const scheduleCleanup = (reason: string): void => {
void runCleanup(reason);
};
try {
// Require caller Authorization; supports both `Bearer <token>` and `Token <token>`.
// Use T49_API_TOKEN only as upstream credential, never as client-auth fallback.
const authHeader = getHeaderValue(req.headers.authorization);
const resolvedAuth = extractAuthorizationToken(authHeader);
const callerToken = resolvedAuth.token;
if (!callerToken) {
setCorsHeaders(res);
setUnauthorizedChallenge(res, req, 'missing_credentials');
res.status(401).json({
error: 'Unauthorized',
message:
'Missing valid Authorization header. Use `Authorization: Bearer <token>` or `Authorization: Token <token>`.',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'missing_authorization',
});
return;
}
const requestedAccountId =
resolvedAuth.scheme === 'Token'
? getHeaderValue(req.headers['x-account-id'])
: undefined;
const credentialType =
resolvedAuth.scheme === 'Token'
? getHeaderValue(req.headers['x-t49-credential-type'])
: undefined;
if (credentialType && credentialType !== 'agent') {
res.status(400).json({
error: 'Bad Request',
message: 'X-T49-Credential-Type is invalid.',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'invalid_credential_type',
});
return;
}
if (requestedAccountId && !UUID.test(requestedAccountId)) {
res.status(400).json({
error: 'Bad Request',
message: 'X-Account-ID must be a UUID.',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'invalid_account_id',
});
return;
}
if (credentialType === 'agent' && !requestedAccountId) {
res.status(400).json({
error: 'Bad Request',
message: 'X-Account-ID is required for a WorkOS agent credential.',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'missing_account_id',
});
return;
}
const configuredApiToken = process.env.T49_API_TOKEN?.trim();
const configuredClientSecret = process.env.T49_MCP_CLIENT_SECRET?.trim();
let resolvedTerminal49Auth: ResolvedTerminal49Auth = {
apiToken:
credentialType === 'agent' ? `Bearer ${callerToken}` : callerToken,
accountId: credentialType === 'agent' ? requestedAccountId : undefined,
authSource: resolvedAuth.source ?? 'authorization',
credentialType: credentialType === 'agent' ? 'agent' : 'api_key',
};
// Intentional: when AuthKit is enabled, `Bearer` is reserved for WorkOS OAuth
// access tokens (resolved below). API keys authenticate with the `Token`
// scheme (passthrough), which is what the docs instruct. Existing Bearer
// API-key clients must migrate to `Token` before AuthKit is enabled — see
// packages/mcp/WORKOS_MCP_SETUP.md (rollout note).
if (authKitMcpEnabled() && resolvedAuth.scheme === 'Bearer') {
try {
const resolved = await resolveConnectedClientToken(
callerToken,
requestId,
deadlineAt,
);
resolvedTerminal49Auth = {
apiToken: resolved.apiToken,
accountId: resolved.accountId,
authSource: 'workos_mcp',
credentialType: 'user',
};
} catch (error) {
const err = asError(error);
const kind: ResolveFailureKind =
err instanceof ConnectedClientResolveError ? err.kind : 'upstream';
const upstreamStatus =
err instanceof ConnectedClientResolveError
? err.upstreamStatus
: undefined;
setCorsHeaders(res);
// Keep the detailed reason in the server log (correlated by request_id);
// return a generic, category-appropriate response so internals never leak.
logLifecycle('mcp.request.complete', requestId, {
reason: 'connected_client_resolve_failed',
kind,
upstream_status: upstreamStatus,
message: err.message,
});
if (kind === 'invalid_token') {
setUnauthorizedChallenge(res, req, 'invalid_token');
res.status(401).json({
error: 'Unauthorized',
message: 'Invalid or expired token.',
});
} else if (kind === 'forbidden') {
res.status(403).json({
error: 'Forbidden',
message: 'Terminal49 access is not enabled for this account.',
});
} else if (kind === 'config') {
res.status(500).json({
error: 'Server misconfiguration',
message: 'Authorization is not configured correctly.',
});
} else {
// Upstream/transient: do NOT send a 401 challenge — that tells clients
// their token is bad and triggers re-auth loops. 502 invites a retry.
res.status(502).json({
error: 'Bad Gateway',
message:
'Authorization service is temporarily unavailable. Please retry.',
});
}
return;
}
} else if (configuredApiToken) {
if (!configuredClientSecret) {
setCorsHeaders(res);
res.status(500).json({
error: 'Server misconfiguration',
message:
'T49_MCP_CLIENT_SECRET must be set when T49_API_TOKEN is configured.',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'missing_client_secret',
});
return;
}
if (!isMatchingClientSecret(callerToken, configuredClientSecret)) {
setCorsHeaders(res);
setUnauthorizedChallenge(res, req, 'invalid_token');
res.status(401).json({
error: 'Unauthorized',
message: 'Invalid client credentials.',
});
logLifecycle('mcp.request.complete', requestId, {
reason: 'invalid_client_secret',
});
return;
}
resolvedTerminal49Auth = {
apiToken: configuredApiToken,
authSource: 'environment',
credentialType: 'shared_token',
};
}
let toolSelection: ToolSelection;
try {
toolSelection = resolveToolSelection({
env: process.env,
credentialType: resolvedTerminal49Auth.credentialType,
toolsetsHeader: getHeaderValue(req.headers['x-t49-mcp-toolsets']),
readOnlyHeader: getHeaderValue(req.headers['x-t49-mcp-read-only']),
});
} catch (error) {
if (!(error instanceof ToolSelectionRequestError)) {
throw error;
}
res.status(400).json({ error: 'Bad Request', message: error.message });
logLifecycle('mcp.request.complete', requestId, {
reason: 'invalid_tool_selection',
});
return;
}
logLifecycle('mcp.request.auth', requestId, {
auth_source: resolvedTerminal49Auth.authSource,
credential_type: resolvedTerminal49Auth.credentialType,
toolsets: [...toolSelection.toolsets],
read_only: String(toolSelection.readOnly),
});
setCorsHeaders(res);
const observeMcpError = (error: Error): void => {
captureMcpException(error);
shouldFlushSentry = true;
logLifecycle('mcp.request.error', requestId, {
error: error.name,
message: error.message,
});
};
// The v2 HTTP entry serves the 2026-07-28 per-request protocol and keeps
// the established stateless 2025-era path for older clients.
mcpHandler = createMcpHandler(
() =>
createTerminal49McpServer(
resolvedTerminal49Auth.apiToken,
process.env.T49_API_BASE_URL,
resolvedTerminal49Auth.accountId,
{
transport: 'http',
authSource: resolvedTerminal49Auth.authSource,
credentialType: resolvedTerminal49Auth.credentialType,
toolsets: toolSelection.toolsets,
readOnly: toolSelection.readOnly,
writeDeadlineAt: deadlineAt,
},
),
{
legacy: 'stateless',
responseMode: 'json',
onerror: observeMcpError,
},
);
const nodeHandler = toNodeHandler(mcpHandler, {
onerror: observeMcpError,
});
// Clean up on response lifecycle and also in finally to guarantee closure.
res.on('close', () => {
scheduleCleanup('response_close');
});
res.on('finish', () => {
scheduleCleanup('response_finish');
});
await nodeHandler(req, res, req.body);
logLifecycle('mcp.request.complete', requestId, { reason: 'handled' });
} catch (error) {
const err = asError(error);
captureMcpException(err);
shouldFlushSentry = true;
logLifecycle('mcp.request.error', requestId, {
error: err.name,
message: err.message,
});
if (!res.headersSent) {
setCorsHeaders(res);
// The real error is logged above (correlated by request_id). Never echo
// err.message to the client — it can carry upstream URLs, tokens, or
// stack detail.
res.status(500).json({
jsonrpc: '2.0',
error: {
code: -32603,
message: 'Internal server error',
},
id: null,
});
}
} finally {
await runCleanup('finally');
if (shouldFlushSentry || Sentry.isInitialized()) {
await Sentry.flush(2000).catch(() => undefined);
}
// Vercel freezes the function the moment the response is sent, so any batch
// still queued in the PostHog client would be dropped (or leak into the next
// invocation on a reused instance). Awaiting the flush here mirrors the
// Sentry.flush() above: one batched request per invocation. Deliberately
// preferred over `waitUntil`, which would add a @vercel/functions
// dependency for the same guarantee. No-ops when PostHog is unconfigured.
await flushPostHogEvents();
}
}