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