@catamorphic/fastify-plugin 0.1.0-alpha.39 → 0.1.0-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/NOTICE.txt +7 -0
  2. package/dist/app.d.ts +2 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/chunk-jytcc42y.js +592 -0
  5. package/dist/chunk-jytcc42y.js.map +11 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1673 -411
  9. package/dist/index.js.map +29 -25
  10. package/dist/mcp-scopes.d.ts +12 -0
  11. package/dist/mcp-scopes.d.ts.map +1 -0
  12. package/dist/mcp-server.d.ts +158 -0
  13. package/dist/mcp-server.d.ts.map +1 -0
  14. package/dist/mcp-shared.d.ts +3 -50
  15. package/dist/mcp-shared.d.ts.map +1 -1
  16. package/dist/mcp.d.ts +4 -2
  17. package/dist/mcp.d.ts.map +1 -1
  18. package/dist/mcp.js +6 -4
  19. package/dist/mcp.js.map +1 -1
  20. package/dist/plugin.d.ts +26 -2
  21. package/dist/plugin.d.ts.map +1 -1
  22. package/dist/project-capabilities.d.ts.map +1 -1
  23. package/dist/project-mcp-surface.d.ts +3 -4
  24. package/dist/project-mcp-surface.d.ts.map +1 -1
  25. package/dist/routes/agent.d.ts.map +1 -1
  26. package/dist/routes/apps-mcp.d.ts.map +1 -1
  27. package/dist/routes/client-runners.d.ts.map +1 -1
  28. package/dist/routes/connection-mcp.d.ts.map +1 -1
  29. package/dist/routes/documents.d.ts.map +1 -1
  30. package/dist/routes/environments.d.ts.map +1 -1
  31. package/dist/routes/project-mcp.d.ts.map +1 -1
  32. package/dist/routes/projects.d.ts.map +1 -1
  33. package/dist/routes/publications.d.ts.map +1 -1
  34. package/dist/routes/run-errors.d.ts.map +1 -1
  35. package/dist/routes/runs.d.ts.map +1 -1
  36. package/dist/routes/server-mcp.d.ts +17 -0
  37. package/dist/routes/server-mcp.d.ts.map +1 -0
  38. package/dist/routes/session-mailboxes.d.ts.map +1 -1
  39. package/dist/routes/triggers.d.ts.map +1 -1
  40. package/dist/routes/watchers.d.ts.map +1 -1
  41. package/dist/routes/workflow-enablements.d.ts.map +1 -1
  42. package/dist/routes/workflows.d.ts.map +1 -1
  43. package/dist/schemas.d.ts +3684 -28
  44. package/dist/schemas.d.ts.map +1 -1
  45. package/dist/session-mcp.d.ts +54 -0
  46. package/dist/session-mcp.d.ts.map +1 -0
  47. package/dist/session-tools.d.ts +49 -0
  48. package/dist/session-tools.d.ts.map +1 -0
  49. package/package.json +12 -12
  50. package/src/app.ts +3 -0
  51. package/src/index.ts +1 -0
  52. package/src/mcp-scopes.ts +69 -0
  53. package/src/mcp-server.ts +827 -0
  54. package/src/mcp-shared.ts +3 -151
  55. package/src/mcp.ts +6 -5
  56. package/src/plugin.ts +73 -2
  57. package/src/project-capabilities.ts +5 -3
  58. package/src/project-mcp-program.ts +2 -2
  59. package/src/project-mcp-surface.ts +18 -239
  60. package/src/routes/agent.ts +384 -41
  61. package/src/routes/apps-mcp.ts +84 -82
  62. package/src/routes/client-runners.ts +3 -1
  63. package/src/routes/connection-mcp.ts +6 -13
  64. package/src/routes/documents.ts +4 -0
  65. package/src/routes/environments.ts +49 -1
  66. package/src/routes/project-mcp.ts +176 -154
  67. package/src/routes/projects.ts +6 -0
  68. package/src/routes/publications.ts +2 -0
  69. package/src/routes/run-errors.ts +5 -1
  70. package/src/routes/runs.ts +4 -0
  71. package/src/routes/server-mcp.ts +151 -0
  72. package/src/routes/session-mailboxes.ts +1 -0
  73. package/src/routes/triggers.ts +6 -1
  74. package/src/routes/watchers.ts +1 -0
  75. package/src/routes/workflow-enablements.ts +132 -1
  76. package/src/routes/workflows.ts +4 -0
  77. package/src/schemas.ts +347 -5
  78. package/src/session-mcp.ts +696 -0
  79. package/src/session-tools.ts +169 -0
  80. package/dist/chunk-baagvvm3.js +0 -164
  81. package/dist/chunk-baagvvm3.js.map +0 -10
@@ -0,0 +1,827 @@
1
+ import { type TokenScope, TokenScopeRequiredError } from "@catamorphic/core";
2
+ import type { FastifyReply, FastifyRequest } from "fastify";
3
+ import { z } from "zod";
4
+ import {
5
+ type ForwardedToolDefinition,
6
+ forwardedTool,
7
+ forwardedToolResult,
8
+ } from "./mcp-shared.js";
9
+
10
+ /**
11
+ * One MCP endpoint for both protocol eras (ADR 0347). A request carrying
12
+ * the per-request `_meta` envelope, or a modern `MCP-Protocol-Version`
13
+ * header, is served by the current revision: stateless, validated against
14
+ * its mirrored headers, with `server/discover`, result types, caching
15
+ * hints, `subscriptions/listen` and the tasks extension. Anything else is
16
+ * a 2025-era client and gets the stateless `initialize` shell with plain
17
+ * tools. Neither path keeps a session: every request stands alone, and
18
+ * whatever must outlive one is in Postgres.
19
+ */
20
+
21
+ /** The revisions served with per-request metadata, newest first. */
22
+ export const MODERN_PROTOCOL_VERSIONS = ["2026-07-28"] as const;
23
+
24
+ /** The handshake revisions a 2025-era client may negotiate. */
25
+ export const SUPPORTED_PROTOCOL_VERSIONS = new Set([
26
+ "2024-11-05",
27
+ "2025-03-26",
28
+ "2025-06-18",
29
+ "2025-11-25",
30
+ ]);
31
+ export const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
32
+
33
+ export const MCP_META = {
34
+ protocolVersion: "io.modelcontextprotocol/protocolVersion",
35
+ clientInfo: "io.modelcontextprotocol/clientInfo",
36
+ clientCapabilities: "io.modelcontextprotocol/clientCapabilities",
37
+ serverInfo: "io.modelcontextprotocol/serverInfo",
38
+ subscriptionId: "io.modelcontextprotocol/subscriptionId",
39
+ } as const;
40
+
41
+ /** The tasks extension (SEP-2663): a durable handle for a long call. */
42
+ export const TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
43
+
44
+ export const MCP_ERROR = {
45
+ parse: -32700,
46
+ invalidRequest: -32600,
47
+ methodNotFound: -32601,
48
+ invalidParams: -32602,
49
+ internal: -32603,
50
+ headerMismatch: -32020,
51
+ missingClientCapability: -32021,
52
+ unsupportedProtocolVersion: -32022,
53
+ } as const;
54
+
55
+ /** How long a keep-alive comment keeps a quiet listen stream open. */
56
+ export const MCP_KEEP_ALIVE_MS = 15_000;
57
+
58
+ /** A failure that answers with a specific JSON-RPC error and HTTP status. */
59
+ export class McpError extends Error {
60
+ constructor(
61
+ readonly code: number,
62
+ message: string,
63
+ readonly options: { status?: number; data?: unknown } = {},
64
+ ) {
65
+ super(message);
66
+ this.name = "McpError";
67
+ }
68
+ }
69
+
70
+ /** The token lacks a scope the call needs: answered as a step-up (403). */
71
+ export class McpScopeError extends Error {
72
+ constructor(readonly scope: string) {
73
+ super(`This call needs the ${scope} scope`);
74
+ this.name = "McpScopeError";
75
+ }
76
+ }
77
+
78
+ /** What a handler is told about the request it serves. */
79
+ export interface McpCallContext {
80
+ era: "modern" | "legacy";
81
+ protocolVersion: string;
82
+ /** What the client declared for this request; empty for a legacy one. */
83
+ clientCapabilities: Record<string, unknown>;
84
+ /** Aborted when the caller went away. */
85
+ signal: AbortSignal;
86
+ /** A retried call's answers to what the server asked (MRTR). */
87
+ inputResponses?: Record<string, unknown>;
88
+ /** The state the server handed out with what it asked. */
89
+ requestState?: string;
90
+ }
91
+
92
+ /** A tool's answer in MCP's shape. */
93
+ export type McpToolResult = Record<string, unknown>;
94
+
95
+ /**
96
+ * One tool an MCP endpoint serves: what clients list, the OAuth scope a
97
+ * token needs for it, and how it runs. A result may carry its own
98
+ * `resultType` (`input_required`, `task`) for a modern caller.
99
+ */
100
+ export interface McpTool {
101
+ definition: Record<string, unknown>;
102
+ /** The OAuth scope a token must carry to list or call it; none: any. */
103
+ scope?: TokenScope;
104
+ call: (
105
+ args: Record<string, unknown>,
106
+ context?: McpCallContext,
107
+ ) => Promise<McpToolResult>;
108
+ }
109
+
110
+ /** What a listen stream is told changed; `stop` ends the watching. */
111
+ export interface McpWatch {
112
+ /** The subset of what was asked for that is watched. */
113
+ accepted: string[];
114
+ stop(): void;
115
+ }
116
+
117
+ export interface McpResources {
118
+ list(): Promise<Array<Record<string, unknown>>>;
119
+ templates(): Promise<Array<Record<string, unknown>>>;
120
+ /** The resource's contents; an unknown URI throws {@link McpError}. */
121
+ read(uri: string): Promise<Array<Record<string, unknown>>>;
122
+ /** Tell `changed` when one of these resources changes; none: no listening. */
123
+ watch?(
124
+ uris: readonly string[],
125
+ changed: (uri: string) => void,
126
+ ended: () => void,
127
+ ): Promise<McpWatch>;
128
+ }
129
+
130
+ export interface McpTasks {
131
+ /** The task's state; an unknown id throws {@link McpError}. */
132
+ get(taskId: string): Promise<Record<string, unknown>>;
133
+ update(
134
+ taskId: string,
135
+ inputResponses: Record<string, unknown>,
136
+ ): Promise<void>;
137
+ cancel(taskId: string): Promise<void>;
138
+ /** Tell `changed` with the task's state whenever its status changes. */
139
+ watch(
140
+ taskIds: readonly string[],
141
+ changed: (task: Record<string, unknown>) => void,
142
+ ): Promise<McpWatch>;
143
+ }
144
+
145
+ /** Everything one endpoint serves to one caller. */
146
+ export interface McpEndpoint {
147
+ serverInfo: { name: string; title?: string; version: string };
148
+ /** What every client is told first; none: nothing to say. */
149
+ instructions?(): Promise<string>;
150
+ /** The tools this caller may list and call. */
151
+ tools(): Promise<McpTool[]>;
152
+ /**
153
+ * Runs a call itself instead of the listed tool: for an endpoint that
154
+ * forwards another server's tools and need not list them to call one.
155
+ */
156
+ callTool?(
157
+ call: { name: string; arguments: Record<string, unknown> },
158
+ context: McpCallContext,
159
+ ): Promise<McpToolResult>;
160
+ /** Tools this caller would see with a scope its token lacks. */
161
+ withheld?(): Promise<ReadonlyMap<string, string>>;
162
+ resources?: McpResources;
163
+ tasks?: McpTasks;
164
+ }
165
+
166
+ const Message = z.looseObject({
167
+ jsonrpc: z.string().optional(),
168
+ id: z.union([z.string(), z.number(), z.null()]).optional(),
169
+ method: z.unknown(),
170
+ params: z.record(z.string(), z.unknown()).optional(),
171
+ });
172
+
173
+ const CallParams = z.looseObject({
174
+ name: z.string().min(1),
175
+ arguments: z.record(z.string(), z.unknown()).default({}),
176
+ inputResponses: z.record(z.string(), z.unknown()).optional(),
177
+ requestState: z.string().optional(),
178
+ });
179
+
180
+ function isModernVersion(version: string): boolean {
181
+ const [newest] = MODERN_PROTOCOL_VERSIONS;
182
+ return /^\d{4}-\d{2}-\d{2}$/.test(version) && version >= newest;
183
+ }
184
+
185
+ function header(request: FastifyRequest, name: string): string | undefined {
186
+ const value = request.headers[name];
187
+ return Array.isArray(value) ? value[0] : value;
188
+ }
189
+
190
+ /** A mirrored header's value, decoded from the Base64 sentinel form. */
191
+ function mirrored(value: string): string {
192
+ const encoded = /^=\?base64\?(.*)\?=$/.exec(value);
193
+ return encoded?.[1] !== undefined
194
+ ? Buffer.from(encoded[1], "base64").toString("utf8")
195
+ : value;
196
+ }
197
+
198
+ function record(value: unknown): Record<string, unknown> {
199
+ return typeof value === "object" && value !== null && !Array.isArray(value)
200
+ ? Object.fromEntries(Object.entries(value))
201
+ : {};
202
+ }
203
+
204
+ /** Whether the client declared the tasks extension on this request. */
205
+ export function declaresTasks(context: McpCallContext | undefined): boolean {
206
+ return (
207
+ context?.era === "modern" &&
208
+ TASKS_EXTENSION in record(context.clientCapabilities.extensions)
209
+ );
210
+ }
211
+
212
+ /** Whether the client can ask its person a form elicitation. */
213
+ export function declaresElicitation(
214
+ context: McpCallContext | undefined,
215
+ ): boolean {
216
+ if (context?.era !== "modern") return false;
217
+ const elicitation = context.clientCapabilities.elicitation;
218
+ if (typeof elicitation !== "object" || elicitation === null) return false;
219
+ // An empty object means form mode, as before modes were named.
220
+ const modes = record(elicitation);
221
+ return Object.keys(modes).length === 0 || "form" in modes;
222
+ }
223
+
224
+ /** Results clients may keep for a while, and for whom. */
225
+ const CACHEABLE: Readonly<Record<string, number>> = {
226
+ "server/discover": 300_000,
227
+ "tools/list": 60_000,
228
+ "prompts/list": 300_000,
229
+ "resources/list": 0,
230
+ "resources/templates/list": 300_000,
231
+ "resources/read": 0,
232
+ };
233
+
234
+ function send(
235
+ reply: FastifyReply,
236
+ status: number,
237
+ body: Record<string, unknown>,
238
+ ): FastifyReply {
239
+ return reply
240
+ .status(status)
241
+ .header("content-type", "application/json")
242
+ .send({ jsonrpc: "2.0", ...body });
243
+ }
244
+
245
+ function fail(
246
+ reply: FastifyReply,
247
+ id: string | number | null,
248
+ error: McpError,
249
+ ): FastifyReply {
250
+ return send(reply, error.options.status ?? 200, {
251
+ id,
252
+ error: {
253
+ code: error.code,
254
+ message: error.message,
255
+ ...(error.options.data !== undefined ? { data: error.options.data } : {}),
256
+ },
257
+ });
258
+ }
259
+
260
+ /** Serve one POST to an MCP endpoint, in whichever era the client speaks. */
261
+ export async function serveMcp(args: {
262
+ request: FastifyRequest;
263
+ reply: FastifyReply;
264
+ endpoint: McpEndpoint;
265
+ /** Named in a step-up challenge, when the host publishes one. */
266
+ resourceMetadataUrl?: string;
267
+ }): Promise<FastifyReply> {
268
+ const { request, reply, endpoint } = args;
269
+ const parsed = Message.safeParse(request.body);
270
+ if (!parsed.success || Array.isArray(request.body))
271
+ return fail(
272
+ reply,
273
+ null,
274
+ new McpError(
275
+ MCP_ERROR.invalidRequest,
276
+ "Expected a single JSON-RPC message",
277
+ { status: 400 },
278
+ ),
279
+ );
280
+ const message = parsed.data;
281
+ const params = message.params ?? {};
282
+ const meta = record(params._meta);
283
+ const claimed = meta[MCP_META.protocolVersion];
284
+ const versionHeader = header(request, "mcp-protocol-version");
285
+ const modern =
286
+ claimed !== undefined ||
287
+ (versionHeader !== undefined && isModernVersion(versionHeader));
288
+ // Notifications (initialized, cancelled) need no body in return.
289
+ if (message.id === undefined || message.id === null)
290
+ return reply.status(202).send();
291
+ const id = message.id;
292
+ if (typeof message.method !== "string")
293
+ return fail(
294
+ reply,
295
+ id,
296
+ new McpError(MCP_ERROR.invalidRequest, "Missing method", { status: 400 }),
297
+ );
298
+ const method = message.method;
299
+ const abort = new AbortController();
300
+ reply.raw.once("close", () => {
301
+ if (!reply.raw.writableFinished) abort.abort();
302
+ });
303
+ try {
304
+ if (!modern)
305
+ return send(reply, 200, {
306
+ id,
307
+ result: await legacy({
308
+ endpoint,
309
+ method,
310
+ params,
311
+ context: {
312
+ era: "legacy",
313
+ protocolVersion: versionHeader ?? DEFAULT_PROTOCOL_VERSION,
314
+ clientCapabilities: {},
315
+ signal: abort.signal,
316
+ },
317
+ }),
318
+ });
319
+ const context = validateModern({
320
+ request,
321
+ method,
322
+ params,
323
+ meta,
324
+ signal: abort.signal,
325
+ });
326
+ if (method === "subscriptions/listen")
327
+ return await listen({
328
+ reply,
329
+ endpoint,
330
+ id,
331
+ params,
332
+ signal: abort.signal,
333
+ });
334
+ const result = await modernResult({ endpoint, method, params, context });
335
+ const complete = (result.resultType ?? "complete") === "complete";
336
+ const ttlMs = CACHEABLE[method];
337
+ return send(reply, 200, {
338
+ id,
339
+ result: {
340
+ resultType: "complete",
341
+ ...(complete && ttlMs !== undefined
342
+ ? { ttlMs, cacheScope: "private" }
343
+ : {}),
344
+ ...result,
345
+ _meta: {
346
+ ...record(result._meta),
347
+ [MCP_META.serverInfo]: {
348
+ name: endpoint.serverInfo.name,
349
+ version: endpoint.serverInfo.version,
350
+ },
351
+ },
352
+ },
353
+ });
354
+ } catch (error) {
355
+ // The grant lacks the scope: a step-up challenge, as on every route.
356
+ if (
357
+ error instanceof McpScopeError ||
358
+ error instanceof TokenScopeRequiredError
359
+ )
360
+ return reply
361
+ .status(403)
362
+ .header(
363
+ "www-authenticate",
364
+ `Bearer error="insufficient_scope", scope="${error.scope}"${
365
+ args.resourceMetadataUrl
366
+ ? `, resource_metadata="${args.resourceMetadataUrl}"`
367
+ : ""
368
+ }`,
369
+ )
370
+ .header("content-type", "application/json")
371
+ .send({
372
+ jsonrpc: "2.0",
373
+ id,
374
+ error: { code: MCP_ERROR.invalidRequest, message: error.message },
375
+ });
376
+ if (error instanceof McpError) return fail(reply, id, error);
377
+ return fail(
378
+ reply,
379
+ id,
380
+ new McpError(
381
+ MCP_ERROR.internal,
382
+ error instanceof Error ? error.message : "Internal error",
383
+ ),
384
+ );
385
+ }
386
+ }
387
+
388
+ /** The request's own claims, checked as the current revision requires. */
389
+ function validateModern(input: {
390
+ request: FastifyRequest;
391
+ method: string;
392
+ params: Record<string, unknown>;
393
+ meta: Record<string, unknown>;
394
+ signal: AbortSignal;
395
+ }): McpCallContext {
396
+ const { request, method, params, meta } = input;
397
+ const mismatch = (text: string) =>
398
+ new McpError(MCP_ERROR.headerMismatch, `Header mismatch: ${text}`, {
399
+ status: 400,
400
+ });
401
+ const versionHeader = header(request, "mcp-protocol-version");
402
+ if (versionHeader === undefined)
403
+ throw mismatch("the MCP-Protocol-Version header is missing");
404
+ const version = meta[MCP_META.protocolVersion];
405
+ if (typeof version !== "string")
406
+ throw new McpError(
407
+ MCP_ERROR.invalidParams,
408
+ `Missing _meta["${MCP_META.protocolVersion}"]`,
409
+ { status: 400 },
410
+ );
411
+ if (versionHeader !== version)
412
+ throw mismatch(
413
+ `MCP-Protocol-Version header value '${versionHeader}' does not match body value '${version}'`,
414
+ );
415
+ if (!MODERN_PROTOCOL_VERSIONS.some((supported) => supported === version))
416
+ throw new McpError(
417
+ MCP_ERROR.unsupportedProtocolVersion,
418
+ "Unsupported protocol version",
419
+ {
420
+ status: 400,
421
+ data: {
422
+ supported: [...MODERN_PROTOCOL_VERSIONS, ...LEGACY_VERSIONS],
423
+ requested: version,
424
+ },
425
+ },
426
+ );
427
+ const methodHeader = header(request, "mcp-method");
428
+ if (methodHeader === undefined)
429
+ throw mismatch("the Mcp-Method header is missing");
430
+ if (methodHeader !== method)
431
+ throw mismatch(
432
+ `Mcp-Method header value '${methodHeader}' does not match body value '${method}'`,
433
+ );
434
+ const named =
435
+ method === "tools/call" || method === "prompts/get"
436
+ ? params.name
437
+ : method === "resources/read"
438
+ ? params.uri
439
+ : undefined;
440
+ if (typeof named === "string") {
441
+ const nameHeader = header(request, "mcp-name");
442
+ if (nameHeader === undefined)
443
+ throw mismatch("the Mcp-Name header is missing");
444
+ if (mirrored(nameHeader) !== named)
445
+ throw mismatch(
446
+ `Mcp-Name header value '${mirrored(nameHeader)}' does not match body value '${named}'`,
447
+ );
448
+ }
449
+ const capabilities = meta[MCP_META.clientCapabilities];
450
+ if (
451
+ typeof capabilities !== "object" ||
452
+ capabilities === null ||
453
+ Array.isArray(capabilities)
454
+ )
455
+ throw new McpError(
456
+ MCP_ERROR.invalidParams,
457
+ `Missing _meta["${MCP_META.clientCapabilities}"]`,
458
+ { status: 400 },
459
+ );
460
+ return {
461
+ era: "modern",
462
+ protocolVersion: version,
463
+ clientCapabilities: record(capabilities),
464
+ signal: input.signal,
465
+ };
466
+ }
467
+
468
+ const LEGACY_VERSIONS = [...SUPPORTED_PROTOCOL_VERSIONS].sort().reverse();
469
+
470
+ async function callTool(input: {
471
+ endpoint: McpEndpoint;
472
+ params: Record<string, unknown>;
473
+ context: McpCallContext;
474
+ }): Promise<McpToolResult> {
475
+ const call = CallParams.safeParse(input.params);
476
+ if (!call.success)
477
+ throw new McpError(MCP_ERROR.invalidParams, "Invalid tool call");
478
+ if (input.endpoint.callTool)
479
+ return input.endpoint.callTool(
480
+ { name: call.data.name, arguments: call.data.arguments },
481
+ input.context,
482
+ );
483
+ const tool = (await input.endpoint.tools()).find(
484
+ (candidate) => candidate.definition.name === call.data.name,
485
+ );
486
+ if (!tool) {
487
+ const scope = (await input.endpoint.withheld?.())?.get(call.data.name);
488
+ if (scope) throw new McpScopeError(scope);
489
+ throw new McpError(
490
+ MCP_ERROR.invalidParams,
491
+ `Unknown tool: ${call.data.name}`,
492
+ );
493
+ }
494
+ return tool.call(call.data.arguments, {
495
+ ...input.context,
496
+ ...(call.data.inputResponses
497
+ ? { inputResponses: call.data.inputResponses }
498
+ : {}),
499
+ ...(call.data.requestState !== undefined
500
+ ? { requestState: call.data.requestState }
501
+ : {}),
502
+ });
503
+ }
504
+
505
+ function capabilities(endpoint: McpEndpoint): Record<string, unknown> {
506
+ return {
507
+ tools: {},
508
+ ...(endpoint.resources ? { resources: {} } : {}),
509
+ ...(endpoint.tasks ? { extensions: { [TASKS_EXTENSION]: {} } } : {}),
510
+ };
511
+ }
512
+
513
+ function textParam(params: Record<string, unknown>, name: string): string {
514
+ const value = params[name];
515
+ if (typeof value !== "string" || value === "")
516
+ throw new McpError(MCP_ERROR.invalidParams, `Missing ${name}`);
517
+ return value;
518
+ }
519
+
520
+ async function modernResult(input: {
521
+ endpoint: McpEndpoint;
522
+ method: string;
523
+ params: Record<string, unknown>;
524
+ context: McpCallContext;
525
+ }): Promise<Record<string, unknown>> {
526
+ const { endpoint, method, params, context } = input;
527
+ const notFound = () =>
528
+ new McpError(MCP_ERROR.methodNotFound, `Method not found: ${method}`, {
529
+ status: 404,
530
+ });
531
+ switch (method) {
532
+ case "server/discover":
533
+ return {
534
+ supportedVersions: [...MODERN_PROTOCOL_VERSIONS, ...LEGACY_VERSIONS],
535
+ capabilities: capabilities(endpoint),
536
+ ...(endpoint.instructions
537
+ ? { instructions: await endpoint.instructions() }
538
+ : {}),
539
+ _meta: {
540
+ [MCP_META.serverInfo]: {
541
+ name: endpoint.serverInfo.name,
542
+ ...(endpoint.serverInfo.title
543
+ ? { title: endpoint.serverInfo.title }
544
+ : {}),
545
+ version: endpoint.serverInfo.version,
546
+ },
547
+ },
548
+ };
549
+ case "tools/list":
550
+ return {
551
+ tools: (await endpoint.tools()).map((tool) => tool.definition),
552
+ };
553
+ case "tools/call":
554
+ return callTool({ endpoint, params, context });
555
+ case "resources/list":
556
+ return { resources: (await endpoint.resources?.list()) ?? [] };
557
+ case "resources/templates/list":
558
+ return {
559
+ resourceTemplates: (await endpoint.resources?.templates()) ?? [],
560
+ };
561
+ case "resources/read": {
562
+ if (!endpoint.resources) throw notFound();
563
+ return {
564
+ contents: await endpoint.resources.read(textParam(params, "uri")),
565
+ };
566
+ }
567
+ case "prompts/list":
568
+ return { prompts: [] };
569
+ case "tasks/get": {
570
+ if (!endpoint.tasks) throw notFound();
571
+ return endpoint.tasks.get(textParam(params, "taskId"));
572
+ }
573
+ case "tasks/update": {
574
+ if (!endpoint.tasks) throw notFound();
575
+ await endpoint.tasks.update(
576
+ textParam(params, "taskId"),
577
+ record(params.inputResponses),
578
+ );
579
+ return {};
580
+ }
581
+ case "tasks/cancel": {
582
+ if (!endpoint.tasks) throw notFound();
583
+ await endpoint.tasks.cancel(textParam(params, "taskId"));
584
+ return {};
585
+ }
586
+ default:
587
+ throw notFound();
588
+ }
589
+ }
590
+
591
+ /** What only later revisions define, taken out of a legacy answer. */
592
+ function legacyToolResult(
593
+ result: McpToolResult,
594
+ version: string,
595
+ ): McpToolResult {
596
+ if (version >= "2025-06-18" || !Array.isArray(result.content)) return result;
597
+ return {
598
+ ...result,
599
+ content: result.content.filter(
600
+ (part) => record(part).type !== "resource_link",
601
+ ),
602
+ };
603
+ }
604
+
605
+ /**
606
+ * The 2025-era shell: the `initialize` handshake answered statelessly,
607
+ * plain tools, and resources to read. A long turn is waited on with
608
+ * `session_wait`, as on every surface; there is no task, no stream and
609
+ * nothing asked of the client.
610
+ */
611
+ async function legacy(input: {
612
+ endpoint: McpEndpoint;
613
+ method: string;
614
+ params: Record<string, unknown>;
615
+ context: McpCallContext;
616
+ }): Promise<Record<string, unknown>> {
617
+ const { endpoint, method, params, context } = input;
618
+ switch (method) {
619
+ case "initialize": {
620
+ const requested = params.protocolVersion;
621
+ return {
622
+ protocolVersion:
623
+ typeof requested === "string" &&
624
+ SUPPORTED_PROTOCOL_VERSIONS.has(requested)
625
+ ? requested
626
+ : DEFAULT_PROTOCOL_VERSION,
627
+ capabilities: {
628
+ tools: { listChanged: false },
629
+ ...(endpoint.resources ? { resources: {} } : {}),
630
+ },
631
+ serverInfo: endpoint.serverInfo,
632
+ ...(endpoint.instructions
633
+ ? { instructions: await endpoint.instructions() }
634
+ : {}),
635
+ };
636
+ }
637
+ case "ping":
638
+ return {};
639
+ case "tools/list":
640
+ return {
641
+ tools: (await endpoint.tools()).map((tool) => tool.definition),
642
+ };
643
+ case "resources/list":
644
+ return { resources: (await endpoint.resources?.list()) ?? [] };
645
+ case "resources/templates/list":
646
+ return {
647
+ resourceTemplates: (await endpoint.resources?.templates()) ?? [],
648
+ };
649
+ case "resources/read": {
650
+ if (!endpoint.resources)
651
+ throw new McpError(
652
+ MCP_ERROR.methodNotFound,
653
+ `Method not found: ${method}`,
654
+ );
655
+ return {
656
+ contents: await endpoint.resources.read(textParam(params, "uri")),
657
+ };
658
+ }
659
+ case "prompts/list":
660
+ return { prompts: [] };
661
+ case "tools/call":
662
+ return legacyToolResult(
663
+ await callTool({ endpoint, params, context }),
664
+ context.protocolVersion,
665
+ );
666
+ default:
667
+ throw new McpError(
668
+ MCP_ERROR.methodNotFound,
669
+ `Method not found: ${method}`,
670
+ );
671
+ }
672
+ }
673
+
674
+ const ListenFilter = z.looseObject({
675
+ resourceSubscriptions: z.array(z.string()).max(200).optional(),
676
+ taskIds: z.array(z.string()).max(200).optional(),
677
+ });
678
+
679
+ /**
680
+ * `subscriptions/listen`: one long-lived response stream. The
681
+ * acknowledgement comes first, naming what is watched; then a notification
682
+ * for each change, each stamped with the subscription's id; a comment
683
+ * keeps a quiet stream open. Closing the stream ends the subscription.
684
+ */
685
+ async function listen(input: {
686
+ reply: FastifyReply;
687
+ endpoint: McpEndpoint;
688
+ id: string | number;
689
+ params: Record<string, unknown>;
690
+ signal: AbortSignal;
691
+ }): Promise<FastifyReply> {
692
+ const { reply, endpoint, id } = input;
693
+ const filter = ListenFilter.safeParse(record(input.params.notifications));
694
+ if (!filter.success)
695
+ throw new McpError(MCP_ERROR.invalidParams, "Invalid notification filter");
696
+ const raw = reply.raw;
697
+ let open = false;
698
+ let ended = false;
699
+ const pending: string[] = [];
700
+ const write = (frame: string) => {
701
+ if (ended) return;
702
+ if (open) raw.write(frame);
703
+ else pending.push(frame);
704
+ };
705
+ const notify = (method: string, params: Record<string, unknown>) =>
706
+ write(
707
+ `event: message\ndata: ${JSON.stringify({
708
+ jsonrpc: "2.0",
709
+ method,
710
+ params: {
711
+ ...params,
712
+ _meta: { ...record(params._meta), [MCP_META.subscriptionId]: id },
713
+ },
714
+ })}\n\n`,
715
+ );
716
+ const watches: McpWatch[] = [];
717
+ const end = (graceful: boolean) => {
718
+ if (ended) return;
719
+ if (graceful && open)
720
+ raw.write(
721
+ `event: message\ndata: ${JSON.stringify({
722
+ jsonrpc: "2.0",
723
+ id,
724
+ result: {
725
+ resultType: "complete",
726
+ _meta: { [MCP_META.subscriptionId]: id },
727
+ },
728
+ })}\n\n`,
729
+ );
730
+ ended = true;
731
+ clearInterval(keepAlive);
732
+ for (const watch of watches) watch.stop();
733
+ if (open) raw.end();
734
+ };
735
+ const keepAlive = setInterval(() => write(":\n\n"), MCP_KEEP_ALIVE_MS);
736
+ keepAlive.unref?.();
737
+ input.signal.addEventListener("abort", () => end(false), { once: true });
738
+ try {
739
+ // Watching starts before the acknowledgement is written, so a refusal
740
+ // is still an ordinary error; what it reports waits behind the ack.
741
+ const resources =
742
+ endpoint.resources?.watch && filter.data.resourceSubscriptions?.length
743
+ ? await endpoint.resources.watch(
744
+ filter.data.resourceSubscriptions,
745
+ (uri) => notify("notifications/resources/updated", { uri }),
746
+ () => end(true),
747
+ )
748
+ : undefined;
749
+ if (resources) watches.push(resources);
750
+ const tasks =
751
+ endpoint.tasks && filter.data.taskIds?.length
752
+ ? await endpoint.tasks.watch(filter.data.taskIds, (task) =>
753
+ notify("notifications/tasks", task),
754
+ )
755
+ : undefined;
756
+ if (tasks) watches.push(tasks);
757
+ reply.hijack();
758
+ const own: Record<string, string | string[]> = {};
759
+ for (const [name, value] of Object.entries(reply.getHeaders()))
760
+ if (value !== undefined)
761
+ own[name] = typeof value === "number" ? String(value) : value;
762
+ raw.writeHead(200, {
763
+ ...own,
764
+ "content-type": "text/event-stream; charset=utf-8",
765
+ "cache-control": "no-cache, no-transform",
766
+ connection: "keep-alive",
767
+ // Proxies that buffer responses (nginx) would hold the stream back.
768
+ "x-accel-buffering": "no",
769
+ });
770
+ open = true;
771
+ raw.write(
772
+ `event: message\ndata: ${JSON.stringify({
773
+ jsonrpc: "2.0",
774
+ method: "notifications/subscriptions/acknowledged",
775
+ params: {
776
+ _meta: { [MCP_META.subscriptionId]: id },
777
+ notifications: {
778
+ ...(resources ? { resourceSubscriptions: resources.accepted } : {}),
779
+ ...(tasks ? { taskIds: tasks.accepted } : {}),
780
+ },
781
+ },
782
+ })}\n\n`,
783
+ );
784
+ for (const frame of pending.splice(0)) raw.write(frame);
785
+ if (input.signal.aborted) end(false);
786
+ return reply;
787
+ } catch (error) {
788
+ end(false);
789
+ throw error;
790
+ }
791
+ }
792
+
793
+ /**
794
+ * An MCP endpoint serving another server's tools: tools listed and results
795
+ * returned as that server declared and sent them (ADR 0225), in whichever
796
+ * era the client speaks. `callTool` answers with the server's own result
797
+ * (any tool result passes through), or throws {@link McpError} for a
798
+ * refusal at the protocol boundary.
799
+ */
800
+ export function serveForwardedTools(args: {
801
+ request: FastifyRequest;
802
+ reply: FastifyReply;
803
+ serverName: string;
804
+ listTools(): Promise<readonly ForwardedToolDefinition[]>;
805
+ callTool(call: {
806
+ name: string;
807
+ arguments: Record<string, unknown>;
808
+ }): Promise<unknown>;
809
+ }): Promise<FastifyReply> {
810
+ return serveMcp({
811
+ request: args.request,
812
+ reply: args.reply,
813
+ endpoint: {
814
+ serverInfo: { name: args.serverName, version: "1" },
815
+ tools: async () =>
816
+ (await args.listTools()).map((tool) => ({
817
+ definition: forwardedTool(tool),
818
+ call: async (input) =>
819
+ forwardedToolResult(
820
+ await args.callTool({ name: tool.name, arguments: input }),
821
+ ),
822
+ })),
823
+ // The server refuses a name it does not have: no list is read first.
824
+ callTool: async (call) => forwardedToolResult(await args.callTool(call)),
825
+ },
826
+ });
827
+ }