@mcpfn/core 0.0.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,2621 @@
1
+ // src/errors.ts
2
+ function jsonSafe(value) {
3
+ const ancestors = [];
4
+ try {
5
+ const serialized = JSON.stringify(value, function(_key, entry) {
6
+ if (typeof entry === "bigint") return entry.toString();
7
+ if (entry && typeof entry === "object") {
8
+ while (ancestors.length && ancestors.at(-1) !== this) ancestors.pop();
9
+ if (ancestors.includes(entry)) return "[Circular]";
10
+ ancestors.push(entry);
11
+ }
12
+ return entry;
13
+ });
14
+ return serialized === void 0 ? String(value) : JSON.parse(serialized);
15
+ } catch {
16
+ return "[Unserializable]";
17
+ }
18
+ }
19
+ var McpFnError = class extends Error {
20
+ code;
21
+ details;
22
+ constructor(code, message, details) {
23
+ super(message);
24
+ this.name = "McpFnError";
25
+ this.code = code;
26
+ this.details = details;
27
+ }
28
+ };
29
+ var McpFnValidationError = class extends McpFnError {
30
+ constructor(message, details) {
31
+ super("MCPFN_INVALID_ARGUMENTS", message, details);
32
+ this.name = "McpFnValidationError";
33
+ }
34
+ };
35
+ var McpFnOutputValidationError = class extends McpFnError {
36
+ constructor(message, details) {
37
+ super("MCPFN_INVALID_OUTPUT", message, details);
38
+ this.name = "McpFnOutputValidationError";
39
+ }
40
+ };
41
+ function errorResult(error, options = {}) {
42
+ const normalized = error instanceof McpFnError ? { code: error.code, message: error.message, details: error.details } : error instanceof Error && "code" in error && typeof error.code === "string" ? {
43
+ code: error.code,
44
+ message: error.message,
45
+ details: "details" in error ? error.details : "metadata" in error ? error.metadata : void 0
46
+ } : error && typeof error === "object" && "code" in error && typeof error.code === "string" && "message" in error && typeof error.message === "string" ? {
47
+ code: error.code,
48
+ message: error.message,
49
+ details: "details" in error ? error.details : "metadata" in error ? error.metadata : void 0
50
+ } : {
51
+ code: "MCPFN_TOOL_ERROR",
52
+ message: error instanceof Error ? error.message : String(error)
53
+ };
54
+ const structuredContent = jsonSafe({
55
+ ok: false,
56
+ error: Object.fromEntries(
57
+ Object.entries(normalized).filter(([, value]) => value !== void 0)
58
+ )
59
+ });
60
+ return {
61
+ content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }],
62
+ ...options.includeStructuredContent === false ? {} : { structuredContent },
63
+ isError: true
64
+ };
65
+ }
66
+
67
+ // src/apps.ts
68
+ var MCP_APP_EXTENSION_ID = "io.modelcontextprotocol/ui";
69
+ var MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
70
+ function assertUiUri(uri) {
71
+ if (!uri.startsWith("ui://")) {
72
+ throw new McpFnValidationError(`MCP App resource URI must use ui://: ${uri}`);
73
+ }
74
+ try {
75
+ new URL(uri);
76
+ } catch {
77
+ throw new McpFnValidationError(`Invalid MCP App resource URI: ${uri}`);
78
+ }
79
+ }
80
+ function assertHtml(html) {
81
+ if (!html.trim() || !/(<!doctype\s+html|<html(?:\s|>))/i.test(html)) {
82
+ throw new McpFnValidationError("MCP App resources must contain an HTML5 document");
83
+ }
84
+ }
85
+ function assertCsp(csp) {
86
+ if (!csp) return;
87
+ for (const [kind, domains] of Object.entries(csp)) {
88
+ if (domains === void 0) continue;
89
+ if (!Array.isArray(domains)) {
90
+ throw new McpFnValidationError(`MCP App CSP ${kind} must be an array`);
91
+ }
92
+ for (const domain of domains) {
93
+ let url;
94
+ try {
95
+ url = new URL(domain);
96
+ } catch {
97
+ throw new McpFnValidationError(`Invalid MCP App CSP domain: ${domain}`);
98
+ }
99
+ if (url.protocol !== "https:" && url.protocol !== "wss:") {
100
+ throw new McpFnValidationError(`MCP App CSP domains must use https or wss: ${domain}`);
101
+ }
102
+ }
103
+ }
104
+ }
105
+ function mcpAppToolMetadata(resourceUri, visibility = ["model", "app"]) {
106
+ assertUiUri(resourceUri);
107
+ if (!visibility.length || visibility.some((value) => value !== "model" && value !== "app")) {
108
+ throw new McpFnValidationError("MCP App visibility must contain model and/or app");
109
+ }
110
+ return { ui: { resourceUri, visibility: [...new Set(visibility)] } };
111
+ }
112
+ function createMcpAppResource(options) {
113
+ assertUiUri(options.uri);
114
+ assertCsp(options.ui?.csp);
115
+ if (typeof options.html === "string") assertHtml(options.html);
116
+ const ui = options.ui ?? {};
117
+ return {
118
+ uri: options.uri,
119
+ name: options.name,
120
+ ...options.title ? { title: options.title } : {},
121
+ ...options.description ? { description: options.description } : {},
122
+ mimeType: MCP_APP_MIME_TYPE,
123
+ ...options.annotations ? { annotations: options.annotations } : {},
124
+ ...options.icons ? { icons: options.icons } : {},
125
+ ...options.subscribe ? { subscribe: options.subscribe } : {},
126
+ ...options.unsubscribe ? { unsubscribe: options.unsubscribe } : {},
127
+ metadata: { ...options.metadata, ui },
128
+ read: async (_uri, context) => {
129
+ const html = typeof options.html === "function" ? await options.html(context) : options.html;
130
+ assertHtml(html);
131
+ return {
132
+ contents: [{
133
+ uri: options.uri,
134
+ mimeType: MCP_APP_MIME_TYPE,
135
+ text: html,
136
+ _meta: { ui }
137
+ }]
138
+ };
139
+ }
140
+ };
141
+ }
142
+ function assertMcpAppContracts(registry) {
143
+ const resources = new Map(registry.resourceDefinitions().map((resource) => [resource.uri, resource]));
144
+ for (const resource of resources.values()) {
145
+ if (!resource.uri.startsWith("ui://")) continue;
146
+ if (resource.mimeType !== MCP_APP_MIME_TYPE) {
147
+ throw new McpFnValidationError(
148
+ `MCP App resource ${resource.uri} must use ${MCP_APP_MIME_TYPE}`
149
+ );
150
+ }
151
+ const ui = resource.metadata?.ui;
152
+ assertCsp(ui?.csp);
153
+ }
154
+ for (const tool of registry.definitions()) {
155
+ const ui = tool.metadata?.ui;
156
+ if (!ui) continue;
157
+ assertUiUri(ui.resourceUri);
158
+ const resource = resources.get(ui.resourceUri);
159
+ if (!resource) {
160
+ throw new McpFnValidationError(
161
+ `Tool ${tool.name} links to missing MCP App resource ${ui.resourceUri}`
162
+ );
163
+ }
164
+ if (resource.mimeType !== MCP_APP_MIME_TYPE) {
165
+ throw new McpFnValidationError(
166
+ `Tool ${tool.name} links to a resource without the MCP App MIME type`
167
+ );
168
+ }
169
+ if (ui.visibility !== void 0 && (!Array.isArray(ui.visibility) || !ui.visibility.length || ui.visibility.some((value) => value !== "model" && value !== "app"))) throw new McpFnValidationError(`Tool ${tool.name} has invalid MCP App visibility`);
170
+ }
171
+ }
172
+
173
+ // src/canonical.ts
174
+ import { createHash } from "crypto";
175
+ function compareCodeUnits(left, right) {
176
+ return left < right ? -1 : left > right ? 1 : 0;
177
+ }
178
+ function canonicalize(value) {
179
+ if (Array.isArray(value)) {
180
+ return value.map(canonicalize);
181
+ }
182
+ if (value && typeof value === "object") {
183
+ return Object.fromEntries(
184
+ Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => compareCodeUnits(left, right)).map(([key, entry]) => [key, canonicalize(entry)])
185
+ );
186
+ }
187
+ return value;
188
+ }
189
+ function canonicalJson(value) {
190
+ return JSON.stringify(canonicalize(value));
191
+ }
192
+ function sha256(value) {
193
+ return createHash("sha256").update(canonicalJson(value)).digest("hex");
194
+ }
195
+
196
+ // src/diff.ts
197
+ function push(changes, change) {
198
+ changes.push(change);
199
+ }
200
+ function valueSet(value) {
201
+ return Array.isArray(value) ? new Set(value.map((entry) => canonicalJson(entry))) : void 0;
202
+ }
203
+ function equal(left, right) {
204
+ return canonicalJson(left) === canonicalJson(right);
205
+ }
206
+ function schemaTypes(schema) {
207
+ if (Array.isArray(schema.type)) {
208
+ return new Set(schema.type.filter((value) => typeof value === "string"));
209
+ }
210
+ return typeof schema.type === "string" ? /* @__PURE__ */ new Set([schema.type]) : void 0;
211
+ }
212
+ function equalSets(left, right) {
213
+ return left.size === right.size && [...left].every((value) => right.has(value));
214
+ }
215
+ function hasUnescapedAlternation(pattern) {
216
+ let escaped = false;
217
+ for (const character of pattern) {
218
+ if (escaped) {
219
+ escaped = false;
220
+ continue;
221
+ }
222
+ if (character === "\\") {
223
+ escaped = true;
224
+ continue;
225
+ }
226
+ if (character === "|") return true;
227
+ }
228
+ return false;
229
+ }
230
+ function anchoredLiteralPrefix(pattern) {
231
+ if (!pattern.startsWith("^")) return void 0;
232
+ let prefix = "";
233
+ for (let index = 1; index < pattern.length; index += 1) {
234
+ const character = pattern[index];
235
+ if (character === "\\") {
236
+ const escaped = pattern[index + 1];
237
+ if (!escaped || /[A-Za-z0-9]/.test(escaped)) break;
238
+ prefix += escaped;
239
+ index += 1;
240
+ continue;
241
+ }
242
+ if (".^$*+?()[]{}|".includes(character)) break;
243
+ prefix += character;
244
+ }
245
+ return prefix || void 0;
246
+ }
247
+ function anchoredLiteralSuffix(pattern) {
248
+ if (!pattern.endsWith("$") || pattern.endsWith("\\$")) return void 0;
249
+ let suffix = "";
250
+ for (let index = 0; index < pattern.length - 1; index += 1) {
251
+ const character = pattern[index];
252
+ if (character === "\\") {
253
+ const escaped = pattern[index + 1];
254
+ if (!escaped) break;
255
+ suffix = /[A-Za-z0-9]/.test(escaped) ? "" : suffix + escaped;
256
+ index += 1;
257
+ continue;
258
+ }
259
+ suffix = ".^$*+?()[]{}|".includes(character) ? "" : suffix + character;
260
+ }
261
+ return suffix || void 0;
262
+ }
263
+ function patternsMayOverlap(left, right) {
264
+ if (hasUnescapedAlternation(left) || hasUnescapedAlternation(right)) return true;
265
+ const leftPrefix = anchoredLiteralPrefix(left);
266
+ const rightPrefix = anchoredLiteralPrefix(right);
267
+ if (leftPrefix && rightPrefix && !leftPrefix.startsWith(rightPrefix) && !rightPrefix.startsWith(leftPrefix)) return false;
268
+ const leftSuffix = anchoredLiteralSuffix(left);
269
+ const rightSuffix = anchoredLiteralSuffix(right);
270
+ if (leftSuffix && rightSuffix && !leftSuffix.endsWith(rightSuffix) && !rightSuffix.endsWith(leftSuffix)) return false;
271
+ return true;
272
+ }
273
+ function capabilityRecord(value) {
274
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
275
+ }
276
+ function nestedCapabilityChanges(before, after, path) {
277
+ if (equal(before, after)) return [];
278
+ if (before === true && after === false) {
279
+ return [{ severity: "breaking", path, before, after }];
280
+ }
281
+ if (before === false && after === true) {
282
+ return [{ severity: "additive", path, before, after }];
283
+ }
284
+ if (capabilityRecord(before) && capabilityRecord(after)) {
285
+ return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].sort(compareCodeUnits).flatMap((name) => {
286
+ const childPath = `${path}.${name}`;
287
+ const hadBefore = Object.prototype.hasOwnProperty.call(before, name);
288
+ const hasAfter = Object.prototype.hasOwnProperty.call(after, name);
289
+ if (!hasAfter) {
290
+ return [{ severity: "breaking", path: childPath, before: before[name], after: void 0 }];
291
+ }
292
+ if (!hadBefore) {
293
+ return [{ severity: "additive", path: childPath, before: void 0, after: after[name] }];
294
+ }
295
+ return nestedCapabilityChanges(before[name], after[name], childPath);
296
+ });
297
+ }
298
+ if (capabilityRecord(before) && after === false) {
299
+ return [{ severity: "breaking", path, before, after }];
300
+ }
301
+ if (before === false && capabilityRecord(after)) {
302
+ return [{ severity: "additive", path, before, after }];
303
+ }
304
+ return [{ severity: "behavioral", path, before, after }];
305
+ }
306
+ function matchingPatternSchemas(schema, propertyName) {
307
+ const patterns = schema.patternProperties;
308
+ if (!patterns || typeof patterns !== "object" || Array.isArray(patterns)) {
309
+ return [];
310
+ }
311
+ return Object.entries(patterns).filter(([pattern]) => {
312
+ try {
313
+ return new RegExp(pattern).test(propertyName);
314
+ } catch {
315
+ return false;
316
+ }
317
+ }).map(([, patternSchema]) => patternSchema);
318
+ }
319
+ function diffSchema(before, after, path, direction, changes) {
320
+ if (before && typeof before === "object" && !Object.keys(before).length) before = true;
321
+ if (after && typeof after === "object" && !Object.keys(after).length) after = true;
322
+ if (before === void 0 && after !== void 0) {
323
+ push(changes, {
324
+ severity: direction === "input" ? "breaking" : "additive",
325
+ code: "schema-added",
326
+ path,
327
+ message: `Schema added at ${path}`,
328
+ after
329
+ });
330
+ return;
331
+ }
332
+ if (before !== void 0 && after === void 0) {
333
+ push(changes, {
334
+ severity: direction === "input" ? "additive" : "breaking",
335
+ code: "schema-removed",
336
+ path,
337
+ message: `Schema removed at ${path}`,
338
+ before
339
+ });
340
+ return;
341
+ }
342
+ if (before === void 0 || after === void 0 || equal(before, after)) return;
343
+ if (typeof before === "boolean" || typeof after === "boolean") {
344
+ const tightened = before === true || after === false;
345
+ const relaxed = before === false || after === true;
346
+ const breaking = direction === "input" ? tightened : relaxed;
347
+ push(changes, {
348
+ severity: breaking ? "breaking" : "additive",
349
+ code: "boolean-schema-changed",
350
+ path,
351
+ message: `Boolean schema changed at ${path}`,
352
+ before,
353
+ after
354
+ });
355
+ return;
356
+ }
357
+ const beforeTypes = schemaTypes(before);
358
+ const afterTypes = schemaTypes(after);
359
+ if (!equal(before.type, after.type) && !(beforeTypes && afterTypes && equalSets(beforeTypes, afterTypes))) {
360
+ const removed = beforeTypes && afterTypes ? [...beforeTypes].filter((value) => !afterTypes?.has(value)) : [];
361
+ const added = beforeTypes && afterTypes ? [...afterTypes].filter((value) => !beforeTypes?.has(value)) : [];
362
+ const tightened = beforeTypes === void 0 ? afterTypes !== void 0 : afterTypes !== void 0 && removed.length > 0;
363
+ const relaxed = afterTypes === void 0 || added.length > 0;
364
+ const breaking = direction === "input" ? tightened : relaxed;
365
+ push(changes, {
366
+ severity: breaking ? "breaking" : "additive",
367
+ code: "schema-type-changed",
368
+ path,
369
+ message: `Type changed from ${canonicalJson(before.type ?? "unspecified")} to ${canonicalJson(after.type ?? "unspecified")}`,
370
+ before: before.type,
371
+ after: after.type
372
+ });
373
+ }
374
+ const beforeEnum = valueSet(before.enum);
375
+ const afterEnum = valueSet(after.enum);
376
+ if (!beforeEnum && afterEnum) {
377
+ push(changes, {
378
+ severity: direction === "input" ? "breaking" : "additive",
379
+ code: "enum-introduced",
380
+ path,
381
+ message: `An enum constraint was introduced at ${path}`,
382
+ after: after.enum
383
+ });
384
+ } else if (beforeEnum && !afterEnum) {
385
+ push(changes, {
386
+ severity: direction === "input" ? "additive" : "breaking",
387
+ code: "enum-removed",
388
+ path,
389
+ message: `The enum constraint was removed at ${path}`,
390
+ before: before.enum
391
+ });
392
+ } else if (beforeEnum && afterEnum) {
393
+ const removed = [...beforeEnum].filter((entry) => !afterEnum.has(entry));
394
+ const added = [...afterEnum].filter((entry) => !beforeEnum.has(entry));
395
+ if (removed.length) {
396
+ push(changes, {
397
+ severity: direction === "input" ? "breaking" : "additive",
398
+ code: "enum-narrowed",
399
+ path,
400
+ message: `Allowed values were removed at ${path}`,
401
+ before: before.enum,
402
+ after: after.enum
403
+ });
404
+ }
405
+ if (added.length) {
406
+ push(changes, {
407
+ severity: direction === "input" ? "additive" : "breaking",
408
+ code: "enum-widened",
409
+ path,
410
+ message: `Allowed values were added at ${path}`,
411
+ before: before.enum,
412
+ after: after.enum
413
+ });
414
+ }
415
+ }
416
+ const tightening = [
417
+ ["minimum", "higher"],
418
+ ["exclusiveMinimum", "higher"],
419
+ ["minLength", "higher"],
420
+ ["minItems", "higher"],
421
+ ["maximum", "lower"],
422
+ ["exclusiveMaximum", "lower"],
423
+ ["maxLength", "lower"],
424
+ ["maxItems", "lower"],
425
+ ["minProperties", "higher"],
426
+ ["maxProperties", "lower"]
427
+ ];
428
+ for (const [keyword, tightDirection] of tightening) {
429
+ const oldValue = before[keyword];
430
+ const newValue = after[keyword];
431
+ if (equal(oldValue, newValue)) {
432
+ continue;
433
+ }
434
+ if (oldValue !== void 0 && typeof oldValue !== "number" || newValue !== void 0 && typeof newValue !== "number") {
435
+ push(changes, {
436
+ severity: "breaking",
437
+ code: "schema-keyword-changed",
438
+ path: `${path}.${keyword}`,
439
+ message: `${keyword} changed at ${path}`,
440
+ before: oldValue,
441
+ after: newValue
442
+ });
443
+ continue;
444
+ }
445
+ const tightened = oldValue === void 0 ? true : newValue === void 0 ? false : tightDirection === "higher" ? newValue > oldValue : newValue < oldValue;
446
+ const breaking = direction === "input" ? tightened : !tightened;
447
+ push(changes, {
448
+ severity: breaking ? "breaking" : "additive",
449
+ code: tightened ? "constraint-tightened" : "constraint-relaxed",
450
+ path: `${path}.${keyword}`,
451
+ message: `${keyword} changed from ${oldValue ?? "unspecified"} to ${newValue ?? "unspecified"}`,
452
+ before: oldValue,
453
+ after: newValue
454
+ });
455
+ }
456
+ for (const keyword of ["pattern", "format", "const"]) {
457
+ const oldValue = before[keyword];
458
+ const newValue = after[keyword];
459
+ if (equal(oldValue, newValue)) continue;
460
+ const tightened = oldValue === void 0 && newValue !== void 0;
461
+ const relaxed = oldValue !== void 0 && newValue === void 0;
462
+ push(changes, {
463
+ severity: tightened || relaxed ? (direction === "input" ? tightened : relaxed) ? "breaking" : "additive" : "breaking",
464
+ code: tightened ? "constraint-tightened" : relaxed ? "constraint-relaxed" : "schema-keyword-changed",
465
+ path: `${path}.${keyword}`,
466
+ message: `${keyword} changed at ${path}`,
467
+ before: oldValue,
468
+ after: newValue
469
+ });
470
+ }
471
+ const beforeUniqueItems = before.uniqueItems ?? false;
472
+ const afterUniqueItems = after.uniqueItems ?? false;
473
+ if (!equal(beforeUniqueItems, afterUniqueItems)) {
474
+ if (typeof beforeUniqueItems !== "boolean" || typeof afterUniqueItems !== "boolean") {
475
+ push(changes, {
476
+ severity: "breaking",
477
+ code: "schema-keyword-changed",
478
+ path: `${path}.uniqueItems`,
479
+ message: `uniqueItems changed at ${path}`,
480
+ before: before.uniqueItems,
481
+ after: after.uniqueItems
482
+ });
483
+ } else {
484
+ const tightened = !beforeUniqueItems && afterUniqueItems;
485
+ const breaking = direction === "input" ? tightened : !tightened;
486
+ push(changes, {
487
+ severity: breaking ? "breaking" : "additive",
488
+ code: tightened ? "constraint-tightened" : "constraint-relaxed",
489
+ path: `${path}.uniqueItems`,
490
+ message: `uniqueItems changed from ${beforeUniqueItems} to ${afterUniqueItems}`,
491
+ before: before.uniqueItems,
492
+ after: after.uniqueItems
493
+ });
494
+ }
495
+ }
496
+ const normalizeAdditionalProperties = (value) => value && typeof value === "object" && !Array.isArray(value) && !Object.keys(value).length ? true : value;
497
+ const beforeAdditional = normalizeAdditionalProperties(before.additionalProperties ?? true);
498
+ const afterAdditional = normalizeAdditionalProperties(after.additionalProperties ?? true);
499
+ if (beforeAdditional !== false && afterAdditional === false) {
500
+ push(changes, {
501
+ severity: direction === "input" ? "breaking" : "additive",
502
+ code: "additional-properties-disabled",
503
+ path,
504
+ message: `Additional properties are no longer accepted at ${path}`
505
+ });
506
+ } else if (beforeAdditional === false && afterAdditional !== false) {
507
+ push(changes, {
508
+ severity: direction === "input" ? "additive" : "breaking",
509
+ code: "additional-properties-enabled",
510
+ path,
511
+ message: `Additional properties are now accepted at ${path}`
512
+ });
513
+ } else if (!equal(beforeAdditional, afterAdditional)) {
514
+ diffSchema(
515
+ beforeAdditional,
516
+ afterAdditional,
517
+ `${path}.additionalProperties`,
518
+ direction,
519
+ changes
520
+ );
521
+ }
522
+ const beforeProperties = before.properties ?? {};
523
+ const afterProperties = after.properties ?? {};
524
+ const propertyNames = [.../* @__PURE__ */ new Set([
525
+ ...Object.keys(beforeProperties),
526
+ ...Object.keys(afterProperties),
527
+ ...Array.isArray(before.required) ? before.required : [],
528
+ ...Array.isArray(after.required) ? after.required : []
529
+ ])].sort();
530
+ const beforeRequired = new Set(
531
+ Array.isArray(before.required) ? before.required : []
532
+ );
533
+ const afterRequired = new Set(
534
+ Array.isArray(after.required) ? after.required : []
535
+ );
536
+ for (const name of propertyNames) {
537
+ const propertyPath = `${path}.properties.${name}`;
538
+ const oldProperty = beforeProperties[name];
539
+ const newProperty = afterProperties[name];
540
+ const hadOldProperty = Object.prototype.hasOwnProperty.call(beforeProperties, name);
541
+ const hasNewProperty = Object.prototype.hasOwnProperty.call(afterProperties, name);
542
+ if (!hadOldProperty && hasNewProperty) {
543
+ const newlyRequired = afterRequired.has(name);
544
+ const additionalPropertyChanges = [];
545
+ if (direction === "output" && typeof beforeAdditional === "object") {
546
+ diffSchema(
547
+ beforeAdditional,
548
+ newProperty,
549
+ `${propertyPath}.additionalProperties`,
550
+ "output",
551
+ additionalPropertyChanges
552
+ );
553
+ }
554
+ const inputFallbackChanges = [];
555
+ if (direction === "input") {
556
+ const patternSchemas = matchingPatternSchemas(before, name);
557
+ const fallbackSchemas = patternSchemas.length ? patternSchemas : [beforeAdditional];
558
+ fallbackSchemas.forEach((fallbackSchema, index) => diffSchema(
559
+ fallbackSchema,
560
+ newProperty,
561
+ `${propertyPath}.${patternSchemas.length ? `patternProperties.${index}` : "additionalProperties"}`,
562
+ "input",
563
+ inputFallbackChanges
564
+ ));
565
+ }
566
+ const breaksDeclaredOutput = direction === "output" && (beforeAdditional === false || additionalPropertyChanges.some((change) => change.severity === "breaking"));
567
+ const narrowsAcceptedInput = direction === "input" && inputFallbackChanges.some((change) => change.severity === "breaking");
568
+ push(changes, {
569
+ severity: direction === "input" && (newlyRequired || narrowsAcceptedInput) || breaksDeclaredOutput ? "breaking" : "additive",
570
+ code: direction === "input" && newlyRequired ? "required-input-added" : breaksDeclaredOutput ? "output-property-added" : "property-added",
571
+ path: propertyPath,
572
+ message: `${newlyRequired ? "Required" : "Optional"} property ${name} was added`,
573
+ after: newProperty
574
+ });
575
+ continue;
576
+ }
577
+ if (hadOldProperty && !hasNewProperty) {
578
+ const fallbackChanges = [];
579
+ const patternSchemas = matchingPatternSchemas(after, name);
580
+ const fallbackSchemas = patternSchemas.length ? patternSchemas : [afterAdditional];
581
+ fallbackSchemas.forEach((fallbackSchema, index) => diffSchema(
582
+ oldProperty,
583
+ fallbackSchema,
584
+ `${propertyPath}.${patternSchemas.length ? `patternProperties.${index}` : "additionalProperties"}`,
585
+ direction,
586
+ fallbackChanges
587
+ ));
588
+ const breaking2 = direction === "output" && beforeRequired.has(name) || fallbackChanges.some((change) => change.severity === "breaking");
589
+ push(changes, {
590
+ severity: breaking2 ? "breaking" : "additive",
591
+ code: "property-removed",
592
+ path: propertyPath,
593
+ message: `Property ${name} was removed`,
594
+ before: oldProperty
595
+ });
596
+ continue;
597
+ }
598
+ diffSchema(oldProperty, newProperty, propertyPath, direction, changes);
599
+ const wasRequired = beforeRequired.has(name);
600
+ const isRequired = afterRequired.has(name);
601
+ if (wasRequired === isRequired) continue;
602
+ const breaking = direction === "input" ? !wasRequired && isRequired : wasRequired && !isRequired;
603
+ push(changes, {
604
+ severity: breaking ? "breaking" : "additive",
605
+ code: breaking ? "requiredness-broken" : "requiredness-compatible",
606
+ path: propertyPath,
607
+ message: `Property ${name} changed from ${wasRequired ? "required" : "optional"} to ${isRequired ? "required" : "optional"}`
608
+ });
609
+ }
610
+ if (before.items !== void 0 || after.items !== void 0) {
611
+ diffSchema(
612
+ before.items,
613
+ after.items,
614
+ `${path}.items`,
615
+ direction,
616
+ changes
617
+ );
618
+ }
619
+ const beforePatterns = before.patternProperties ?? {};
620
+ const afterPatterns = after.patternProperties ?? {};
621
+ const patternNames = [.../* @__PURE__ */ new Set([
622
+ ...Object.keys(beforePatterns),
623
+ ...Object.keys(afterPatterns)
624
+ ])].sort();
625
+ for (const pattern of patternNames) {
626
+ const hadBeforePattern = Object.prototype.hasOwnProperty.call(beforePatterns, pattern);
627
+ const hasAfterPattern = Object.prototype.hasOwnProperty.call(afterPatterns, pattern);
628
+ diffSchema(
629
+ hadBeforePattern ? beforePatterns[pattern] : beforeAdditional,
630
+ hasAfterPattern ? afterPatterns[pattern] : afterAdditional,
631
+ `${path}.patternProperties.${pattern}`,
632
+ direction,
633
+ changes
634
+ );
635
+ const overlapChanges = [];
636
+ if (direction === "input" && !hadBeforePattern && hasAfterPattern) {
637
+ for (const [existingPattern, existingSchema] of Object.entries(beforePatterns)) {
638
+ if (!patternsMayOverlap(existingPattern, pattern)) continue;
639
+ diffSchema(
640
+ existingSchema,
641
+ afterPatterns[pattern],
642
+ `${path}.patternProperties.${pattern}.overlap.${existingPattern}`,
643
+ "input",
644
+ overlapChanges
645
+ );
646
+ }
647
+ }
648
+ if (direction === "output" && hadBeforePattern && !hasAfterPattern) {
649
+ for (const [remainingPattern, remainingSchema] of Object.entries(afterPatterns)) {
650
+ if (!patternsMayOverlap(pattern, remainingPattern)) continue;
651
+ diffSchema(
652
+ beforePatterns[pattern],
653
+ remainingSchema,
654
+ `${path}.patternProperties.${pattern}.overlap.${remainingPattern}`,
655
+ "output",
656
+ overlapChanges
657
+ );
658
+ }
659
+ }
660
+ if (overlapChanges.some((change) => change.severity === "breaking")) {
661
+ push(changes, {
662
+ severity: "breaking",
663
+ code: "overlapping-pattern-constraint-changed",
664
+ path: `${path}.patternProperties.${pattern}`,
665
+ message: `${hadBeforePattern ? "Removing" : "Adding"} pattern ${pattern} can change constraints for properties matched by another pattern`,
666
+ before: hadBeforePattern ? beforePatterns[pattern] : void 0,
667
+ after: hasAfterPattern ? afterPatterns[pattern] : void 0
668
+ });
669
+ }
670
+ }
671
+ const handledKeywords = /* @__PURE__ */ new Set([
672
+ "type",
673
+ "enum",
674
+ "properties",
675
+ "required",
676
+ "items",
677
+ "additionalProperties",
678
+ "patternProperties",
679
+ "pattern",
680
+ "format",
681
+ "const",
682
+ "uniqueItems",
683
+ ...tightening.map(([keyword]) => keyword)
684
+ ]);
685
+ const behavioralKeywords = /* @__PURE__ */ new Set([
686
+ "$comment",
687
+ "$id",
688
+ "$schema",
689
+ "default",
690
+ "deprecated",
691
+ "description",
692
+ "examples",
693
+ "readOnly",
694
+ "title",
695
+ "writeOnly"
696
+ ]);
697
+ const keywords = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].sort();
698
+ for (const keyword of keywords) {
699
+ if (handledKeywords.has(keyword) || equal(before[keyword], after[keyword])) continue;
700
+ const behavioral = behavioralKeywords.has(keyword) || /^x-/i.test(keyword);
701
+ push(changes, {
702
+ severity: behavioral ? "behavioral" : "breaking",
703
+ code: behavioral ? "schema-guidance-changed" : "schema-keyword-changed",
704
+ path: `${path}.${keyword}`,
705
+ message: `${keyword} changed at ${path}`,
706
+ before: before[keyword],
707
+ after: after[keyword]
708
+ });
709
+ }
710
+ }
711
+ function diffTool(before, after, changes) {
712
+ const root = `tools.${before.name}`;
713
+ if (before.title !== after.title) {
714
+ push(changes, {
715
+ severity: "behavioral",
716
+ code: "tool-title-changed",
717
+ path: `${root}.title`,
718
+ message: `Tool title changed for ${before.name}`,
719
+ before: before.title,
720
+ after: after.title
721
+ });
722
+ }
723
+ if (before.description !== after.description) {
724
+ push(changes, {
725
+ severity: "behavioral",
726
+ code: "tool-description-changed",
727
+ path: `${root}.description`,
728
+ message: `Tool description changed for ${before.name}`,
729
+ before: before.description,
730
+ after: after.description
731
+ });
732
+ }
733
+ if (!equal(before.annotations ?? {}, after.annotations ?? {})) {
734
+ push(changes, {
735
+ severity: "behavioral",
736
+ code: "tool-annotations-changed",
737
+ path: `${root}.annotations`,
738
+ message: `Tool annotations changed for ${before.name}`,
739
+ before: before.annotations,
740
+ after: after.annotations
741
+ });
742
+ }
743
+ if (!equal(before.execution ?? {}, after.execution ?? {})) {
744
+ const oldSupport = before.execution?.taskSupport ?? "forbidden";
745
+ const newSupport = after.execution?.taskSupport ?? "forbidden";
746
+ const breaking = newSupport === "required" || oldSupport !== "forbidden" && newSupport === "forbidden";
747
+ push(changes, {
748
+ severity: breaking ? "breaking" : "additive",
749
+ code: "tool-task-support-changed",
750
+ path: `${root}.execution.taskSupport`,
751
+ message: `Tool task support changed from ${oldSupport} to ${newSupport}`,
752
+ before: oldSupport,
753
+ after: newSupport
754
+ });
755
+ }
756
+ if (!equal(before.icons ?? [], after.icons ?? [])) {
757
+ push(changes, {
758
+ severity: "behavioral",
759
+ code: "tool-icons-changed",
760
+ path: `${root}.icons`,
761
+ message: `Tool icons changed for ${before.name}`,
762
+ before: before.icons,
763
+ after: after.icons
764
+ });
765
+ }
766
+ if (!equal(before.metadata ?? {}, after.metadata ?? {})) {
767
+ push(changes, {
768
+ severity: "behavioral",
769
+ code: "tool-metadata-changed",
770
+ path: `${root}.metadata`,
771
+ message: `Tool metadata changed for ${before.name}`,
772
+ before: before.metadata,
773
+ after: after.metadata
774
+ });
775
+ }
776
+ diffSchema(before.inputSchema, after.inputSchema, `${root}.inputSchema`, "input", changes);
777
+ diffSchema(before.outputSchema, after.outputSchema, `${root}.outputSchema`, "output", changes);
778
+ }
779
+ function diffResource(before, after, changes) {
780
+ const root = `resources.${before.uri}`;
781
+ if ((before.subscribable ?? false) !== (after.subscribable ?? false)) {
782
+ const enabled = after.subscribable === true;
783
+ push(changes, {
784
+ severity: enabled ? "additive" : "breaking",
785
+ code: enabled ? "resource-subscription-enabled" : "resource-subscription-removed",
786
+ path: `${root}.subscribable`,
787
+ message: `Resource subscription support was ${enabled ? "enabled" : "removed"} for ${before.uri}`,
788
+ before: before.subscribable,
789
+ after: after.subscribable
790
+ });
791
+ }
792
+ if (before.mimeType !== after.mimeType) {
793
+ push(changes, {
794
+ severity: "breaking",
795
+ code: "resource-mime-type-changed",
796
+ path: `${root}.mimeType`,
797
+ message: `Resource MIME type changed for ${before.uri}`,
798
+ before: before.mimeType,
799
+ after: after.mimeType
800
+ });
801
+ }
802
+ for (const key of ["name", "title", "description", "annotations", "icons", "metadata"]) {
803
+ if (!equal(before[key], after[key])) {
804
+ push(changes, {
805
+ severity: "behavioral",
806
+ code: `resource-${key}-changed`,
807
+ path: `${root}.${key}`,
808
+ message: `Resource ${key} changed for ${before.uri}`,
809
+ before: before[key],
810
+ after: after[key]
811
+ });
812
+ }
813
+ }
814
+ }
815
+ function diffResourceTemplate(before, after, changes) {
816
+ const root = `resourceTemplates.${before.name}`;
817
+ if ((before.subscribable ?? false) !== (after.subscribable ?? false)) {
818
+ const enabled = after.subscribable === true;
819
+ push(changes, {
820
+ severity: enabled ? "additive" : "breaking",
821
+ code: enabled ? "resource-template-subscription-enabled" : "resource-template-subscription-removed",
822
+ path: `${root}.subscribable`,
823
+ message: `Resource template subscription support was ${enabled ? "enabled" : "removed"} for ${before.name}`,
824
+ before: before.subscribable,
825
+ after: after.subscribable
826
+ });
827
+ }
828
+ if (before.uriTemplate !== after.uriTemplate) {
829
+ push(changes, {
830
+ severity: "breaking",
831
+ code: "resource-template-uri-changed",
832
+ path: `${root}.uriTemplate`,
833
+ message: `Resource template URI changed for ${before.name}`,
834
+ before: before.uriTemplate,
835
+ after: after.uriTemplate
836
+ });
837
+ }
838
+ if (before.mimeType !== after.mimeType) {
839
+ push(changes, {
840
+ severity: "breaking",
841
+ code: "resource-template-mime-type-changed",
842
+ path: `${root}.mimeType`,
843
+ message: `Resource template MIME type changed for ${before.name}`,
844
+ before: before.mimeType,
845
+ after: after.mimeType
846
+ });
847
+ }
848
+ for (const key of ["title", "description", "annotations", "icons", "metadata"]) {
849
+ if (!equal(before[key], after[key])) {
850
+ push(changes, {
851
+ severity: "behavioral",
852
+ code: `resource-template-${key}-changed`,
853
+ path: `${root}.${key}`,
854
+ message: `Resource template ${key} changed for ${before.name}`,
855
+ before: before[key],
856
+ after: after[key]
857
+ });
858
+ }
859
+ }
860
+ }
861
+ function promptArgumentSchema(prompt) {
862
+ if (prompt.argumentsSchema) return prompt.argumentsSchema;
863
+ return {
864
+ type: "object",
865
+ properties: Object.fromEntries(
866
+ (prompt.arguments ?? []).map((argument) => [argument.name, { type: "string" }])
867
+ ),
868
+ required: (prompt.arguments ?? []).filter((argument) => argument.required).map((argument) => argument.name),
869
+ additionalProperties: false
870
+ };
871
+ }
872
+ function diffPrompt(before, after, changes) {
873
+ const root = `prompts.${before.name}`;
874
+ for (const key of ["title", "description", "icons", "metadata"]) {
875
+ if (!equal(before[key], after[key])) {
876
+ push(changes, {
877
+ severity: "behavioral",
878
+ code: `prompt-${key}-changed`,
879
+ path: `${root}.${key}`,
880
+ message: `Prompt ${key} changed for ${before.name}`,
881
+ before: before[key],
882
+ after: after[key]
883
+ });
884
+ }
885
+ }
886
+ diffSchema(
887
+ promptArgumentSchema(before),
888
+ promptArgumentSchema(after),
889
+ `${root}.arguments`,
890
+ "input",
891
+ changes
892
+ );
893
+ if (!equal(before.arguments ?? [], after.arguments ?? [])) {
894
+ push(changes, {
895
+ severity: "behavioral",
896
+ code: "prompt-arguments-changed",
897
+ path: `${root}.argumentsMetadata`,
898
+ message: `Prompt argument metadata changed for ${before.name}`,
899
+ before: before.arguments,
900
+ after: after.arguments
901
+ });
902
+ }
903
+ }
904
+ function requirementValues(value) {
905
+ if (value === true) return /* @__PURE__ */ new Set(["true"]);
906
+ if (Array.isArray(value)) return new Set(value.map((entry) => canonicalJson(entry)));
907
+ return /* @__PURE__ */ new Set();
908
+ }
909
+ function extensionRequired(value) {
910
+ return Boolean(value && typeof value === "object" && !Array.isArray(value) && value.required === true);
911
+ }
912
+ function diffCollection(label, before, after, key, compare, changes) {
913
+ const beforeValues = new Map(before.map((value) => [key(value), value]));
914
+ const afterValues = new Map(after.map((value) => [key(value), value]));
915
+ for (const name of [...beforeValues.keys()].sort()) {
916
+ const next = afterValues.get(name);
917
+ if (!next) {
918
+ push(changes, {
919
+ severity: "breaking",
920
+ code: `${label}-removed`,
921
+ path: `${label}.${name}`,
922
+ message: `${label} ${name} was removed`,
923
+ before: beforeValues.get(name)
924
+ });
925
+ } else compare(beforeValues.get(name), next, changes);
926
+ }
927
+ for (const name of [...afterValues.keys()].sort()) {
928
+ if (!beforeValues.has(name)) {
929
+ push(changes, {
930
+ severity: "additive",
931
+ code: `${label}-added`,
932
+ path: `${label}.${name}`,
933
+ message: `${label} ${name} was added`,
934
+ after: afterValues.get(name)
935
+ });
936
+ }
937
+ }
938
+ }
939
+ function diffManifests(before, after) {
940
+ const changes = [];
941
+ if (before.server.name !== after.server.name) {
942
+ push(changes, {
943
+ severity: "breaking",
944
+ code: "server-name-changed",
945
+ path: "server.name",
946
+ message: `Server name changed from ${before.server.name} to ${after.server.name}`,
947
+ before: before.server.name,
948
+ after: after.server.name
949
+ });
950
+ }
951
+ if (before.server.instructions !== after.server.instructions) {
952
+ push(changes, {
953
+ severity: "behavioral",
954
+ code: "server-instructions-changed",
955
+ path: "server.instructions",
956
+ message: "Server instructions changed",
957
+ before: before.server.instructions,
958
+ after: after.server.instructions
959
+ });
960
+ }
961
+ const beforeTools = new Map(before.tools.map((tool) => [tool.name, tool]));
962
+ const afterTools = new Map(after.tools.map((tool) => [tool.name, tool]));
963
+ for (const name of [...beforeTools.keys()].sort()) {
964
+ const oldTool = beforeTools.get(name);
965
+ const newTool = afterTools.get(name);
966
+ if (!newTool) {
967
+ push(changes, {
968
+ severity: "breaking",
969
+ code: "tool-removed",
970
+ path: `tools.${name}`,
971
+ message: `Tool ${name} was removed`,
972
+ before: oldTool
973
+ });
974
+ } else {
975
+ diffTool(oldTool, newTool, changes);
976
+ }
977
+ }
978
+ for (const name of [...afterTools.keys()].sort()) {
979
+ if (!beforeTools.has(name)) {
980
+ push(changes, {
981
+ severity: "additive",
982
+ code: "tool-added",
983
+ path: `tools.${name}`,
984
+ message: `Tool ${name} was added`,
985
+ after: afterTools.get(name)
986
+ });
987
+ }
988
+ }
989
+ diffCollection(
990
+ "resources",
991
+ before.resources ?? [],
992
+ after.resources ?? [],
993
+ (resource) => resource.uri,
994
+ diffResource,
995
+ changes
996
+ );
997
+ diffCollection(
998
+ "resourceTemplates",
999
+ before.resourceTemplates ?? [],
1000
+ after.resourceTemplates ?? [],
1001
+ (resource) => resource.name,
1002
+ diffResourceTemplate,
1003
+ changes
1004
+ );
1005
+ diffCollection(
1006
+ "prompts",
1007
+ before.prompts ?? [],
1008
+ after.prompts ?? [],
1009
+ (prompt) => prompt.name,
1010
+ diffPrompt,
1011
+ changes
1012
+ );
1013
+ for (const key of ["capabilities", "clientRequirements", "extensions"]) {
1014
+ const oldRecord = before[key] ?? {};
1015
+ const newRecord = after[key] ?? {};
1016
+ for (const name of [.../* @__PURE__ */ new Set([...Object.keys(oldRecord), ...Object.keys(newRecord)])].sort()) {
1017
+ if (equal(oldRecord[name], newRecord[name])) continue;
1018
+ const removed = oldRecord[name] !== void 0 && newRecord[name] === void 0;
1019
+ const added = oldRecord[name] === void 0 && newRecord[name] !== void 0;
1020
+ const requirementChanged = key === "clientRequirements";
1021
+ const oldRequiredValues = requirementValues(oldRecord[name]);
1022
+ const newRequiredValues = requirementValues(newRecord[name]);
1023
+ const requirementAdded = [...newRequiredValues].some((value) => !oldRequiredValues.has(value));
1024
+ const requirementRemoved = [...oldRequiredValues].some((value) => !newRequiredValues.has(value));
1025
+ if (requirementChanged && !requirementAdded && !requirementRemoved) continue;
1026
+ const extensionWasRequired = key === "extensions" && extensionRequired(oldRecord[name]);
1027
+ const extensionIsRequired = key === "extensions" && extensionRequired(newRecord[name]);
1028
+ const capabilityChanges = key === "capabilities" && !removed && !added ? nestedCapabilityChanges(oldRecord[name], newRecord[name], `${key}.${name}`) : [];
1029
+ if (capabilityChanges.length) {
1030
+ for (const capabilityChange of capabilityChanges) {
1031
+ const action = capabilityChange.severity === "breaking" ? "removed" : capabilityChange.severity === "additive" ? "added" : "changed";
1032
+ push(changes, {
1033
+ severity: capabilityChange.severity,
1034
+ code: `capability-support-${action}`,
1035
+ path: capabilityChange.path,
1036
+ message: `Capability support was ${action} at ${capabilityChange.path}`,
1037
+ before: capabilityChange.before,
1038
+ after: capabilityChange.after
1039
+ });
1040
+ }
1041
+ continue;
1042
+ }
1043
+ push(changes, {
1044
+ severity: requirementChanged && requirementAdded ? "breaking" : requirementChanged && requirementRemoved ? "additive" : key === "extensions" && !extensionWasRequired && extensionIsRequired ? "breaking" : key === "extensions" && extensionWasRequired && !extensionIsRequired ? "additive" : removed ? "breaking" : added ? "additive" : "behavioral",
1045
+ code: `${key}-${removed ? "removed" : added ? "added" : "changed"}`,
1046
+ path: `${key}.${name}`,
1047
+ message: `${key} ${name} was ${removed ? "removed" : added ? "added" : "changed"}`,
1048
+ before: oldRecord[name],
1049
+ after: newRecord[name]
1050
+ });
1051
+ }
1052
+ }
1053
+ for (const key of ["protocolVersions", "transports"]) {
1054
+ const oldValues = new Set(before[key] ?? []);
1055
+ const newValues = new Set(after[key] ?? []);
1056
+ for (const value of [...oldValues].sort()) {
1057
+ if (!newValues.has(value)) {
1058
+ push(changes, {
1059
+ severity: "breaking",
1060
+ code: `${key}-support-removed`,
1061
+ path: key,
1062
+ message: `${key} support removed: ${value}`,
1063
+ before: value
1064
+ });
1065
+ }
1066
+ }
1067
+ for (const value of [...newValues].sort()) {
1068
+ if (!oldValues.has(value)) {
1069
+ push(changes, {
1070
+ severity: "additive",
1071
+ code: `${key}-support-added`,
1072
+ path: key,
1073
+ message: `${key} support added: ${value}`,
1074
+ after: value
1075
+ });
1076
+ }
1077
+ }
1078
+ }
1079
+ changes.sort(
1080
+ (left, right) => compareCodeUnits(left.path, right.path) || compareCodeUnits(left.code, right.code)
1081
+ );
1082
+ const summary = {
1083
+ breaking: changes.filter((change) => change.severity === "breaking").length,
1084
+ additive: changes.filter((change) => change.severity === "additive").length,
1085
+ behavioral: changes.filter((change) => change.severity === "behavioral").length
1086
+ };
1087
+ return { compatible: summary.breaking === 0, changes, summary };
1088
+ }
1089
+
1090
+ // src/manifest.ts
1091
+ import Ajv2 from "ajv";
1092
+ import addFormats2 from "ajv-formats";
1093
+ import { UriTemplate as UriTemplate2 } from "@modelcontextprotocol/sdk/shared/uriTemplate.js";
1094
+ import { ServerCapabilitiesSchema } from "@modelcontextprotocol/sdk/types.js";
1095
+
1096
+ // src/uri-template.ts
1097
+ function unsupportedUriTemplateOperator(uriTemplate) {
1098
+ for (const match of uriTemplate.matchAll(/\{([^{}]+)\}/g)) {
1099
+ if (match[1]?.startsWith(";")) return ";";
1100
+ }
1101
+ return void 0;
1102
+ }
1103
+ function uriTemplateMatchShape(uriTemplate) {
1104
+ return uriTemplate.replace(/\{([^{}]+)\}/g, (_match, expression) => {
1105
+ const operator = /^[+#./?&]/.exec(expression)?.[0] ?? "";
1106
+ if (operator === "?" || operator === "&") {
1107
+ const names = expression.slice(1).split(",").map((name) => name.replace(/\*/g, "").trim()).join(",");
1108
+ return `{query:${operator}:${names}}`;
1109
+ }
1110
+ const exploded = expression.includes("*");
1111
+ if (operator === "+" || operator === "#") return "{reserved}";
1112
+ if (operator === ".") return ".{simple}";
1113
+ if (operator === "/") return exploded ? "/{simple-exploded}" : "/{simple}";
1114
+ return exploded ? "{simple-exploded}" : "{simple}";
1115
+ });
1116
+ }
1117
+ function uriTemplateAutomaton(uriTemplate) {
1118
+ const states = [{ epsilon: [], transitions: [] }];
1119
+ let state = 0;
1120
+ const nextState = () => {
1121
+ states.push({ epsilon: [], transitions: [] });
1122
+ return states.length - 1;
1123
+ };
1124
+ const literal = (value) => {
1125
+ for (const character of value) {
1126
+ const next = nextState();
1127
+ states[state].transitions.push({
1128
+ predicate: { kind: "literal", value: character },
1129
+ to: next
1130
+ });
1131
+ state = next;
1132
+ }
1133
+ };
1134
+ const oneOrMore = (excluded) => {
1135
+ const loop = nextState();
1136
+ const next = nextState();
1137
+ const predicate = { kind: "except", value: excluded };
1138
+ states[state].transitions.push({ predicate, to: loop });
1139
+ states[loop].transitions.push({ predicate, to: loop });
1140
+ states[loop].epsilon.push(next);
1141
+ state = next;
1142
+ };
1143
+ const commaSeparated = () => {
1144
+ oneOrMore("/,");
1145
+ const boundary = state;
1146
+ const firstComponentCharacter = nextState();
1147
+ const component = nextState();
1148
+ states[boundary].transitions.push({
1149
+ predicate: { kind: "literal", value: "," },
1150
+ to: firstComponentCharacter
1151
+ });
1152
+ const predicate = { kind: "except", value: "/," };
1153
+ states[firstComponentCharacter].transitions.push({ predicate, to: component });
1154
+ states[component].transitions.push({ predicate, to: component });
1155
+ states[component].epsilon.push(boundary);
1156
+ };
1157
+ const expression = (value) => {
1158
+ const operator = /^[+#./?&]/.exec(value)?.[0] ?? "";
1159
+ const exploded = value.includes("*");
1160
+ const names = value.slice(operator.length).split(",").map((name) => name.replace(/\*/g, "").trim()).filter(Boolean);
1161
+ if (operator === "?" || operator === "&") {
1162
+ names.forEach((name, index) => {
1163
+ literal(index === 0 ? operator : "&");
1164
+ literal(`${name}=`);
1165
+ oneOrMore("&");
1166
+ });
1167
+ return;
1168
+ }
1169
+ if (operator === ".") literal(".");
1170
+ if (operator === "/") literal("/");
1171
+ if (operator === "+" || operator === "#") oneOrMore("");
1172
+ else if (exploded && (operator === "" || operator === "/")) commaSeparated();
1173
+ else oneOrMore("/,");
1174
+ };
1175
+ const matcher = /\{([^{}]+)\}/g;
1176
+ let cursor = 0;
1177
+ for (const match of uriTemplate.matchAll(matcher)) {
1178
+ literal(uriTemplate.slice(cursor, match.index));
1179
+ expression(match[1]);
1180
+ cursor = match.index + match[0].length;
1181
+ }
1182
+ literal(uriTemplate.slice(cursor));
1183
+ return { final: state, states };
1184
+ }
1185
+ function epsilonClosure(automaton, initial) {
1186
+ const closure = /* @__PURE__ */ new Set([initial]);
1187
+ const queue = [initial];
1188
+ while (queue.length) {
1189
+ const state = queue.shift();
1190
+ for (const next of automaton.states[state].epsilon) {
1191
+ if (closure.has(next)) continue;
1192
+ closure.add(next);
1193
+ queue.push(next);
1194
+ }
1195
+ }
1196
+ return closure;
1197
+ }
1198
+ function predicatesOverlap(left, right) {
1199
+ if (left.kind === "literal" && right.kind === "literal") return left.value === right.value;
1200
+ if (left.kind === "literal") return !right.value.includes(left.value);
1201
+ if (right.kind === "literal") return !left.value.includes(right.value);
1202
+ return true;
1203
+ }
1204
+ function uriTemplatesOverlap(left, right) {
1205
+ if (uriTemplateMatchShape(left) === uriTemplateMatchShape(right)) return true;
1206
+ const leftAutomaton = uriTemplateAutomaton(left);
1207
+ const rightAutomaton = uriTemplateAutomaton(right);
1208
+ const queue = [[0, 0]];
1209
+ const visited = /* @__PURE__ */ new Set();
1210
+ while (queue.length) {
1211
+ const [leftState, rightState] = queue.shift();
1212
+ const key = `${leftState}:${rightState}`;
1213
+ if (visited.has(key)) continue;
1214
+ visited.add(key);
1215
+ const leftClosure = epsilonClosure(leftAutomaton, leftState);
1216
+ const rightClosure = epsilonClosure(rightAutomaton, rightState);
1217
+ if (leftClosure.has(leftAutomaton.final) && rightClosure.has(rightAutomaton.final)) {
1218
+ return true;
1219
+ }
1220
+ for (const leftCurrent of leftClosure) {
1221
+ for (const rightCurrent of rightClosure) {
1222
+ for (const leftTransition of leftAutomaton.states[leftCurrent].transitions) {
1223
+ for (const rightTransition of rightAutomaton.states[rightCurrent].transitions) {
1224
+ if (predicatesOverlap(leftTransition.predicate, rightTransition.predicate)) {
1225
+ queue.push([leftTransition.to, rightTransition.to]);
1226
+ }
1227
+ }
1228
+ }
1229
+ }
1230
+ }
1231
+ }
1232
+ return false;
1233
+ }
1234
+
1235
+ // src/registry.ts
1236
+ import Ajv from "ajv";
1237
+ import addFormats from "ajv-formats";
1238
+ import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js";
1239
+ function formatErrors(errors) {
1240
+ return (errors ?? []).map((error) => ({
1241
+ path: error.instancePath || "/",
1242
+ message: error.message ?? "Schema validation failed",
1243
+ keyword: error.keyword
1244
+ }));
1245
+ }
1246
+ function assertName(kind, name) {
1247
+ if (!/^[A-Za-z0-9_.-]{1,128}$/.test(name)) {
1248
+ throw new McpFnValidationError(
1249
+ `Invalid MCP ${kind} name ${JSON.stringify(name)}`
1250
+ );
1251
+ }
1252
+ }
1253
+ function assertSubscriptionCallbacks(kind, name, subscribe, unsubscribe) {
1254
+ if (subscribe === void 0 !== (unsubscribe === void 0) || subscribe !== void 0 && typeof subscribe !== "function" || unsubscribe !== void 0 && typeof unsubscribe !== "function") {
1255
+ throw new McpFnValidationError(
1256
+ `${kind} ${name} must define subscribe and unsubscribe together as functions`
1257
+ );
1258
+ }
1259
+ }
1260
+ function assertUri(kind, uri) {
1261
+ try {
1262
+ new URL(uri);
1263
+ } catch {
1264
+ throw new McpFnValidationError(`Invalid MCP ${kind} URI ${JSON.stringify(uri)}`);
1265
+ }
1266
+ }
1267
+ function mergePromptSchemaInventory(target, source) {
1268
+ for (const [name, description] of source.descriptions) {
1269
+ if (!target.descriptions.has(name)) target.descriptions.set(name, description);
1270
+ }
1271
+ for (const [name, schemas] of source.propertySchemas) {
1272
+ target.propertySchemas.set(name, [...target.propertySchemas.get(name) ?? [], ...schemas]);
1273
+ }
1274
+ for (const name of source.required) target.required.add(name);
1275
+ }
1276
+ function resolveLocalSchemaReference(root, reference) {
1277
+ if (reference === "#") return root;
1278
+ if (!reference.startsWith("#/")) return void 0;
1279
+ return reference.slice(2).split("/").reduce((current, segment) => {
1280
+ if (!current || typeof current !== "object" || Array.isArray(current)) return void 0;
1281
+ const key = segment.replace(/~1/g, "/").replace(/~0/g, "~");
1282
+ return current[key];
1283
+ }, root);
1284
+ }
1285
+ function derivePromptSchemaInventory(schema, root, references = /* @__PURE__ */ new Set()) {
1286
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return void 0;
1287
+ const value = schema;
1288
+ const nonFlatKeywords = [
1289
+ "anyOf",
1290
+ "oneOf",
1291
+ "not",
1292
+ "if",
1293
+ "then",
1294
+ "else",
1295
+ "patternProperties",
1296
+ "dependentSchemas",
1297
+ "propertyNames"
1298
+ ];
1299
+ if (nonFlatKeywords.some((keyword) => Object.hasOwn(value, keyword))) return void 0;
1300
+ const inventory = {
1301
+ descriptions: /* @__PURE__ */ new Map(),
1302
+ propertySchemas: /* @__PURE__ */ new Map(),
1303
+ required: /* @__PURE__ */ new Set()
1304
+ };
1305
+ if (value.$ref !== void 0) {
1306
+ if (typeof value.$ref !== "string" || references.has(value.$ref)) return void 0;
1307
+ const referenced = resolveLocalSchemaReference(root, value.$ref);
1308
+ if (!referenced) return void 0;
1309
+ const nextReferences = new Set(references).add(value.$ref);
1310
+ const referencedInventory = derivePromptSchemaInventory(referenced, root, nextReferences);
1311
+ if (!referencedInventory) return void 0;
1312
+ mergePromptSchemaInventory(inventory, referencedInventory);
1313
+ }
1314
+ if (value.allOf !== void 0) {
1315
+ if (!Array.isArray(value.allOf)) return void 0;
1316
+ for (const member of value.allOf) {
1317
+ const memberInventory = derivePromptSchemaInventory(member, root, references);
1318
+ if (!memberInventory) return void 0;
1319
+ mergePromptSchemaInventory(inventory, memberInventory);
1320
+ }
1321
+ }
1322
+ const properties = value.properties;
1323
+ if (properties !== void 0 && (typeof properties !== "object" || properties === null || Array.isArray(properties))) return void 0;
1324
+ if (value.required !== void 0 && !Array.isArray(value.required)) return void 0;
1325
+ const required = Array.isArray(value.required) ? value.required.filter((entry) => typeof entry === "string") : [];
1326
+ for (const name of required) inventory.required.add(name);
1327
+ const propertySchemas = properties ?? {};
1328
+ for (const [name, propertySchema] of Object.entries(propertySchemas)) {
1329
+ inventory.propertySchemas.set(name, [
1330
+ ...inventory.propertySchemas.get(name) ?? [],
1331
+ propertySchema
1332
+ ]);
1333
+ if (propertySchema && typeof propertySchema === "object" && !Array.isArray(propertySchema) && typeof propertySchema.description === "string") {
1334
+ inventory.descriptions.set(
1335
+ name,
1336
+ propertySchema.description
1337
+ );
1338
+ }
1339
+ }
1340
+ return inventory;
1341
+ }
1342
+ function intersectStringCandidates(left, right) {
1343
+ if (!left) return right;
1344
+ if (!right) return left;
1345
+ return new Set([...left].filter((candidate) => right.has(candidate)));
1346
+ }
1347
+ function finiteStringCandidates(schema, root, references = /* @__PURE__ */ new Set()) {
1348
+ if (typeof schema === "boolean") return schema ? void 0 : /* @__PURE__ */ new Set();
1349
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return /* @__PURE__ */ new Set();
1350
+ const value = schema;
1351
+ let candidates;
1352
+ if (typeof value.type === "string" && value.type !== "string") return /* @__PURE__ */ new Set();
1353
+ if (Array.isArray(value.type) && !value.type.includes("string")) return /* @__PURE__ */ new Set();
1354
+ if (Object.hasOwn(value, "const")) {
1355
+ candidates = typeof value.const === "string" ? /* @__PURE__ */ new Set([value.const]) : /* @__PURE__ */ new Set();
1356
+ }
1357
+ if (Array.isArray(value.enum)) {
1358
+ candidates = intersectStringCandidates(
1359
+ candidates,
1360
+ new Set(value.enum.filter((entry) => typeof entry === "string"))
1361
+ );
1362
+ }
1363
+ if (value.$ref !== void 0) {
1364
+ if (typeof value.$ref !== "string" || references.has(value.$ref)) return /* @__PURE__ */ new Set();
1365
+ const referenced = resolveLocalSchemaReference(root, value.$ref);
1366
+ if (!referenced) return /* @__PURE__ */ new Set();
1367
+ candidates = intersectStringCandidates(
1368
+ candidates,
1369
+ finiteStringCandidates(referenced, root, new Set(references).add(value.$ref))
1370
+ );
1371
+ }
1372
+ if (Array.isArray(value.allOf)) {
1373
+ for (const member of value.allOf) {
1374
+ candidates = intersectStringCandidates(
1375
+ candidates,
1376
+ finiteStringCandidates(member, root, references)
1377
+ );
1378
+ }
1379
+ }
1380
+ for (const keyword of ["anyOf", "oneOf"]) {
1381
+ if (!Array.isArray(value[keyword])) continue;
1382
+ let union = /* @__PURE__ */ new Set();
1383
+ for (const member of value[keyword]) {
1384
+ const memberCandidates = finiteStringCandidates(member, root, references);
1385
+ if (!memberCandidates) {
1386
+ union = void 0;
1387
+ break;
1388
+ }
1389
+ for (const candidate of memberCandidates) union.add(candidate);
1390
+ }
1391
+ candidates = intersectStringCandidates(candidates, union);
1392
+ }
1393
+ return candidates;
1394
+ }
1395
+ function schemaMayAcceptString(schema, root, references = /* @__PURE__ */ new Set()) {
1396
+ if (typeof schema === "boolean") return schema;
1397
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return false;
1398
+ const value = schema;
1399
+ const finiteCandidates = finiteStringCandidates(schema, root, references);
1400
+ if (finiteCandidates?.size === 0) return false;
1401
+ if (value.$ref !== void 0) {
1402
+ if (typeof value.$ref !== "string" || references.has(value.$ref)) return false;
1403
+ const referenced = resolveLocalSchemaReference(root, value.$ref);
1404
+ if (!referenced) return false;
1405
+ const nextReferences = new Set(references).add(value.$ref);
1406
+ if (!schemaMayAcceptString(referenced, root, nextReferences)) return false;
1407
+ }
1408
+ if (typeof value.type === "string" && value.type !== "string") return false;
1409
+ if (Array.isArray(value.type) && !value.type.includes("string")) return false;
1410
+ if (Object.hasOwn(value, "const") && typeof value.const !== "string") return false;
1411
+ if (Array.isArray(value.enum) && !value.enum.some((entry) => typeof entry === "string")) {
1412
+ return false;
1413
+ }
1414
+ if (Array.isArray(value.allOf) && !value.allOf.every((member) => schemaMayAcceptString(member, root, references))) return false;
1415
+ if (Array.isArray(value.anyOf) && !value.anyOf.some((member) => schemaMayAcceptString(member, root, references))) return false;
1416
+ if (Array.isArray(value.oneOf) && !value.oneOf.some((member) => schemaMayAcceptString(member, root, references))) return false;
1417
+ return true;
1418
+ }
1419
+ function assertPromptSchemaSupportsStringValues(schema, label) {
1420
+ const inventory = derivePromptSchemaInventory(schema, schema);
1421
+ if (!inventory) {
1422
+ throw new McpFnValidationError(
1423
+ `${label} must use derivable properties, allOf, or local $ref declarations`
1424
+ );
1425
+ }
1426
+ for (const [name, schemas] of inventory.propertySchemas) {
1427
+ const finiteCandidates = finiteStringCandidates({ allOf: schemas }, schema);
1428
+ let hasStringWitness = schemas.every(
1429
+ (propertySchema) => schemaMayAcceptString(propertySchema, schema)
1430
+ );
1431
+ if (hasStringWitness && finiteCandidates) {
1432
+ const candidateSchema = {
1433
+ ...schema.$defs && typeof schema.$defs === "object" ? { $defs: schema.$defs } : {},
1434
+ ...schema.definitions && typeof schema.definitions === "object" ? { definitions: schema.definitions } : {},
1435
+ allOf: schemas
1436
+ };
1437
+ let validate;
1438
+ try {
1439
+ validate = new Ajv({ strict: false, allowUnionTypes: true }).compile(candidateSchema);
1440
+ } catch {
1441
+ hasStringWitness = false;
1442
+ }
1443
+ if (validate) {
1444
+ hasStringWitness = [...finiteCandidates].some((candidate) => validate(candidate));
1445
+ }
1446
+ }
1447
+ if (!hasStringWitness) {
1448
+ throw new McpFnValidationError(
1449
+ `${label} argument ${name} must accept string values`
1450
+ );
1451
+ }
1452
+ }
1453
+ }
1454
+ function schemaPromptArguments(definition) {
1455
+ const schema = definition.argumentsSchema;
1456
+ if (!schema) return void 0;
1457
+ const inventory = derivePromptSchemaInventory(schema, schema);
1458
+ if (!inventory) return void 0;
1459
+ const names = [.../* @__PURE__ */ new Set([
1460
+ ...inventory.propertySchemas.keys(),
1461
+ ...inventory.required
1462
+ ])].sort(compareCodeUnits);
1463
+ return names.map((name) => {
1464
+ return {
1465
+ name,
1466
+ ...inventory.descriptions.has(name) ? { description: inventory.descriptions.get(name) } : {},
1467
+ ...inventory.required.has(name) ? { required: true } : {}
1468
+ };
1469
+ });
1470
+ }
1471
+ function promptSchema(definition) {
1472
+ if (definition.argumentsSchema) return definition.argumentsSchema;
1473
+ const properties = Object.fromEntries(
1474
+ (definition.arguments ?? []).map((argument) => [
1475
+ argument.name,
1476
+ { type: "string", ...argument.description ? { description: argument.description } : {} }
1477
+ ])
1478
+ );
1479
+ return {
1480
+ type: "object",
1481
+ properties,
1482
+ required: (definition.arguments ?? []).filter((argument) => argument.required).map((argument) => argument.name),
1483
+ additionalProperties: false
1484
+ };
1485
+ }
1486
+ function promptArguments(definition) {
1487
+ return Array.isArray(definition.arguments) ? definition.arguments : schemaPromptArguments(definition);
1488
+ }
1489
+ var McpFnRegistry = class {
1490
+ ajv;
1491
+ tools = /* @__PURE__ */ new Map();
1492
+ resources = /* @__PURE__ */ new Map();
1493
+ resourceTemplates = /* @__PURE__ */ new Map();
1494
+ prompts = /* @__PURE__ */ new Map();
1495
+ constructor() {
1496
+ this.ajv = new Ajv({ allErrors: true, strict: false, allowUnionTypes: true });
1497
+ addFormats(this.ajv);
1498
+ }
1499
+ register(definition) {
1500
+ assertName("tool", definition.name);
1501
+ if (this.tools.has(definition.name)) {
1502
+ throw new McpFnValidationError(`Duplicate MCP tool: ${definition.name}`);
1503
+ }
1504
+ if (!definition.description.trim()) {
1505
+ throw new McpFnValidationError(
1506
+ `Tool ${definition.name} requires a non-empty description`
1507
+ );
1508
+ }
1509
+ if (typeof definition.handler !== "function") {
1510
+ throw new McpFnValidationError(
1511
+ `Tool ${definition.name} requires a handler function`
1512
+ );
1513
+ }
1514
+ if (definition.inputSchema.type !== "object") {
1515
+ throw new McpFnValidationError(
1516
+ `Tool ${definition.name} inputSchema must be an object schema`
1517
+ );
1518
+ }
1519
+ if (definition.outputSchema !== void 0 && (definition.outputSchema === null || typeof definition.outputSchema !== "object" || Array.isArray(definition.outputSchema) || definition.outputSchema.type !== "object")) {
1520
+ throw new McpFnValidationError(
1521
+ `Tool ${definition.name} outputSchema must be an object schema`
1522
+ );
1523
+ }
1524
+ const taskSupport = definition.execution?.taskSupport ?? "forbidden";
1525
+ if (!["forbidden", "optional", "required"].includes(taskSupport)) {
1526
+ throw new McpFnValidationError(
1527
+ `Tool ${definition.name} has invalid taskSupport=${String(taskSupport)}`
1528
+ );
1529
+ }
1530
+ if ((taskSupport === "required" || taskSupport === "optional") && !definition.taskHandler) {
1531
+ throw new McpFnValidationError(
1532
+ `Tool ${definition.name} declares taskSupport=${taskSupport} but has no taskHandler`
1533
+ );
1534
+ }
1535
+ if (taskSupport === "forbidden" && definition.taskHandler) {
1536
+ throw new McpFnValidationError(
1537
+ `Tool ${definition.name} has a taskHandler but forbids task execution`
1538
+ );
1539
+ }
1540
+ let validateInput;
1541
+ let validateOutput;
1542
+ try {
1543
+ validateInput = this.ajv.compile(definition.inputSchema);
1544
+ validateOutput = definition.outputSchema !== void 0 ? this.ajv.compile(definition.outputSchema) : void 0;
1545
+ } catch (error) {
1546
+ throw new McpFnValidationError(
1547
+ `Tool ${definition.name} contains an invalid JSON Schema`,
1548
+ { cause: error instanceof Error ? error.message : String(error) }
1549
+ );
1550
+ }
1551
+ this.tools.set(definition.name, {
1552
+ definition,
1553
+ validateInput,
1554
+ validateOutput
1555
+ });
1556
+ return this;
1557
+ }
1558
+ registerAll(definitions) {
1559
+ for (const definition of definitions) this.register(definition);
1560
+ return this;
1561
+ }
1562
+ registerResource(definition) {
1563
+ assertUri("resource", definition.uri);
1564
+ assertName("resource", definition.name);
1565
+ if (typeof definition.read !== "function") {
1566
+ throw new McpFnValidationError(
1567
+ `Resource ${definition.name} requires a read handler function`
1568
+ );
1569
+ }
1570
+ if (this.resources.has(definition.uri)) {
1571
+ throw new McpFnValidationError(`Duplicate MCP resource: ${definition.uri}`);
1572
+ }
1573
+ assertSubscriptionCallbacks(
1574
+ "Resource",
1575
+ definition.name,
1576
+ definition.subscribe,
1577
+ definition.unsubscribe
1578
+ );
1579
+ this.resources.set(definition.uri, definition);
1580
+ return this;
1581
+ }
1582
+ registerResourceTemplate(definition) {
1583
+ assertName("resource template", definition.name);
1584
+ if (typeof definition.read !== "function") {
1585
+ throw new McpFnValidationError(
1586
+ `Resource template ${definition.name} requires a read handler function`
1587
+ );
1588
+ }
1589
+ if (this.resourceTemplates.has(definition.name)) {
1590
+ throw new McpFnValidationError(
1591
+ `Duplicate MCP resource template: ${definition.name}`
1592
+ );
1593
+ }
1594
+ if (typeof definition.uriTemplate !== "string") {
1595
+ throw new McpFnValidationError(
1596
+ `Invalid resource URI template ${JSON.stringify(definition.uriTemplate)}`
1597
+ );
1598
+ }
1599
+ const unsupportedOperator = unsupportedUriTemplateOperator(definition.uriTemplate);
1600
+ if (unsupportedOperator) {
1601
+ throw new McpFnValidationError(
1602
+ `Resource template ${definition.name} uses unsupported URI template operator ${unsupportedOperator}`
1603
+ );
1604
+ }
1605
+ let template;
1606
+ try {
1607
+ template = new UriTemplate(definition.uriTemplate);
1608
+ } catch (error) {
1609
+ throw new McpFnValidationError(
1610
+ `Invalid resource URI template ${JSON.stringify(definition.uriTemplate)}`,
1611
+ { cause: error instanceof Error ? error.message : String(error) }
1612
+ );
1613
+ }
1614
+ if (!template.variableNames.length) {
1615
+ throw new McpFnValidationError(
1616
+ `Resource template ${definition.name} must contain at least one variable`
1617
+ );
1618
+ }
1619
+ assertSubscriptionCallbacks(
1620
+ "Resource template",
1621
+ definition.name,
1622
+ definition.subscribe,
1623
+ definition.unsubscribe
1624
+ );
1625
+ if ([...this.resourceTemplates.values()].some(
1626
+ ({ definition: registered }) => uriTemplatesOverlap(registered.uriTemplate, definition.uriTemplate)
1627
+ )) {
1628
+ throw new McpFnValidationError(
1629
+ `Ambiguous MCP resource URI template: ${definition.uriTemplate}`
1630
+ );
1631
+ }
1632
+ for (const name of Object.keys(definition.complete ?? {})) {
1633
+ if (!template.variableNames.includes(name)) {
1634
+ throw new McpFnValidationError(
1635
+ `Resource template ${definition.name} has a completer for unknown variable ${name}`
1636
+ );
1637
+ }
1638
+ }
1639
+ this.resourceTemplates.set(definition.name, { definition, template });
1640
+ return this;
1641
+ }
1642
+ registerPrompt(definition) {
1643
+ assertName("prompt", definition.name);
1644
+ if (this.prompts.has(definition.name)) {
1645
+ throw new McpFnValidationError(`Duplicate MCP prompt: ${definition.name}`);
1646
+ }
1647
+ if (typeof definition.get !== "function") {
1648
+ throw new McpFnValidationError(
1649
+ `Prompt ${definition.name} requires a get handler function`
1650
+ );
1651
+ }
1652
+ if (definition.arguments !== void 0 && (!Array.isArray(definition.arguments) || definition.arguments.some(
1653
+ (argument) => !argument || typeof argument !== "object" || Array.isArray(argument) || typeof argument.name !== "string"
1654
+ ))) {
1655
+ throw new McpFnValidationError(`Prompt ${definition.name} arguments must be an array`);
1656
+ }
1657
+ for (const argument of definition.arguments ?? []) {
1658
+ assertName("prompt argument", argument.name);
1659
+ if (argument.description !== void 0 && typeof argument.description !== "string") {
1660
+ throw new McpFnValidationError(
1661
+ `Prompt ${definition.name} argument ${argument.name} description must be a string`
1662
+ );
1663
+ }
1664
+ if (argument.required !== void 0 && typeof argument.required !== "boolean") {
1665
+ throw new McpFnValidationError(
1666
+ `Prompt ${definition.name} argument ${argument.name} required must be a boolean`
1667
+ );
1668
+ }
1669
+ }
1670
+ if (definition.argumentsSchema !== void 0 && (!definition.argumentsSchema || typeof definition.argumentsSchema !== "object" || Array.isArray(definition.argumentsSchema) || definition.argumentsSchema.type !== "object")) {
1671
+ throw new McpFnValidationError(
1672
+ `Prompt ${definition.name} argumentsSchema must be an object schema`
1673
+ );
1674
+ }
1675
+ let validateArguments;
1676
+ try {
1677
+ validateArguments = this.ajv.compile(promptSchema(definition));
1678
+ } catch (error) {
1679
+ throw new McpFnValidationError(
1680
+ `Prompt ${definition.name} contains an invalid arguments JSON Schema`,
1681
+ { cause: error instanceof Error ? error.message : String(error) }
1682
+ );
1683
+ }
1684
+ if (definition.argumentsSchema) {
1685
+ assertPromptSchemaSupportsStringValues(
1686
+ definition.argumentsSchema,
1687
+ `Prompt ${definition.name} argumentsSchema`
1688
+ );
1689
+ }
1690
+ const argumentNames = (promptArguments(definition) ?? []).map(({ name }) => name);
1691
+ if (new Set(argumentNames).size !== argumentNames.length) {
1692
+ throw new McpFnValidationError(`Prompt ${definition.name} has duplicate arguments`);
1693
+ }
1694
+ if (definition.arguments && definition.argumentsSchema) {
1695
+ const declared = definition.arguments.map(({ name, required }) => ({ name, required: required === true })).sort((left, right) => compareCodeUnits(left.name, right.name));
1696
+ const schemaDeclared = schemaPromptArguments(definition).map(
1697
+ ({ name, required }) => ({ name, required: required === true })
1698
+ );
1699
+ if (JSON.stringify(declared) !== JSON.stringify(schemaDeclared)) {
1700
+ throw new McpFnValidationError(
1701
+ `Prompt ${definition.name} arguments and argumentsSchema disagree`
1702
+ );
1703
+ }
1704
+ }
1705
+ for (const name of Object.keys(definition.complete ?? {})) {
1706
+ if (!argumentNames.includes(name)) {
1707
+ throw new McpFnValidationError(
1708
+ `Prompt ${definition.name} has a completer for unknown argument ${name}`
1709
+ );
1710
+ }
1711
+ }
1712
+ this.prompts.set(definition.name, { definition, validateArguments });
1713
+ return this;
1714
+ }
1715
+ has(name) {
1716
+ return this.tools.has(name);
1717
+ }
1718
+ hasOutputSchema(name) {
1719
+ return Boolean(this.tools.get(name)?.validateOutput);
1720
+ }
1721
+ definitions() {
1722
+ return [...this.tools.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
1723
+ }
1724
+ resourceDefinitions() {
1725
+ return [...this.resources.values()].sort((left, right) => compareCodeUnits(left.uri, right.uri));
1726
+ }
1727
+ resourceTemplateDefinitions() {
1728
+ return [...this.resourceTemplates.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
1729
+ }
1730
+ promptDefinitions() {
1731
+ return [...this.prompts.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
1732
+ }
1733
+ capabilities(options = {}) {
1734
+ const capabilities = {};
1735
+ if (this.tools.size) capabilities.tools = { listChanged: options.listChanged ?? true };
1736
+ if (this.resources.size || this.resourceTemplates.size) {
1737
+ capabilities.resources = {
1738
+ listChanged: options.listChanged ?? true,
1739
+ subscribe: [...this.resources.values()].some((value) => value.subscribe) || [...this.resourceTemplates.values()].some(({ definition }) => definition.subscribe)
1740
+ };
1741
+ }
1742
+ if (this.prompts.size) capabilities.prompts = { listChanged: options.listChanged ?? true };
1743
+ if ([...this.resourceTemplates.values()].some(({ definition }) => definition.complete) || [...this.prompts.values()].some(({ definition }) => definition.complete)) capabilities.completions = {};
1744
+ if (this.definitions().some((definition) => {
1745
+ const support = definition.execution?.taskSupport;
1746
+ return support === "optional" || support === "required";
1747
+ })) capabilities.tasks = { requests: { tools: { call: {} } } };
1748
+ return capabilities;
1749
+ }
1750
+ listTools() {
1751
+ return this.definitions().map((definition) => ({
1752
+ name: definition.name,
1753
+ ...definition.title ? { title: definition.title } : {},
1754
+ description: definition.description,
1755
+ inputSchema: definition.inputSchema,
1756
+ ...definition.outputSchema ? { outputSchema: definition.outputSchema } : {},
1757
+ ...definition.annotations ? { annotations: definition.annotations } : {},
1758
+ ...definition.execution ? { execution: definition.execution } : {},
1759
+ ...definition.icons ? { icons: definition.icons } : {},
1760
+ ...definition.metadata ? { _meta: definition.metadata } : {}
1761
+ }));
1762
+ }
1763
+ async listResources(context, extra) {
1764
+ const resources = this.resourceDefinitions().map((definition) => ({
1765
+ uri: definition.uri,
1766
+ name: definition.name,
1767
+ ...definition.title ? { title: definition.title } : {},
1768
+ ...definition.description ? { description: definition.description } : {},
1769
+ ...definition.mimeType ? { mimeType: definition.mimeType } : {},
1770
+ ...definition.annotations ? { annotations: definition.annotations } : {},
1771
+ ...definition.icons ? { icons: definition.icons } : {},
1772
+ ...definition.metadata ? { _meta: definition.metadata } : {}
1773
+ }));
1774
+ for (const { definition } of this.resourceTemplates.values()) {
1775
+ if (definition.list) resources.push(...(await definition.list(context, extra)).resources);
1776
+ }
1777
+ return resources.sort((left, right) => compareCodeUnits(left.uri, right.uri));
1778
+ }
1779
+ listResourceTemplates() {
1780
+ return this.resourceTemplateDefinitions().map((definition) => ({
1781
+ uriTemplate: definition.uriTemplate,
1782
+ name: definition.name,
1783
+ ...definition.title ? { title: definition.title } : {},
1784
+ ...definition.description ? { description: definition.description } : {},
1785
+ ...definition.mimeType ? { mimeType: definition.mimeType } : {},
1786
+ ...definition.annotations ? { annotations: definition.annotations } : {},
1787
+ ...definition.icons ? { icons: definition.icons } : {},
1788
+ ...definition.metadata ? { _meta: definition.metadata } : {}
1789
+ }));
1790
+ }
1791
+ listPrompts() {
1792
+ return this.promptDefinitions().map((definition) => ({
1793
+ name: definition.name,
1794
+ ...definition.title ? { title: definition.title } : {},
1795
+ ...definition.description ? { description: definition.description } : {},
1796
+ ...promptArguments(definition) ? { arguments: promptArguments(definition) } : {},
1797
+ ...definition.icons ? { icons: definition.icons } : {},
1798
+ ...definition.metadata ? { _meta: definition.metadata } : {}
1799
+ }));
1800
+ }
1801
+ normalizeAndValidateArgs(registered, args) {
1802
+ const normalizedArgs = args ?? {};
1803
+ if (!registered.validateInput(normalizedArgs)) {
1804
+ return {
1805
+ args: normalizedArgs && typeof normalizedArgs === "object" && !Array.isArray(normalizedArgs) ? normalizedArgs : {},
1806
+ issues: formatErrors(registered.validateInput.errors)
1807
+ };
1808
+ }
1809
+ return { args: normalizedArgs };
1810
+ }
1811
+ async callTool(name, args, context, extra) {
1812
+ const registered = this.tools.get(name);
1813
+ if (!registered) throw new McpFnValidationError(`Unknown MCP tool: ${name}`, { name });
1814
+ const normalized = this.normalizeAndValidateArgs(registered, args);
1815
+ if (normalized.issues) {
1816
+ if (registered.definition.handleInvalidArguments) {
1817
+ return this.finalizeResult(
1818
+ registered,
1819
+ await registered.definition.handleInvalidArguments(
1820
+ normalized.args,
1821
+ normalized.issues,
1822
+ context,
1823
+ extra
1824
+ )
1825
+ );
1826
+ }
1827
+ throw new McpFnValidationError(`Invalid arguments for ${name}`, { issues: normalized.issues });
1828
+ }
1829
+ return this.finalizeResult(
1830
+ registered,
1831
+ await registered.definition.handler(normalized.args, context, extra)
1832
+ );
1833
+ }
1834
+ taskSupport(name) {
1835
+ return this.tools.get(name)?.definition.execution?.taskSupport ?? "forbidden";
1836
+ }
1837
+ async createToolTask(name, args, context, extra) {
1838
+ const registered = this.tools.get(name);
1839
+ if (!registered) throw new McpFnValidationError(`Unknown MCP tool: ${name}`, { name });
1840
+ const normalized = this.normalizeAndValidateArgs(registered, args);
1841
+ if (normalized.issues) {
1842
+ throw new McpFnValidationError(`Invalid arguments for ${name}`, { issues: normalized.issues });
1843
+ }
1844
+ if (!registered.definition.taskHandler) {
1845
+ throw new McpFnValidationError(`Tool ${name} does not support task execution`);
1846
+ }
1847
+ const taskStore = new Proxy(extra.taskStore, {
1848
+ get: (target, property, receiver) => {
1849
+ if (property === "storeTaskResult") {
1850
+ return async (taskId, status, result) => target.storeTaskResult(
1851
+ taskId,
1852
+ status,
1853
+ this.finalizeResult(registered, result)
1854
+ );
1855
+ }
1856
+ const value = Reflect.get(target, property, receiver);
1857
+ return typeof value === "function" ? value.bind(target) : value;
1858
+ }
1859
+ });
1860
+ return registered.definition.taskHandler.createTask(
1861
+ normalized.args,
1862
+ context,
1863
+ { ...extra, taskStore }
1864
+ );
1865
+ }
1866
+ matchResource(uri) {
1867
+ const exact = this.resources.get(uri);
1868
+ if (exact) return { kind: "resource", definition: exact };
1869
+ for (const { definition, template } of this.resourceTemplates.values()) {
1870
+ const variables = template.match(uri);
1871
+ if (variables) return { kind: "template", definition, variables };
1872
+ }
1873
+ return void 0;
1874
+ }
1875
+ async readResource(uri, context, extra) {
1876
+ const match = this.matchResource(uri);
1877
+ if (!match) throw new McpFnValidationError(`Unknown MCP resource: ${uri}`);
1878
+ const url = new URL(uri);
1879
+ return match.kind === "resource" ? match.definition.read(url, context, extra) : match.definition.read(url, match.variables, context, extra);
1880
+ }
1881
+ async changeSubscription(uri, subscribed, context, extra) {
1882
+ const match = this.matchResource(uri);
1883
+ if (!match) throw new McpFnValidationError(`Unknown MCP resource: ${uri}`);
1884
+ const url = new URL(uri);
1885
+ if (match.kind === "resource") {
1886
+ const callback2 = subscribed ? match.definition.subscribe : match.definition.unsubscribe;
1887
+ if (!callback2) {
1888
+ throw new McpFnValidationError(
1889
+ `Resource ${uri} does not support ${subscribed ? "subscriptions" : "unsubscription"}`
1890
+ );
1891
+ }
1892
+ await callback2(url, context, extra);
1893
+ return;
1894
+ }
1895
+ const callback = subscribed ? match.definition.subscribe : match.definition.unsubscribe;
1896
+ if (!callback) {
1897
+ throw new McpFnValidationError(
1898
+ `Resource ${uri} does not support ${subscribed ? "subscriptions" : "unsubscription"}`
1899
+ );
1900
+ }
1901
+ await callback(url, match.variables, context, extra);
1902
+ }
1903
+ async getPrompt(name, args, context, extra) {
1904
+ const registered = this.prompts.get(name);
1905
+ if (!registered) throw new McpFnValidationError(`Unknown MCP prompt: ${name}`);
1906
+ const normalized = args ?? {};
1907
+ if (!registered.validateArguments(normalized)) {
1908
+ throw new McpFnValidationError(`Invalid arguments for prompt ${name}`, {
1909
+ issues: formatErrors(registered.validateArguments.errors)
1910
+ });
1911
+ }
1912
+ return registered.definition.get(normalized, context, extra);
1913
+ }
1914
+ async complete(ref, argument, completionContext, context, extra) {
1915
+ const empty = { completion: { values: [], total: 0, hasMore: false } };
1916
+ if (ref.type === "ref/prompt") {
1917
+ const prompt = this.prompts.get(ref.name);
1918
+ if (!prompt) throw new McpFnValidationError(`Unknown MCP prompt: ${ref.name}`);
1919
+ return prompt.definition.complete?.[argument.name]?.(
1920
+ argument.value,
1921
+ completionContext,
1922
+ context,
1923
+ extra
1924
+ ) ?? empty;
1925
+ }
1926
+ const template = [...this.resourceTemplates.values()].find(({ definition }) => definition.uriTemplate === ref.uri);
1927
+ if (!template) {
1928
+ if (this.resources.has(ref.uri)) return empty;
1929
+ throw new McpFnValidationError(`Unknown MCP resource template: ${ref.uri}`);
1930
+ }
1931
+ return template.definition.complete?.[argument.name]?.(
1932
+ argument.value,
1933
+ completionContext,
1934
+ context,
1935
+ extra
1936
+ ) ?? empty;
1937
+ }
1938
+ finalizeResult(registered, result) {
1939
+ if (registered.validateOutput && result.isError) {
1940
+ const { structuredContent: _omitted, ...errorWithoutStructuredContent } = result;
1941
+ return errorWithoutStructuredContent;
1942
+ }
1943
+ if (registered.validateOutput) {
1944
+ if (!result.structuredContent) {
1945
+ throw new McpFnOutputValidationError(
1946
+ `Tool ${registered.definition.name} declares outputSchema but returned no structuredContent`
1947
+ );
1948
+ }
1949
+ if (!registered.validateOutput(result.structuredContent)) {
1950
+ throw new McpFnOutputValidationError(
1951
+ `Invalid output from ${registered.definition.name}`,
1952
+ { issues: formatErrors(registered.validateOutput.errors) }
1953
+ );
1954
+ }
1955
+ }
1956
+ return result;
1957
+ }
1958
+ };
1959
+
1960
+ // src/manifest.ts
1961
+ function assertSortedUnique(label, values) {
1962
+ const canonical = [...new Set(values)].sort(compareCodeUnits);
1963
+ if (canonical.length !== values.length || canonical.some((value, index) => value !== values[index])) throw new McpFnValidationError(`${label} must be sorted and unique`);
1964
+ }
1965
+ function assertObject(label, value) {
1966
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1967
+ throw new McpFnValidationError(`${label} must be an object`);
1968
+ }
1969
+ }
1970
+ function assertName2(label, name) {
1971
+ if (typeof name !== "string" || !/^[A-Za-z0-9_.-]{1,128}$/.test(name)) {
1972
+ throw new McpFnValidationError(`${label} requires a name (letters, digits, dot, dash, or underscore)`);
1973
+ }
1974
+ }
1975
+ function assertMetadata(label, value) {
1976
+ if (value !== void 0) assertObject(label, value);
1977
+ }
1978
+ function assertSortedBy(label, values, select) {
1979
+ assertSortedUnique(label, values.map(select));
1980
+ }
1981
+ function createManifest(info, registry, options = {}) {
1982
+ assertMcpAppContracts(registry);
1983
+ const tools = registry.definitions().map((tool) => ({
1984
+ name: tool.name,
1985
+ ...tool.title ? { title: tool.title } : {},
1986
+ description: tool.description,
1987
+ inputSchema: tool.inputSchema,
1988
+ ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
1989
+ ...tool.annotations ? { annotations: tool.annotations } : {},
1990
+ ...tool.execution ? { execution: tool.execution } : {},
1991
+ ...tool.icons ? { icons: tool.icons } : {},
1992
+ ...tool.metadata ? { metadata: tool.metadata } : {}
1993
+ }));
1994
+ const resources = registry.resourceDefinitions().map((resource) => ({
1995
+ uri: resource.uri,
1996
+ name: resource.name,
1997
+ ...resource.title ? { title: resource.title } : {},
1998
+ ...resource.description ? { description: resource.description } : {},
1999
+ ...resource.mimeType ? { mimeType: resource.mimeType } : {},
2000
+ ...resource.annotations ? { annotations: resource.annotations } : {},
2001
+ ...resource.icons ? { icons: resource.icons } : {},
2002
+ ...resource.subscribe ? { subscribable: true } : {},
2003
+ ...resource.metadata ? { metadata: resource.metadata } : {}
2004
+ }));
2005
+ const resourceTemplates = registry.resourceTemplateDefinitions().map((resource) => ({
2006
+ uriTemplate: resource.uriTemplate,
2007
+ name: resource.name,
2008
+ ...resource.title ? { title: resource.title } : {},
2009
+ ...resource.description ? { description: resource.description } : {},
2010
+ ...resource.mimeType ? { mimeType: resource.mimeType } : {},
2011
+ ...resource.annotations ? { annotations: resource.annotations } : {},
2012
+ ...resource.icons ? { icons: resource.icons } : {},
2013
+ ...resource.subscribe ? { subscribable: true } : {},
2014
+ ...resource.metadata ? { metadata: resource.metadata } : {}
2015
+ }));
2016
+ const prompts = registry.promptDefinitions().map((prompt) => ({
2017
+ name: prompt.name,
2018
+ ...prompt.title ? { title: prompt.title } : {},
2019
+ ...prompt.description ? { description: prompt.description } : {},
2020
+ ...promptArguments(prompt) ? { arguments: promptArguments(prompt) } : {},
2021
+ ...prompt.argumentsSchema ? { argumentsSchema: prompt.argumentsSchema } : {},
2022
+ ...prompt.icons ? { icons: prompt.icons } : {},
2023
+ ...prompt.metadata ? { metadata: prompt.metadata } : {}
2024
+ }));
2025
+ const body = {
2026
+ formatVersion: 1,
2027
+ server: {
2028
+ name: info.name,
2029
+ version: info.version,
2030
+ ...info.instructions ? { instructions: info.instructions } : {}
2031
+ },
2032
+ ...options.protocolVersions ? { protocolVersions: [...new Set(options.protocolVersions)].sort() } : {},
2033
+ ...options.transports ? { transports: [...new Set(options.transports)].sort() } : {},
2034
+ capabilities: options.capabilities ?? registry.capabilities(),
2035
+ ...options.clientRequirements ? {
2036
+ clientRequirements: {
2037
+ ...options.clientRequirements,
2038
+ ...options.clientRequirements.elicitation ? { elicitation: [...new Set(options.clientRequirements.elicitation)].sort() } : {}
2039
+ }
2040
+ } : {},
2041
+ ...options.extensions ? { extensions: options.extensions } : {},
2042
+ tools,
2043
+ resources,
2044
+ resourceTemplates,
2045
+ prompts
2046
+ };
2047
+ return { ...body, hash: sha256(body) };
2048
+ }
2049
+ function validateManifest(value) {
2050
+ assertObject("McpFn manifest", value);
2051
+ const manifest = value;
2052
+ if (manifest.formatVersion !== 1) {
2053
+ throw new McpFnValidationError("Unsupported McpFn manifest formatVersion");
2054
+ }
2055
+ if (!manifest.server || typeof manifest.server.name !== "string" || !manifest.server.name.trim() || typeof manifest.server.version !== "string" || !manifest.server.version.trim()) throw new McpFnValidationError("Manifest server name and version are required");
2056
+ if (manifest.server.instructions !== void 0 && typeof manifest.server.instructions !== "string") throw new McpFnValidationError("Manifest server instructions must be a string");
2057
+ if (!Array.isArray(manifest.tools)) {
2058
+ throw new McpFnValidationError("Manifest tools must be an array");
2059
+ }
2060
+ for (const [label, entries] of [
2061
+ ["resources", manifest.resources],
2062
+ ["resourceTemplates", manifest.resourceTemplates],
2063
+ ["prompts", manifest.prompts]
2064
+ ]) {
2065
+ if (entries !== void 0 && !Array.isArray(entries)) {
2066
+ throw new McpFnValidationError(`Manifest ${label} must be an array`);
2067
+ }
2068
+ }
2069
+ if (manifest.protocolVersions !== void 0 && (!Array.isArray(manifest.protocolVersions) || manifest.protocolVersions.some((version) => typeof version !== "string" || !version))) throw new McpFnValidationError("Manifest protocolVersions must contain non-empty strings");
2070
+ if (manifest.protocolVersions) assertSortedUnique("Manifest protocolVersions", manifest.protocolVersions);
2071
+ if (manifest.transports !== void 0 && (!Array.isArray(manifest.transports) || manifest.transports.some((transport) => transport !== "stdio" && transport !== "streamable-http"))) throw new McpFnValidationError("Manifest contains an unsupported transport");
2072
+ if (manifest.transports) assertSortedUnique("Manifest transports", manifest.transports);
2073
+ if (manifest.capabilities !== void 0) {
2074
+ const parsed = ServerCapabilitiesSchema.safeParse(manifest.capabilities);
2075
+ if (!parsed.success) throw new McpFnValidationError("Manifest capabilities are invalid");
2076
+ }
2077
+ if (manifest.clientRequirements !== void 0) {
2078
+ assertObject("Manifest clientRequirements", manifest.clientRequirements);
2079
+ if (manifest.clientRequirements.sampling !== void 0 && typeof manifest.clientRequirements.sampling !== "boolean") throw new McpFnValidationError("Manifest sampling requirement must be a boolean");
2080
+ if (manifest.clientRequirements.roots !== void 0 && typeof manifest.clientRequirements.roots !== "boolean") throw new McpFnValidationError("Manifest roots requirement must be a boolean");
2081
+ if (manifest.clientRequirements.elicitation !== void 0 && (!Array.isArray(manifest.clientRequirements.elicitation) || manifest.clientRequirements.elicitation.some((mode) => mode !== "form" && mode !== "url"))) throw new McpFnValidationError("Manifest elicitation requirements are invalid");
2082
+ if (manifest.clientRequirements.elicitation) {
2083
+ assertSortedUnique(
2084
+ "Manifest elicitation requirements",
2085
+ manifest.clientRequirements.elicitation
2086
+ );
2087
+ }
2088
+ }
2089
+ assertMetadata("Manifest extensions", manifest.extensions);
2090
+ const ajv = new Ajv2({ allErrors: true, strict: false, allowUnionTypes: true });
2091
+ addFormats2(ajv);
2092
+ for (const tool of manifest.tools) {
2093
+ assertObject("Every manifest tool", tool);
2094
+ assertName2("Every manifest tool", tool.name);
2095
+ if (typeof tool.description !== "string" || !tool.description.trim()) {
2096
+ throw new McpFnValidationError(`Manifest tool ${tool.name} requires a description`);
2097
+ }
2098
+ if (!tool.inputSchema || tool.inputSchema.type !== "object") {
2099
+ throw new McpFnValidationError(`Manifest tool ${tool.name} requires an object inputSchema`);
2100
+ }
2101
+ if (tool.outputSchema !== void 0) {
2102
+ assertObject(`Manifest tool ${tool.name} outputSchema`, tool.outputSchema);
2103
+ if (tool.outputSchema.type !== "object") {
2104
+ throw new McpFnValidationError(`Manifest tool ${tool.name} requires an object outputSchema`);
2105
+ }
2106
+ }
2107
+ try {
2108
+ ajv.compile(tool.inputSchema);
2109
+ if (tool.outputSchema !== void 0) ajv.compile(tool.outputSchema);
2110
+ } catch (error) {
2111
+ throw new McpFnValidationError(
2112
+ `Manifest tool ${tool.name} contains an invalid JSON Schema`,
2113
+ { cause: error instanceof Error ? error.message : String(error) }
2114
+ );
2115
+ }
2116
+ for (const [label, metadata] of [
2117
+ ["annotations", tool.annotations],
2118
+ ["execution", tool.execution],
2119
+ ["metadata", tool.metadata]
2120
+ ]) assertMetadata(`Manifest tool ${tool.name} ${label}`, metadata);
2121
+ const taskSupport = tool.execution?.taskSupport;
2122
+ if (taskSupport !== void 0 && taskSupport !== "forbidden" && taskSupport !== "optional" && taskSupport !== "required") {
2123
+ throw new McpFnValidationError(
2124
+ `Manifest tool ${tool.name} has invalid taskSupport=${String(taskSupport)}`
2125
+ );
2126
+ }
2127
+ }
2128
+ assertSortedBy("Manifest tool names", manifest.tools, (tool) => tool.name);
2129
+ for (const resource of manifest.resources ?? []) {
2130
+ assertObject("Every manifest resource", resource);
2131
+ assertName2("Every manifest resource", resource.name);
2132
+ try {
2133
+ new URL(resource.uri);
2134
+ } catch {
2135
+ throw new McpFnValidationError(`Manifest resource ${resource.name} has an invalid URI`);
2136
+ }
2137
+ if (resource.subscribable !== void 0 && typeof resource.subscribable !== "boolean") {
2138
+ throw new McpFnValidationError(
2139
+ `Manifest resource ${resource.name} subscribable must be a boolean`
2140
+ );
2141
+ }
2142
+ assertMetadata(`Manifest resource ${resource.name} metadata`, resource.metadata);
2143
+ }
2144
+ assertSortedBy("Manifest resource URIs", manifest.resources ?? [], (resource) => resource.uri);
2145
+ const resourceTemplateUris = [];
2146
+ for (const resource of manifest.resourceTemplates ?? []) {
2147
+ assertObject("Every manifest resource template", resource);
2148
+ assertName2("Every manifest resource template", resource.name);
2149
+ if (typeof resource.uriTemplate !== "string") {
2150
+ throw new McpFnValidationError(
2151
+ `Manifest resource template ${resource.name} has an invalid URI template`
2152
+ );
2153
+ }
2154
+ const unsupportedOperator = unsupportedUriTemplateOperator(resource.uriTemplate);
2155
+ if (unsupportedOperator) {
2156
+ throw new McpFnValidationError(
2157
+ `Manifest resource template ${resource.name} uses unsupported URI template operator ${unsupportedOperator}`
2158
+ );
2159
+ }
2160
+ let template;
2161
+ try {
2162
+ template = new UriTemplate2(resource.uriTemplate);
2163
+ } catch {
2164
+ throw new McpFnValidationError(
2165
+ `Manifest resource template ${resource.name} has an invalid URI template`
2166
+ );
2167
+ }
2168
+ if (!template.variableNames.length) {
2169
+ throw new McpFnValidationError(
2170
+ `Manifest resource template ${resource.name} must contain at least one variable`
2171
+ );
2172
+ }
2173
+ if (resourceTemplateUris.some(
2174
+ (uriTemplate) => uriTemplatesOverlap(uriTemplate, resource.uriTemplate)
2175
+ )) {
2176
+ throw new McpFnValidationError(
2177
+ `Manifest contains an ambiguous resource URI template: ${resource.uriTemplate}`
2178
+ );
2179
+ }
2180
+ resourceTemplateUris.push(resource.uriTemplate);
2181
+ if (resource.subscribable !== void 0 && typeof resource.subscribable !== "boolean") {
2182
+ throw new McpFnValidationError(
2183
+ `Manifest resource template ${resource.name} subscribable must be a boolean`
2184
+ );
2185
+ }
2186
+ assertMetadata(`Manifest resource template ${resource.name} metadata`, resource.metadata);
2187
+ }
2188
+ assertSortedBy(
2189
+ "Manifest resource template names",
2190
+ manifest.resourceTemplates ?? [],
2191
+ (resource) => resource.name
2192
+ );
2193
+ for (const prompt of manifest.prompts ?? []) {
2194
+ assertObject("Every manifest prompt", prompt);
2195
+ assertName2("Every manifest prompt", prompt.name);
2196
+ assertMetadata(`Manifest prompt ${prompt.name} metadata`, prompt.metadata);
2197
+ if (prompt.arguments !== void 0 && !Array.isArray(prompt.arguments)) {
2198
+ throw new McpFnValidationError(`Manifest prompt ${prompt.name} arguments must be an array`);
2199
+ }
2200
+ const argumentNames = [];
2201
+ for (const argument of prompt.arguments ?? []) {
2202
+ assertObject(`Manifest prompt ${prompt.name} argument`, argument);
2203
+ assertName2(`Manifest prompt ${prompt.name} argument`, argument.name);
2204
+ if (argument.description !== void 0 && typeof argument.description !== "string") {
2205
+ throw new McpFnValidationError(
2206
+ `Manifest prompt ${prompt.name} argument ${argument.name} description must be a string`
2207
+ );
2208
+ }
2209
+ if (argument.required !== void 0 && typeof argument.required !== "boolean") {
2210
+ throw new McpFnValidationError(
2211
+ `Manifest prompt ${prompt.name} argument ${argument.name} required must be a boolean`
2212
+ );
2213
+ }
2214
+ argumentNames.push(argument.name);
2215
+ }
2216
+ if (new Set(argumentNames).size !== argumentNames.length) {
2217
+ throw new McpFnValidationError(`Manifest prompt ${prompt.name} has duplicate arguments`);
2218
+ }
2219
+ if (prompt.argumentsSchema !== void 0) {
2220
+ assertObject(`Manifest prompt ${prompt.name} argumentsSchema`, prompt.argumentsSchema);
2221
+ if (prompt.argumentsSchema.type !== "object") {
2222
+ throw new McpFnValidationError(
2223
+ `Manifest prompt ${prompt.name} argumentsSchema must be an object schema`
2224
+ );
2225
+ }
2226
+ try {
2227
+ ajv.compile(prompt.argumentsSchema);
2228
+ } catch {
2229
+ throw new McpFnValidationError(
2230
+ `Manifest prompt ${prompt.name} has an invalid arguments JSON Schema`
2231
+ );
2232
+ }
2233
+ assertPromptSchemaSupportsStringValues(
2234
+ prompt.argumentsSchema,
2235
+ `Manifest prompt ${prompt.name} argumentsSchema`
2236
+ );
2237
+ if (prompt.arguments) {
2238
+ const declared = prompt.arguments.map(({ name, required }) => ({ name, required: required === true })).sort((left, right) => compareCodeUnits(left.name, right.name));
2239
+ const schemaDeclared = schemaPromptArguments(prompt).map(
2240
+ ({ name, required }) => ({ name, required: required === true })
2241
+ );
2242
+ if (JSON.stringify(declared) !== JSON.stringify(schemaDeclared)) {
2243
+ throw new McpFnValidationError(
2244
+ `Manifest prompt ${prompt.name} arguments and argumentsSchema disagree`
2245
+ );
2246
+ }
2247
+ }
2248
+ }
2249
+ }
2250
+ assertSortedBy("Manifest prompt names", manifest.prompts ?? [], (prompt) => prompt.name);
2251
+ if (typeof manifest.hash !== "string" || !/^[a-f0-9]{64}$/.test(manifest.hash)) {
2252
+ throw new McpFnValidationError("Manifest hash must be a lowercase SHA-256 digest");
2253
+ }
2254
+ const { hash: _ignored, ...body } = manifest;
2255
+ const expectedHash = sha256(body);
2256
+ if (manifest.hash !== expectedHash) {
2257
+ throw new McpFnValidationError("Manifest hash does not match its contents", {
2258
+ expectedHash,
2259
+ actualHash: manifest.hash
2260
+ });
2261
+ }
2262
+ return manifest;
2263
+ }
2264
+
2265
+ // src/results.ts
2266
+ function textResult(text) {
2267
+ return { content: [{ type: "text", text }] };
2268
+ }
2269
+ function structuredResult(structuredContent, content) {
2270
+ const normalized = jsonSafe(structuredContent);
2271
+ if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
2272
+ throw new McpFnOutputValidationError(
2273
+ "structuredContent must serialize to an object"
2274
+ );
2275
+ }
2276
+ return {
2277
+ content: content ?? [
2278
+ { type: "text", text: JSON.stringify(normalized, null, 2) }
2279
+ ],
2280
+ structuredContent: normalized
2281
+ };
2282
+ }
2283
+
2284
+ // src/server.ts
2285
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2286
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2287
+ import {
2288
+ WebStandardStreamableHTTPServerTransport
2289
+ } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
2290
+ import {
2291
+ CallToolRequestSchema,
2292
+ CompleteRequestSchema,
2293
+ CreateMessageResultSchema,
2294
+ CreateMessageResultWithToolsSchema,
2295
+ ElicitResultSchema,
2296
+ ErrorCode,
2297
+ GetPromptRequestSchema,
2298
+ ListPromptsRequestSchema,
2299
+ ListRootsResultSchema,
2300
+ ListResourcesRequestSchema,
2301
+ ListResourceTemplatesRequestSchema,
2302
+ ListToolsRequestSchema,
2303
+ McpError,
2304
+ ReadResourceRequestSchema,
2305
+ SubscribeRequestSchema,
2306
+ UnsubscribeRequestSchema
2307
+ } from "@modelcontextprotocol/sdk/types.js";
2308
+ function mergeCapabilities(base, extra) {
2309
+ const merged = { ...base, ...extra };
2310
+ for (const key of ["prompts", "resources", "tools", "tasks"]) {
2311
+ if (base[key] || extra?.[key]) {
2312
+ merged[key] = {
2313
+ ...base[key],
2314
+ ...extra?.[key]
2315
+ };
2316
+ }
2317
+ }
2318
+ return merged;
2319
+ }
2320
+ function page(values, cursor, pageSize) {
2321
+ let offset = 0;
2322
+ if (cursor !== void 0) {
2323
+ const match = /^mcpfn:(\d+)$/.exec(cursor);
2324
+ if (!match) throw new McpError(ErrorCode.InvalidParams, "Invalid McpFn pagination cursor");
2325
+ offset = Number(match[1]);
2326
+ if (!Number.isSafeInteger(offset) || offset > values.length) {
2327
+ throw new McpError(ErrorCode.InvalidParams, "Expired McpFn pagination cursor");
2328
+ }
2329
+ }
2330
+ const selected = values.slice(offset, offset + pageSize);
2331
+ const nextOffset = offset + selected.length;
2332
+ return {
2333
+ values: selected,
2334
+ ...nextOffset < values.length ? { nextCursor: `mcpfn:${nextOffset}` } : {}
2335
+ };
2336
+ }
2337
+ var McpFnServer = class {
2338
+ registry;
2339
+ info;
2340
+ protocol;
2341
+ capabilities;
2342
+ contextFactory;
2343
+ toolVisibility;
2344
+ manifestOptions;
2345
+ pageSize;
2346
+ connected = false;
2347
+ constructor(options) {
2348
+ this.info = options.info;
2349
+ this.registry = options.registry;
2350
+ assertMcpAppContracts(this.registry);
2351
+ this.contextFactory = options.context ?? (() => void 0);
2352
+ this.toolVisibility = options.toolVisibility;
2353
+ this.pageSize = options.pageSize ?? 100;
2354
+ if (!Number.isInteger(this.pageSize) || this.pageSize < 1) {
2355
+ throw new Error("McpFn pageSize must be a positive integer");
2356
+ }
2357
+ const registryCapabilities = this.registry.capabilities();
2358
+ if (registryCapabilities.tasks && !options.taskStore) {
2359
+ throw new Error("Task-capable McpFn tools require a taskStore");
2360
+ }
2361
+ if (registryCapabilities.tasks && options.taskStore) {
2362
+ registryCapabilities.tasks = {
2363
+ ...registryCapabilities.tasks,
2364
+ list: {},
2365
+ cancel: {}
2366
+ };
2367
+ }
2368
+ this.capabilities = mergeCapabilities(registryCapabilities, options.additionalCapabilities);
2369
+ this.manifestOptions = {
2370
+ protocolVersions: options.protocolVersions,
2371
+ transports: options.transports,
2372
+ extensions: options.extensions,
2373
+ capabilities: this.capabilities,
2374
+ clientRequirements: options.clientRequirements
2375
+ };
2376
+ this.protocol = new Server(
2377
+ { name: options.info.name, version: options.info.version },
2378
+ {
2379
+ capabilities: this.capabilities,
2380
+ instructions: options.info.instructions,
2381
+ taskStore: options.taskStore,
2382
+ taskMessageQueue: options.taskMessageQueue,
2383
+ defaultTaskPollInterval: options.defaultTaskPollInterval,
2384
+ maxTaskQueueSize: options.maxTaskQueueSize,
2385
+ enforceStrictCapabilities: options.enforceStrictCapabilities,
2386
+ debouncedNotificationMethods: [
2387
+ "notifications/tools/list_changed",
2388
+ "notifications/resources/list_changed",
2389
+ "notifications/prompts/list_changed"
2390
+ ]
2391
+ }
2392
+ );
2393
+ this.installHandlers();
2394
+ }
2395
+ installHandlers() {
2396
+ if (this.capabilities.tools) {
2397
+ this.protocol.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
2398
+ const tools = this.registry.listTools();
2399
+ const visibleTools = this.toolVisibility ? await this.filterVisibleTools(tools, await this.contextFactory(extra), extra) : tools;
2400
+ const result = page(visibleTools, request.params?.cursor, this.pageSize);
2401
+ return { tools: result.values, ...result.nextCursor ? { nextCursor: result.nextCursor } : {} };
2402
+ });
2403
+ this.protocol.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
2404
+ const context = await this.contextFactory(extra);
2405
+ const listedTool = this.registry.listTools().find((tool) => tool.name === request.params.name);
2406
+ if (!listedTool || this.toolVisibility && !await this.toolVisibility({ tool: listedTool, context, extra })) {
2407
+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} not found`);
2408
+ }
2409
+ const taskSupport = this.registry.taskSupport(request.params.name);
2410
+ const isTaskRequest = Boolean(request.params.task);
2411
+ if (taskSupport === "required" && !isTaskRequest) {
2412
+ throw new McpError(
2413
+ ErrorCode.MethodNotFound,
2414
+ `Tool ${request.params.name} requires task augmentation`
2415
+ );
2416
+ }
2417
+ if (taskSupport === "forbidden" && isTaskRequest) {
2418
+ throw new McpError(
2419
+ ErrorCode.MethodNotFound,
2420
+ `Tool ${request.params.name} does not support task augmentation`
2421
+ );
2422
+ }
2423
+ try {
2424
+ if (isTaskRequest) {
2425
+ if (!extra.taskStore) throw new Error("No task store is available");
2426
+ return await this.registry.createToolTask(
2427
+ request.params.name,
2428
+ request.params.arguments,
2429
+ context,
2430
+ extra
2431
+ );
2432
+ }
2433
+ return await this.registry.callTool(
2434
+ request.params.name,
2435
+ request.params.arguments,
2436
+ context,
2437
+ extra
2438
+ );
2439
+ } catch (error) {
2440
+ if (isTaskRequest) throw error;
2441
+ return errorResult(error, {
2442
+ includeStructuredContent: !this.registry.hasOutputSchema(request.params.name)
2443
+ });
2444
+ }
2445
+ });
2446
+ }
2447
+ if (this.capabilities.resources) {
2448
+ this.protocol.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
2449
+ const context = await this.contextFactory(extra);
2450
+ const result = page(
2451
+ await this.registry.listResources(context, extra),
2452
+ request.params?.cursor,
2453
+ this.pageSize
2454
+ );
2455
+ return {
2456
+ resources: result.values,
2457
+ ...result.nextCursor ? { nextCursor: result.nextCursor } : {}
2458
+ };
2459
+ });
2460
+ this.protocol.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) => {
2461
+ const result = page(
2462
+ this.registry.listResourceTemplates(),
2463
+ request.params?.cursor,
2464
+ this.pageSize
2465
+ );
2466
+ return {
2467
+ resourceTemplates: result.values,
2468
+ ...result.nextCursor ? { nextCursor: result.nextCursor } : {}
2469
+ };
2470
+ });
2471
+ this.protocol.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
2472
+ const context = await this.contextFactory(extra);
2473
+ return this.registry.readResource(request.params.uri, context, extra);
2474
+ });
2475
+ if (this.capabilities.resources.subscribe) {
2476
+ this.protocol.setRequestHandler(SubscribeRequestSchema, async (request, extra) => {
2477
+ const context = await this.contextFactory(extra);
2478
+ await this.registry.changeSubscription(request.params.uri, true, context, extra);
2479
+ return {};
2480
+ });
2481
+ this.protocol.setRequestHandler(UnsubscribeRequestSchema, async (request, extra) => {
2482
+ const context = await this.contextFactory(extra);
2483
+ await this.registry.changeSubscription(request.params.uri, false, context, extra);
2484
+ return {};
2485
+ });
2486
+ }
2487
+ }
2488
+ if (this.capabilities.prompts) {
2489
+ this.protocol.setRequestHandler(ListPromptsRequestSchema, async (request) => {
2490
+ const result = page(this.registry.listPrompts(), request.params?.cursor, this.pageSize);
2491
+ return {
2492
+ prompts: result.values,
2493
+ ...result.nextCursor ? { nextCursor: result.nextCursor } : {}
2494
+ };
2495
+ });
2496
+ this.protocol.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
2497
+ const context = await this.contextFactory(extra);
2498
+ return this.registry.getPrompt(
2499
+ request.params.name,
2500
+ request.params.arguments,
2501
+ context,
2502
+ extra
2503
+ );
2504
+ });
2505
+ }
2506
+ if (this.capabilities.completions) {
2507
+ this.protocol.setRequestHandler(CompleteRequestSchema, async (request, extra) => {
2508
+ const context = await this.contextFactory(extra);
2509
+ return this.registry.complete(
2510
+ request.params.ref,
2511
+ request.params.argument,
2512
+ request.params.context?.arguments,
2513
+ context,
2514
+ extra
2515
+ );
2516
+ });
2517
+ }
2518
+ }
2519
+ async filterVisibleTools(tools, context, extra) {
2520
+ if (!this.toolVisibility) return tools;
2521
+ const decisions = await Promise.all(tools.map((tool) => this.toolVisibility({ tool, context, extra })));
2522
+ return tools.filter((_, index) => decisions[index]);
2523
+ }
2524
+ manifest() {
2525
+ return createManifest(this.info, this.registry, this.manifestOptions);
2526
+ }
2527
+ async connect(transport) {
2528
+ if (this.connected) throw new Error("McpFnServer is already connected to a transport");
2529
+ await this.protocol.connect(transport);
2530
+ this.connected = true;
2531
+ }
2532
+ async serveStdio() {
2533
+ await this.connect(new StdioServerTransport());
2534
+ }
2535
+ async createWebStandardHandler(options = {}) {
2536
+ const transport = new WebStandardStreamableHTTPServerTransport(options);
2537
+ await this.connect(transport);
2538
+ return (request, handleOptions) => transport.handleRequest(request, handleOptions);
2539
+ }
2540
+ sample(params, options) {
2541
+ return this.protocol.createMessage(params, options);
2542
+ }
2543
+ sampleForRequest(extra, params, options) {
2544
+ const schema = params.tools?.length ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
2545
+ return extra.sendRequest(
2546
+ { method: "sampling/createMessage", params },
2547
+ schema,
2548
+ options
2549
+ );
2550
+ }
2551
+ elicit(params, options) {
2552
+ return this.protocol.elicitInput(params, options);
2553
+ }
2554
+ elicitForRequest(extra, params, options) {
2555
+ return extra.sendRequest(
2556
+ { method: "elicitation/create", params },
2557
+ ElicitResultSchema,
2558
+ options
2559
+ );
2560
+ }
2561
+ listRoots(options) {
2562
+ return this.protocol.listRoots(void 0, options);
2563
+ }
2564
+ listRootsForRequest(extra, options) {
2565
+ return extra.sendRequest(
2566
+ { method: "roots/list" },
2567
+ ListRootsResultSchema,
2568
+ options
2569
+ );
2570
+ }
2571
+ sendLoggingMessage(params, sessionId) {
2572
+ return this.protocol.sendLoggingMessage(params, sessionId);
2573
+ }
2574
+ sendResourceUpdated(params) {
2575
+ return this.protocol.sendResourceUpdated(params);
2576
+ }
2577
+ sendResourceListChanged() {
2578
+ return this.protocol.sendResourceListChanged();
2579
+ }
2580
+ sendToolListChanged() {
2581
+ return this.protocol.sendToolListChanged();
2582
+ }
2583
+ sendPromptListChanged() {
2584
+ return this.protocol.sendPromptListChanged();
2585
+ }
2586
+ async close() {
2587
+ await this.protocol.close();
2588
+ this.connected = false;
2589
+ }
2590
+ };
2591
+ function createMcpFnServer(options) {
2592
+ return new McpFnServer(options);
2593
+ }
2594
+ export {
2595
+ MCP_APP_EXTENSION_ID,
2596
+ MCP_APP_MIME_TYPE,
2597
+ McpFnError,
2598
+ McpFnOutputValidationError,
2599
+ McpFnRegistry,
2600
+ McpFnServer,
2601
+ McpFnValidationError,
2602
+ assertMcpAppContracts,
2603
+ assertPromptSchemaSupportsStringValues,
2604
+ canonicalJson,
2605
+ canonicalize,
2606
+ compareCodeUnits,
2607
+ createManifest,
2608
+ createMcpAppResource,
2609
+ createMcpFnServer,
2610
+ diffManifests,
2611
+ errorResult,
2612
+ jsonSafe,
2613
+ mcpAppToolMetadata,
2614
+ promptArguments,
2615
+ schemaPromptArguments,
2616
+ sha256,
2617
+ structuredResult,
2618
+ textResult,
2619
+ validateManifest
2620
+ };
2621
+ //# sourceMappingURL=index.js.map