@mcpfn/core 0.0.1 → 0.0.2

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