@mcpfn/core 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -193,2403 +193,2592 @@ 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
- });
553
+ if (!hasStringWitness) {
554
+ throw new McpFnValidationError(
555
+ `${label} argument ${name} must accept string values`
556
+ );
669
557
  }
670
558
  }
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
559
  }
711
- function diffTool(before, after, changes) {
712
- const root = `tools.${before.name}`;
713
- if (before.title !== after.title) {
714
- push(changes, {
715
- severity: "behavioral",
716
- code: "tool-title-changed",
717
- path: `${root}.title`,
718
- message: `Tool title changed for ${before.name}`,
719
- before: before.title,
720
- after: after.title
721
- });
722
- }
723
- if (before.description !== after.description) {
724
- push(changes, {
725
- severity: "behavioral",
726
- code: "tool-description-changed",
727
- path: `${root}.description`,
728
- message: `Tool description changed for ${before.name}`,
729
- before: before.description,
730
- after: after.description
731
- });
732
- }
733
- if (!equal(before.annotations ?? {}, after.annotations ?? {})) {
734
- push(changes, {
735
- severity: "behavioral",
736
- code: "tool-annotations-changed",
737
- path: `${root}.annotations`,
738
- message: `Tool annotations changed for ${before.name}`,
739
- before: before.annotations,
740
- after: after.annotations
741
- });
742
- }
743
- if (!equal(before.execution ?? {}, after.execution ?? {})) {
744
- const oldSupport = before.execution?.taskSupport ?? "forbidden";
745
- const newSupport = after.execution?.taskSupport ?? "forbidden";
746
- const breaking = newSupport === "required" || oldSupport !== "forbidden" && newSupport === "forbidden";
747
- push(changes, {
748
- severity: breaking ? "breaking" : "additive",
749
- code: "tool-task-support-changed",
750
- path: `${root}.execution.taskSupport`,
751
- message: `Tool task support changed from ${oldSupport} to ${newSupport}`,
752
- before: oldSupport,
753
- after: newSupport
754
- });
755
- }
756
- if (!equal(before.icons ?? [], after.icons ?? [])) {
757
- push(changes, {
758
- severity: "behavioral",
759
- code: "tool-icons-changed",
760
- path: `${root}.icons`,
761
- message: `Tool icons changed for ${before.name}`,
762
- before: before.icons,
763
- after: after.icons
764
- });
765
- }
766
- if (!equal(before.metadata ?? {}, after.metadata ?? {})) {
767
- push(changes, {
768
- severity: "behavioral",
769
- code: "tool-metadata-changed",
770
- path: `${root}.metadata`,
771
- message: `Tool metadata changed for ${before.name}`,
772
- before: before.metadata,
773
- after: after.metadata
774
- });
775
- }
776
- diffSchema(before.inputSchema, after.inputSchema, `${root}.inputSchema`, "input", changes);
777
- diffSchema(before.outputSchema, after.outputSchema, `${root}.outputSchema`, "output", changes);
778
- }
779
- function diffResource(before, after, changes) {
780
- const root = `resources.${before.uri}`;
781
- if ((before.subscribable ?? false) !== (after.subscribable ?? false)) {
782
- const enabled = after.subscribable === true;
783
- push(changes, {
784
- severity: enabled ? "additive" : "breaking",
785
- code: enabled ? "resource-subscription-enabled" : "resource-subscription-removed",
786
- path: `${root}.subscribable`,
787
- message: `Resource subscription support was ${enabled ? "enabled" : "removed"} for ${before.uri}`,
788
- before: before.subscribable,
789
- after: after.subscribable
790
- });
791
- }
792
- if (before.mimeType !== after.mimeType) {
793
- push(changes, {
794
- severity: "breaking",
795
- code: "resource-mime-type-changed",
796
- path: `${root}.mimeType`,
797
- message: `Resource MIME type changed for ${before.uri}`,
798
- before: before.mimeType,
799
- after: after.mimeType
800
- });
801
- }
802
- for (const key of ["name", "title", "description", "annotations", "icons", "metadata"]) {
803
- if (!equal(before[key], after[key])) {
804
- push(changes, {
805
- severity: "behavioral",
806
- code: `resource-${key}-changed`,
807
- path: `${root}.${key}`,
808
- message: `Resource ${key} changed for ${before.uri}`,
809
- before: before[key],
810
- after: after[key]
811
- });
812
- }
813
- }
814
- }
815
- function diffResourceTemplate(before, after, changes) {
816
- const root = `resourceTemplates.${before.name}`;
817
- if ((before.subscribable ?? false) !== (after.subscribable ?? false)) {
818
- const enabled = after.subscribable === true;
819
- push(changes, {
820
- severity: enabled ? "additive" : "breaking",
821
- code: enabled ? "resource-template-subscription-enabled" : "resource-template-subscription-removed",
822
- path: `${root}.subscribable`,
823
- message: `Resource template subscription support was ${enabled ? "enabled" : "removed"} for ${before.name}`,
824
- before: before.subscribable,
825
- after: after.subscribable
826
- });
827
- }
828
- if (before.uriTemplate !== after.uriTemplate) {
829
- push(changes, {
830
- severity: "breaking",
831
- code: "resource-template-uri-changed",
832
- path: `${root}.uriTemplate`,
833
- message: `Resource template URI changed for ${before.name}`,
834
- before: before.uriTemplate,
835
- after: after.uriTemplate
836
- });
837
- }
838
- if (before.mimeType !== after.mimeType) {
839
- push(changes, {
840
- severity: "breaking",
841
- code: "resource-template-mime-type-changed",
842
- path: `${root}.mimeType`,
843
- message: `Resource template MIME type changed for ${before.name}`,
844
- before: before.mimeType,
845
- after: after.mimeType
846
- });
847
- }
848
- for (const key of ["title", "description", "annotations", "icons", "metadata"]) {
849
- if (!equal(before[key], after[key])) {
850
- push(changes, {
851
- severity: "behavioral",
852
- code: `resource-template-${key}-changed`,
853
- path: `${root}.${key}`,
854
- message: `Resource template ${key} changed for ${before.name}`,
855
- before: before[key],
856
- after: after[key]
857
- });
858
- }
859
- }
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
+ );
699
+ }
700
+ if (typeof definition.uriTemplate !== "string") {
701
+ throw new McpFnValidationError(
702
+ `Invalid resource URI template ${JSON.stringify(definition.uriTemplate)}`
703
+ );
704
+ }
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
+ );
710
+ }
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
+ );
719
+ }
720
+ if (!template.variableNames.length) {
721
+ throw new McpFnValidationError(
722
+ `Resource template ${definition.name} must contain at least one variable`
723
+ );
724
+ }
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
+ );
1066
737
  }
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
- });
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
+ );
1076
743
  }
1077
744
  }
745
+ this.resourceTemplates.set(definition.name, { definition, template });
746
+ return this;
1078
747
  }
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}}`;
748
+ registerPrompt(definition) {
749
+ assertName("prompt", definition.name);
750
+ if (this.prompts.has(definition.name)) {
751
+ throw new McpFnValidationError(`Duplicate MCP prompt: ${definition.name}`);
1109
752
  }
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;
753
+ if (typeof definition.get !== "function") {
754
+ throw new McpFnValidationError(
755
+ `Prompt ${definition.name} requires a get handler function`
756
+ );
1132
757
  }
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;
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`);
1168
762
  }
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);
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
+ }
1194
775
  }
1195
- }
1196
- return closure;
1197
- }
1198
- function predicatesOverlap(left, right) {
1199
- if (left.kind === "literal" && right.kind === "literal") return left.value === right.value;
1200
- if (left.kind === "literal") return !right.value.includes(left.value);
1201
- if (right.kind === "literal") return !left.value.includes(right.value);
1202
- return true;
1203
- }
1204
- function uriTemplatesOverlap(left, right) {
1205
- if (uriTemplateMatchShape(left) === uriTemplateMatchShape(right)) return true;
1206
- const leftAutomaton = uriTemplateAutomaton(left);
1207
- const rightAutomaton = uriTemplateAutomaton(right);
1208
- const queue = [[0, 0]];
1209
- const visited = /* @__PURE__ */ new Set();
1210
- while (queue.length) {
1211
- const [leftState, rightState] = queue.shift();
1212
- const key = `${leftState}:${rightState}`;
1213
- if (visited.has(key)) continue;
1214
- visited.add(key);
1215
- const leftClosure = epsilonClosure(leftAutomaton, leftState);
1216
- const rightClosure = epsilonClosure(rightAutomaton, rightState);
1217
- if (leftClosure.has(leftAutomaton.final) && rightClosure.has(rightAutomaton.final)) {
1218
- return true;
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
+ );
1219
780
  }
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
- }
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;
820
+ }
821
+ has(name) {
822
+ return this.tools.has(name);
823
+ }
824
+ hasOutputSchema(name) {
825
+ return Boolean(this.tools.get(name)?.validateOutput);
826
+ }
827
+ definitions() {
828
+ return [...this.tools.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
829
+ }
830
+ resourceDefinitions() {
831
+ return [...this.resources.values()].sort((left, right) => compareCodeUnits(left.uri, right.uri));
832
+ }
833
+ resourceTemplateDefinitions() {
834
+ return [...this.resourceTemplates.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
835
+ }
836
+ promptDefinitions() {
837
+ return [...this.prompts.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
838
+ }
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
+ };
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;
1231
855
  }
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
- );
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
+ }));
1251
868
  }
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
- );
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));
1258
884
  }
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)}`);
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
+ }));
1265
896
  }
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);
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
+ }));
1270
906
  }
1271
- for (const [name, schemas] of source.propertySchemas) {
1272
- target.propertySchemas.set(name, [...target.propertySchemas.get(name) ?? [], ...schemas]);
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
+ };
914
+ }
915
+ return { args: normalizedArgs };
1273
916
  }
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);
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
+ );
932
+ }
933
+ throw new McpFnValidationError(`Invalid arguments for ${name}`, { issues: normalized.issues });
934
+ }
935
+ return this.finalizeResult(
936
+ registered,
937
+ await registered.definition.handler(normalized.args, context, extra)
938
+ );
1313
939
  }
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);
940
+ taskSupport(name) {
941
+ return this.tools.get(name)?.definition.execution?.taskSupport ?? "forbidden";
942
+ }
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`);
1320
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 }
970
+ );
1321
971
  }
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
- );
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 };
1338
978
  }
979
+ return void 0;
1339
980
  }
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();
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);
1356
986
  }
1357
- if (Array.isArray(value.enum)) {
1358
- candidates = intersectStringCandidates(
1359
- candidates,
1360
- new Set(value.enum.filter((entry) => typeof entry === "string"))
1361
- );
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;
1000
+ }
1001
+ const callback = subscribed ? match.definition.subscribe : match.definition.unsubscribe;
1002
+ if (!callback) {
1003
+ throw new McpFnValidationError(
1004
+ `Resource ${uri} does not support ${subscribed ? "subscriptions" : "unsubscription"}`
1005
+ );
1006
+ }
1007
+ await callback(url, match.variables, context, extra);
1362
1008
  }
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
- );
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
+ });
1017
+ }
1018
+ return registered.definition.get(normalized, context, extra);
1371
1019
  }
1372
- if (Array.isArray(value.allOf)) {
1373
- for (const member of value.allOf) {
1374
- candidates = intersectStringCandidates(
1375
- candidates,
1376
- finiteStringCandidates(member, root, references)
1377
- );
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;
1031
+ }
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}`);
1378
1036
  }
1037
+ return template.definition.complete?.[argument.name]?.(
1038
+ argument.value,
1039
+ completionContext,
1040
+ context,
1041
+ extra
1042
+ ) ?? empty;
1379
1043
  }
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;
1044
+ finalizeResult(registered, result) {
1045
+ if (registered.validateOutput && result.isError) {
1046
+ const { structuredContent: _omitted, ...errorWithoutStructuredContent } = result;
1047
+ return errorWithoutStructuredContent;
1048
+ }
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
+ );
1388
1060
  }
1389
- for (const candidate of memberCandidates) union.add(candidate);
1390
1061
  }
1391
- candidates = intersectStringCandidates(candidates, union);
1062
+ return result;
1392
1063
  }
1393
- return candidates;
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`);
1394
1070
  }
1395
- function schemaMayAcceptString(schema, root, references = /* @__PURE__ */ new Set()) {
1396
- if (typeof schema === "boolean") return schema;
1397
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) return false;
1398
- const value = schema;
1399
- const finiteCandidates = finiteStringCandidates(schema, root, references);
1400
- if (finiteCandidates?.size === 0) return false;
1401
- if (value.$ref !== void 0) {
1402
- if (typeof value.$ref !== "string" || references.has(value.$ref)) return false;
1403
- const referenced = resolveLocalSchemaReference(root, value.$ref);
1404
- if (!referenced) return false;
1405
- const nextReferences = new Set(references).add(value.$ref);
1406
- if (!schemaMayAcceptString(referenced, root, nextReferences)) return false;
1407
- }
1408
- if (typeof value.type === "string" && value.type !== "string") return false;
1409
- if (Array.isArray(value.type) && !value.type.includes("string")) return false;
1410
- if (Object.hasOwn(value, "const") && typeof value.const !== "string") return false;
1411
- if (Array.isArray(value.enum) && !value.enum.some((entry) => typeof entry === "string")) {
1412
- return false;
1071
+ function assertObject(label, value) {
1072
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1073
+ throw new McpFnValidationError(`${label} must be an object`);
1413
1074
  }
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
1075
  }
1419
- function assertPromptSchemaSupportsStringValues(schema, label) {
1420
- const inventory = derivePromptSchemaInventory(schema, schema);
1421
- if (!inventory) {
1422
- throw new McpFnValidationError(
1423
- `${label} must use derivable properties, allOf, or local $ref declarations`
1424
- );
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)`);
1425
1079
  }
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;
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() } : {}
1442
1145
  }
1443
- if (validate) {
1444
- hasStringWitness = [...finiteCandidates].some((candidate) => validate(candidate));
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`);
1173
+ }
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
+ );
1193
+ }
1194
+ }
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`);
1445
1211
  }
1446
1212
  }
1447
- if (!hasStringWitness) {
1213
+ try {
1214
+ ajv.compile(tool.inputSchema);
1215
+ if (tool.outputSchema !== void 0) ajv.compile(tool.outputSchema);
1216
+ } catch (error) {
1448
1217
  throw new McpFnValidationError(
1449
- `${label} argument ${name} must accept string values`
1218
+ `Manifest tool ${tool.name} contains an invalid JSON Schema`,
1219
+ { cause: error instanceof Error ? error.message : String(error) }
1220
+ );
1221
+ }
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") {
1229
+ throw new McpFnValidationError(
1230
+ `Manifest tool ${tool.name} has invalid taskSupport=${String(taskSupport)}`
1450
1231
  );
1451
1232
  }
1452
1233
  }
1453
- }
1454
- function schemaPromptArguments(definition) {
1455
- const schema = definition.argumentsSchema;
1456
- if (!schema) return void 0;
1457
- const inventory = derivePromptSchemaInventory(schema, schema);
1458
- if (!inventory) return void 0;
1459
- const names = [.../* @__PURE__ */ new Set([
1460
- ...inventory.propertySchemas.keys(),
1461
- ...inventory.required
1462
- ])].sort(compareCodeUnits);
1463
- return names.map((name) => {
1464
- return {
1465
- name,
1466
- ...inventory.descriptions.has(name) ? { description: inventory.descriptions.get(name) } : {},
1467
- ...inventory.required.has(name) ? { required: true } : {}
1468
- };
1469
- });
1470
- }
1471
- function promptSchema(definition) {
1472
- if (definition.argumentsSchema) return definition.argumentsSchema;
1473
- const properties = Object.fromEntries(
1474
- (definition.arguments ?? []).map((argument) => [
1475
- argument.name,
1476
- { type: "string", ...argument.description ? { description: argument.description } : {} }
1477
- ])
1478
- );
1479
- return {
1480
- type: "object",
1481
- properties,
1482
- required: (definition.arguments ?? []).filter((argument) => argument.required).map((argument) => argument.name),
1483
- additionalProperties: false
1484
- };
1485
- }
1486
- function promptArguments(definition) {
1487
- return Array.isArray(definition.arguments) ? definition.arguments : schemaPromptArguments(definition);
1488
- }
1489
- var McpFnRegistry = class {
1490
- ajv;
1491
- tools = /* @__PURE__ */ new Map();
1492
- resources = /* @__PURE__ */ new Map();
1493
- resourceTemplates = /* @__PURE__ */ new Map();
1494
- prompts = /* @__PURE__ */ new Map();
1495
- constructor() {
1496
- this.ajv = new Ajv({ allErrors: true, strict: false, allowUnionTypes: true });
1497
- addFormats(this.ajv);
1498
- }
1499
- register(definition) {
1500
- assertName("tool", definition.name);
1501
- if (this.tools.has(definition.name)) {
1502
- throw new McpFnValidationError(`Duplicate MCP tool: ${definition.name}`);
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`);
1503
1242
  }
1504
- if (!definition.description.trim()) {
1243
+ if (resource.subscribable !== void 0 && typeof resource.subscribable !== "boolean") {
1505
1244
  throw new McpFnValidationError(
1506
- `Tool ${definition.name} requires a non-empty description`
1245
+ `Manifest resource ${resource.name} subscribable must be a boolean`
1507
1246
  );
1508
1247
  }
1509
- if (typeof definition.handler !== "function") {
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") {
1510
1256
  throw new McpFnValidationError(
1511
- `Tool ${definition.name} requires a handler function`
1257
+ `Manifest resource template ${resource.name} has an invalid URI template`
1512
1258
  );
1513
1259
  }
1514
- if (definition.inputSchema.type !== "object") {
1260
+ const unsupportedOperator = unsupportedUriTemplateOperator(resource.uriTemplate);
1261
+ if (unsupportedOperator) {
1515
1262
  throw new McpFnValidationError(
1516
- `Tool ${definition.name} inputSchema must be an object schema`
1263
+ `Manifest resource template ${resource.name} uses unsupported URI template operator ${unsupportedOperator}`
1517
1264
  );
1518
1265
  }
1519
- if (definition.outputSchema !== void 0 && (definition.outputSchema === null || typeof definition.outputSchema !== "object" || Array.isArray(definition.outputSchema) || definition.outputSchema.type !== "object")) {
1266
+ let template;
1267
+ try {
1268
+ template = new UriTemplate2(resource.uriTemplate);
1269
+ } catch {
1520
1270
  throw new McpFnValidationError(
1521
- `Tool ${definition.name} outputSchema must be an object schema`
1271
+ `Manifest resource template ${resource.name} has an invalid URI template`
1522
1272
  );
1523
1273
  }
1524
- const taskSupport = definition.execution?.taskSupport ?? "forbidden";
1525
- if (!["forbidden", "optional", "required"].includes(taskSupport)) {
1274
+ if (!template.variableNames.length) {
1526
1275
  throw new McpFnValidationError(
1527
- `Tool ${definition.name} has invalid taskSupport=${String(taskSupport)}`
1276
+ `Manifest resource template ${resource.name} must contain at least one variable`
1528
1277
  );
1529
1278
  }
1530
- if ((taskSupport === "required" || taskSupport === "optional") && !definition.taskHandler) {
1279
+ if (resourceTemplateUris.some(
1280
+ (uriTemplate) => uriTemplatesOverlap(uriTemplate, resource.uriTemplate)
1281
+ )) {
1531
1282
  throw new McpFnValidationError(
1532
- `Tool ${definition.name} declares taskSupport=${taskSupport} but has no taskHandler`
1283
+ `Manifest contains an ambiguous resource URI template: ${resource.uriTemplate}`
1533
1284
  );
1534
1285
  }
1535
- if (taskSupport === "forbidden" && definition.taskHandler) {
1286
+ resourceTemplateUris.push(resource.uriTemplate);
1287
+ if (resource.subscribable !== void 0 && typeof resource.subscribable !== "boolean") {
1536
1288
  throw new McpFnValidationError(
1537
- `Tool ${definition.name} has a taskHandler but forbids task execution`
1289
+ `Manifest resource template ${resource.name} subscribable must be a boolean`
1538
1290
  );
1539
1291
  }
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) }
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`);
1305
+ }
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") {
1311
+ throw new McpFnValidationError(
1312
+ `Manifest prompt ${prompt.name} argument ${argument.name} description must be a string`
1313
+ );
1314
+ }
1315
+ if (argument.required !== void 0 && typeof argument.required !== "boolean") {
1316
+ throw new McpFnValidationError(
1317
+ `Manifest prompt ${prompt.name} argument ${argument.name} required must be a boolean`
1318
+ );
1319
+ }
1320
+ argumentNames.push(argument.name);
1321
+ }
1322
+ if (new Set(argumentNames).size !== argumentNames.length) {
1323
+ throw new McpFnValidationError(`Manifest prompt ${prompt.name} has duplicate arguments`);
1324
+ }
1325
+ if (prompt.argumentsSchema !== void 0) {
1326
+ assertObject(`Manifest prompt ${prompt.name} argumentsSchema`, prompt.argumentsSchema);
1327
+ if (prompt.argumentsSchema.type !== "object") {
1328
+ throw new McpFnValidationError(
1329
+ `Manifest prompt ${prompt.name} argumentsSchema must be an object schema`
1330
+ );
1331
+ }
1332
+ try {
1333
+ ajv.compile(prompt.argumentsSchema);
1334
+ } catch {
1335
+ throw new McpFnValidationError(
1336
+ `Manifest prompt ${prompt.name} has an invalid arguments JSON Schema`
1337
+ );
1338
+ }
1339
+ assertPromptSchemaSupportsStringValues(
1340
+ prompt.argumentsSchema,
1341
+ `Manifest prompt ${prompt.name} argumentsSchema`
1549
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 })
1347
+ );
1348
+ if (JSON.stringify(declared) !== JSON.stringify(schemaDeclared)) {
1349
+ throw new McpFnValidationError(
1350
+ `Manifest prompt ${prompt.name} arguments and argumentsSchema disagree`
1351
+ );
1352
+ }
1353
+ }
1550
1354
  }
1551
- this.tools.set(definition.name, {
1552
- definition,
1553
- validateInput,
1554
- validateOutput
1355
+ }
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");
1359
+ }
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
1555
1366
  });
1556
- return this;
1557
1367
  }
1558
- registerAll(definitions) {
1559
- for (const definition of definitions) this.register(definition);
1560
- return this;
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]
1402
+ };
1403
+ }
1404
+ }
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
+ };
1561
1415
  }
1562
- registerResource(definition) {
1563
- assertUri("resource", definition.uri);
1564
- assertName("resource", definition.name);
1565
- if (typeof definition.read !== "function") {
1566
- throw new McpFnValidationError(
1567
- `Resource ${definition.name} requires a read handler function`
1568
- );
1569
- }
1570
- if (this.resources.has(definition.uri)) {
1571
- throw new McpFnValidationError(`Duplicate MCP resource: ${definition.uri}`);
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");
1572
1426
  }
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
1427
  }
1582
- registerResourceTemplate(definition) {
1583
- assertName("resource template", definition.name);
1584
- if (typeof definition.read !== "function") {
1585
- throw new McpFnValidationError(
1586
- `Resource template ${definition.name} requires a read handler function`
1587
- );
1588
- }
1589
- if (this.resourceTemplates.has(definition.name)) {
1590
- throw new McpFnValidationError(
1591
- `Duplicate MCP resource template: ${definition.name}`
1592
- );
1593
- }
1594
- if (typeof definition.uriTemplate !== "string") {
1595
- throw new McpFnValidationError(
1596
- `Invalid resource URI template ${JSON.stringify(definition.uriTemplate)}`
1597
- );
1598
- }
1599
- const unsupportedOperator = unsupportedUriTemplateOperator(definition.uriTemplate);
1600
- if (unsupportedOperator) {
1601
- throw new McpFnValidationError(
1602
- `Resource template ${definition.name} uses unsupported URI template operator ${unsupportedOperator}`
1603
- );
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
+ async function releaseAfterResponse(response, release) {
1436
+ if (!response.body || !response.headers.get("content-type")?.includes("text/event-stream")) {
1437
+ await release();
1438
+ return response;
1439
+ }
1440
+ const reader = response.body.getReader();
1441
+ const body = new ReadableStream({
1442
+ async pull(controller) {
1443
+ try {
1444
+ const result = await reader.read();
1445
+ if (result.done) {
1446
+ controller.close();
1447
+ await release();
1448
+ } else {
1449
+ controller.enqueue(result.value);
1450
+ }
1451
+ } catch (error) {
1452
+ controller.error(error);
1453
+ await release();
1454
+ }
1455
+ },
1456
+ async cancel(reason) {
1457
+ try {
1458
+ await reader.cancel(reason);
1459
+ } finally {
1460
+ await release();
1461
+ }
1604
1462
  }
1605
- let template;
1606
- try {
1607
- template = new UriTemplate(definition.uriTemplate);
1608
- } catch (error) {
1609
- throw new McpFnValidationError(
1610
- `Invalid resource URI template ${JSON.stringify(definition.uriTemplate)}`,
1611
- { cause: error instanceof Error ? error.message : String(error) }
1612
- );
1463
+ });
1464
+ return new Response(body, {
1465
+ status: response.status,
1466
+ statusText: response.statusText,
1467
+ headers: response.headers
1468
+ });
1469
+ }
1470
+ var McpFnServer = class _McpFnServer {
1471
+ registry;
1472
+ info;
1473
+ protocol;
1474
+ capabilities;
1475
+ contextFactory;
1476
+ toolVisibility;
1477
+ manifestOptions;
1478
+ pageSize;
1479
+ serverOptions;
1480
+ requestServers = /* @__PURE__ */ new Set();
1481
+ connected = false;
1482
+ constructor(options) {
1483
+ this.serverOptions = { ...options };
1484
+ this.info = options.info;
1485
+ this.registry = options.registry;
1486
+ assertMcpAppContracts(this.registry);
1487
+ this.contextFactory = options.context ?? (() => void 0);
1488
+ this.toolVisibility = options.toolVisibility;
1489
+ this.pageSize = options.pageSize ?? 100;
1490
+ if (!Number.isInteger(this.pageSize) || this.pageSize < 1) {
1491
+ throw new Error("McpFn pageSize must be a positive integer");
1613
1492
  }
1614
- if (!template.variableNames.length) {
1615
- throw new McpFnValidationError(
1616
- `Resource template ${definition.name} must contain at least one variable`
1617
- );
1493
+ const hasTaskTools = Boolean(this.registry.capabilities().tasks);
1494
+ if (hasTaskTools && !options.taskStore) {
1495
+ throw new Error("Task-capable McpFn tools require a taskStore");
1618
1496
  }
1619
- assertSubscriptionCallbacks(
1620
- "Resource template",
1621
- definition.name,
1622
- definition.subscribe,
1623
- definition.unsubscribe
1497
+ const declaredCapabilities = mergeCapabilities(
1498
+ options.capabilities ?? {},
1499
+ options.additionalCapabilities
1624
1500
  );
1625
- if ([...this.resourceTemplates.values()].some(
1626
- ({ definition: registered }) => uriTemplatesOverlap(registered.uriTemplate, definition.uriTemplate)
1627
- )) {
1628
- throw new McpFnValidationError(
1629
- `Ambiguous MCP resource URI template: ${definition.uriTemplate}`
1630
- );
1631
- }
1632
- for (const name of Object.keys(definition.complete ?? {})) {
1633
- if (!template.variableNames.includes(name)) {
1634
- throw new McpFnValidationError(
1635
- `Resource template ${definition.name} has a completer for unknown variable ${name}`
1636
- );
1501
+ this.capabilities = resolveMcpFnServerCapabilities(
1502
+ this.registry,
1503
+ declaredCapabilities,
1504
+ Boolean(options.taskStore)
1505
+ );
1506
+ this.manifestOptions = {
1507
+ protocolVersions: options.protocolVersions,
1508
+ transports: options.transports,
1509
+ extensions: options.extensions,
1510
+ capabilities: this.capabilities,
1511
+ clientRequirements: options.clientRequirements
1512
+ };
1513
+ const { instructions, ...implementation } = options.info;
1514
+ this.protocol = new Server(
1515
+ implementation,
1516
+ {
1517
+ capabilities: this.capabilities,
1518
+ instructions,
1519
+ taskStore: options.taskStore,
1520
+ taskMessageQueue: options.taskMessageQueue,
1521
+ defaultTaskPollInterval: options.defaultTaskPollInterval,
1522
+ maxTaskQueueSize: options.maxTaskQueueSize,
1523
+ enforceStrictCapabilities: options.enforceStrictCapabilities,
1524
+ debouncedNotificationMethods: [
1525
+ "notifications/tools/list_changed",
1526
+ "notifications/resources/list_changed",
1527
+ "notifications/prompts/list_changed"
1528
+ ]
1637
1529
  }
1638
- }
1639
- this.resourceTemplates.set(definition.name, { definition, template });
1640
- return this;
1530
+ );
1531
+ this.installHandlers();
1641
1532
  }
1642
- registerPrompt(definition) {
1643
- assertName("prompt", definition.name);
1644
- if (this.prompts.has(definition.name)) {
1645
- throw new McpFnValidationError(`Duplicate MCP prompt: ${definition.name}`);
1646
- }
1647
- if (typeof definition.get !== "function") {
1648
- throw new McpFnValidationError(
1649
- `Prompt ${definition.name} requires a get handler function`
1650
- );
1651
- }
1652
- if (definition.arguments !== void 0 && (!Array.isArray(definition.arguments) || definition.arguments.some(
1653
- (argument) => !argument || typeof argument !== "object" || Array.isArray(argument) || typeof argument.name !== "string"
1654
- ))) {
1655
- throw new McpFnValidationError(`Prompt ${definition.name} arguments must be an array`);
1533
+ installHandlers() {
1534
+ if (this.capabilities.tools) {
1535
+ this.protocol.setRequestHandler(ListToolsRequestSchema, async (request, extra) => {
1536
+ const tools = this.registry.listTools();
1537
+ const visibleTools = this.toolVisibility ? await this.filterVisibleTools(tools, await this.contextFactory(extra), extra) : tools;
1538
+ const result = page(visibleTools, request.params?.cursor, this.pageSize);
1539
+ return { tools: result.values, ...result.nextCursor ? { nextCursor: result.nextCursor } : {} };
1540
+ });
1541
+ this.protocol.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
1542
+ const context = await this.contextFactory(extra);
1543
+ const listedTool = this.registry.listTools().find((tool) => tool.name === request.params.name);
1544
+ if (!listedTool || this.toolVisibility && !await this.toolVisibility({ tool: listedTool, context, extra })) {
1545
+ throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} not found`);
1546
+ }
1547
+ const taskSupport = this.registry.taskSupport(request.params.name);
1548
+ const isTaskRequest = Boolean(request.params.task);
1549
+ if (taskSupport === "required" && !isTaskRequest) {
1550
+ throw new McpError(
1551
+ ErrorCode.MethodNotFound,
1552
+ `Tool ${request.params.name} requires task augmentation`
1553
+ );
1554
+ }
1555
+ if (taskSupport === "forbidden" && isTaskRequest) {
1556
+ throw new McpError(
1557
+ ErrorCode.MethodNotFound,
1558
+ `Tool ${request.params.name} does not support task augmentation`
1559
+ );
1560
+ }
1561
+ try {
1562
+ if (isTaskRequest) {
1563
+ if (!extra.taskStore) throw new Error("No task store is available");
1564
+ return await this.registry.createToolTask(
1565
+ request.params.name,
1566
+ request.params.arguments,
1567
+ context,
1568
+ extra
1569
+ );
1570
+ }
1571
+ return await this.registry.callTool(
1572
+ request.params.name,
1573
+ request.params.arguments,
1574
+ context,
1575
+ extra
1576
+ );
1577
+ } catch (error) {
1578
+ if (isTaskRequest) throw error;
1579
+ return errorResult(error, {
1580
+ includeStructuredContent: !this.registry.hasOutputSchema(request.params.name)
1581
+ });
1582
+ }
1583
+ });
1656
1584
  }
1657
- for (const argument of definition.arguments ?? []) {
1658
- assertName("prompt argument", argument.name);
1659
- if (argument.description !== void 0 && typeof argument.description !== "string") {
1660
- throw new McpFnValidationError(
1661
- `Prompt ${definition.name} argument ${argument.name} description must be a string`
1585
+ if (this.capabilities.resources) {
1586
+ this.protocol.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {
1587
+ const context = await this.contextFactory(extra);
1588
+ const result = page(
1589
+ await this.registry.listResources(context, extra),
1590
+ request.params?.cursor,
1591
+ this.pageSize
1662
1592
  );
1663
- }
1664
- if (argument.required !== void 0 && typeof argument.required !== "boolean") {
1665
- throw new McpFnValidationError(
1666
- `Prompt ${definition.name} argument ${argument.name} required must be a boolean`
1593
+ return {
1594
+ resources: result.values,
1595
+ ...result.nextCursor ? { nextCursor: result.nextCursor } : {}
1596
+ };
1597
+ });
1598
+ this.protocol.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) => {
1599
+ const result = page(
1600
+ this.registry.listResourceTemplates(),
1601
+ request.params?.cursor,
1602
+ this.pageSize
1667
1603
  );
1604
+ return {
1605
+ resourceTemplates: result.values,
1606
+ ...result.nextCursor ? { nextCursor: result.nextCursor } : {}
1607
+ };
1608
+ });
1609
+ this.protocol.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
1610
+ const context = await this.contextFactory(extra);
1611
+ return this.registry.readResource(request.params.uri, context, extra);
1612
+ });
1613
+ if (this.capabilities.resources.subscribe) {
1614
+ this.protocol.setRequestHandler(SubscribeRequestSchema, async (request, extra) => {
1615
+ const context = await this.contextFactory(extra);
1616
+ await this.registry.changeSubscription(request.params.uri, true, context, extra);
1617
+ return {};
1618
+ });
1619
+ this.protocol.setRequestHandler(UnsubscribeRequestSchema, async (request, extra) => {
1620
+ const context = await this.contextFactory(extra);
1621
+ await this.registry.changeSubscription(request.params.uri, false, context, extra);
1622
+ return {};
1623
+ });
1668
1624
  }
1669
1625
  }
1670
- if (definition.argumentsSchema !== void 0 && (!definition.argumentsSchema || typeof definition.argumentsSchema !== "object" || Array.isArray(definition.argumentsSchema) || definition.argumentsSchema.type !== "object")) {
1671
- throw new McpFnValidationError(
1672
- `Prompt ${definition.name} argumentsSchema must be an object schema`
1673
- );
1674
- }
1675
- let validateArguments;
1676
- try {
1677
- validateArguments = this.ajv.compile(promptSchema(definition));
1678
- } catch (error) {
1679
- throw new McpFnValidationError(
1680
- `Prompt ${definition.name} contains an invalid arguments JSON Schema`,
1681
- { cause: error instanceof Error ? error.message : String(error) }
1682
- );
1683
- }
1684
- if (definition.argumentsSchema) {
1685
- assertPromptSchemaSupportsStringValues(
1686
- definition.argumentsSchema,
1687
- `Prompt ${definition.name} argumentsSchema`
1688
- );
1689
- }
1690
- const argumentNames = (promptArguments(definition) ?? []).map(({ name }) => name);
1691
- if (new Set(argumentNames).size !== argumentNames.length) {
1692
- throw new McpFnValidationError(`Prompt ${definition.name} has duplicate arguments`);
1693
- }
1694
- if (definition.arguments && definition.argumentsSchema) {
1695
- const declared = definition.arguments.map(({ name, required }) => ({ name, required: required === true })).sort((left, right) => compareCodeUnits(left.name, right.name));
1696
- const schemaDeclared = schemaPromptArguments(definition).map(
1697
- ({ name, required }) => ({ name, required: required === true })
1698
- );
1699
- if (JSON.stringify(declared) !== JSON.stringify(schemaDeclared)) {
1700
- throw new McpFnValidationError(
1701
- `Prompt ${definition.name} arguments and argumentsSchema disagree`
1626
+ if (this.capabilities.prompts) {
1627
+ this.protocol.setRequestHandler(ListPromptsRequestSchema, async (request) => {
1628
+ const result = page(this.registry.listPrompts(), request.params?.cursor, this.pageSize);
1629
+ return {
1630
+ prompts: result.values,
1631
+ ...result.nextCursor ? { nextCursor: result.nextCursor } : {}
1632
+ };
1633
+ });
1634
+ this.protocol.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {
1635
+ const context = await this.contextFactory(extra);
1636
+ return this.registry.getPrompt(
1637
+ request.params.name,
1638
+ request.params.arguments,
1639
+ context,
1640
+ extra
1702
1641
  );
1703
- }
1642
+ });
1704
1643
  }
1705
- for (const name of Object.keys(definition.complete ?? {})) {
1706
- if (!argumentNames.includes(name)) {
1707
- throw new McpFnValidationError(
1708
- `Prompt ${definition.name} has a completer for unknown argument ${name}`
1644
+ if (this.capabilities.completions) {
1645
+ this.protocol.setRequestHandler(CompleteRequestSchema, async (request, extra) => {
1646
+ const context = await this.contextFactory(extra);
1647
+ return this.registry.complete(
1648
+ request.params.ref,
1649
+ request.params.argument,
1650
+ request.params.context?.arguments,
1651
+ context,
1652
+ extra
1709
1653
  );
1710
- }
1654
+ });
1711
1655
  }
1712
- this.prompts.set(definition.name, { definition, validateArguments });
1713
- return this;
1714
1656
  }
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));
1657
+ async filterVisibleTools(tools, context, extra) {
1658
+ if (!this.toolVisibility) return tools;
1659
+ const decisions = await Promise.all(tools.map((tool) => this.toolVisibility({ tool, context, extra })));
1660
+ return tools.filter((_, index) => decisions[index]);
1723
1661
  }
1724
- resourceDefinitions() {
1725
- return [...this.resources.values()].sort((left, right) => compareCodeUnits(left.uri, right.uri));
1662
+ manifest() {
1663
+ return createManifest(this.info, this.registry, this.manifestOptions);
1726
1664
  }
1727
- resourceTemplateDefinitions() {
1728
- return [...this.resourceTemplates.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
1665
+ async connect(transport) {
1666
+ if (this.connected) throw new Error("McpFnServer is already connected to a transport");
1667
+ await this.protocol.connect(transport);
1668
+ this.connected = true;
1729
1669
  }
1730
- promptDefinitions() {
1731
- return [...this.prompts.values()].map(({ definition }) => definition).sort((left, right) => compareCodeUnits(left.name, right.name));
1670
+ async serveStdio() {
1671
+ await this.connect(new StdioServerTransport());
1732
1672
  }
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)
1673
+ async createWebStandardHandler(options = {}) {
1674
+ if (!options.sessionIdGenerator) {
1675
+ return async (request, handleOptions) => {
1676
+ const requestServer = new _McpFnServer(this.serverOptions);
1677
+ const transport = new WebStandardStreamableHTTPServerTransport(options);
1678
+ this.requestServers.add(requestServer);
1679
+ let released = false;
1680
+ const release = async () => {
1681
+ if (released) return;
1682
+ released = true;
1683
+ this.requestServers.delete(requestServer);
1684
+ await requestServer.close();
1685
+ };
1686
+ try {
1687
+ await requestServer.connect(transport);
1688
+ const response = await transport.handleRequest(request, handleOptions);
1689
+ return releaseAfterResponse(response, release);
1690
+ } catch (error) {
1691
+ await release();
1692
+ throw error;
1693
+ }
1740
1694
  };
1741
1695
  }
1742
- if (this.prompts.size) capabilities.prompts = { listChanged: options.listChanged ?? true };
1743
- if ([...this.resourceTemplates.values()].some(({ definition }) => definition.complete) || [...this.prompts.values()].some(({ definition }) => definition.complete)) capabilities.completions = {};
1744
- if (this.definitions().some((definition) => {
1745
- const support = definition.execution?.taskSupport;
1746
- return support === "optional" || support === "required";
1747
- })) capabilities.tasks = { requests: { tools: { call: {} } } };
1748
- return capabilities;
1749
- }
1750
- listTools() {
1751
- return this.definitions().map((definition) => ({
1752
- name: definition.name,
1753
- ...definition.title ? { title: definition.title } : {},
1754
- description: definition.description,
1755
- inputSchema: definition.inputSchema,
1756
- ...definition.outputSchema ? { outputSchema: definition.outputSchema } : {},
1757
- ...definition.annotations ? { annotations: definition.annotations } : {},
1758
- ...definition.execution ? { execution: definition.execution } : {},
1759
- ...definition.icons ? { icons: definition.icons } : {},
1760
- ...definition.metadata ? { _meta: definition.metadata } : {}
1761
- }));
1762
- }
1763
- async listResources(context, extra) {
1764
- const resources = this.resourceDefinitions().map((definition) => ({
1765
- uri: definition.uri,
1766
- name: definition.name,
1767
- ...definition.title ? { title: definition.title } : {},
1768
- ...definition.description ? { description: definition.description } : {},
1769
- ...definition.mimeType ? { mimeType: definition.mimeType } : {},
1770
- ...definition.annotations ? { annotations: definition.annotations } : {},
1771
- ...definition.icons ? { icons: definition.icons } : {},
1772
- ...definition.metadata ? { _meta: definition.metadata } : {}
1773
- }));
1774
- for (const { definition } of this.resourceTemplates.values()) {
1775
- if (definition.list) resources.push(...(await definition.list(context, extra)).resources);
1776
- }
1777
- return resources.sort((left, right) => compareCodeUnits(left.uri, right.uri));
1696
+ const sessions = /* @__PURE__ */ new Map();
1697
+ return async (request, handleOptions) => {
1698
+ const sessionId = request.headers.get("mcp-session-id");
1699
+ if (sessionId) {
1700
+ const session = sessions.get(sessionId);
1701
+ if (!session) {
1702
+ return new Response(JSON.stringify({
1703
+ jsonrpc: "2.0",
1704
+ error: { code: -32001, message: "Session not found" },
1705
+ id: null
1706
+ }), {
1707
+ status: 404,
1708
+ headers: { "content-type": "application/json" }
1709
+ });
1710
+ }
1711
+ return session.transport.handleRequest(request, handleOptions);
1712
+ }
1713
+ const requestServer = new _McpFnServer(this.serverOptions);
1714
+ let initializedSessionId;
1715
+ let released = false;
1716
+ let transport;
1717
+ const release = async () => {
1718
+ if (released) return;
1719
+ released = true;
1720
+ if (initializedSessionId) sessions.delete(initializedSessionId);
1721
+ this.requestServers.delete(requestServer);
1722
+ await requestServer.close();
1723
+ };
1724
+ transport = new WebStandardStreamableHTTPServerTransport({
1725
+ ...options,
1726
+ onsessioninitialized: async (id) => {
1727
+ await options.onsessioninitialized?.(id);
1728
+ initializedSessionId = id;
1729
+ sessions.set(id, { server: requestServer, transport });
1730
+ },
1731
+ onsessionclosed: async (id) => {
1732
+ sessions.delete(id);
1733
+ this.requestServers.delete(requestServer);
1734
+ await options.onsessionclosed?.(id);
1735
+ }
1736
+ });
1737
+ this.requestServers.add(requestServer);
1738
+ try {
1739
+ await requestServer.connect(transport);
1740
+ const response = await transport.handleRequest(request, handleOptions);
1741
+ if (initializedSessionId) return response;
1742
+ return releaseAfterResponse(response, release);
1743
+ } catch (error) {
1744
+ await release();
1745
+ throw error;
1746
+ }
1747
+ };
1778
1748
  }
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
- }));
1749
+ sample(params, options) {
1750
+ return this.protocol.createMessage(params, options);
1790
1751
  }
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
- }));
1752
+ sampleForRequest(extra, params, options) {
1753
+ const schema = params.tools?.length ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
1754
+ return extra.sendRequest(
1755
+ { method: "sampling/createMessage", params },
1756
+ schema,
1757
+ options
1758
+ );
1800
1759
  }
1801
- normalizeAndValidateArgs(registered, args) {
1802
- const normalizedArgs = args ?? {};
1803
- if (!registered.validateInput(normalizedArgs)) {
1804
- return {
1805
- args: normalizedArgs && typeof normalizedArgs === "object" && !Array.isArray(normalizedArgs) ? normalizedArgs : {},
1806
- issues: formatErrors(registered.validateInput.errors)
1807
- };
1808
- }
1809
- return { args: normalizedArgs };
1760
+ elicit(params, options) {
1761
+ return this.protocol.elicitInput(params, options);
1810
1762
  }
1811
- async callTool(name, args, context, extra) {
1812
- const registered = this.tools.get(name);
1813
- if (!registered) throw new McpFnValidationError(`Unknown MCP tool: ${name}`, { name });
1814
- const normalized = this.normalizeAndValidateArgs(registered, args);
1815
- if (normalized.issues) {
1816
- if (registered.definition.handleInvalidArguments) {
1817
- return this.finalizeResult(
1818
- registered,
1819
- await registered.definition.handleInvalidArguments(
1820
- normalized.args,
1821
- normalized.issues,
1822
- context,
1823
- extra
1824
- )
1825
- );
1826
- }
1827
- throw new McpFnValidationError(`Invalid arguments for ${name}`, { issues: normalized.issues });
1828
- }
1829
- return this.finalizeResult(
1830
- registered,
1831
- await registered.definition.handler(normalized.args, context, extra)
1763
+ elicitForRequest(extra, params, options) {
1764
+ return extra.sendRequest(
1765
+ { method: "elicitation/create", params },
1766
+ ElicitResultSchema,
1767
+ options
1832
1768
  );
1833
1769
  }
1834
- taskSupport(name) {
1835
- return this.tools.get(name)?.definition.execution?.taskSupport ?? "forbidden";
1770
+ listRoots(options) {
1771
+ return this.protocol.listRoots(void 0, options);
1836
1772
  }
1837
- async createToolTask(name, args, context, extra) {
1838
- const registered = this.tools.get(name);
1839
- if (!registered) throw new McpFnValidationError(`Unknown MCP tool: ${name}`, { name });
1840
- const normalized = this.normalizeAndValidateArgs(registered, args);
1841
- if (normalized.issues) {
1842
- throw new McpFnValidationError(`Invalid arguments for ${name}`, { issues: normalized.issues });
1843
- }
1844
- if (!registered.definition.taskHandler) {
1845
- throw new McpFnValidationError(`Tool ${name} does not support task execution`);
1846
- }
1847
- const taskStore = new Proxy(extra.taskStore, {
1848
- get: (target, property, receiver) => {
1849
- if (property === "storeTaskResult") {
1850
- return async (taskId, status, result) => target.storeTaskResult(
1851
- taskId,
1852
- status,
1853
- this.finalizeResult(registered, result)
1854
- );
1855
- }
1856
- const value = Reflect.get(target, property, receiver);
1857
- return typeof value === "function" ? value.bind(target) : value;
1858
- }
1859
- });
1860
- return registered.definition.taskHandler.createTask(
1861
- normalized.args,
1862
- context,
1863
- { ...extra, taskStore }
1773
+ listRootsForRequest(extra, options) {
1774
+ return extra.sendRequest(
1775
+ { method: "roots/list" },
1776
+ ListRootsResultSchema,
1777
+ options
1864
1778
  );
1865
1779
  }
1866
- matchResource(uri) {
1867
- const exact = this.resources.get(uri);
1868
- if (exact) return { kind: "resource", definition: exact };
1869
- for (const { definition, template } of this.resourceTemplates.values()) {
1870
- const variables = template.match(uri);
1871
- if (variables) return { kind: "template", definition, variables };
1872
- }
1873
- return void 0;
1780
+ sendLoggingMessage(params, sessionId) {
1781
+ return this.protocol.sendLoggingMessage(params, sessionId);
1874
1782
  }
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);
1783
+ sendResourceUpdated(params) {
1784
+ return this.protocol.sendResourceUpdated(params);
1880
1785
  }
1881
- async changeSubscription(uri, subscribed, context, extra) {
1882
- const match = this.matchResource(uri);
1883
- if (!match) throw new McpFnValidationError(`Unknown MCP resource: ${uri}`);
1884
- const url = new URL(uri);
1885
- if (match.kind === "resource") {
1886
- const callback2 = subscribed ? match.definition.subscribe : match.definition.unsubscribe;
1887
- if (!callback2) {
1888
- throw new McpFnValidationError(
1889
- `Resource ${uri} does not support ${subscribed ? "subscriptions" : "unsubscription"}`
1890
- );
1891
- }
1892
- await callback2(url, context, extra);
1893
- return;
1894
- }
1895
- const callback = subscribed ? match.definition.subscribe : match.definition.unsubscribe;
1896
- if (!callback) {
1897
- throw new McpFnValidationError(
1898
- `Resource ${uri} does not support ${subscribed ? "subscriptions" : "unsubscription"}`
1899
- );
1900
- }
1901
- await callback(url, match.variables, context, extra);
1786
+ sendResourceListChanged() {
1787
+ return this.protocol.sendResourceListChanged();
1902
1788
  }
1903
- async getPrompt(name, args, context, extra) {
1904
- const registered = this.prompts.get(name);
1905
- if (!registered) throw new McpFnValidationError(`Unknown MCP prompt: ${name}`);
1906
- const normalized = args ?? {};
1907
- if (!registered.validateArguments(normalized)) {
1908
- throw new McpFnValidationError(`Invalid arguments for prompt ${name}`, {
1909
- issues: formatErrors(registered.validateArguments.errors)
1910
- });
1911
- }
1912
- return registered.definition.get(normalized, context, extra);
1789
+ sendToolListChanged() {
1790
+ return this.protocol.sendToolListChanged();
1913
1791
  }
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;
1792
+ sendPromptListChanged() {
1793
+ return this.protocol.sendPromptListChanged();
1937
1794
  }
1938
- finalizeResult(registered, result) {
1939
- if (registered.validateOutput && result.isError) {
1940
- const { structuredContent: _omitted, ...errorWithoutStructuredContent } = result;
1941
- return errorWithoutStructuredContent;
1942
- }
1943
- if (registered.validateOutput) {
1944
- if (!result.structuredContent) {
1945
- throw new McpFnOutputValidationError(
1946
- `Tool ${registered.definition.name} declares outputSchema but returned no structuredContent`
1947
- );
1948
- }
1949
- if (!registered.validateOutput(result.structuredContent)) {
1950
- throw new McpFnOutputValidationError(
1951
- `Invalid output from ${registered.definition.name}`,
1952
- { issues: formatErrors(registered.validateOutput.errors) }
1953
- );
1954
- }
1955
- }
1956
- return result;
1795
+ async close() {
1796
+ const requestServers = [...this.requestServers];
1797
+ this.requestServers.clear();
1798
+ await Promise.all(requestServers.map((server) => server.close()));
1799
+ await this.protocol.close();
1800
+ this.connected = false;
1957
1801
  }
1958
1802
  };
1803
+ function createMcpFnServer(options) {
1804
+ return new McpFnServer(options);
1805
+ }
1959
1806
 
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`);
1807
+ // src/declaration.ts
1808
+ function hasDefinitionAdditions(options) {
1809
+ return Boolean(
1810
+ options.tools?.length || options.resources?.length || options.resourceTemplates?.length || options.prompts?.length
1811
+ );
1964
1812
  }
1965
- function assertObject(label, value) {
1966
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1967
- throw new McpFnValidationError(`${label} must be an object`);
1813
+ function cloneRegistry(source) {
1814
+ const clone = new McpFnRegistry();
1815
+ for (const tool of source.definitions()) clone.register(tool);
1816
+ for (const resource of source.resourceDefinitions()) clone.registerResource(resource);
1817
+ for (const template of source.resourceTemplateDefinitions()) {
1818
+ clone.registerResourceTemplate(template);
1968
1819
  }
1820
+ for (const prompt of source.promptDefinitions()) clone.registerPrompt(prompt);
1821
+ return clone;
1969
1822
  }
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)`);
1823
+ var McpFnServerDeclaration = class {
1824
+ info;
1825
+ registry;
1826
+ manifestOptions;
1827
+ constructor(options) {
1828
+ this.info = options.info;
1829
+ this.registry = options.registry && hasDefinitionAdditions(options) ? cloneRegistry(options.registry) : options.registry ?? new McpFnRegistry();
1830
+ for (const tool of options.tools ?? []) this.registry.register(tool);
1831
+ for (const resource of options.resources ?? []) this.registry.registerResource(resource);
1832
+ for (const template of options.resourceTemplates ?? []) {
1833
+ this.registry.registerResourceTemplate(template);
1834
+ }
1835
+ for (const prompt of options.prompts ?? []) this.registry.registerPrompt(prompt);
1836
+ const capabilities = resolveMcpFnServerCapabilities(
1837
+ this.registry,
1838
+ options.capabilities,
1839
+ Boolean(this.registry.capabilities().tasks)
1840
+ );
1841
+ this.manifestOptions = {
1842
+ protocolVersions: options.protocolVersions,
1843
+ transports: options.transports,
1844
+ extensions: options.extensions,
1845
+ capabilities,
1846
+ clientRequirements: options.clientRequirements
1847
+ };
1848
+ }
1849
+ manifest() {
1850
+ return createManifest(this.info, this.registry, this.manifestOptions);
1851
+ }
1852
+ createServer(runtime = {}) {
1853
+ if (Object.hasOwn(runtime, "additionalCapabilities") || Object.hasOwn(runtime, "capabilities")) {
1854
+ throw new Error(
1855
+ "McpFn declaration capabilities must be configured on defineMcpFnServer(), not createServer()"
1856
+ );
1857
+ }
1858
+ return createMcpFnServer({
1859
+ ...runtime,
1860
+ ...this.manifestOptions,
1861
+ info: this.info,
1862
+ registry: this.registry,
1863
+ additionalCapabilities: this.manifestOptions.capabilities
1864
+ });
1973
1865
  }
1866
+ };
1867
+ function defineMcpFnServer(options) {
1868
+ return new McpFnServerDeclaration(options);
1974
1869
  }
1975
- function assertMetadata(label, value) {
1976
- if (value !== void 0) assertObject(label, value);
1870
+
1871
+ // src/diff.ts
1872
+ function push(changes, change) {
1873
+ changes.push(change);
1977
1874
  }
1978
- function assertSortedBy(label, values, select) {
1979
- assertSortedUnique(label, values.map(select));
1875
+ function valueSet(value) {
1876
+ return Array.isArray(value) ? new Set(value.map((entry) => canonicalJson(entry))) : void 0;
1980
1877
  }
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) };
1878
+ function equal(left, right) {
1879
+ return canonicalJson(left) === canonicalJson(right);
2048
1880
  }
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");
1881
+ function schemaTypes(schema) {
1882
+ if (Array.isArray(schema.type)) {
1883
+ return new Set(schema.type.filter((value) => typeof value === "string"));
2054
1884
  }
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");
1885
+ return typeof schema.type === "string" ? /* @__PURE__ */ new Set([schema.type]) : void 0;
1886
+ }
1887
+ function equalSets(left, right) {
1888
+ return left.size === right.size && [...left].every((value) => right.has(value));
1889
+ }
1890
+ function hasUnescapedAlternation(pattern) {
1891
+ let escaped = false;
1892
+ for (const character of pattern) {
1893
+ if (escaped) {
1894
+ escaped = false;
1895
+ continue;
1896
+ }
1897
+ if (character === "\\") {
1898
+ escaped = true;
1899
+ continue;
1900
+ }
1901
+ if (character === "|") return true;
1902
+ }
1903
+ return false;
1904
+ }
1905
+ function anchoredLiteralPrefix(pattern) {
1906
+ if (!pattern.startsWith("^")) return void 0;
1907
+ let prefix = "";
1908
+ for (let index = 1; index < pattern.length; index += 1) {
1909
+ const character = pattern[index];
1910
+ if (character === "\\") {
1911
+ const escaped = pattern[index + 1];
1912
+ if (!escaped || /[A-Za-z0-9]/.test(escaped)) break;
1913
+ prefix += escaped;
1914
+ index += 1;
1915
+ continue;
1916
+ }
1917
+ if (".^$*+?()[]{}|".includes(character)) break;
1918
+ prefix += character;
2059
1919
  }
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`);
1920
+ return prefix || void 0;
1921
+ }
1922
+ function anchoredLiteralSuffix(pattern) {
1923
+ if (!pattern.endsWith("$") || pattern.endsWith("\\$")) return void 0;
1924
+ let suffix = "";
1925
+ for (let index = 0; index < pattern.length - 1; index += 1) {
1926
+ const character = pattern[index];
1927
+ if (character === "\\") {
1928
+ const escaped = pattern[index + 1];
1929
+ if (!escaped) break;
1930
+ suffix = /[A-Za-z0-9]/.test(escaped) ? "" : suffix + escaped;
1931
+ index += 1;
1932
+ continue;
2067
1933
  }
1934
+ suffix = ".^$*+?()[]{}|".includes(character) ? "" : suffix + character;
2068
1935
  }
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");
1936
+ return suffix || void 0;
1937
+ }
1938
+ function patternsMayOverlap(left, right) {
1939
+ if (hasUnescapedAlternation(left) || hasUnescapedAlternation(right)) return true;
1940
+ const leftPrefix = anchoredLiteralPrefix(left);
1941
+ const rightPrefix = anchoredLiteralPrefix(right);
1942
+ if (leftPrefix && rightPrefix && !leftPrefix.startsWith(rightPrefix) && !rightPrefix.startsWith(leftPrefix)) return false;
1943
+ const leftSuffix = anchoredLiteralSuffix(left);
1944
+ const rightSuffix = anchoredLiteralSuffix(right);
1945
+ if (leftSuffix && rightSuffix && !leftSuffix.endsWith(rightSuffix) && !rightSuffix.endsWith(leftSuffix)) return false;
1946
+ return true;
1947
+ }
1948
+ function capabilityRecord(value) {
1949
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1950
+ }
1951
+ function nestedCapabilityChanges(before, after, path) {
1952
+ if (equal(before, after)) return [];
1953
+ if (before === true && after === false) {
1954
+ return [{ severity: "breaking", path, before, after }];
2076
1955
  }
2077
- if (manifest.clientRequirements !== void 0) {
2078
- assertObject("Manifest clientRequirements", manifest.clientRequirements);
2079
- if (manifest.clientRequirements.sampling !== void 0 && typeof manifest.clientRequirements.sampling !== "boolean") throw new McpFnValidationError("Manifest sampling requirement must be a boolean");
2080
- if (manifest.clientRequirements.roots !== void 0 && typeof manifest.clientRequirements.roots !== "boolean") throw new McpFnValidationError("Manifest roots requirement must be a boolean");
2081
- if (manifest.clientRequirements.elicitation !== void 0 && (!Array.isArray(manifest.clientRequirements.elicitation) || manifest.clientRequirements.elicitation.some((mode) => mode !== "form" && mode !== "url"))) throw new McpFnValidationError("Manifest elicitation requirements are invalid");
2082
- if (manifest.clientRequirements.elicitation) {
2083
- assertSortedUnique(
2084
- "Manifest elicitation requirements",
2085
- manifest.clientRequirements.elicitation
2086
- );
2087
- }
1956
+ if (before === false && after === true) {
1957
+ return [{ severity: "additive", path, before, after }];
2088
1958
  }
2089
- assertMetadata("Manifest extensions", manifest.extensions);
2090
- const ajv = new Ajv2({ allErrors: true, strict: false, allowUnionTypes: true });
2091
- addFormats2(ajv);
2092
- for (const tool of manifest.tools) {
2093
- assertObject("Every manifest tool", tool);
2094
- assertName2("Every manifest tool", tool.name);
2095
- if (typeof tool.description !== "string" || !tool.description.trim()) {
2096
- throw new McpFnValidationError(`Manifest tool ${tool.name} requires a description`);
2097
- }
2098
- if (!tool.inputSchema || tool.inputSchema.type !== "object") {
2099
- throw new McpFnValidationError(`Manifest tool ${tool.name} requires an object inputSchema`);
2100
- }
2101
- if (tool.outputSchema !== void 0) {
2102
- assertObject(`Manifest tool ${tool.name} outputSchema`, tool.outputSchema);
2103
- if (tool.outputSchema.type !== "object") {
2104
- throw new McpFnValidationError(`Manifest tool ${tool.name} requires an object outputSchema`);
1959
+ if (capabilityRecord(before) && capabilityRecord(after)) {
1960
+ return [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].sort(compareCodeUnits).flatMap((name) => {
1961
+ const childPath = `${path}.${name}`;
1962
+ const hadBefore = Object.prototype.hasOwnProperty.call(before, name);
1963
+ const hasAfter = Object.prototype.hasOwnProperty.call(after, name);
1964
+ if (!hasAfter) {
1965
+ return [{ severity: "breaking", path: childPath, before: before[name], after: void 0 }];
2105
1966
  }
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
- }
1967
+ if (!hadBefore) {
1968
+ return [{ severity: "additive", path: childPath, before: void 0, after: after[name] }];
1969
+ }
1970
+ return nestedCapabilityChanges(before[name], after[name], childPath);
1971
+ });
2127
1972
  }
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);
1973
+ if (capabilityRecord(before) && after === false) {
1974
+ return [{ severity: "breaking", path, before, after }];
1975
+ }
1976
+ if (before === false && capabilityRecord(after)) {
1977
+ return [{ severity: "additive", path, before, after }];
1978
+ }
1979
+ return [{ severity: "behavioral", path, before, after }];
1980
+ }
1981
+ function matchingPatternSchemas(schema, propertyName) {
1982
+ const patterns = schema.patternProperties;
1983
+ if (!patterns || typeof patterns !== "object" || Array.isArray(patterns)) {
1984
+ return [];
1985
+ }
1986
+ return Object.entries(patterns).filter(([pattern]) => {
2132
1987
  try {
2133
- new URL(resource.uri);
1988
+ return new RegExp(pattern).test(propertyName);
2134
1989
  } 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
- );
1990
+ return false;
2141
1991
  }
2142
- assertMetadata(`Manifest resource ${resource.name} metadata`, resource.metadata);
1992
+ }).map(([, patternSchema]) => patternSchema);
1993
+ }
1994
+ function diffSchema(before, after, path, direction, changes) {
1995
+ if (before && typeof before === "object" && !Object.keys(before).length) before = true;
1996
+ if (after && typeof after === "object" && !Object.keys(after).length) after = true;
1997
+ if (before === void 0 && after !== void 0) {
1998
+ push(changes, {
1999
+ severity: direction === "input" ? "breaking" : "additive",
2000
+ code: "schema-added",
2001
+ path,
2002
+ message: `Schema added at ${path}`,
2003
+ after
2004
+ });
2005
+ return;
2143
2006
  }
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
- );
2007
+ if (before !== void 0 && after === void 0) {
2008
+ push(changes, {
2009
+ severity: direction === "input" ? "additive" : "breaking",
2010
+ code: "schema-removed",
2011
+ path,
2012
+ message: `Schema removed at ${path}`,
2013
+ before
2014
+ });
2015
+ return;
2016
+ }
2017
+ if (before === void 0 || after === void 0 || equal(before, after)) return;
2018
+ if (typeof before === "boolean" || typeof after === "boolean") {
2019
+ const tightened = before === true || after === false;
2020
+ const relaxed = before === false || after === true;
2021
+ const breaking = direction === "input" ? tightened : relaxed;
2022
+ push(changes, {
2023
+ severity: breaking ? "breaking" : "additive",
2024
+ code: "boolean-schema-changed",
2025
+ path,
2026
+ message: `Boolean schema changed at ${path}`,
2027
+ before,
2028
+ after
2029
+ });
2030
+ return;
2031
+ }
2032
+ const beforeTypes = schemaTypes(before);
2033
+ const afterTypes = schemaTypes(after);
2034
+ if (!equal(before.type, after.type) && !(beforeTypes && afterTypes && equalSets(beforeTypes, afterTypes))) {
2035
+ const removed = beforeTypes && afterTypes ? [...beforeTypes].filter((value) => !afterTypes?.has(value)) : [];
2036
+ const added = beforeTypes && afterTypes ? [...afterTypes].filter((value) => !beforeTypes?.has(value)) : [];
2037
+ const tightened = beforeTypes === void 0 ? afterTypes !== void 0 : afterTypes !== void 0 && removed.length > 0;
2038
+ const relaxed = afterTypes === void 0 || added.length > 0;
2039
+ const breaking = direction === "input" ? tightened : relaxed;
2040
+ push(changes, {
2041
+ severity: breaking ? "breaking" : "additive",
2042
+ code: "schema-type-changed",
2043
+ path,
2044
+ message: `Type changed from ${canonicalJson(before.type ?? "unspecified")} to ${canonicalJson(after.type ?? "unspecified")}`,
2045
+ before: before.type,
2046
+ after: after.type
2047
+ });
2048
+ }
2049
+ const beforeEnum = valueSet(before.enum);
2050
+ const afterEnum = valueSet(after.enum);
2051
+ if (!beforeEnum && afterEnum) {
2052
+ push(changes, {
2053
+ severity: direction === "input" ? "breaking" : "additive",
2054
+ code: "enum-introduced",
2055
+ path,
2056
+ message: `An enum constraint was introduced at ${path}`,
2057
+ after: after.enum
2058
+ });
2059
+ } else if (beforeEnum && !afterEnum) {
2060
+ push(changes, {
2061
+ severity: direction === "input" ? "additive" : "breaking",
2062
+ code: "enum-removed",
2063
+ path,
2064
+ message: `The enum constraint was removed at ${path}`,
2065
+ before: before.enum
2066
+ });
2067
+ } else if (beforeEnum && afterEnum) {
2068
+ const removed = [...beforeEnum].filter((entry) => !afterEnum.has(entry));
2069
+ const added = [...afterEnum].filter((entry) => !beforeEnum.has(entry));
2070
+ if (removed.length) {
2071
+ push(changes, {
2072
+ severity: direction === "input" ? "breaking" : "additive",
2073
+ code: "enum-narrowed",
2074
+ path,
2075
+ message: `Allowed values were removed at ${path}`,
2076
+ before: before.enum,
2077
+ after: after.enum
2078
+ });
2159
2079
  }
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
- );
2080
+ if (added.length) {
2081
+ push(changes, {
2082
+ severity: direction === "input" ? "additive" : "breaking",
2083
+ code: "enum-widened",
2084
+ path,
2085
+ message: `Allowed values were added at ${path}`,
2086
+ before: before.enum,
2087
+ after: after.enum
2088
+ });
2167
2089
  }
2168
- if (!template.variableNames.length) {
2169
- throw new McpFnValidationError(
2170
- `Manifest resource template ${resource.name} must contain at least one variable`
2171
- );
2090
+ }
2091
+ const tightening = [
2092
+ ["minimum", "higher"],
2093
+ ["exclusiveMinimum", "higher"],
2094
+ ["minLength", "higher"],
2095
+ ["minItems", "higher"],
2096
+ ["maximum", "lower"],
2097
+ ["exclusiveMaximum", "lower"],
2098
+ ["maxLength", "lower"],
2099
+ ["maxItems", "lower"],
2100
+ ["minProperties", "higher"],
2101
+ ["maxProperties", "lower"]
2102
+ ];
2103
+ for (const [keyword, tightDirection] of tightening) {
2104
+ const oldValue = before[keyword];
2105
+ const newValue = after[keyword];
2106
+ if (equal(oldValue, newValue)) {
2107
+ continue;
2172
2108
  }
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
- );
2109
+ if (oldValue !== void 0 && typeof oldValue !== "number" || newValue !== void 0 && typeof newValue !== "number") {
2110
+ push(changes, {
2111
+ severity: "breaking",
2112
+ code: "schema-keyword-changed",
2113
+ path: `${path}.${keyword}`,
2114
+ message: `${keyword} changed at ${path}`,
2115
+ before: oldValue,
2116
+ after: newValue
2117
+ });
2118
+ continue;
2179
2119
  }
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
- );
2120
+ const tightened = oldValue === void 0 ? true : newValue === void 0 ? false : tightDirection === "higher" ? newValue > oldValue : newValue < oldValue;
2121
+ const breaking = direction === "input" ? tightened : !tightened;
2122
+ push(changes, {
2123
+ severity: breaking ? "breaking" : "additive",
2124
+ code: tightened ? "constraint-tightened" : "constraint-relaxed",
2125
+ path: `${path}.${keyword}`,
2126
+ message: `${keyword} changed from ${oldValue ?? "unspecified"} to ${newValue ?? "unspecified"}`,
2127
+ before: oldValue,
2128
+ after: newValue
2129
+ });
2130
+ }
2131
+ for (const keyword of ["pattern", "format", "const"]) {
2132
+ const oldValue = before[keyword];
2133
+ const newValue = after[keyword];
2134
+ if (equal(oldValue, newValue)) continue;
2135
+ const tightened = oldValue === void 0 && newValue !== void 0;
2136
+ const relaxed = oldValue !== void 0 && newValue === void 0;
2137
+ push(changes, {
2138
+ severity: tightened || relaxed ? (direction === "input" ? tightened : relaxed) ? "breaking" : "additive" : "breaking",
2139
+ code: tightened ? "constraint-tightened" : relaxed ? "constraint-relaxed" : "schema-keyword-changed",
2140
+ path: `${path}.${keyword}`,
2141
+ message: `${keyword} changed at ${path}`,
2142
+ before: oldValue,
2143
+ after: newValue
2144
+ });
2145
+ }
2146
+ const beforeUniqueItems = before.uniqueItems ?? false;
2147
+ const afterUniqueItems = after.uniqueItems ?? false;
2148
+ if (!equal(beforeUniqueItems, afterUniqueItems)) {
2149
+ if (typeof beforeUniqueItems !== "boolean" || typeof afterUniqueItems !== "boolean") {
2150
+ push(changes, {
2151
+ severity: "breaking",
2152
+ code: "schema-keyword-changed",
2153
+ path: `${path}.uniqueItems`,
2154
+ message: `uniqueItems changed at ${path}`,
2155
+ before: before.uniqueItems,
2156
+ after: after.uniqueItems
2157
+ });
2158
+ } else {
2159
+ const tightened = !beforeUniqueItems && afterUniqueItems;
2160
+ const breaking = direction === "input" ? tightened : !tightened;
2161
+ push(changes, {
2162
+ severity: breaking ? "breaking" : "additive",
2163
+ code: tightened ? "constraint-tightened" : "constraint-relaxed",
2164
+ path: `${path}.uniqueItems`,
2165
+ message: `uniqueItems changed from ${beforeUniqueItems} to ${afterUniqueItems}`,
2166
+ before: before.uniqueItems,
2167
+ after: after.uniqueItems
2168
+ });
2185
2169
  }
2186
- assertMetadata(`Manifest resource template ${resource.name} metadata`, resource.metadata);
2187
2170
  }
2188
- assertSortedBy(
2189
- "Manifest resource template names",
2190
- manifest.resourceTemplates ?? [],
2191
- (resource) => resource.name
2171
+ const normalizeAdditionalProperties = (value) => value && typeof value === "object" && !Array.isArray(value) && !Object.keys(value).length ? true : value;
2172
+ const beforeAdditional = normalizeAdditionalProperties(before.additionalProperties ?? true);
2173
+ const afterAdditional = normalizeAdditionalProperties(after.additionalProperties ?? true);
2174
+ if (beforeAdditional !== false && afterAdditional === false) {
2175
+ push(changes, {
2176
+ severity: direction === "input" ? "breaking" : "additive",
2177
+ code: "additional-properties-disabled",
2178
+ path,
2179
+ message: `Additional properties are no longer accepted at ${path}`
2180
+ });
2181
+ } else if (beforeAdditional === false && afterAdditional !== false) {
2182
+ push(changes, {
2183
+ severity: direction === "input" ? "additive" : "breaking",
2184
+ code: "additional-properties-enabled",
2185
+ path,
2186
+ message: `Additional properties are now accepted at ${path}`
2187
+ });
2188
+ } else if (!equal(beforeAdditional, afterAdditional)) {
2189
+ diffSchema(
2190
+ beforeAdditional,
2191
+ afterAdditional,
2192
+ `${path}.additionalProperties`,
2193
+ direction,
2194
+ changes
2195
+ );
2196
+ }
2197
+ const beforeProperties = before.properties ?? {};
2198
+ const afterProperties = after.properties ?? {};
2199
+ const propertyNames = [.../* @__PURE__ */ new Set([
2200
+ ...Object.keys(beforeProperties),
2201
+ ...Object.keys(afterProperties),
2202
+ ...Array.isArray(before.required) ? before.required : [],
2203
+ ...Array.isArray(after.required) ? after.required : []
2204
+ ])].sort();
2205
+ const beforeRequired = new Set(
2206
+ Array.isArray(before.required) ? before.required : []
2192
2207
  );
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`
2208
+ const afterRequired = new Set(
2209
+ Array.isArray(after.required) ? after.required : []
2210
+ );
2211
+ for (const name of propertyNames) {
2212
+ const propertyPath = `${path}.properties.${name}`;
2213
+ const oldProperty = beforeProperties[name];
2214
+ const newProperty = afterProperties[name];
2215
+ const hadOldProperty = Object.prototype.hasOwnProperty.call(beforeProperties, name);
2216
+ const hasNewProperty = Object.prototype.hasOwnProperty.call(afterProperties, name);
2217
+ if (!hadOldProperty && hasNewProperty) {
2218
+ const newlyRequired = afterRequired.has(name);
2219
+ const additionalPropertyChanges = [];
2220
+ if (direction === "output" && typeof beforeAdditional === "object") {
2221
+ diffSchema(
2222
+ beforeAdditional,
2223
+ newProperty,
2224
+ `${propertyPath}.additionalProperties`,
2225
+ "output",
2226
+ additionalPropertyChanges
2207
2227
  );
2208
2228
  }
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`
2229
+ const inputFallbackChanges = [];
2230
+ if (direction === "input") {
2231
+ const patternSchemas = matchingPatternSchemas(before, name);
2232
+ const fallbackSchemas = patternSchemas.length ? patternSchemas : [beforeAdditional];
2233
+ fallbackSchemas.forEach((fallbackSchema, index) => diffSchema(
2234
+ fallbackSchema,
2235
+ newProperty,
2236
+ `${propertyPath}.${patternSchemas.length ? `patternProperties.${index}` : "additionalProperties"}`,
2237
+ "input",
2238
+ inputFallbackChanges
2239
+ ));
2240
+ }
2241
+ const breaksDeclaredOutput = direction === "output" && (beforeAdditional === false || additionalPropertyChanges.some((change) => change.severity === "breaking"));
2242
+ const narrowsAcceptedInput = direction === "input" && inputFallbackChanges.some((change) => change.severity === "breaking");
2243
+ push(changes, {
2244
+ severity: direction === "input" && (newlyRequired || narrowsAcceptedInput) || breaksDeclaredOutput ? "breaking" : "additive",
2245
+ code: direction === "input" && newlyRequired ? "required-input-added" : breaksDeclaredOutput ? "output-property-added" : "property-added",
2246
+ path: propertyPath,
2247
+ message: `${newlyRequired ? "Required" : "Optional"} property ${name} was added`,
2248
+ after: newProperty
2249
+ });
2250
+ continue;
2251
+ }
2252
+ if (hadOldProperty && !hasNewProperty) {
2253
+ const fallbackChanges = [];
2254
+ const patternSchemas = matchingPatternSchemas(after, name);
2255
+ const fallbackSchemas = patternSchemas.length ? patternSchemas : [afterAdditional];
2256
+ fallbackSchemas.forEach((fallbackSchema, index) => diffSchema(
2257
+ oldProperty,
2258
+ fallbackSchema,
2259
+ `${propertyPath}.${patternSchemas.length ? `patternProperties.${index}` : "additionalProperties"}`,
2260
+ direction,
2261
+ fallbackChanges
2262
+ ));
2263
+ const breaking2 = direction === "output" && beforeRequired.has(name) || fallbackChanges.some((change) => change.severity === "breaking");
2264
+ push(changes, {
2265
+ severity: breaking2 ? "breaking" : "additive",
2266
+ code: "property-removed",
2267
+ path: propertyPath,
2268
+ message: `Property ${name} was removed`,
2269
+ before: oldProperty
2270
+ });
2271
+ continue;
2272
+ }
2273
+ diffSchema(oldProperty, newProperty, propertyPath, direction, changes);
2274
+ const wasRequired = beforeRequired.has(name);
2275
+ const isRequired = afterRequired.has(name);
2276
+ if (wasRequired === isRequired) continue;
2277
+ const breaking = direction === "input" ? !wasRequired && isRequired : wasRequired && !isRequired;
2278
+ push(changes, {
2279
+ severity: breaking ? "breaking" : "additive",
2280
+ code: breaking ? "requiredness-broken" : "requiredness-compatible",
2281
+ path: propertyPath,
2282
+ message: `Property ${name} changed from ${wasRequired ? "required" : "optional"} to ${isRequired ? "required" : "optional"}`
2283
+ });
2284
+ }
2285
+ if (before.items !== void 0 || after.items !== void 0) {
2286
+ diffSchema(
2287
+ before.items,
2288
+ after.items,
2289
+ `${path}.items`,
2290
+ direction,
2291
+ changes
2292
+ );
2293
+ }
2294
+ const beforePatterns = before.patternProperties ?? {};
2295
+ const afterPatterns = after.patternProperties ?? {};
2296
+ const patternNames = [.../* @__PURE__ */ new Set([
2297
+ ...Object.keys(beforePatterns),
2298
+ ...Object.keys(afterPatterns)
2299
+ ])].sort();
2300
+ for (const pattern of patternNames) {
2301
+ const hadBeforePattern = Object.prototype.hasOwnProperty.call(beforePatterns, pattern);
2302
+ const hasAfterPattern = Object.prototype.hasOwnProperty.call(afterPatterns, pattern);
2303
+ diffSchema(
2304
+ hadBeforePattern ? beforePatterns[pattern] : beforeAdditional,
2305
+ hasAfterPattern ? afterPatterns[pattern] : afterAdditional,
2306
+ `${path}.patternProperties.${pattern}`,
2307
+ direction,
2308
+ changes
2309
+ );
2310
+ const overlapChanges = [];
2311
+ if (direction === "input" && !hadBeforePattern && hasAfterPattern) {
2312
+ for (const [existingPattern, existingSchema] of Object.entries(beforePatterns)) {
2313
+ if (!patternsMayOverlap(existingPattern, pattern)) continue;
2314
+ diffSchema(
2315
+ existingSchema,
2316
+ afterPatterns[pattern],
2317
+ `${path}.patternProperties.${pattern}.overlap.${existingPattern}`,
2318
+ "input",
2319
+ overlapChanges
2212
2320
  );
2213
2321
  }
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
2322
  }
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 })
2323
+ if (direction === "output" && hadBeforePattern && !hasAfterPattern) {
2324
+ for (const [remainingPattern, remainingSchema] of Object.entries(afterPatterns)) {
2325
+ if (!patternsMayOverlap(pattern, remainingPattern)) continue;
2326
+ diffSchema(
2327
+ beforePatterns[pattern],
2328
+ remainingSchema,
2329
+ `${path}.patternProperties.${pattern}.overlap.${remainingPattern}`,
2330
+ "output",
2331
+ overlapChanges
2241
2332
  );
2242
- if (JSON.stringify(declared) !== JSON.stringify(schemaDeclared)) {
2243
- throw new McpFnValidationError(
2244
- `Manifest prompt ${prompt.name} arguments and argumentsSchema disagree`
2245
- );
2246
- }
2247
2333
  }
2248
2334
  }
2335
+ if (overlapChanges.some((change) => change.severity === "breaking")) {
2336
+ push(changes, {
2337
+ severity: "breaking",
2338
+ code: "overlapping-pattern-constraint-changed",
2339
+ path: `${path}.patternProperties.${pattern}`,
2340
+ message: `${hadBeforePattern ? "Removing" : "Adding"} pattern ${pattern} can change constraints for properties matched by another pattern`,
2341
+ before: hadBeforePattern ? beforePatterns[pattern] : void 0,
2342
+ after: hasAfterPattern ? afterPatterns[pattern] : void 0
2343
+ });
2344
+ }
2249
2345
  }
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
2346
+ const handledKeywords = /* @__PURE__ */ new Set([
2347
+ "type",
2348
+ "enum",
2349
+ "properties",
2350
+ "required",
2351
+ "items",
2352
+ "additionalProperties",
2353
+ "patternProperties",
2354
+ "pattern",
2355
+ "format",
2356
+ "const",
2357
+ "uniqueItems",
2358
+ ...tightening.map(([keyword]) => keyword)
2359
+ ]);
2360
+ const behavioralKeywords = /* @__PURE__ */ new Set([
2361
+ "$comment",
2362
+ "$id",
2363
+ "$schema",
2364
+ "default",
2365
+ "deprecated",
2366
+ "description",
2367
+ "examples",
2368
+ "readOnly",
2369
+ "title",
2370
+ "writeOnly"
2371
+ ]);
2372
+ const keywords = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].sort();
2373
+ for (const keyword of keywords) {
2374
+ if (handledKeywords.has(keyword) || equal(before[keyword], after[keyword])) continue;
2375
+ const behavioral = behavioralKeywords.has(keyword) || /^x-/i.test(keyword);
2376
+ push(changes, {
2377
+ severity: behavioral ? "behavioral" : "breaking",
2378
+ code: behavioral ? "schema-guidance-changed" : "schema-keyword-changed",
2379
+ path: `${path}.${keyword}`,
2380
+ message: `${keyword} changed at ${path}`,
2381
+ before: before[keyword],
2382
+ after: after[keyword]
2260
2383
  });
2261
2384
  }
2262
- return manifest;
2263
- }
2264
-
2265
- // src/results.ts
2266
- function textResult(text) {
2267
- return { content: [{ type: "text", text }] };
2268
2385
  }
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
- );
2386
+ function diffTool(before, after, changes) {
2387
+ const root = `tools.${before.name}`;
2388
+ if (before.title !== after.title) {
2389
+ push(changes, {
2390
+ severity: "behavioral",
2391
+ code: "tool-title-changed",
2392
+ path: `${root}.title`,
2393
+ message: `Tool title changed for ${before.name}`,
2394
+ before: before.title,
2395
+ after: after.title
2396
+ });
2275
2397
  }
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
- }
2398
+ if (before.description !== after.description) {
2399
+ push(changes, {
2400
+ severity: "behavioral",
2401
+ code: "tool-description-changed",
2402
+ path: `${root}.description`,
2403
+ message: `Tool description changed for ${before.name}`,
2404
+ before: before.description,
2405
+ after: after.description
2406
+ });
2317
2407
  }
2318
- return merged;
2408
+ if (!equal(before.annotations ?? {}, after.annotations ?? {})) {
2409
+ push(changes, {
2410
+ severity: "behavioral",
2411
+ code: "tool-annotations-changed",
2412
+ path: `${root}.annotations`,
2413
+ message: `Tool annotations changed for ${before.name}`,
2414
+ before: before.annotations,
2415
+ after: after.annotations
2416
+ });
2417
+ }
2418
+ if (!equal(before.execution ?? {}, after.execution ?? {})) {
2419
+ const oldSupport = before.execution?.taskSupport ?? "forbidden";
2420
+ const newSupport = after.execution?.taskSupport ?? "forbidden";
2421
+ const breaking = newSupport === "required" || oldSupport !== "forbidden" && newSupport === "forbidden";
2422
+ push(changes, {
2423
+ severity: breaking ? "breaking" : "additive",
2424
+ code: "tool-task-support-changed",
2425
+ path: `${root}.execution.taskSupport`,
2426
+ message: `Tool task support changed from ${oldSupport} to ${newSupport}`,
2427
+ before: oldSupport,
2428
+ after: newSupport
2429
+ });
2430
+ }
2431
+ if (!equal(before.icons ?? [], after.icons ?? [])) {
2432
+ push(changes, {
2433
+ severity: "behavioral",
2434
+ code: "tool-icons-changed",
2435
+ path: `${root}.icons`,
2436
+ message: `Tool icons changed for ${before.name}`,
2437
+ before: before.icons,
2438
+ after: after.icons
2439
+ });
2440
+ }
2441
+ if (!equal(before.metadata ?? {}, after.metadata ?? {})) {
2442
+ push(changes, {
2443
+ severity: "behavioral",
2444
+ code: "tool-metadata-changed",
2445
+ path: `${root}.metadata`,
2446
+ message: `Tool metadata changed for ${before.name}`,
2447
+ before: before.metadata,
2448
+ after: after.metadata
2449
+ });
2450
+ }
2451
+ diffSchema(before.inputSchema, after.inputSchema, `${root}.inputSchema`, "input", changes);
2452
+ diffSchema(before.outputSchema, after.outputSchema, `${root}.outputSchema`, "output", changes);
2319
2453
  }
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");
2454
+ function diffResource(before, after, changes) {
2455
+ const root = `resources.${before.uri}`;
2456
+ if ((before.subscribable ?? false) !== (after.subscribable ?? false)) {
2457
+ const enabled = after.subscribable === true;
2458
+ push(changes, {
2459
+ severity: enabled ? "additive" : "breaking",
2460
+ code: enabled ? "resource-subscription-enabled" : "resource-subscription-removed",
2461
+ path: `${root}.subscribable`,
2462
+ message: `Resource subscription support was ${enabled ? "enabled" : "removed"} for ${before.uri}`,
2463
+ before: before.subscribable,
2464
+ after: after.subscribable
2465
+ });
2466
+ }
2467
+ if (before.mimeType !== after.mimeType) {
2468
+ push(changes, {
2469
+ severity: "breaking",
2470
+ code: "resource-mime-type-changed",
2471
+ path: `${root}.mimeType`,
2472
+ message: `Resource MIME type changed for ${before.uri}`,
2473
+ before: before.mimeType,
2474
+ after: after.mimeType
2475
+ });
2476
+ }
2477
+ for (const key of ["name", "title", "description", "annotations", "icons", "metadata"]) {
2478
+ if (!equal(before[key], after[key])) {
2479
+ push(changes, {
2480
+ severity: "behavioral",
2481
+ code: `resource-${key}-changed`,
2482
+ path: `${root}.${key}`,
2483
+ message: `Resource ${key} changed for ${before.uri}`,
2484
+ before: before[key],
2485
+ after: after[key]
2486
+ });
2328
2487
  }
2329
2488
  }
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
2489
  }
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();
2490
+ function diffResourceTemplate(before, after, changes) {
2491
+ const root = `resourceTemplates.${before.name}`;
2492
+ if ((before.subscribable ?? false) !== (after.subscribable ?? false)) {
2493
+ const enabled = after.subscribable === true;
2494
+ push(changes, {
2495
+ severity: enabled ? "additive" : "breaking",
2496
+ code: enabled ? "resource-template-subscription-enabled" : "resource-template-subscription-removed",
2497
+ path: `${root}.subscribable`,
2498
+ message: `Resource template subscription support was ${enabled ? "enabled" : "removed"} for ${before.name}`,
2499
+ before: before.subscribable,
2500
+ after: after.subscribable
2501
+ });
2394
2502
  }
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
- }
2503
+ if (before.uriTemplate !== after.uriTemplate) {
2504
+ push(changes, {
2505
+ severity: "breaking",
2506
+ code: "resource-template-uri-changed",
2507
+ path: `${root}.uriTemplate`,
2508
+ message: `Resource template URI changed for ${before.name}`,
2509
+ before: before.uriTemplate,
2510
+ after: after.uriTemplate
2511
+ });
2512
+ }
2513
+ if (before.mimeType !== after.mimeType) {
2514
+ push(changes, {
2515
+ severity: "breaking",
2516
+ code: "resource-template-mime-type-changed",
2517
+ path: `${root}.mimeType`,
2518
+ message: `Resource template MIME type changed for ${before.name}`,
2519
+ before: before.mimeType,
2520
+ after: after.mimeType
2521
+ });
2522
+ }
2523
+ for (const key of ["title", "description", "annotations", "icons", "metadata"]) {
2524
+ if (!equal(before[key], after[key])) {
2525
+ push(changes, {
2526
+ severity: "behavioral",
2527
+ code: `resource-template-${key}-changed`,
2528
+ path: `${root}.${key}`,
2529
+ message: `Resource template ${key} changed for ${before.name}`,
2530
+ before: before[key],
2531
+ after: after[key]
2445
2532
  });
2446
2533
  }
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);
2534
+ }
2535
+ }
2536
+ function promptArgumentSchema(prompt) {
2537
+ if (prompt.argumentsSchema) return prompt.argumentsSchema;
2538
+ return {
2539
+ type: "object",
2540
+ properties: Object.fromEntries(
2541
+ (prompt.arguments ?? []).map((argument) => [argument.name, { type: "string" }])
2542
+ ),
2543
+ required: (prompt.arguments ?? []).filter((argument) => argument.required).map((argument) => argument.name),
2544
+ additionalProperties: false
2545
+ };
2546
+ }
2547
+ function diffPrompt(before, after, changes) {
2548
+ const root = `prompts.${before.name}`;
2549
+ for (const key of ["title", "description", "icons", "metadata"]) {
2550
+ if (!equal(before[key], after[key])) {
2551
+ push(changes, {
2552
+ severity: "behavioral",
2553
+ code: `prompt-${key}-changed`,
2554
+ path: `${root}.${key}`,
2555
+ message: `Prompt ${key} changed for ${before.name}`,
2556
+ before: before[key],
2557
+ after: after[key]
2474
2558
  });
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
2559
  }
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
- );
2560
+ }
2561
+ diffSchema(
2562
+ promptArgumentSchema(before),
2563
+ promptArgumentSchema(after),
2564
+ `${root}.arguments`,
2565
+ "input",
2566
+ changes
2567
+ );
2568
+ if (!equal(before.arguments ?? [], after.arguments ?? [])) {
2569
+ push(changes, {
2570
+ severity: "behavioral",
2571
+ code: "prompt-arguments-changed",
2572
+ path: `${root}.argumentsMetadata`,
2573
+ message: `Prompt argument metadata changed for ${before.name}`,
2574
+ before: before.arguments,
2575
+ after: after.arguments
2576
+ });
2577
+ }
2578
+ }
2579
+ function requirementValues(value) {
2580
+ if (value === true) return /* @__PURE__ */ new Set(["true"]);
2581
+ if (Array.isArray(value)) return new Set(value.map((entry) => canonicalJson(entry)));
2582
+ return /* @__PURE__ */ new Set();
2583
+ }
2584
+ function extensionRequired(value) {
2585
+ return Boolean(value && typeof value === "object" && !Array.isArray(value) && value.required === true);
2586
+ }
2587
+ function diffCollection(label, before, after, key, compare, changes) {
2588
+ const beforeValues = new Map(before.map((value) => [key(value), value]));
2589
+ const afterValues = new Map(after.map((value) => [key(value), value]));
2590
+ for (const name of [...beforeValues.keys()].sort()) {
2591
+ const next = afterValues.get(name);
2592
+ if (!next) {
2593
+ push(changes, {
2594
+ severity: "breaking",
2595
+ code: `${label}-removed`,
2596
+ path: `${label}.${name}`,
2597
+ message: `${label} ${name} was removed`,
2598
+ before: beforeValues.get(name)
2504
2599
  });
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
- );
2600
+ } else compare(beforeValues.get(name), next, changes);
2601
+ }
2602
+ for (const name of [...afterValues.keys()].sort()) {
2603
+ if (!beforeValues.has(name)) {
2604
+ push(changes, {
2605
+ severity: "additive",
2606
+ code: `${label}-added`,
2607
+ path: `${label}.${name}`,
2608
+ message: `${label} ${name} was added`,
2609
+ after: afterValues.get(name)
2516
2610
  });
2517
2611
  }
2518
2612
  }
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);
2613
+ }
2614
+ function diffManifests(before, after) {
2615
+ const changes = [];
2616
+ if (before.server.name !== after.server.name) {
2617
+ push(changes, {
2618
+ severity: "breaking",
2619
+ code: "server-name-changed",
2620
+ path: "server.name",
2621
+ message: `Server name changed from ${before.server.name} to ${after.server.name}`,
2622
+ before: before.server.name,
2623
+ after: after.server.name
2624
+ });
2539
2625
  }
2540
- sample(params, options) {
2541
- return this.protocol.createMessage(params, options);
2626
+ if (before.server.instructions !== after.server.instructions) {
2627
+ push(changes, {
2628
+ severity: "behavioral",
2629
+ code: "server-instructions-changed",
2630
+ path: "server.instructions",
2631
+ message: "Server instructions changed",
2632
+ before: before.server.instructions,
2633
+ after: after.server.instructions
2634
+ });
2542
2635
  }
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
- );
2636
+ const beforeTools = new Map(before.tools.map((tool) => [tool.name, tool]));
2637
+ const afterTools = new Map(after.tools.map((tool) => [tool.name, tool]));
2638
+ for (const name of [...beforeTools.keys()].sort()) {
2639
+ const oldTool = beforeTools.get(name);
2640
+ const newTool = afterTools.get(name);
2641
+ if (!newTool) {
2642
+ push(changes, {
2643
+ severity: "breaking",
2644
+ code: "tool-removed",
2645
+ path: `tools.${name}`,
2646
+ message: `Tool ${name} was removed`,
2647
+ before: oldTool
2648
+ });
2649
+ } else {
2650
+ diffTool(oldTool, newTool, changes);
2651
+ }
2550
2652
  }
2551
- elicit(params, options) {
2552
- return this.protocol.elicitInput(params, options);
2653
+ for (const name of [...afterTools.keys()].sort()) {
2654
+ if (!beforeTools.has(name)) {
2655
+ push(changes, {
2656
+ severity: "additive",
2657
+ code: "tool-added",
2658
+ path: `tools.${name}`,
2659
+ message: `Tool ${name} was added`,
2660
+ after: afterTools.get(name)
2661
+ });
2662
+ }
2553
2663
  }
2554
- elicitForRequest(extra, params, options) {
2555
- return extra.sendRequest(
2556
- { method: "elicitation/create", params },
2557
- ElicitResultSchema,
2558
- options
2559
- );
2664
+ diffCollection(
2665
+ "resources",
2666
+ before.resources ?? [],
2667
+ after.resources ?? [],
2668
+ (resource) => resource.uri,
2669
+ diffResource,
2670
+ changes
2671
+ );
2672
+ diffCollection(
2673
+ "resourceTemplates",
2674
+ before.resourceTemplates ?? [],
2675
+ after.resourceTemplates ?? [],
2676
+ (resource) => resource.name,
2677
+ diffResourceTemplate,
2678
+ changes
2679
+ );
2680
+ diffCollection(
2681
+ "prompts",
2682
+ before.prompts ?? [],
2683
+ after.prompts ?? [],
2684
+ (prompt) => prompt.name,
2685
+ diffPrompt,
2686
+ changes
2687
+ );
2688
+ for (const key of ["capabilities", "clientRequirements", "extensions"]) {
2689
+ const oldRecord = before[key] ?? {};
2690
+ const newRecord = after[key] ?? {};
2691
+ for (const name of [.../* @__PURE__ */ new Set([...Object.keys(oldRecord), ...Object.keys(newRecord)])].sort()) {
2692
+ if (equal(oldRecord[name], newRecord[name])) continue;
2693
+ const removed = oldRecord[name] !== void 0 && newRecord[name] === void 0;
2694
+ const added = oldRecord[name] === void 0 && newRecord[name] !== void 0;
2695
+ const requirementChanged = key === "clientRequirements";
2696
+ const oldRequiredValues = requirementValues(oldRecord[name]);
2697
+ const newRequiredValues = requirementValues(newRecord[name]);
2698
+ const requirementAdded = [...newRequiredValues].some((value) => !oldRequiredValues.has(value));
2699
+ const requirementRemoved = [...oldRequiredValues].some((value) => !newRequiredValues.has(value));
2700
+ if (requirementChanged && !requirementAdded && !requirementRemoved) continue;
2701
+ const extensionWasRequired = key === "extensions" && extensionRequired(oldRecord[name]);
2702
+ const extensionIsRequired = key === "extensions" && extensionRequired(newRecord[name]);
2703
+ const capabilityChanges = key === "capabilities" && !removed && !added ? nestedCapabilityChanges(oldRecord[name], newRecord[name], `${key}.${name}`) : [];
2704
+ if (capabilityChanges.length) {
2705
+ for (const capabilityChange of capabilityChanges) {
2706
+ const action = capabilityChange.severity === "breaking" ? "removed" : capabilityChange.severity === "additive" ? "added" : "changed";
2707
+ push(changes, {
2708
+ severity: capabilityChange.severity,
2709
+ code: `capability-support-${action}`,
2710
+ path: capabilityChange.path,
2711
+ message: `Capability support was ${action} at ${capabilityChange.path}`,
2712
+ before: capabilityChange.before,
2713
+ after: capabilityChange.after
2714
+ });
2715
+ }
2716
+ continue;
2717
+ }
2718
+ push(changes, {
2719
+ severity: requirementChanged && requirementAdded ? "breaking" : requirementChanged && requirementRemoved ? "additive" : key === "extensions" && !extensionWasRequired && extensionIsRequired ? "breaking" : key === "extensions" && extensionWasRequired && !extensionIsRequired ? "additive" : removed ? "breaking" : added ? "additive" : "behavioral",
2720
+ code: `${key}-${removed ? "removed" : added ? "added" : "changed"}`,
2721
+ path: `${key}.${name}`,
2722
+ message: `${key} ${name} was ${removed ? "removed" : added ? "added" : "changed"}`,
2723
+ before: oldRecord[name],
2724
+ after: newRecord[name]
2725
+ });
2726
+ }
2560
2727
  }
2561
- listRoots(options) {
2562
- return this.protocol.listRoots(void 0, options);
2728
+ for (const key of ["protocolVersions", "transports"]) {
2729
+ const oldValues = new Set(before[key] ?? []);
2730
+ const newValues = new Set(after[key] ?? []);
2731
+ for (const value of [...oldValues].sort()) {
2732
+ if (!newValues.has(value)) {
2733
+ push(changes, {
2734
+ severity: "breaking",
2735
+ code: `${key}-support-removed`,
2736
+ path: key,
2737
+ message: `${key} support removed: ${value}`,
2738
+ before: value
2739
+ });
2740
+ }
2741
+ }
2742
+ for (const value of [...newValues].sort()) {
2743
+ if (!oldValues.has(value)) {
2744
+ push(changes, {
2745
+ severity: "additive",
2746
+ code: `${key}-support-added`,
2747
+ path: key,
2748
+ message: `${key} support added: ${value}`,
2749
+ after: value
2750
+ });
2751
+ }
2752
+ }
2563
2753
  }
2564
- listRootsForRequest(extra, options) {
2565
- return extra.sendRequest(
2566
- { method: "roots/list" },
2567
- ListRootsResultSchema,
2568
- options
2754
+ changes.sort(
2755
+ (left, right) => compareCodeUnits(left.path, right.path) || compareCodeUnits(left.code, right.code)
2756
+ );
2757
+ const summary = {
2758
+ breaking: changes.filter((change) => change.severity === "breaking").length,
2759
+ additive: changes.filter((change) => change.severity === "additive").length,
2760
+ behavioral: changes.filter((change) => change.severity === "behavioral").length
2761
+ };
2762
+ return { compatible: summary.breaking === 0, changes, summary };
2763
+ }
2764
+
2765
+ // src/results.ts
2766
+ function textResult(text) {
2767
+ return { content: [{ type: "text", text }] };
2768
+ }
2769
+ function structuredResult(structuredContent, content) {
2770
+ const normalized = jsonSafe(structuredContent);
2771
+ if (!normalized || typeof normalized !== "object" || Array.isArray(normalized)) {
2772
+ throw new McpFnOutputValidationError(
2773
+ "structuredContent must serialize to an object"
2569
2774
  );
2570
2775
  }
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);
2776
+ return {
2777
+ content: content ?? [
2778
+ { type: "text", text: JSON.stringify(normalized, null, 2) }
2779
+ ],
2780
+ structuredContent: normalized
2781
+ };
2593
2782
  }
2594
2783
  export {
2595
2784
  MCP_APP_EXTENSION_ID,
@@ -2598,6 +2787,7 @@ export {
2598
2787
  McpFnOutputValidationError,
2599
2788
  McpFnRegistry,
2600
2789
  McpFnServer,
2790
+ McpFnServerDeclaration,
2601
2791
  McpFnValidationError,
2602
2792
  assertMcpAppContracts,
2603
2793
  assertPromptSchemaSupportsStringValues,
@@ -2607,11 +2797,13 @@ export {
2607
2797
  createManifest,
2608
2798
  createMcpAppResource,
2609
2799
  createMcpFnServer,
2800
+ defineMcpFnServer,
2610
2801
  diffManifests,
2611
2802
  errorResult,
2612
2803
  jsonSafe,
2613
2804
  mcpAppToolMetadata,
2614
2805
  promptArguments,
2806
+ resolveMcpFnServerCapabilities,
2615
2807
  schemaPromptArguments,
2616
2808
  sha256,
2617
2809
  structuredResult,