@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
package/NOTICE.txt CHANGED
@@ -30,3 +30,10 @@ command-score
30
30
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
31
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
32
  SOFTWARE.
33
+
34
+ bergamot-translator
35
+ apps/desktop/src/main/translation/vendor/bergamot-translator.js is Firefox's
36
+ unmodified glue for the Bergamot translation engine
37
+ (https://github.com/mozilla/translations). It is subject to the terms of the
38
+ Mozilla Public License, v. 2.0. You can obtain a copy of the MPL at
39
+ http://mozilla.org/MPL/2.0/. Its source form is the file itself.
package/dist/app.d.ts CHANGED
@@ -20,6 +20,8 @@ export interface AppConfig {
20
20
  publicApiBase?: string;
21
21
  /** See `CatamorphicPluginOptions.projectMcp`. */
22
22
  projectMcp?: CatamorphicPluginOptions["projectMcp"];
23
+ /** See `CatamorphicPluginOptions.mcp`. */
24
+ mcp?: CatamorphicPluginOptions["mcp"];
23
25
  }
24
26
  export declare function createApp(config: AppConfig): import("fastify").FastifyInstance<import("fastify").RawServerDefault, import("node:http").IncomingMessage, import("node:http").ServerResponse<import("node:http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault> & PromiseLike<import("fastify").FastifyInstance<import("fastify").RawServerDefault, import("node:http").IncomingMessage, import("node:http").ServerResponse<import("node:http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>> & {
25
27
  __linterBrands: 'SafePromiseLike';
package/dist/app.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AASzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,KAAK,wBAAwB,EAAqB,MAAM,aAAa,CAAC;AAQ/E,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,SAAS;IACxB;;;;OAIG;IACH,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB;;;OAGG;IACH,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,sEAAsE;IACtE,QAAQ,CAAC,EAAE,wBAAwB,CAAC,UAAU,CAAC,CAAC;IAChD,oDAAoD;IACpD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iDAAiD;IACjD,UAAU,CAAC,EAAE,wBAAwB,CAAC,YAAY,CAAC,CAAC;CACrD;AAwBD,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS;;EAoD1C"}
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AASzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,KAAK,wBAAwB,EAAqB,MAAM,aAAa,CAAC;AAQ/E,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,SAAS;IACxB;;;;OAIG;IACH,IAAI,CAAC,EAAE,eAAe,CAAC;IACvB;;;OAGG;IACH,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,sEAAsE;IACtE,QAAQ,CAAC,EAAE,wBAAwB,CAAC,UAAU,CAAC,CAAC;IAChD,oDAAoD;IACpD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iDAAiD;IACjD,UAAU,CAAC,EAAE,wBAAwB,CAAC,YAAY,CAAC,CAAC;IACpD,0CAA0C;IAC1C,GAAG,CAAC,EAAE,wBAAwB,CAAC,KAAK,CAAC,CAAC;CACvC;AAwBD,wBAAgB,SAAS,CAAC,MAAM,EAAE,SAAS;;EAqD1C"}
@@ -0,0 +1,592 @@
1
+ // src/mcp-server.ts
2
+ import { TokenScopeRequiredError } from "@catamorphic/core";
3
+ import { z as z2 } from "zod";
4
+
5
+ // src/mcp-shared.ts
6
+ import { MCP_POLL_RUN_TOOL, RunNotFoundError } from "@catamorphic/core";
7
+ import { z } from "zod";
8
+ function toolValue(value) {
9
+ return {
10
+ content: [{ type: "text", text: JSON.stringify(value) ?? "null" }],
11
+ ...typeof value === "object" && value !== null && !Array.isArray(value) ? { structuredContent: value } : {}
12
+ };
13
+ }
14
+ function toolError2(message) {
15
+ return { content: [{ type: "text", text: message }], isError: true };
16
+ }
17
+ function forwardedTool(tool) {
18
+ return {
19
+ name: tool.name,
20
+ ...tool.title ? { title: tool.title } : {},
21
+ ...tool.description ? { description: tool.description } : {},
22
+ inputSchema: tool.inputSchema,
23
+ ...isObjectSchema(tool.outputSchema) ? { outputSchema: tool.outputSchema } : {},
24
+ ...tool.annotations ? { annotations: tool.annotations } : {}
25
+ };
26
+ }
27
+ var ForwardedToolResultSchema = z.looseObject({
28
+ content: z.array(z.unknown()),
29
+ structuredContent: z.unknown().optional()
30
+ });
31
+ function forwardedToolResult(result) {
32
+ const parsed = ForwardedToolResultSchema.safeParse(result);
33
+ if (!parsed.success)
34
+ return toolValue(result);
35
+ const { structuredContent, ...rest } = parsed.data;
36
+ if (structuredContent === undefined)
37
+ return rest;
38
+ if (isObject(structuredContent))
39
+ return { ...rest, structuredContent };
40
+ return rest.content.length > 0 ? rest : {
41
+ ...rest,
42
+ content: [{ type: "text", text: JSON.stringify(structuredContent) }]
43
+ };
44
+ }
45
+ function isObject(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ function isObjectSchema(schema) {
49
+ return isObject(schema) && schema.type === "object";
50
+ }
51
+ var POLL_RUN_TOOL = MCP_POLL_RUN_TOOL;
52
+ var POLL_RUN_TOOL_DEFINITION = {
53
+ name: POLL_RUN_TOOL,
54
+ annotations: { readOnlyHint: true },
55
+ description: "Poll a workflow run by its runId — one started asynchronously or one " + "that detached mid-call. Returns the run's status, output (once " + "completed), and batch progress.",
56
+ inputSchema: {
57
+ type: "object",
58
+ properties: { runId: { type: "string" } },
59
+ required: ["runId"]
60
+ }
61
+ };
62
+ async function callPollRunTool(core, identity, args) {
63
+ const runId = typeof args.runId === "string" ? args.runId : "";
64
+ try {
65
+ return toolValue(await fetchRunSnapshot(core, identity, runId));
66
+ } catch (error) {
67
+ if (error instanceof RunNotFoundError)
68
+ return toolError2("Run not found");
69
+ throw error;
70
+ }
71
+ }
72
+ async function fetchRunSnapshot(core, identity, runId) {
73
+ const run = await core.runs.get({ identity, runId });
74
+ const batch = run.batchScopes?.[0];
75
+ return {
76
+ runId: run.id,
77
+ status: run.status,
78
+ output: run.result ?? null,
79
+ error: run.error ?? null,
80
+ ...batch ? {
81
+ progress: {
82
+ discovered: batch.discovered,
83
+ succeeded: batch.succeeded,
84
+ failed: batch.failed,
85
+ skipped: batch.skipped
86
+ }
87
+ } : {}
88
+ };
89
+ }
90
+
91
+ // src/mcp-server.ts
92
+ var MODERN_PROTOCOL_VERSIONS = ["2026-07-28"];
93
+ var SUPPORTED_PROTOCOL_VERSIONS = new Set([
94
+ "2024-11-05",
95
+ "2025-03-26",
96
+ "2025-06-18",
97
+ "2025-11-25"
98
+ ]);
99
+ var DEFAULT_PROTOCOL_VERSION = "2025-06-18";
100
+ var MCP_META = {
101
+ protocolVersion: "io.modelcontextprotocol/protocolVersion",
102
+ clientInfo: "io.modelcontextprotocol/clientInfo",
103
+ clientCapabilities: "io.modelcontextprotocol/clientCapabilities",
104
+ serverInfo: "io.modelcontextprotocol/serverInfo",
105
+ subscriptionId: "io.modelcontextprotocol/subscriptionId"
106
+ };
107
+ var TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
108
+ var MCP_ERROR2 = {
109
+ parse: -32700,
110
+ invalidRequest: -32600,
111
+ methodNotFound: -32601,
112
+ invalidParams: -32602,
113
+ internal: -32603,
114
+ headerMismatch: -32020,
115
+ missingClientCapability: -32021,
116
+ unsupportedProtocolVersion: -32022
117
+ };
118
+ var MCP_KEEP_ALIVE_MS = 15000;
119
+
120
+ class McpError2 extends Error {
121
+ code;
122
+ options;
123
+ constructor(code, message, options = {}) {
124
+ super(message);
125
+ this.code = code;
126
+ this.options = options;
127
+ this.name = "McpError";
128
+ }
129
+ }
130
+
131
+ class McpScopeError extends Error {
132
+ scope;
133
+ constructor(scope) {
134
+ super(`This call needs the ${scope} scope`);
135
+ this.scope = scope;
136
+ this.name = "McpScopeError";
137
+ }
138
+ }
139
+ var Message = z2.looseObject({
140
+ jsonrpc: z2.string().optional(),
141
+ id: z2.union([z2.string(), z2.number(), z2.null()]).optional(),
142
+ method: z2.unknown(),
143
+ params: z2.record(z2.string(), z2.unknown()).optional()
144
+ });
145
+ var CallParams = z2.looseObject({
146
+ name: z2.string().min(1),
147
+ arguments: z2.record(z2.string(), z2.unknown()).default({}),
148
+ inputResponses: z2.record(z2.string(), z2.unknown()).optional(),
149
+ requestState: z2.string().optional()
150
+ });
151
+ function isModernVersion(version) {
152
+ const [newest] = MODERN_PROTOCOL_VERSIONS;
153
+ return /^\d{4}-\d{2}-\d{2}$/.test(version) && version >= newest;
154
+ }
155
+ function header(request, name) {
156
+ const value = request.headers[name];
157
+ return Array.isArray(value) ? value[0] : value;
158
+ }
159
+ function mirrored(value) {
160
+ const encoded = /^=\?base64\?(.*)\?=$/.exec(value);
161
+ return encoded?.[1] !== undefined ? Buffer.from(encoded[1], "base64").toString("utf8") : value;
162
+ }
163
+ function record(value) {
164
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : {};
165
+ }
166
+ function declaresTasks(context) {
167
+ return context?.era === "modern" && TASKS_EXTENSION in record(context.clientCapabilities.extensions);
168
+ }
169
+ function declaresElicitation(context) {
170
+ if (context?.era !== "modern")
171
+ return false;
172
+ const elicitation = context.clientCapabilities.elicitation;
173
+ if (typeof elicitation !== "object" || elicitation === null)
174
+ return false;
175
+ const modes = record(elicitation);
176
+ return Object.keys(modes).length === 0 || "form" in modes;
177
+ }
178
+ var CACHEABLE = {
179
+ "server/discover": 300000,
180
+ "tools/list": 60000,
181
+ "prompts/list": 300000,
182
+ "resources/list": 0,
183
+ "resources/templates/list": 300000,
184
+ "resources/read": 0
185
+ };
186
+ function send(reply, status, body) {
187
+ return reply.status(status).header("content-type", "application/json").send({ jsonrpc: "2.0", ...body });
188
+ }
189
+ function fail(reply, id, error) {
190
+ return send(reply, error.options.status ?? 200, {
191
+ id,
192
+ error: {
193
+ code: error.code,
194
+ message: error.message,
195
+ ...error.options.data !== undefined ? { data: error.options.data } : {}
196
+ }
197
+ });
198
+ }
199
+ async function serveMcp(args) {
200
+ const { request, reply, endpoint } = args;
201
+ const parsed = Message.safeParse(request.body);
202
+ if (!parsed.success || Array.isArray(request.body))
203
+ return fail(reply, null, new McpError2(MCP_ERROR2.invalidRequest, "Expected a single JSON-RPC message", { status: 400 }));
204
+ const message = parsed.data;
205
+ const params = message.params ?? {};
206
+ const meta = record(params._meta);
207
+ const claimed = meta[MCP_META.protocolVersion];
208
+ const versionHeader = header(request, "mcp-protocol-version");
209
+ const modern = claimed !== undefined || versionHeader !== undefined && isModernVersion(versionHeader);
210
+ if (message.id === undefined || message.id === null)
211
+ return reply.status(202).send();
212
+ const id = message.id;
213
+ if (typeof message.method !== "string")
214
+ return fail(reply, id, new McpError2(MCP_ERROR2.invalidRequest, "Missing method", { status: 400 }));
215
+ const method = message.method;
216
+ const abort = new AbortController;
217
+ reply.raw.once("close", () => {
218
+ if (!reply.raw.writableFinished)
219
+ abort.abort();
220
+ });
221
+ try {
222
+ if (!modern)
223
+ return send(reply, 200, {
224
+ id,
225
+ result: await legacy({
226
+ endpoint,
227
+ method,
228
+ params,
229
+ context: {
230
+ era: "legacy",
231
+ protocolVersion: versionHeader ?? DEFAULT_PROTOCOL_VERSION,
232
+ clientCapabilities: {},
233
+ signal: abort.signal
234
+ }
235
+ })
236
+ });
237
+ const context = validateModern({
238
+ request,
239
+ method,
240
+ params,
241
+ meta,
242
+ signal: abort.signal
243
+ });
244
+ if (method === "subscriptions/listen")
245
+ return await listen({
246
+ reply,
247
+ endpoint,
248
+ id,
249
+ params,
250
+ signal: abort.signal
251
+ });
252
+ const result = await modernResult({ endpoint, method, params, context });
253
+ const complete = (result.resultType ?? "complete") === "complete";
254
+ const ttlMs = CACHEABLE[method];
255
+ return send(reply, 200, {
256
+ id,
257
+ result: {
258
+ resultType: "complete",
259
+ ...complete && ttlMs !== undefined ? { ttlMs, cacheScope: "private" } : {},
260
+ ...result,
261
+ _meta: {
262
+ ...record(result._meta),
263
+ [MCP_META.serverInfo]: {
264
+ name: endpoint.serverInfo.name,
265
+ version: endpoint.serverInfo.version
266
+ }
267
+ }
268
+ }
269
+ });
270
+ } catch (error) {
271
+ if (error instanceof McpScopeError || error instanceof TokenScopeRequiredError)
272
+ return reply.status(403).header("www-authenticate", `Bearer error="insufficient_scope", scope="${error.scope}"${args.resourceMetadataUrl ? `, resource_metadata="${args.resourceMetadataUrl}"` : ""}`).header("content-type", "application/json").send({
273
+ jsonrpc: "2.0",
274
+ id,
275
+ error: { code: MCP_ERROR2.invalidRequest, message: error.message }
276
+ });
277
+ if (error instanceof McpError2)
278
+ return fail(reply, id, error);
279
+ return fail(reply, id, new McpError2(MCP_ERROR2.internal, error instanceof Error ? error.message : "Internal error"));
280
+ }
281
+ }
282
+ function validateModern(input) {
283
+ const { request, method, params, meta } = input;
284
+ const mismatch = (text) => new McpError2(MCP_ERROR2.headerMismatch, `Header mismatch: ${text}`, {
285
+ status: 400
286
+ });
287
+ const versionHeader = header(request, "mcp-protocol-version");
288
+ if (versionHeader === undefined)
289
+ throw mismatch("the MCP-Protocol-Version header is missing");
290
+ const version = meta[MCP_META.protocolVersion];
291
+ if (typeof version !== "string")
292
+ throw new McpError2(MCP_ERROR2.invalidParams, `Missing _meta["${MCP_META.protocolVersion}"]`, { status: 400 });
293
+ if (versionHeader !== version)
294
+ throw mismatch(`MCP-Protocol-Version header value '${versionHeader}' does not match body value '${version}'`);
295
+ if (!MODERN_PROTOCOL_VERSIONS.some((supported) => supported === version))
296
+ throw new McpError2(MCP_ERROR2.unsupportedProtocolVersion, "Unsupported protocol version", {
297
+ status: 400,
298
+ data: {
299
+ supported: [...MODERN_PROTOCOL_VERSIONS, ...LEGACY_VERSIONS],
300
+ requested: version
301
+ }
302
+ });
303
+ const methodHeader = header(request, "mcp-method");
304
+ if (methodHeader === undefined)
305
+ throw mismatch("the Mcp-Method header is missing");
306
+ if (methodHeader !== method)
307
+ throw mismatch(`Mcp-Method header value '${methodHeader}' does not match body value '${method}'`);
308
+ const named = method === "tools/call" || method === "prompts/get" ? params.name : method === "resources/read" ? params.uri : undefined;
309
+ if (typeof named === "string") {
310
+ const nameHeader = header(request, "mcp-name");
311
+ if (nameHeader === undefined)
312
+ throw mismatch("the Mcp-Name header is missing");
313
+ if (mirrored(nameHeader) !== named)
314
+ throw mismatch(`Mcp-Name header value '${mirrored(nameHeader)}' does not match body value '${named}'`);
315
+ }
316
+ const capabilities = meta[MCP_META.clientCapabilities];
317
+ if (typeof capabilities !== "object" || capabilities === null || Array.isArray(capabilities))
318
+ throw new McpError2(MCP_ERROR2.invalidParams, `Missing _meta["${MCP_META.clientCapabilities}"]`, { status: 400 });
319
+ return {
320
+ era: "modern",
321
+ protocolVersion: version,
322
+ clientCapabilities: record(capabilities),
323
+ signal: input.signal
324
+ };
325
+ }
326
+ var LEGACY_VERSIONS = [...SUPPORTED_PROTOCOL_VERSIONS].sort().reverse();
327
+ async function callTool(input) {
328
+ const call = CallParams.safeParse(input.params);
329
+ if (!call.success)
330
+ throw new McpError2(MCP_ERROR2.invalidParams, "Invalid tool call");
331
+ if (input.endpoint.callTool)
332
+ return input.endpoint.callTool({ name: call.data.name, arguments: call.data.arguments }, input.context);
333
+ const tool = (await input.endpoint.tools()).find((candidate) => candidate.definition.name === call.data.name);
334
+ if (!tool) {
335
+ const scope = (await input.endpoint.withheld?.())?.get(call.data.name);
336
+ if (scope)
337
+ throw new McpScopeError(scope);
338
+ throw new McpError2(MCP_ERROR2.invalidParams, `Unknown tool: ${call.data.name}`);
339
+ }
340
+ return tool.call(call.data.arguments, {
341
+ ...input.context,
342
+ ...call.data.inputResponses ? { inputResponses: call.data.inputResponses } : {},
343
+ ...call.data.requestState !== undefined ? { requestState: call.data.requestState } : {}
344
+ });
345
+ }
346
+ function capabilities(endpoint) {
347
+ return {
348
+ tools: {},
349
+ ...endpoint.resources ? { resources: {} } : {},
350
+ ...endpoint.tasks ? { extensions: { [TASKS_EXTENSION]: {} } } : {}
351
+ };
352
+ }
353
+ function textParam(params, name) {
354
+ const value = params[name];
355
+ if (typeof value !== "string" || value === "")
356
+ throw new McpError2(MCP_ERROR2.invalidParams, `Missing ${name}`);
357
+ return value;
358
+ }
359
+ async function modernResult(input) {
360
+ const { endpoint, method, params, context } = input;
361
+ const notFound = () => new McpError2(MCP_ERROR2.methodNotFound, `Method not found: ${method}`, {
362
+ status: 404
363
+ });
364
+ switch (method) {
365
+ case "server/discover":
366
+ return {
367
+ supportedVersions: [...MODERN_PROTOCOL_VERSIONS, ...LEGACY_VERSIONS],
368
+ capabilities: capabilities(endpoint),
369
+ ...endpoint.instructions ? { instructions: await endpoint.instructions() } : {},
370
+ _meta: {
371
+ [MCP_META.serverInfo]: {
372
+ name: endpoint.serverInfo.name,
373
+ ...endpoint.serverInfo.title ? { title: endpoint.serverInfo.title } : {},
374
+ version: endpoint.serverInfo.version
375
+ }
376
+ }
377
+ };
378
+ case "tools/list":
379
+ return {
380
+ tools: (await endpoint.tools()).map((tool) => tool.definition)
381
+ };
382
+ case "tools/call":
383
+ return callTool({ endpoint, params, context });
384
+ case "resources/list":
385
+ return { resources: await endpoint.resources?.list() ?? [] };
386
+ case "resources/templates/list":
387
+ return {
388
+ resourceTemplates: await endpoint.resources?.templates() ?? []
389
+ };
390
+ case "resources/read": {
391
+ if (!endpoint.resources)
392
+ throw notFound();
393
+ return {
394
+ contents: await endpoint.resources.read(textParam(params, "uri"))
395
+ };
396
+ }
397
+ case "prompts/list":
398
+ return { prompts: [] };
399
+ case "tasks/get": {
400
+ if (!endpoint.tasks)
401
+ throw notFound();
402
+ return endpoint.tasks.get(textParam(params, "taskId"));
403
+ }
404
+ case "tasks/update": {
405
+ if (!endpoint.tasks)
406
+ throw notFound();
407
+ await endpoint.tasks.update(textParam(params, "taskId"), record(params.inputResponses));
408
+ return {};
409
+ }
410
+ case "tasks/cancel": {
411
+ if (!endpoint.tasks)
412
+ throw notFound();
413
+ await endpoint.tasks.cancel(textParam(params, "taskId"));
414
+ return {};
415
+ }
416
+ default:
417
+ throw notFound();
418
+ }
419
+ }
420
+ function legacyToolResult(result, version) {
421
+ if (version >= "2025-06-18" || !Array.isArray(result.content))
422
+ return result;
423
+ return {
424
+ ...result,
425
+ content: result.content.filter((part) => record(part).type !== "resource_link")
426
+ };
427
+ }
428
+ async function legacy(input) {
429
+ const { endpoint, method, params, context } = input;
430
+ switch (method) {
431
+ case "initialize": {
432
+ const requested = params.protocolVersion;
433
+ return {
434
+ protocolVersion: typeof requested === "string" && SUPPORTED_PROTOCOL_VERSIONS.has(requested) ? requested : DEFAULT_PROTOCOL_VERSION,
435
+ capabilities: {
436
+ tools: { listChanged: false },
437
+ ...endpoint.resources ? { resources: {} } : {}
438
+ },
439
+ serverInfo: endpoint.serverInfo,
440
+ ...endpoint.instructions ? { instructions: await endpoint.instructions() } : {}
441
+ };
442
+ }
443
+ case "ping":
444
+ return {};
445
+ case "tools/list":
446
+ return {
447
+ tools: (await endpoint.tools()).map((tool) => tool.definition)
448
+ };
449
+ case "resources/list":
450
+ return { resources: await endpoint.resources?.list() ?? [] };
451
+ case "resources/templates/list":
452
+ return {
453
+ resourceTemplates: await endpoint.resources?.templates() ?? []
454
+ };
455
+ case "resources/read": {
456
+ if (!endpoint.resources)
457
+ throw new McpError2(MCP_ERROR2.methodNotFound, `Method not found: ${method}`);
458
+ return {
459
+ contents: await endpoint.resources.read(textParam(params, "uri"))
460
+ };
461
+ }
462
+ case "prompts/list":
463
+ return { prompts: [] };
464
+ case "tools/call":
465
+ return legacyToolResult(await callTool({ endpoint, params, context }), context.protocolVersion);
466
+ default:
467
+ throw new McpError2(MCP_ERROR2.methodNotFound, `Method not found: ${method}`);
468
+ }
469
+ }
470
+ var ListenFilter = z2.looseObject({
471
+ resourceSubscriptions: z2.array(z2.string()).max(200).optional(),
472
+ taskIds: z2.array(z2.string()).max(200).optional()
473
+ });
474
+ async function listen(input) {
475
+ const { reply, endpoint, id } = input;
476
+ const filter = ListenFilter.safeParse(record(input.params.notifications));
477
+ if (!filter.success)
478
+ throw new McpError2(MCP_ERROR2.invalidParams, "Invalid notification filter");
479
+ const raw = reply.raw;
480
+ let open = false;
481
+ let ended = false;
482
+ const pending = [];
483
+ const write = (frame) => {
484
+ if (ended)
485
+ return;
486
+ if (open)
487
+ raw.write(frame);
488
+ else
489
+ pending.push(frame);
490
+ };
491
+ const notify = (method, params) => write(`event: message
492
+ data: ${JSON.stringify({
493
+ jsonrpc: "2.0",
494
+ method,
495
+ params: {
496
+ ...params,
497
+ _meta: { ...record(params._meta), [MCP_META.subscriptionId]: id }
498
+ }
499
+ })}
500
+
501
+ `);
502
+ const watches = [];
503
+ const end = (graceful) => {
504
+ if (ended)
505
+ return;
506
+ if (graceful && open)
507
+ raw.write(`event: message
508
+ data: ${JSON.stringify({
509
+ jsonrpc: "2.0",
510
+ id,
511
+ result: {
512
+ resultType: "complete",
513
+ _meta: { [MCP_META.subscriptionId]: id }
514
+ }
515
+ })}
516
+
517
+ `);
518
+ ended = true;
519
+ clearInterval(keepAlive);
520
+ for (const watch of watches)
521
+ watch.stop();
522
+ if (open)
523
+ raw.end();
524
+ };
525
+ const keepAlive = setInterval(() => write(`:
526
+
527
+ `), MCP_KEEP_ALIVE_MS);
528
+ keepAlive.unref?.();
529
+ input.signal.addEventListener("abort", () => end(false), { once: true });
530
+ try {
531
+ const resources = endpoint.resources?.watch && filter.data.resourceSubscriptions?.length ? await endpoint.resources.watch(filter.data.resourceSubscriptions, (uri) => notify("notifications/resources/updated", { uri }), () => end(true)) : undefined;
532
+ if (resources)
533
+ watches.push(resources);
534
+ const tasks = endpoint.tasks && filter.data.taskIds?.length ? await endpoint.tasks.watch(filter.data.taskIds, (task) => notify("notifications/tasks", task)) : undefined;
535
+ if (tasks)
536
+ watches.push(tasks);
537
+ reply.hijack();
538
+ const own = {};
539
+ for (const [name, value] of Object.entries(reply.getHeaders()))
540
+ if (value !== undefined)
541
+ own[name] = typeof value === "number" ? String(value) : value;
542
+ raw.writeHead(200, {
543
+ ...own,
544
+ "content-type": "text/event-stream; charset=utf-8",
545
+ "cache-control": "no-cache, no-transform",
546
+ connection: "keep-alive",
547
+ "x-accel-buffering": "no"
548
+ });
549
+ open = true;
550
+ raw.write(`event: message
551
+ data: ${JSON.stringify({
552
+ jsonrpc: "2.0",
553
+ method: "notifications/subscriptions/acknowledged",
554
+ params: {
555
+ _meta: { [MCP_META.subscriptionId]: id },
556
+ notifications: {
557
+ ...resources ? { resourceSubscriptions: resources.accepted } : {},
558
+ ...tasks ? { taskIds: tasks.accepted } : {}
559
+ }
560
+ }
561
+ })}
562
+
563
+ `);
564
+ for (const frame of pending.splice(0))
565
+ raw.write(frame);
566
+ if (input.signal.aborted)
567
+ end(false);
568
+ return reply;
569
+ } catch (error) {
570
+ end(false);
571
+ throw error;
572
+ }
573
+ }
574
+ function serveForwardedTools2(args) {
575
+ return serveMcp({
576
+ request: args.request,
577
+ reply: args.reply,
578
+ endpoint: {
579
+ serverInfo: { name: args.serverName, version: "1" },
580
+ tools: async () => (await args.listTools()).map((tool) => ({
581
+ definition: forwardedTool(tool),
582
+ call: async (input) => forwardedToolResult(await args.callTool({ name: tool.name, arguments: input }))
583
+ })),
584
+ callTool: async (call) => forwardedToolResult(await args.callTool(call))
585
+ }
586
+ });
587
+ }
588
+
589
+ export { toolValue, toolError2, POLL_RUN_TOOL, POLL_RUN_TOOL_DEFINITION, callPollRunTool, MCP_ERROR2, McpError2, declaresTasks, declaresElicitation, serveMcp, serveForwardedTools2 };
590
+
591
+ //# debugId=9A50D14C8697525D64756E2164756E21
592
+ //# sourceMappingURL=chunk-jytcc42y.js.map