@mcpfn/core 0.0.1 → 0.0.3

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