@dudko.dev/agent-web 0.0.40 → 0.0.41
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 +301 -22
- package/dist/agent-web.js +169 -161
- package/dist/agent-web.js.map +1 -1
- package/dist/chunk-4FBTBE74.js +510 -0
- package/dist/chunk-4FBTBE74.js.map +1 -0
- package/dist/{chunk-TZITKUFW.js → chunk-L7Y3QRAM.js} +152 -20
- package/dist/chunk-L7Y3QRAM.js.map +1 -0
- package/dist/{chunk-V3JOK7EW.js → chunk-YPCHD6DV.js} +4 -2
- package/dist/chunk-YPCHD6DV.js.map +1 -0
- package/dist/chunk-YUA2BHRM.js +584 -0
- package/dist/chunk-YUA2BHRM.js.map +1 -0
- package/dist/elicitation-BA1knkdA.d.cts +566 -0
- package/dist/elicitation-BA1knkdA.d.ts +566 -0
- package/dist/index.cjs +1813 -221
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +690 -117
- package/dist/index.d.ts +690 -117
- package/dist/index.js +1275 -185
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +2135 -49
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +285 -9
- package/dist/mcp.d.ts +285 -9
- package/dist/mcp.js +1573 -48
- package/dist/mcp.js.map +1 -1
- package/dist/{sandbox-KG6OUG24.js → sandbox-ZDQIIZS7.js} +21 -8
- package/dist/sandbox-ZDQIIZS7.js.map +1 -0
- package/dist/sandbox-worker.cjs +3 -1
- package/dist/sandbox-worker.cjs.map +1 -1
- package/dist/sandbox-worker.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-A6ZJALLU.js +0 -254
- package/dist/chunk-A6ZJALLU.js.map +0 -1
- package/dist/chunk-CTXDKSDD.js +0 -39
- package/dist/chunk-CTXDKSDD.js.map +0 -1
- package/dist/chunk-TZITKUFW.js.map +0 -1
- package/dist/chunk-V3JOK7EW.js.map +0 -1
- package/dist/sandbox-KG6OUG24.js.map +0 -1
- package/dist/vault-BatBaRQP.d.cts +0 -36
- package/dist/vault-BatBaRQP.d.ts +0 -36
package/dist/mcp.js
CHANGED
|
@@ -1,28 +1,970 @@
|
|
|
1
1
|
import {
|
|
2
2
|
IndexedDBVault,
|
|
3
|
+
MCP_APPS_EXTENSION,
|
|
4
|
+
MCP_APP_DEFAULT_VISIBILITY,
|
|
5
|
+
MCP_APP_MAX_DOMAINS,
|
|
6
|
+
MCP_APP_MAX_DOWNLOAD_BYTES,
|
|
7
|
+
MCP_APP_MAX_HTML_CHARS,
|
|
8
|
+
MCP_APP_MAX_RESULT_CHARS,
|
|
9
|
+
MCP_APP_MIME_TYPE,
|
|
3
10
|
MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER,
|
|
4
11
|
MCP_INSTRUCTIONS_MAX_CHARS_TOTAL,
|
|
12
|
+
MCP_MODERN_PROTOCOL_VERSION,
|
|
13
|
+
MCP_MODERN_REFUSED_HINT,
|
|
14
|
+
MCP_MODERN_REQUEST_HEADERS,
|
|
15
|
+
McpAppResourceError,
|
|
5
16
|
cleanMcpInstructions,
|
|
6
17
|
createLogger,
|
|
18
|
+
describeMcpAppPolicy,
|
|
7
19
|
dropStructuredDuplicates,
|
|
20
|
+
isMcpAppMimeType,
|
|
21
|
+
isMcpAppUri,
|
|
8
22
|
isStructuredContent,
|
|
9
23
|
markMcpTool,
|
|
24
|
+
mcpAppCspOf,
|
|
25
|
+
mcpAppDownloadOf,
|
|
26
|
+
mcpAppOrigin,
|
|
27
|
+
mcpAppPermissionsOf,
|
|
28
|
+
mcpAppResourceOf,
|
|
29
|
+
mcpAppToolMeta,
|
|
30
|
+
mcpAppToolResultOf,
|
|
31
|
+
mcpAppsModeOf,
|
|
32
|
+
mcpInputRequiredMessage,
|
|
33
|
+
mcpProtocolMode,
|
|
34
|
+
mcpVersionNegotiation,
|
|
10
35
|
outputSchemaNote,
|
|
11
36
|
renderMcpInstructions,
|
|
12
37
|
withStructuredContent
|
|
13
|
-
} from "./chunk-
|
|
14
|
-
import
|
|
38
|
+
} from "./chunk-4FBTBE74.js";
|
|
39
|
+
import {
|
|
40
|
+
MCP_SKILLS_EXTENSION,
|
|
41
|
+
createMcpSkillCatalog,
|
|
42
|
+
markMcpSkills,
|
|
43
|
+
mcpSkillsSettingOf
|
|
44
|
+
} from "./chunk-YUA2BHRM.js";
|
|
15
45
|
|
|
16
46
|
// src/mcp/http.ts
|
|
17
47
|
import {
|
|
18
48
|
auth as auth2,
|
|
19
49
|
Client,
|
|
50
|
+
SdkError,
|
|
51
|
+
SdkErrorCode,
|
|
20
52
|
StreamableHTTPClientTransport,
|
|
21
53
|
UnauthorizedError
|
|
22
54
|
} from "@modelcontextprotocol/client";
|
|
23
55
|
import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/client/validators/cf-worker";
|
|
24
56
|
import { dynamicTool, jsonSchema } from "ai";
|
|
25
57
|
|
|
58
|
+
// src/mcp/elicitation.ts
|
|
59
|
+
var MCP_ELICITATION_TIMEOUT_MS = 3e5;
|
|
60
|
+
var MCP_ELICITATION_TIMEOUT_MAX_MS = 2147483647;
|
|
61
|
+
var MCP_ELICITATION_MAX_PER_TOOL_CALL = 5;
|
|
62
|
+
var MCP_ELICITATION_MAX_PER_RUN = 20;
|
|
63
|
+
var MCP_ELICITATION_MESSAGE_MAX_CHARS = 2e3;
|
|
64
|
+
var MCP_ELICITATION_LABEL_MAX_CHARS = 200;
|
|
65
|
+
var MCP_ELICITATION_DESCRIPTION_MAX_CHARS = 500;
|
|
66
|
+
var MCP_ELICITATION_MAX_FIELDS = 50;
|
|
67
|
+
var MCP_ELICITATION_MAX_OPTIONS = 100;
|
|
68
|
+
var MCP_ELICITATION_NAME_MAX_CHARS = 200;
|
|
69
|
+
var MCP_ELICITATION_URL_MAX_CHARS = 2048;
|
|
70
|
+
var MCP_ELICITATION_VALUE_MAX_CHARS = 1e4;
|
|
71
|
+
var MCP_ELICITATION_TRUNCATED = "... [truncated]";
|
|
72
|
+
var MCP_INPUT_REQUIRED_MAX_ROUNDS = 10;
|
|
73
|
+
var MCP_INPUT_REQUIRED_PACING_MS = 250;
|
|
74
|
+
var MCP_TOOL_CALL_TIMEOUT_MS = 6e4;
|
|
75
|
+
var McpElicitationError = class extends Error {
|
|
76
|
+
constructor(message) {
|
|
77
|
+
super(message);
|
|
78
|
+
this.name = "McpElicitationError";
|
|
79
|
+
}
|
|
80
|
+
toJSON() {
|
|
81
|
+
return this.message;
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
var shownValue = (value) => typeof value === "number" ? String(value) : JSON.stringify(value) ?? String(value);
|
|
85
|
+
var settingOf = (value, name, fallback, min) => {
|
|
86
|
+
if (value === void 0 || value === null) {
|
|
87
|
+
return fallback;
|
|
88
|
+
}
|
|
89
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min) {
|
|
90
|
+
throw new Error(
|
|
91
|
+
`elicitation.${name} must be a number of at least ${min} (got ${shownValue(value)})`
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
return Math.floor(value);
|
|
95
|
+
};
|
|
96
|
+
var timeoutOf = (value) => {
|
|
97
|
+
if (value === void 0 || value === null) {
|
|
98
|
+
return MCP_ELICITATION_TIMEOUT_MS;
|
|
99
|
+
}
|
|
100
|
+
if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
`elicitation.timeoutMs must be a number of at least 0 (0 or Infinity: no limit) (got ${shownValue(value)})`
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
return value === 0 || value > MCP_ELICITATION_TIMEOUT_MAX_MS ? 0 : Math.max(1, Math.floor(value));
|
|
106
|
+
};
|
|
107
|
+
var resolveMcpElicitationOptions = (raw) => ({
|
|
108
|
+
timeoutMs: timeoutOf(raw?.timeoutMs),
|
|
109
|
+
maxPerToolCall: settingOf(
|
|
110
|
+
raw?.maxPerToolCall,
|
|
111
|
+
"maxPerToolCall",
|
|
112
|
+
MCP_ELICITATION_MAX_PER_TOOL_CALL,
|
|
113
|
+
1
|
|
114
|
+
),
|
|
115
|
+
maxPerRun: settingOf(raw?.maxPerRun, "maxPerRun", MCP_ELICITATION_MAX_PER_RUN, 1),
|
|
116
|
+
url: raw?.url === true,
|
|
117
|
+
subagents: raw?.subagents === true
|
|
118
|
+
});
|
|
119
|
+
var mcpElicitationCapability = (options) => options.url ? { form: {}, url: {} } : { form: {} };
|
|
120
|
+
var INVISIBLE = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F---]/g;
|
|
121
|
+
var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
122
|
+
var cleanMcpElicitationText = (raw, max) => {
|
|
123
|
+
if (typeof raw !== "string") {
|
|
124
|
+
return "";
|
|
125
|
+
}
|
|
126
|
+
const text = raw.replace(/\r\n?/g, "\n").replace(INVISIBLE, "").trim();
|
|
127
|
+
return text.length > max ? `${text.slice(0, Math.max(0, max))}${MCP_ELICITATION_TRUNCATED}` : text;
|
|
128
|
+
};
|
|
129
|
+
var isVerbatim = (value) => typeof value === "string" && value.length > 0 && value.length <= MCP_ELICITATION_NAME_MAX_CHARS && value.replace(INVISIBLE, "") === value && !/[\r\n\t]/.test(value);
|
|
130
|
+
var UNSAFE_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
131
|
+
var fieldLabel = (name) => JSON.stringify(cleanMcpElicitationText(name, 64).replace(/\s+/g, " "));
|
|
132
|
+
var bad = (reason) => ({ ok: false, reason });
|
|
133
|
+
var label = (raw, max) => {
|
|
134
|
+
const text = cleanMcpElicitationText(raw, max);
|
|
135
|
+
return text ? text : void 0;
|
|
136
|
+
};
|
|
137
|
+
var count = (raw) => raw === void 0 ? void 0 : typeof raw === "number" && Number.isInteger(raw) && raw >= 0 ? raw : null;
|
|
138
|
+
var plainOptions = (raw) => Array.isArray(raw) && raw.length > 0 && raw.length <= MCP_ELICITATION_MAX_OPTIONS && raw.every(isVerbatim) ? [...raw] : void 0;
|
|
139
|
+
var titledOptions = (raw) => {
|
|
140
|
+
if (!Array.isArray(raw) || raw.length === 0 || raw.length > MCP_ELICITATION_MAX_OPTIONS) {
|
|
141
|
+
return void 0;
|
|
142
|
+
}
|
|
143
|
+
const out = [];
|
|
144
|
+
for (const option of raw) {
|
|
145
|
+
if (!isPlainObject(option) || !isVerbatim(option.const)) {
|
|
146
|
+
return void 0;
|
|
147
|
+
}
|
|
148
|
+
out.push({
|
|
149
|
+
const: option.const,
|
|
150
|
+
title: label(option.title, MCP_ELICITATION_LABEL_MAX_CHARS) ?? option.const
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
};
|
|
155
|
+
var FORMATS = /* @__PURE__ */ new Set(["email", "uri", "date", "date-time"]);
|
|
156
|
+
var normalizeField = (name, raw) => {
|
|
157
|
+
const at = `field ${fieldLabel(name)}`;
|
|
158
|
+
if (!isPlainObject(raw)) {
|
|
159
|
+
return bad(`${at} is not a schema`);
|
|
160
|
+
}
|
|
161
|
+
const type = raw.type;
|
|
162
|
+
if (type !== "string" && type !== "number" && type !== "integer" && type !== "boolean" && type !== "array") {
|
|
163
|
+
return bad(
|
|
164
|
+
`${at} has an unsupported type (${cleanMcpElicitationText(typeof type === "string" ? type : typeof type, 20)}); a form may hold only strings, numbers, booleans and selects`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
if (raw.properties !== void 0 || raw.additionalProperties !== void 0) {
|
|
168
|
+
return bad(`${at} is a nested object; a form is flat`);
|
|
169
|
+
}
|
|
170
|
+
const field = { type };
|
|
171
|
+
const title = label(raw.title, MCP_ELICITATION_LABEL_MAX_CHARS);
|
|
172
|
+
if (title) {
|
|
173
|
+
field.title = title;
|
|
174
|
+
}
|
|
175
|
+
const description = label(raw.description, MCP_ELICITATION_DESCRIPTION_MAX_CHARS);
|
|
176
|
+
if (description) {
|
|
177
|
+
field.description = description;
|
|
178
|
+
}
|
|
179
|
+
if (type === "string") {
|
|
180
|
+
if (raw.enum !== void 0 && raw.oneOf !== void 0) {
|
|
181
|
+
return bad(`${at} has both "enum" and "oneOf"`);
|
|
182
|
+
}
|
|
183
|
+
if (raw.enum !== void 0) {
|
|
184
|
+
const options = plainOptions(raw.enum);
|
|
185
|
+
if (!options) {
|
|
186
|
+
return bad(`${at} has options that cannot be shown`);
|
|
187
|
+
}
|
|
188
|
+
field.enum = options;
|
|
189
|
+
if (Array.isArray(raw.enumNames) && raw.enumNames.length === options.length) {
|
|
190
|
+
field.enumNames = raw.enumNames.map(
|
|
191
|
+
(n, i) => label(n, MCP_ELICITATION_LABEL_MAX_CHARS) ?? options[i]
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
} else if (raw.oneOf !== void 0) {
|
|
195
|
+
const options = titledOptions(raw.oneOf);
|
|
196
|
+
if (!options) {
|
|
197
|
+
return bad(`${at} has options that cannot be shown`);
|
|
198
|
+
}
|
|
199
|
+
field.oneOf = options;
|
|
200
|
+
} else {
|
|
201
|
+
const min = count(raw.minLength);
|
|
202
|
+
const max = count(raw.maxLength);
|
|
203
|
+
if (min === null || max === null) {
|
|
204
|
+
return bad(`${at} has a length limit that is not a whole number`);
|
|
205
|
+
}
|
|
206
|
+
if (min !== void 0) {
|
|
207
|
+
field.minLength = min;
|
|
208
|
+
}
|
|
209
|
+
if (max !== void 0) {
|
|
210
|
+
field.maxLength = max;
|
|
211
|
+
}
|
|
212
|
+
if (raw.format !== void 0) {
|
|
213
|
+
if (typeof raw.format !== "string" || !FORMATS.has(raw.format)) {
|
|
214
|
+
return bad(`${at} has an unsupported format`);
|
|
215
|
+
}
|
|
216
|
+
field.format = raw.format;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
} else if (type === "number" || type === "integer") {
|
|
220
|
+
for (const key of ["minimum", "maximum"]) {
|
|
221
|
+
const bound = raw[key];
|
|
222
|
+
if (bound === void 0) {
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (typeof bound !== "number" || !Number.isFinite(bound)) {
|
|
226
|
+
return bad(`${at} has a bound that is not a number`);
|
|
227
|
+
}
|
|
228
|
+
field[key] = bound;
|
|
229
|
+
}
|
|
230
|
+
} else if (type === "array") {
|
|
231
|
+
const items = raw.items;
|
|
232
|
+
if (!isPlainObject(items) || items.properties !== void 0) {
|
|
233
|
+
return bad(`${at} is a list of something other than options; a form is flat`);
|
|
234
|
+
}
|
|
235
|
+
if (items.enum !== void 0 && items.anyOf === void 0) {
|
|
236
|
+
const options = plainOptions(items.enum);
|
|
237
|
+
if (!options || items.type !== void 0 && items.type !== "string") {
|
|
238
|
+
return bad(`${at} has options that cannot be shown`);
|
|
239
|
+
}
|
|
240
|
+
field.items = { type: "string", enum: options };
|
|
241
|
+
} else if (items.anyOf !== void 0 && items.enum === void 0) {
|
|
242
|
+
const options = titledOptions(items.anyOf);
|
|
243
|
+
if (!options) {
|
|
244
|
+
return bad(`${at} has options that cannot be shown`);
|
|
245
|
+
}
|
|
246
|
+
field.items = { anyOf: options };
|
|
247
|
+
} else {
|
|
248
|
+
return bad(`${at} is a list of something other than options; a form is flat`);
|
|
249
|
+
}
|
|
250
|
+
const min = count(raw.minItems);
|
|
251
|
+
const max = count(raw.maxItems);
|
|
252
|
+
if (min === null || max === null) {
|
|
253
|
+
return bad(`${at} has a size limit that is not a whole number`);
|
|
254
|
+
}
|
|
255
|
+
if (min !== void 0) {
|
|
256
|
+
field.minItems = min;
|
|
257
|
+
}
|
|
258
|
+
if (max !== void 0) {
|
|
259
|
+
field.maxItems = max;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (raw.default !== void 0 && checkValue(name, field, raw.default) === void 0) {
|
|
263
|
+
field.default = Array.isArray(raw.default) ? [...raw.default] : raw.default;
|
|
264
|
+
}
|
|
265
|
+
return { ok: true, value: field };
|
|
266
|
+
};
|
|
267
|
+
var normalizeMcpElicitationSchema = (raw) => {
|
|
268
|
+
if (!isPlainObject(raw) || raw.type !== "object" || !isPlainObject(raw.properties)) {
|
|
269
|
+
return bad("the form is not an object with properties");
|
|
270
|
+
}
|
|
271
|
+
const names = Object.keys(raw.properties);
|
|
272
|
+
if (names.length > MCP_ELICITATION_MAX_FIELDS) {
|
|
273
|
+
return bad(`the form has more than ${MCP_ELICITATION_MAX_FIELDS} fields`);
|
|
274
|
+
}
|
|
275
|
+
const properties = {};
|
|
276
|
+
for (const name of names) {
|
|
277
|
+
if (!isVerbatim(name) || UNSAFE_NAMES.has(name)) {
|
|
278
|
+
return bad(`the form has a field name that cannot be used (${fieldLabel(name)})`);
|
|
279
|
+
}
|
|
280
|
+
const field = normalizeField(name, raw.properties[name]);
|
|
281
|
+
if (!field.ok) {
|
|
282
|
+
return field;
|
|
283
|
+
}
|
|
284
|
+
properties[name] = field.value;
|
|
285
|
+
}
|
|
286
|
+
const schema = { type: "object", properties };
|
|
287
|
+
if (raw.required !== void 0) {
|
|
288
|
+
if (!Array.isArray(raw.required)) {
|
|
289
|
+
return bad(`the form's "required" is not a list`);
|
|
290
|
+
}
|
|
291
|
+
const required = [];
|
|
292
|
+
for (const name of raw.required) {
|
|
293
|
+
if (typeof name !== "string" || !Object.hasOwn(properties, name)) {
|
|
294
|
+
return bad("the form requires a field it does not have");
|
|
295
|
+
}
|
|
296
|
+
if (!required.includes(name)) {
|
|
297
|
+
required.push(name);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (required.length) {
|
|
301
|
+
schema.required = required;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return { ok: true, value: schema };
|
|
305
|
+
};
|
|
306
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
307
|
+
var checkMcpElicitationUrl = (raw) => {
|
|
308
|
+
if (typeof raw !== "string" || !raw || raw.length > MCP_ELICITATION_URL_MAX_CHARS) {
|
|
309
|
+
return bad("the link is missing or too long");
|
|
310
|
+
}
|
|
311
|
+
if (raw.replace(INVISIBLE, "") !== raw || /\s/.test(raw)) {
|
|
312
|
+
return bad("the link contains characters that cannot be shown");
|
|
313
|
+
}
|
|
314
|
+
let parsed;
|
|
315
|
+
try {
|
|
316
|
+
parsed = new URL(raw);
|
|
317
|
+
} catch {
|
|
318
|
+
return bad("the link is not a valid URL");
|
|
319
|
+
}
|
|
320
|
+
if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname))) {
|
|
321
|
+
return bad("only https links are accepted (http on a loopback host)");
|
|
322
|
+
}
|
|
323
|
+
if (parsed.username || parsed.password) {
|
|
324
|
+
return bad("the link carries credentials");
|
|
325
|
+
}
|
|
326
|
+
return { ok: true, value: parsed.href };
|
|
327
|
+
};
|
|
328
|
+
var parseMcpElicitationParams = (params, options) => {
|
|
329
|
+
if (!isPlainObject(params)) {
|
|
330
|
+
return { ok: false, reason: "invalid-request", detail: "the request has no parameters" };
|
|
331
|
+
}
|
|
332
|
+
const mode = params.mode ?? "form";
|
|
333
|
+
if (mode !== "form" && mode !== "url") {
|
|
334
|
+
return { ok: false, reason: "unsupported-mode", detail: "the mode is neither form nor url" };
|
|
335
|
+
}
|
|
336
|
+
if (typeof params.message !== "string") {
|
|
337
|
+
return { ok: false, reason: "invalid-request", detail: "the request has no message" };
|
|
338
|
+
}
|
|
339
|
+
const message = cleanMcpElicitationText(params.message, MCP_ELICITATION_MESSAGE_MAX_CHARS);
|
|
340
|
+
if (mode === "url") {
|
|
341
|
+
if (!options.url) {
|
|
342
|
+
return {
|
|
343
|
+
ok: false,
|
|
344
|
+
reason: "unsupported-mode",
|
|
345
|
+
detail: "URL mode was not offered (elicitation.url)"
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
const url = checkMcpElicitationUrl(params.url);
|
|
349
|
+
if (!url.ok) {
|
|
350
|
+
return { ok: false, reason: "insecure-url", detail: url.reason };
|
|
351
|
+
}
|
|
352
|
+
const elicitationId = label(params.elicitationId, MCP_ELICITATION_NAME_MAX_CHARS);
|
|
353
|
+
return {
|
|
354
|
+
ok: true,
|
|
355
|
+
mode,
|
|
356
|
+
message,
|
|
357
|
+
url: url.value,
|
|
358
|
+
...elicitationId ? { elicitationId } : {}
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
const schema = normalizeMcpElicitationSchema(params.requestedSchema);
|
|
362
|
+
if (!schema.ok) {
|
|
363
|
+
return { ok: false, reason: "unsupported-schema", detail: schema.reason };
|
|
364
|
+
}
|
|
365
|
+
return { ok: true, mode, message, requestedSchema: schema.value };
|
|
366
|
+
};
|
|
367
|
+
var optionValues = (field) => field.enum ?? field.oneOf?.map((o) => o.const);
|
|
368
|
+
var validFormat = (format, value) => {
|
|
369
|
+
switch (format) {
|
|
370
|
+
case "email":
|
|
371
|
+
return /^[^@\s]+@[^@\s]+$/.test(value);
|
|
372
|
+
case "uri":
|
|
373
|
+
try {
|
|
374
|
+
return Boolean(new URL(value));
|
|
375
|
+
} catch {
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
case "date":
|
|
379
|
+
return /^\d{4}-\d{2}-\d{2}$/.test(value) && !Number.isNaN(Date.parse(value));
|
|
380
|
+
case "date-time":
|
|
381
|
+
return /^\d{4}-\d{2}-\d{2}T/.test(value) && !Number.isNaN(Date.parse(value));
|
|
382
|
+
default:
|
|
383
|
+
return true;
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
var checkValue = (name, field, value) => {
|
|
387
|
+
const at = `field ${fieldLabel(name)}`;
|
|
388
|
+
switch (field.type) {
|
|
389
|
+
case "string": {
|
|
390
|
+
if (typeof value !== "string") {
|
|
391
|
+
return `${at} must be a text`;
|
|
392
|
+
}
|
|
393
|
+
const options = optionValues(field);
|
|
394
|
+
if (options) {
|
|
395
|
+
return options.includes(value) ? void 0 : `${at} is not one of the options`;
|
|
396
|
+
}
|
|
397
|
+
if (value.length > (field.maxLength ?? MCP_ELICITATION_VALUE_MAX_CHARS)) {
|
|
398
|
+
return `${at} is too long`;
|
|
399
|
+
}
|
|
400
|
+
if (field.minLength !== void 0 && value.length < field.minLength) {
|
|
401
|
+
return `${at} is too short`;
|
|
402
|
+
}
|
|
403
|
+
return validFormat(field.format, value) ? void 0 : `${at} is not a valid ${field.format ?? "text"}`;
|
|
404
|
+
}
|
|
405
|
+
case "number":
|
|
406
|
+
case "integer": {
|
|
407
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
408
|
+
return `${at} must be a number`;
|
|
409
|
+
}
|
|
410
|
+
if (field.type === "integer" && !Number.isInteger(value)) {
|
|
411
|
+
return `${at} must be a whole number`;
|
|
412
|
+
}
|
|
413
|
+
if (field.minimum !== void 0 && value < field.minimum) {
|
|
414
|
+
return `${at} is below the minimum`;
|
|
415
|
+
}
|
|
416
|
+
return field.maximum !== void 0 && value > field.maximum ? `${at} is above the maximum` : void 0;
|
|
417
|
+
}
|
|
418
|
+
case "boolean":
|
|
419
|
+
return typeof value === "boolean" ? void 0 : `${at} must be true or false`;
|
|
420
|
+
case "array": {
|
|
421
|
+
const options = field.items?.enum ?? field.items?.anyOf?.map((o) => o.const) ?? [];
|
|
422
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
|
|
423
|
+
return `${at} must be a list of options`;
|
|
424
|
+
}
|
|
425
|
+
if (!value.every((item) => options.includes(item))) {
|
|
426
|
+
return `${at} holds something that is not one of the options`;
|
|
427
|
+
}
|
|
428
|
+
if (field.minItems !== void 0 && value.length < field.minItems) {
|
|
429
|
+
return `${at} has too few selected`;
|
|
430
|
+
}
|
|
431
|
+
return field.maxItems !== void 0 && value.length > field.maxItems || value.length > MCP_ELICITATION_MAX_OPTIONS ? `${at} has too many selected` : void 0;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
var validateMcpElicitationContent = (schema, content) => {
|
|
436
|
+
if (content !== void 0 && !isPlainObject(content)) {
|
|
437
|
+
return bad("the answer is not an object of field values");
|
|
438
|
+
}
|
|
439
|
+
const given = content ?? {};
|
|
440
|
+
for (const name of Object.keys(given)) {
|
|
441
|
+
if (!Object.hasOwn(schema.properties, name)) {
|
|
442
|
+
return bad(`${fieldLabel(name)} is not a field of the form`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
const required = new Set(schema.required ?? []);
|
|
446
|
+
const value = {};
|
|
447
|
+
for (const [name, field] of Object.entries(schema.properties)) {
|
|
448
|
+
const answered = Object.hasOwn(given, name) ? given[name] : void 0;
|
|
449
|
+
if (answered === void 0 || answered === null) {
|
|
450
|
+
if (required.has(name)) {
|
|
451
|
+
return bad(`field ${fieldLabel(name)} is required`);
|
|
452
|
+
}
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
const problem = checkValue(name, field, answered);
|
|
456
|
+
if (problem) {
|
|
457
|
+
return bad(problem);
|
|
458
|
+
}
|
|
459
|
+
value[name] = Array.isArray(answered) ? [...answered] : answered;
|
|
460
|
+
}
|
|
461
|
+
return { ok: true, value };
|
|
462
|
+
};
|
|
463
|
+
var newId = () => {
|
|
464
|
+
const c = globalThis.crypto;
|
|
465
|
+
return typeof c?.randomUUID === "function" ? c.randomUUID() : `e-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
466
|
+
};
|
|
467
|
+
var isTimeoutAbort = (signal) => signal?.reason?.name === "TimeoutError";
|
|
468
|
+
var abortReason = (signal) => {
|
|
469
|
+
if (signal?.reason !== void 0) {
|
|
470
|
+
return signal.reason;
|
|
471
|
+
}
|
|
472
|
+
const err = new Error("Aborted");
|
|
473
|
+
err.name = "AbortError";
|
|
474
|
+
return err;
|
|
475
|
+
};
|
|
476
|
+
var mcpElicitationFailure = (tool, reason, options, detail) => {
|
|
477
|
+
const why = {
|
|
478
|
+
"unsupported-schema": `the form it sent cannot be shown (${detail ?? "unsupported schema"})`,
|
|
479
|
+
"unsupported-mode": `it asked in a way this client does not offer (${detail ?? "unsupported mode"})`,
|
|
480
|
+
"insecure-url": `the link it sent was refused (${detail ?? "not https"})`,
|
|
481
|
+
"invalid-request": `its request was malformed (${detail ?? "invalid"})`,
|
|
482
|
+
subagent: "a helper is not allowed to ask the user (elicitation.subagents); the question was not shown",
|
|
483
|
+
"cap-per-call": `it had already asked ${options.maxPerToolCall} time(s) in this call (elicitation.maxPerToolCall)`,
|
|
484
|
+
"cap-per-run": `${options.maxPerRun} question(s) were already asked in this run (elicitation.maxPerRun)`,
|
|
485
|
+
"handler-error": "the host could not ask the user (its elicitation handler failed)",
|
|
486
|
+
timeout: `nobody answered within ${options.timeoutMs} ms (elicitation.timeoutMs)`,
|
|
487
|
+
"invalid-answer": `the answer did not fit the form (${detail ?? "invalid"}) and was not sent`,
|
|
488
|
+
aborted: "the run was stopped",
|
|
489
|
+
"step-timeout": "the tool call's time limit ended before the question was answered",
|
|
490
|
+
"after-failure": "an earlier question of the same call had already failed",
|
|
491
|
+
"no-tool-call": "no tool call was in progress"
|
|
492
|
+
};
|
|
493
|
+
return `MCP tool "${tool}" did not finish: the server asked the user for input, and ${why[reason]}. The call was not repeated; do not call the tool again only because of this.`;
|
|
494
|
+
};
|
|
495
|
+
var answerMcpElicitation = async (deps, call, params) => {
|
|
496
|
+
const { options, log } = deps;
|
|
497
|
+
const id = newId();
|
|
498
|
+
const where = `[mcp] ${call.server}: elicitation during ${call.tool}`;
|
|
499
|
+
const answered = (action2, automatic, reason, fields) => call.emit?.({
|
|
500
|
+
type: "mcp.elicitation-answered",
|
|
501
|
+
id,
|
|
502
|
+
server: call.server,
|
|
503
|
+
tool: call.tool,
|
|
504
|
+
action: action2,
|
|
505
|
+
automatic,
|
|
506
|
+
...reason ? { reason } : {},
|
|
507
|
+
...fields ? { fields } : {}
|
|
508
|
+
});
|
|
509
|
+
const refuse = (reason, detail) => {
|
|
510
|
+
const action2 = ["unsupported-schema", "unsupported-mode", "insecure-url", "invalid-request"].includes(reason) ? "decline" : "cancel";
|
|
511
|
+
call.failure ??= mcpElicitationFailure(call.tool, reason, options, detail);
|
|
512
|
+
log(
|
|
513
|
+
"warn",
|
|
514
|
+
`${where} answered "${action2}" automatically - ${reason}${detail ? `: ${detail}` : ""}`
|
|
515
|
+
);
|
|
516
|
+
answered(action2, true, reason);
|
|
517
|
+
return { action: action2 };
|
|
518
|
+
};
|
|
519
|
+
if (call.failure) {
|
|
520
|
+
return refuse("after-failure");
|
|
521
|
+
}
|
|
522
|
+
const parsed = parseMcpElicitationParams(params, options);
|
|
523
|
+
if (!parsed.ok) {
|
|
524
|
+
return refuse(parsed.reason, parsed.detail);
|
|
525
|
+
}
|
|
526
|
+
if (call.subagent && !options.subagents) {
|
|
527
|
+
return refuse("subagent");
|
|
528
|
+
}
|
|
529
|
+
if (call.asked >= options.maxPerToolCall) {
|
|
530
|
+
return refuse("cap-per-call");
|
|
531
|
+
}
|
|
532
|
+
if (call.run.count >= options.maxPerRun) {
|
|
533
|
+
return refuse("cap-per-run");
|
|
534
|
+
}
|
|
535
|
+
if (call.signal?.aborted) {
|
|
536
|
+
answered("cancel", true, isTimeoutAbort(call.signal) ? "step-timeout" : "aborted");
|
|
537
|
+
throw abortReason(call.signal);
|
|
538
|
+
}
|
|
539
|
+
call.asked += 1;
|
|
540
|
+
call.run.count += 1;
|
|
541
|
+
const request = {
|
|
542
|
+
id,
|
|
543
|
+
server: call.server,
|
|
544
|
+
tool: call.tool,
|
|
545
|
+
mode: parsed.mode,
|
|
546
|
+
message: parsed.message,
|
|
547
|
+
...parsed.mode === "form" ? { requestedSchema: parsed.requestedSchema } : { url: parsed.url },
|
|
548
|
+
...parsed.mode === "url" && parsed.elicitationId ? { elicitationId: parsed.elicitationId } : {},
|
|
549
|
+
...call.runId ? { runId: call.runId } : {},
|
|
550
|
+
...call.subagent ? { subagent: call.subagent } : {}
|
|
551
|
+
};
|
|
552
|
+
call.emit?.({
|
|
553
|
+
type: "mcp.elicitation-requested",
|
|
554
|
+
id,
|
|
555
|
+
server: call.server,
|
|
556
|
+
tool: call.tool,
|
|
557
|
+
mode: request.mode,
|
|
558
|
+
message: request.message,
|
|
559
|
+
...request.requestedSchema ? { requestedSchema: request.requestedSchema } : {},
|
|
560
|
+
...request.url ? { url: request.url } : {},
|
|
561
|
+
...call.subagent ? { subagent: call.subagent } : {}
|
|
562
|
+
});
|
|
563
|
+
const controller = new AbortController();
|
|
564
|
+
let timer;
|
|
565
|
+
let onAbort;
|
|
566
|
+
call.onWait?.(true);
|
|
567
|
+
const resume = call.pause?.();
|
|
568
|
+
const outcome = await new Promise((resolve) => {
|
|
569
|
+
if (options.timeoutMs > 0) {
|
|
570
|
+
timer = setTimeout(() => resolve({ kind: "timeout" }), options.timeoutMs);
|
|
571
|
+
}
|
|
572
|
+
onAbort = () => resolve({ kind: "aborted" });
|
|
573
|
+
call.signal?.addEventListener("abort", onAbort, { once: true });
|
|
574
|
+
Promise.resolve().then(() => deps.handler(request, { signal: controller.signal })).then(
|
|
575
|
+
(value) => resolve({ kind: "answer", value }),
|
|
576
|
+
(error) => resolve({ kind: "error", error })
|
|
577
|
+
);
|
|
578
|
+
});
|
|
579
|
+
resume?.();
|
|
580
|
+
call.onWait?.(false);
|
|
581
|
+
if (timer) {
|
|
582
|
+
clearTimeout(timer);
|
|
583
|
+
}
|
|
584
|
+
if (onAbort) {
|
|
585
|
+
call.signal?.removeEventListener("abort", onAbort);
|
|
586
|
+
}
|
|
587
|
+
controller.abort();
|
|
588
|
+
if (outcome.kind === "aborted") {
|
|
589
|
+
const reason = isTimeoutAbort(call.signal) ? "step-timeout" : "aborted";
|
|
590
|
+
call.failure ??= mcpElicitationFailure(call.tool, reason, options);
|
|
591
|
+
if (reason === "step-timeout") {
|
|
592
|
+
log(
|
|
593
|
+
"warn",
|
|
594
|
+
`${where}: a time limit on the tool call's signal ended while the question was waiting for an answer; only the step's own limit stops while a person is asked, not a limit on the run's signal`
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
answered("cancel", true, reason);
|
|
598
|
+
throw abortReason(call.signal);
|
|
599
|
+
}
|
|
600
|
+
if (outcome.kind === "timeout") {
|
|
601
|
+
return refuse("timeout");
|
|
602
|
+
}
|
|
603
|
+
if (outcome.kind === "error") {
|
|
604
|
+
const name = outcome.error?.name;
|
|
605
|
+
return refuse("handler-error", typeof name === "string" ? name.slice(0, 40) : "error");
|
|
606
|
+
}
|
|
607
|
+
const result = outcome.value;
|
|
608
|
+
const action = result?.action;
|
|
609
|
+
if (action === "decline" || action === "cancel") {
|
|
610
|
+
answered(action, false);
|
|
611
|
+
return { action };
|
|
612
|
+
}
|
|
613
|
+
if (action !== "accept") {
|
|
614
|
+
return refuse("invalid-answer", "the handler returned no accept, decline or cancel");
|
|
615
|
+
}
|
|
616
|
+
if (parsed.mode === "url") {
|
|
617
|
+
answered("accept", false);
|
|
618
|
+
return { action: "accept" };
|
|
619
|
+
}
|
|
620
|
+
const content = validateMcpElicitationContent(parsed.requestedSchema, result?.content);
|
|
621
|
+
if (!content.ok) {
|
|
622
|
+
return refuse("invalid-answer", content.reason);
|
|
623
|
+
}
|
|
624
|
+
answered("accept", false, void 0, Object.keys(content.value));
|
|
625
|
+
return { action: "accept", content: content.value };
|
|
626
|
+
};
|
|
627
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
628
|
+
if (signal?.aborted) {
|
|
629
|
+
reject(abortReason(signal));
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
const onAbort = () => {
|
|
633
|
+
clearTimeout(timer);
|
|
634
|
+
reject(abortReason(signal));
|
|
635
|
+
};
|
|
636
|
+
const timer = setTimeout(() => {
|
|
637
|
+
signal?.removeEventListener("abort", onAbort);
|
|
638
|
+
resolve();
|
|
639
|
+
}, ms);
|
|
640
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
641
|
+
});
|
|
642
|
+
var isInputRequired = (value) => isPlainObject(value) && value.resultType === "input_required";
|
|
643
|
+
var mcpInputRequestUnsupportedMessage = (toolName, method) => `MCP tool "${toolName}" did not finish: the server asked for input this client does not provide (${cleanMcpElicitationText(typeof method === "string" ? method : "a malformed request", 60)}; only elicitation is answered). The call was not repeated.`;
|
|
644
|
+
var mcpInputRequiredRoundsMessage = (toolName) => `MCP tool "${toolName}" did not finish: the server still asked for input after ${MCP_INPUT_REQUIRED_MAX_ROUNDS} rounds. The call was not repeated.`;
|
|
645
|
+
var mcpToolCallTimeoutMessage = (toolName) => `MCP tool "${toolName}" timed out after ${MCP_TOOL_CALL_TIMEOUT_MS} ms (not counting the time its questions waited for the user).`;
|
|
646
|
+
var createMcpElicitationSession = (server, deps) => {
|
|
647
|
+
let current;
|
|
648
|
+
let tail = Promise.resolve();
|
|
649
|
+
const acquire = async (signal) => {
|
|
650
|
+
const before = tail;
|
|
651
|
+
let release;
|
|
652
|
+
tail = new Promise((resolve) => {
|
|
653
|
+
release = resolve;
|
|
654
|
+
});
|
|
655
|
+
try {
|
|
656
|
+
await new Promise((resolve, reject) => {
|
|
657
|
+
if (signal?.aborted) {
|
|
658
|
+
reject(abortReason(signal));
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
const onAbort = () => reject(abortReason(signal));
|
|
662
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
663
|
+
void before.then(() => {
|
|
664
|
+
signal?.removeEventListener("abort", onAbort);
|
|
665
|
+
resolve();
|
|
666
|
+
});
|
|
667
|
+
});
|
|
668
|
+
} catch (err) {
|
|
669
|
+
void before.then(release);
|
|
670
|
+
throw err;
|
|
671
|
+
}
|
|
672
|
+
return release;
|
|
673
|
+
};
|
|
674
|
+
const newCall = (info, signal) => ({
|
|
675
|
+
server,
|
|
676
|
+
tool: info.tool,
|
|
677
|
+
...signal ? { signal } : {},
|
|
678
|
+
...info.emit ? { emit: info.emit } : {},
|
|
679
|
+
...info.runId ? { runId: info.runId } : {},
|
|
680
|
+
...info.subagent ? { subagent: info.subagent } : {},
|
|
681
|
+
...info.pause ? { pause: info.pause } : {},
|
|
682
|
+
run: info.run ?? { count: 0 },
|
|
683
|
+
asked: 0
|
|
684
|
+
});
|
|
685
|
+
const callLegacy = async (info, send) => {
|
|
686
|
+
const release = await acquire(info.signal);
|
|
687
|
+
const controller = new AbortController();
|
|
688
|
+
const onOuterAbort = () => controller.abort(abortReason(info.signal));
|
|
689
|
+
info.signal?.addEventListener("abort", onOuterAbort, { once: true });
|
|
690
|
+
let left = MCP_TOOL_CALL_TIMEOUT_MS;
|
|
691
|
+
let startedAt = Date.now();
|
|
692
|
+
let timedOut = false;
|
|
693
|
+
let timer;
|
|
694
|
+
const start = () => {
|
|
695
|
+
startedAt = Date.now();
|
|
696
|
+
timer = setTimeout(
|
|
697
|
+
() => {
|
|
698
|
+
timedOut = true;
|
|
699
|
+
controller.abort(new McpElicitationError(mcpToolCallTimeoutMessage(info.toolName)));
|
|
700
|
+
},
|
|
701
|
+
Math.max(0, left)
|
|
702
|
+
);
|
|
703
|
+
};
|
|
704
|
+
const stop = () => {
|
|
705
|
+
if (timer) {
|
|
706
|
+
clearTimeout(timer);
|
|
707
|
+
timer = void 0;
|
|
708
|
+
left -= Date.now() - startedAt;
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
const call = Object.assign(newCall(info, controller.signal), {
|
|
712
|
+
abort: (reason) => controller.abort(reason),
|
|
713
|
+
onWait: (waiting) => waiting ? stop() : start()
|
|
714
|
+
});
|
|
715
|
+
current = call;
|
|
716
|
+
try {
|
|
717
|
+
if (info.signal?.aborted) {
|
|
718
|
+
throw abortReason(info.signal);
|
|
719
|
+
}
|
|
720
|
+
start();
|
|
721
|
+
const result = await send({ signal: controller.signal, ownTimeout: true });
|
|
722
|
+
if (call.failure) {
|
|
723
|
+
throw new McpElicitationError(call.failure);
|
|
724
|
+
}
|
|
725
|
+
return result;
|
|
726
|
+
} catch (err) {
|
|
727
|
+
if (info.signal?.aborted) {
|
|
728
|
+
throw err;
|
|
729
|
+
}
|
|
730
|
+
if (call.failure) {
|
|
731
|
+
throw new McpElicitationError(call.failure);
|
|
732
|
+
}
|
|
733
|
+
if (timedOut) {
|
|
734
|
+
throw new McpElicitationError(mcpToolCallTimeoutMessage(info.toolName));
|
|
735
|
+
}
|
|
736
|
+
throw err;
|
|
737
|
+
} finally {
|
|
738
|
+
stop();
|
|
739
|
+
info.signal?.removeEventListener("abort", onOuterAbort);
|
|
740
|
+
if (current === call) {
|
|
741
|
+
current = void 0;
|
|
742
|
+
}
|
|
743
|
+
release();
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
const callModern = async (info, send) => {
|
|
747
|
+
const call = newCall(info, info.signal);
|
|
748
|
+
let retry;
|
|
749
|
+
for (let round = 0; ; round += 1) {
|
|
750
|
+
const result = await send({
|
|
751
|
+
...info.signal ? { signal: info.signal } : {},
|
|
752
|
+
...retry ? { retry } : {}
|
|
753
|
+
});
|
|
754
|
+
if (!isInputRequired(result)) {
|
|
755
|
+
return result;
|
|
756
|
+
}
|
|
757
|
+
if (round >= MCP_INPUT_REQUIRED_MAX_ROUNDS) {
|
|
758
|
+
throw new McpElicitationError(mcpInputRequiredRoundsMessage(info.toolName));
|
|
759
|
+
}
|
|
760
|
+
const requests = isPlainObject(result.inputRequests) ? Object.entries(result.inputRequests) : [];
|
|
761
|
+
const state = typeof result.requestState === "string" ? result.requestState : void 0;
|
|
762
|
+
if (requests.length === 0 && state === void 0) {
|
|
763
|
+
throw new McpElicitationError(
|
|
764
|
+
mcpInputRequestUnsupportedMessage(info.toolName, "an empty input_required result")
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
for (const [, entry] of requests) {
|
|
768
|
+
if (!isPlainObject(entry) || entry.method !== "elicitation/create") {
|
|
769
|
+
throw new McpElicitationError(
|
|
770
|
+
mcpInputRequestUnsupportedMessage(
|
|
771
|
+
info.toolName,
|
|
772
|
+
isPlainObject(entry) ? entry.method : void 0
|
|
773
|
+
)
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const responses = /* @__PURE__ */ Object.create(null);
|
|
778
|
+
for (const [key, entry] of requests) {
|
|
779
|
+
const answer = await answerMcpElicitation(
|
|
780
|
+
deps,
|
|
781
|
+
call,
|
|
782
|
+
entry.params
|
|
783
|
+
);
|
|
784
|
+
if (call.failure) {
|
|
785
|
+
throw new McpElicitationError(call.failure);
|
|
786
|
+
}
|
|
787
|
+
responses[key] = answer;
|
|
788
|
+
}
|
|
789
|
+
if (requests.length === 0) {
|
|
790
|
+
await sleep(MCP_INPUT_REQUIRED_PACING_MS, info.signal);
|
|
791
|
+
}
|
|
792
|
+
retry = {
|
|
793
|
+
...requests.length ? { inputResponses: responses } : {},
|
|
794
|
+
...state !== void 0 ? { requestState: state } : {}
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
};
|
|
798
|
+
return {
|
|
799
|
+
capability: mcpElicitationCapability(deps.options),
|
|
800
|
+
onRequest: async (params) => {
|
|
801
|
+
const call = current;
|
|
802
|
+
if (!call) {
|
|
803
|
+
deps.log(
|
|
804
|
+
"warn",
|
|
805
|
+
`[mcp] ${server}: the server asked the user for input while no tool call was in progress; cancelled`
|
|
806
|
+
);
|
|
807
|
+
return { action: "cancel" };
|
|
808
|
+
}
|
|
809
|
+
const failedBefore = call.failure !== void 0;
|
|
810
|
+
const answer = await answerMcpElicitation(deps, call, params);
|
|
811
|
+
if (failedBefore) {
|
|
812
|
+
call.abort(new McpElicitationError(call.failure));
|
|
813
|
+
}
|
|
814
|
+
return answer;
|
|
815
|
+
},
|
|
816
|
+
call: (era, info, send) => era === "modern" ? callModern(info, send) : callLegacy(info, send)
|
|
817
|
+
};
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
// src/mcp/listen.ts
|
|
821
|
+
var MCP_LISTEN_RETRY_BASE_MS = 1e3;
|
|
822
|
+
var MCP_LISTEN_RETRY_MAX_MS = 6e4;
|
|
823
|
+
var MCP_LISTEN_STABLE_MS = 6e4;
|
|
824
|
+
var MCP_LISTEN_MAX_ATTEMPTS = 10;
|
|
825
|
+
var mcpListenRetryDelay = (attempt, random = Math.random) => {
|
|
826
|
+
const exponent = Math.max(0, Math.floor(attempt) - 1);
|
|
827
|
+
const full = Math.min(MCP_LISTEN_RETRY_MAX_MS, MCP_LISTEN_RETRY_BASE_MS * 2 ** exponent);
|
|
828
|
+
const drawn = random();
|
|
829
|
+
const share = Number.isFinite(drawn) ? Math.min(1, Math.max(0, drawn)) : 0;
|
|
830
|
+
return Math.round(full - full / 2 * share);
|
|
831
|
+
};
|
|
832
|
+
var mcpListenFinalReason = (err) => {
|
|
833
|
+
if (typeof err !== "object" || err === null) return void 0;
|
|
834
|
+
const { name, status, code } = err;
|
|
835
|
+
if (name === "UnauthorizedError" || status === 401 || status === 403) {
|
|
836
|
+
return "the server refused the authorization";
|
|
837
|
+
}
|
|
838
|
+
if (status === 404 || status === 405 || code === -32601 || code === "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION") {
|
|
839
|
+
return "the server does not offer subscriptions/listen";
|
|
840
|
+
}
|
|
841
|
+
if (code === -32602) return "the server refused the request";
|
|
842
|
+
if (code === "NOT_CONNECTED") return "the connection is closed";
|
|
843
|
+
return void 0;
|
|
844
|
+
};
|
|
845
|
+
var REAL_TIME = {
|
|
846
|
+
set: (fire, ms) => setTimeout(fire, ms),
|
|
847
|
+
clear: (handle) => clearTimeout(handle)
|
|
848
|
+
};
|
|
849
|
+
var TEST_TIME = /* @__PURE__ */ Symbol.for("@dudko.dev/agent:mcp-listen-test-time");
|
|
850
|
+
var timeSource = () => {
|
|
851
|
+
const test = globalThis[TEST_TIME];
|
|
852
|
+
return typeof test?.set === "function" && typeof test.clear === "function" ? test : REAL_TIME;
|
|
853
|
+
};
|
|
854
|
+
var seconds = (ms) => `${(ms / 1e3).toFixed(1)} s`;
|
|
855
|
+
var messageOf = (err) => err instanceof Error ? err.message : String(err);
|
|
856
|
+
var createMcpListenSupervisor = (deps) => {
|
|
857
|
+
const { server, log } = deps;
|
|
858
|
+
const random = deps.random ?? Math.random;
|
|
859
|
+
const time = timeSource();
|
|
860
|
+
const timer = deps.timer ?? ((ms, fire) => {
|
|
861
|
+
const handle = time.set(fire, ms);
|
|
862
|
+
return { cancel: () => time.clear(handle) };
|
|
863
|
+
});
|
|
864
|
+
let started = false;
|
|
865
|
+
let stopped = false;
|
|
866
|
+
let attempts = 0;
|
|
867
|
+
let retry;
|
|
868
|
+
let stable;
|
|
869
|
+
let inFlight;
|
|
870
|
+
let current;
|
|
871
|
+
const again = (what) => {
|
|
872
|
+
if (attempts >= MCP_LISTEN_MAX_ATTEMPTS) {
|
|
873
|
+
log(
|
|
874
|
+
"warn",
|
|
875
|
+
`[mcp] ${server}: ${what}; gave up after ${attempts} attempts in a row - tool list changes are not announced until the server is connected again (refreshServer still re-lists)`
|
|
876
|
+
);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
attempts += 1;
|
|
880
|
+
const delay = mcpListenRetryDelay(attempts, random);
|
|
881
|
+
log(
|
|
882
|
+
"warn",
|
|
883
|
+
`[mcp] ${server}: ${what}; listening again in ${seconds(delay)} (attempt ${attempts} of ${MCP_LISTEN_MAX_ATTEMPTS})`
|
|
884
|
+
);
|
|
885
|
+
retry = timer(delay, () => {
|
|
886
|
+
retry = void 0;
|
|
887
|
+
void open(true);
|
|
888
|
+
});
|
|
889
|
+
};
|
|
890
|
+
const ended = (subscription, cause) => {
|
|
891
|
+
if (stopped || current !== subscription) return;
|
|
892
|
+
current = void 0;
|
|
893
|
+
stable?.cancel();
|
|
894
|
+
stable = void 0;
|
|
895
|
+
if (cause === "local") return;
|
|
896
|
+
again(
|
|
897
|
+
`the tool list change stream ended (${cause === "graceful" ? "closed by the server" : "dropped"})`
|
|
898
|
+
);
|
|
899
|
+
};
|
|
900
|
+
const open = async (resubscribe) => {
|
|
901
|
+
if (stopped) return;
|
|
902
|
+
const attempt = new AbortController();
|
|
903
|
+
inFlight = attempt;
|
|
904
|
+
let subscription;
|
|
905
|
+
try {
|
|
906
|
+
subscription = await deps.listen(attempt.signal);
|
|
907
|
+
} catch (err) {
|
|
908
|
+
if (inFlight === attempt) inFlight = void 0;
|
|
909
|
+
if (stopped) return;
|
|
910
|
+
const final = mcpListenFinalReason(err);
|
|
911
|
+
if (final) {
|
|
912
|
+
log(
|
|
913
|
+
"warn",
|
|
914
|
+
`[mcp] ${server}: could not subscribe to tool list changes - ${messageOf(err)}; not tried again: ${final}`
|
|
915
|
+
);
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
again(`could not subscribe to tool list changes - ${messageOf(err)}`);
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
if (inFlight === attempt) inFlight = void 0;
|
|
922
|
+
if (stopped) return;
|
|
923
|
+
if (subscription.honoredFilter?.toolsListChanged !== true) {
|
|
924
|
+
log("info", `[mcp] ${server}: the server did not agree to announce tool list changes`);
|
|
925
|
+
attempt.abort();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
current = subscription;
|
|
929
|
+
stable = timer(MCP_LISTEN_STABLE_MS, () => {
|
|
930
|
+
stable = void 0;
|
|
931
|
+
attempts = 0;
|
|
932
|
+
});
|
|
933
|
+
subscription.closed.then(
|
|
934
|
+
(cause) => ended(subscription, cause),
|
|
935
|
+
() => ended(subscription, "remote")
|
|
936
|
+
);
|
|
937
|
+
if (resubscribe) {
|
|
938
|
+
log(
|
|
939
|
+
"info",
|
|
940
|
+
`[mcp] ${server}: listening for tool list changes again (attempt ${attempts}); the tool list is read again`
|
|
941
|
+
);
|
|
942
|
+
try {
|
|
943
|
+
deps.onResubscribed();
|
|
944
|
+
} catch (err) {
|
|
945
|
+
log("warn", `[mcp] ${server}: the tool list change callback failed - ${messageOf(err)}`);
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
};
|
|
949
|
+
return {
|
|
950
|
+
start: async () => {
|
|
951
|
+
if (started || stopped) return;
|
|
952
|
+
started = true;
|
|
953
|
+
await open(false);
|
|
954
|
+
},
|
|
955
|
+
stop: () => {
|
|
956
|
+
stopped = true;
|
|
957
|
+
retry?.cancel();
|
|
958
|
+
retry = void 0;
|
|
959
|
+
stable?.cancel();
|
|
960
|
+
stable = void 0;
|
|
961
|
+
inFlight?.abort();
|
|
962
|
+
inFlight = void 0;
|
|
963
|
+
current = void 0;
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
};
|
|
967
|
+
|
|
26
968
|
// src/mcp/oauth.ts
|
|
27
969
|
import {
|
|
28
970
|
auth
|
|
@@ -59,31 +1001,47 @@ var namespaceFor = (serverUrl) => {
|
|
|
59
1001
|
const u = new URL(serverUrl);
|
|
60
1002
|
return `mcp-oauth:${u.origin}${u.pathname.replace(/\/+$/, "")}${u.search}`;
|
|
61
1003
|
};
|
|
62
|
-
var
|
|
63
|
-
var assertSecureOAuthUrl = (url,
|
|
1004
|
+
var LOOPBACK_HOSTS2 = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
1005
|
+
var assertSecureOAuthUrl = (url, label2 = "MCP server") => {
|
|
64
1006
|
let parsed;
|
|
65
1007
|
try {
|
|
66
1008
|
parsed = new URL(url);
|
|
67
1009
|
} catch {
|
|
68
|
-
throw new Error(`${
|
|
1010
|
+
throw new Error(`${label2}: "${url}" is not a valid URL`);
|
|
69
1011
|
}
|
|
70
|
-
if (parsed.protocol === "https:" ||
|
|
1012
|
+
if (parsed.protocol === "https:" || LOOPBACK_HOSTS2.has(parsed.hostname)) return;
|
|
71
1013
|
throw new Error(
|
|
72
|
-
`${
|
|
1014
|
+
`${label2}: MCP OAuth requires https (or a loopback host) - refusing to send tokens to "${url}"`
|
|
73
1015
|
);
|
|
74
1016
|
};
|
|
75
|
-
var assertClientMetadataUrl = (url,
|
|
1017
|
+
var assertClientMetadataUrl = (url, label2 = "MCP OAuth") => {
|
|
76
1018
|
let parsed;
|
|
77
1019
|
try {
|
|
78
1020
|
parsed = new URL(url);
|
|
79
1021
|
} catch {
|
|
80
|
-
throw new Error(`${
|
|
1022
|
+
throw new Error(`${label2}: clientMetadataUrl "${url}" is not a valid URL`);
|
|
81
1023
|
}
|
|
82
1024
|
if (parsed.protocol === "https:" && parsed.pathname !== "/") return;
|
|
83
1025
|
throw new Error(
|
|
84
|
-
`${
|
|
1026
|
+
`${label2}: clientMetadataUrl requires https and a non-root path - refusing "${url}"`
|
|
85
1027
|
);
|
|
86
1028
|
};
|
|
1029
|
+
var REGISTRATIONS = ["auto", "cimd", "dcr"];
|
|
1030
|
+
var resolveRegistration = (registration, clientMetadataUrl, label2 = "MCP OAuth") => {
|
|
1031
|
+
if (registration === void 0) return "auto";
|
|
1032
|
+
if (!REGISTRATIONS.includes(registration)) {
|
|
1033
|
+
throw new Error(
|
|
1034
|
+
`${label2}: registration must be 'auto', 'cimd' or 'dcr' - refusing "${String(registration)}"`
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
if (registration === "cimd" && clientMetadataUrl === void 0) {
|
|
1038
|
+
throw new Error(
|
|
1039
|
+
`${label2}: registration 'cimd' needs a clientMetadataUrl - the client ID metadata document to sign in with`
|
|
1040
|
+
);
|
|
1041
|
+
}
|
|
1042
|
+
return registration;
|
|
1043
|
+
};
|
|
1044
|
+
var KIND_KEY = "x-agent-registration";
|
|
87
1045
|
var checkAuthorizationResponseIssuer = (iss, discoveryState, clientIssuer) => {
|
|
88
1046
|
const metadata = discoveryState?.authorizationServerMetadata;
|
|
89
1047
|
const expected = discoveryState ? metadata?.issuer ?? String(discoveryState.authorizationServerUrl) : clientIssuer;
|
|
@@ -109,7 +1067,7 @@ var randomToken = () => {
|
|
|
109
1067
|
var applicationTypeFor = (redirectUrl) => {
|
|
110
1068
|
try {
|
|
111
1069
|
const u = new URL(redirectUrl);
|
|
112
|
-
return u.protocol === "https:" && !
|
|
1070
|
+
return u.protocol === "https:" && !LOOPBACK_HOSTS2.has(u.hostname) ? "web" : "native";
|
|
113
1071
|
} catch {
|
|
114
1072
|
return "native";
|
|
115
1073
|
}
|
|
@@ -123,14 +1081,18 @@ var BrowserOAuthProvider = class {
|
|
|
123
1081
|
_redirectUrl;
|
|
124
1082
|
_clientMetadata;
|
|
125
1083
|
_clientMetadataUrl;
|
|
1084
|
+
_registration;
|
|
126
1085
|
skewMs;
|
|
127
1086
|
onRedirect;
|
|
1087
|
+
/** Once per provider: a stored client of the other kind is forgotten (see `settle`). */
|
|
1088
|
+
settled;
|
|
128
1089
|
constructor(opts) {
|
|
129
1090
|
assertSecureOAuthUrl(opts.serverUrl);
|
|
130
1091
|
if (opts.clientMetadataUrl !== void 0) {
|
|
131
1092
|
assertClientMetadataUrl(opts.clientMetadataUrl);
|
|
132
1093
|
this._clientMetadataUrl = opts.clientMetadataUrl;
|
|
133
1094
|
}
|
|
1095
|
+
this._registration = resolveRegistration(opts.registration, opts.clientMetadataUrl);
|
|
134
1096
|
this.serverUrl = opts.serverUrl;
|
|
135
1097
|
this.storage = opts.storage ?? new VaultOAuthStorage();
|
|
136
1098
|
this.ns = namespaceFor(opts.serverUrl);
|
|
@@ -157,9 +1119,17 @@ var BrowserOAuthProvider = class {
|
|
|
157
1119
|
get clientMetadata() {
|
|
158
1120
|
return this._clientMetadata;
|
|
159
1121
|
}
|
|
160
|
-
/**
|
|
1122
|
+
/**
|
|
1123
|
+
* The client ID metadata document URL (CIMD), when one was configured - and
|
|
1124
|
+
* not with `registration: 'dcr'`: the SDK uses this getter to decide, so a
|
|
1125
|
+
* URL it cannot see is a URL it never uses as the `client_id`.
|
|
1126
|
+
*/
|
|
161
1127
|
get clientMetadataUrl() {
|
|
162
|
-
return this._clientMetadataUrl;
|
|
1128
|
+
return this._registration === "dcr" ? void 0 : this._clientMetadataUrl;
|
|
1129
|
+
}
|
|
1130
|
+
/** How this provider registers its client: `'auto'`, `'cimd'` or `'dcr'`. */
|
|
1131
|
+
get registration() {
|
|
1132
|
+
return this._registration;
|
|
163
1133
|
}
|
|
164
1134
|
key(suffix) {
|
|
165
1135
|
return `${this.ns}:${suffix}`;
|
|
@@ -189,13 +1159,99 @@ var BrowserOAuthProvider = class {
|
|
|
189
1159
|
await this.storage.delete(this.key("state"));
|
|
190
1160
|
return expected !== void 0 && returned !== void 0 && expected === returned;
|
|
191
1161
|
}
|
|
1162
|
+
/** The stored client, without our stamp, and how it was registered. */
|
|
1163
|
+
async readClient() {
|
|
1164
|
+
const stored = await this.readJSON("client");
|
|
1165
|
+
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return void 0;
|
|
1166
|
+
const info = { ...stored };
|
|
1167
|
+
const stamp = info[KIND_KEY];
|
|
1168
|
+
delete info[KIND_KEY];
|
|
1169
|
+
const kind = stamp === "cimd" || stamp === "dcr" ? stamp : this.kindOf(info.client_id);
|
|
1170
|
+
return { info, kind };
|
|
1171
|
+
}
|
|
1172
|
+
kindOf(clientId) {
|
|
1173
|
+
return this._clientMetadataUrl !== void 0 && clientId === this._clientMetadataUrl ? "cimd" : "dcr";
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* May this provider use the stored client? Under `'auto'` any; under `'cimd'`
|
|
1177
|
+
* only the configured document itself; under `'dcr'` only one that was not
|
|
1178
|
+
* registered by a document.
|
|
1179
|
+
*/
|
|
1180
|
+
fits(client) {
|
|
1181
|
+
if (this._registration === "cimd") {
|
|
1182
|
+
return client.kind === "cimd" && client.info.client_id === this._clientMetadataUrl;
|
|
1183
|
+
}
|
|
1184
|
+
if (this._registration === "dcr") return client.kind === "dcr";
|
|
1185
|
+
return true;
|
|
1186
|
+
}
|
|
1187
|
+
/** The client and the tokens issued to it go together: a token belongs to a client. */
|
|
1188
|
+
async forgetClient() {
|
|
1189
|
+
await Promise.all(["client", "tokens"].map((t) => this.storage.delete(this.key(t))));
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Under `'cimd'` / `'dcr'`, before the first read of the client or a token: a
|
|
1193
|
+
* stored client of the other kind (registered under another setting) is
|
|
1194
|
+
* forgotten with its tokens, so the setting is never served by the old
|
|
1195
|
+
* client - not even by its access token, which the transport would otherwise
|
|
1196
|
+
* keep sending until it expires. Once per provider (its setting is fixed); a
|
|
1197
|
+
* failure is not remembered.
|
|
1198
|
+
*/
|
|
1199
|
+
settle() {
|
|
1200
|
+
if (this._registration === "auto") return Promise.resolve();
|
|
1201
|
+
this.settled ??= (async () => {
|
|
1202
|
+
const client = await this.readClient();
|
|
1203
|
+
if (client && !this.fits(client)) await this.forgetClient();
|
|
1204
|
+
})().catch((err) => {
|
|
1205
|
+
this.settled = void 0;
|
|
1206
|
+
throw err;
|
|
1207
|
+
});
|
|
1208
|
+
return this.settled;
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* `'cimd'` with no usable client: the SDK is about to choose between the
|
|
1212
|
+
* document and a dynamic registration, by the authorization server metadata
|
|
1213
|
+
* it has just saved (`saveDiscoveryState` comes first). Without support it
|
|
1214
|
+
* would register - so it is stopped HERE, before any request is made, and
|
|
1215
|
+
* what discovery found is forgotten, so the next attempt reads the server's
|
|
1216
|
+
* metadata again (a server that starts supporting CIMD is noticed).
|
|
1217
|
+
*/
|
|
1218
|
+
async assertCimdSupported() {
|
|
1219
|
+
const discovery = await this.discoveryState();
|
|
1220
|
+
const metadata = discovery?.authorizationServerMetadata;
|
|
1221
|
+
if (metadata?.client_id_metadata_document_supported === true) return;
|
|
1222
|
+
await this.storage.delete(this.key("discovery")).catch(() => {
|
|
1223
|
+
});
|
|
1224
|
+
const server = typeof metadata?.issuer === "string" ? metadata.issuer : discovery?.authorizationServerUrl;
|
|
1225
|
+
throw new Error(
|
|
1226
|
+
server ? `MCP OAuth: the authorization server ${server} of ${this.serverUrl} does not support client ID metadata documents (CIMD), which this connection requires (registration: 'cimd') - nothing was sent to its registration endpoint` : `MCP OAuth: no record of the authorization server of ${this.serverUrl}, so its support for client ID metadata documents (CIMD), which this connection requires (registration: 'cimd'), cannot be confirmed - nothing was registered`
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
192
1229
|
async clientInformation() {
|
|
193
|
-
|
|
1230
|
+
await this.settle();
|
|
1231
|
+
const client = await this.readClient();
|
|
1232
|
+
if (client && this.fits(client)) return client.info;
|
|
1233
|
+
if (client) await this.forgetClient();
|
|
1234
|
+
if (this._registration === "cimd") await this.assertCimdSupported();
|
|
1235
|
+
return void 0;
|
|
194
1236
|
}
|
|
195
1237
|
async saveClientInformation(info) {
|
|
196
|
-
|
|
1238
|
+
const record = { ...info };
|
|
1239
|
+
record[KIND_KEY] = this.kindOf(info.client_id);
|
|
1240
|
+
await this.storage.set(this.key("client"), JSON.stringify(record));
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* How the stored client was registered: `'cimd'` (its `client_id` is the
|
|
1244
|
+
* client ID metadata document), `'dcr'` (registered dynamically - or saved by
|
|
1245
|
+
* the host), or undefined when there is none this provider would use. Read it
|
|
1246
|
+
* after a sign-in to show the user which way was taken.
|
|
1247
|
+
*/
|
|
1248
|
+
async registrationKind() {
|
|
1249
|
+
await this.settle();
|
|
1250
|
+
const client = await this.readClient();
|
|
1251
|
+
return client && this.fits(client) ? client.kind : void 0;
|
|
197
1252
|
}
|
|
198
1253
|
async tokens() {
|
|
1254
|
+
await this.settle();
|
|
199
1255
|
return (await this.readJSON("tokens"))?.tokens;
|
|
200
1256
|
}
|
|
201
1257
|
async saveTokens(tokens) {
|
|
@@ -253,6 +1309,7 @@ var BrowserOAuthProvider = class {
|
|
|
253
1309
|
}
|
|
254
1310
|
/** True when there is no access token, or it expires within the skew window. */
|
|
255
1311
|
async isAccessTokenExpired() {
|
|
1312
|
+
await this.settle();
|
|
256
1313
|
const stored = await this.readJSON("tokens");
|
|
257
1314
|
if (!stored?.tokens?.access_token) return true;
|
|
258
1315
|
if (stored.expiresAt === void 0) return false;
|
|
@@ -337,7 +1394,10 @@ var beginMcpOAuth = async (provider, opts = {}) => {
|
|
|
337
1394
|
};
|
|
338
1395
|
|
|
339
1396
|
// src/mcp/http.ts
|
|
1397
|
+
var MAX_TIMER_MS = 2147483647;
|
|
340
1398
|
var MAX_TOOL_LIST_PAGES = 100;
|
|
1399
|
+
var MCP_LISTEN_ACK_TIMEOUT_MS = 1e4;
|
|
1400
|
+
var isSdkError = (err, code) => (err instanceof SdkError || err instanceof Error && err.name === "SdkError") && err.code === code;
|
|
341
1401
|
var listAllTools = async (client, onTruncated) => {
|
|
342
1402
|
const all = [];
|
|
343
1403
|
let cursor;
|
|
@@ -358,14 +1418,14 @@ var listAllTools = async (client, onTruncated) => {
|
|
|
358
1418
|
};
|
|
359
1419
|
var ConnectTimeoutError = class extends Error {
|
|
360
1420
|
};
|
|
361
|
-
var withTimeout = (p, ms,
|
|
1421
|
+
var withTimeout = (p, ms, label2) => {
|
|
362
1422
|
if (!(ms > 0)) return p;
|
|
363
1423
|
let timer;
|
|
364
1424
|
return Promise.race([
|
|
365
1425
|
p.finally(() => clearTimeout(timer)),
|
|
366
1426
|
new Promise((_, reject) => {
|
|
367
1427
|
timer = setTimeout(
|
|
368
|
-
() => reject(new ConnectTimeoutError(`${
|
|
1428
|
+
() => reject(new ConnectTimeoutError(`${label2} timed out after ${ms} ms`)),
|
|
369
1429
|
ms
|
|
370
1430
|
);
|
|
371
1431
|
})
|
|
@@ -475,20 +1535,48 @@ var refreshIfExpired = async (provider, serverUrl, fetchFn, log, name, detailLog
|
|
|
475
1535
|
}
|
|
476
1536
|
};
|
|
477
1537
|
var isNetworkLevelFailure = (err) => err instanceof TypeError || /failed to fetch|networkerror|load failed/i.test(String(err));
|
|
478
|
-
var diagnoseMcpCors = async (url, fetchFn = globalThis.fetch) => {
|
|
1538
|
+
var diagnoseMcpCors = async (url, fetchFn = globalThis.fetch, opts = {}) => {
|
|
1539
|
+
const body = JSON.stringify({ jsonrpc: "2.0", id: 0, method: "ping" });
|
|
479
1540
|
let plain;
|
|
480
1541
|
try {
|
|
481
1542
|
plain = await fetchFn(url, {
|
|
482
1543
|
method: "POST",
|
|
483
1544
|
headers: { "content-type": "application/json" },
|
|
484
|
-
body
|
|
1545
|
+
body
|
|
485
1546
|
});
|
|
486
1547
|
} catch {
|
|
487
1548
|
return `the browser blocked every request to ${url}, including a plain one. The server is unreachable, or it does not answer the CORS preflight for this origin: it must return Access-Control-Allow-Origin (and handle OPTIONS) on the MCP endpoint, the OAuth endpoints and the /.well-known documents.`;
|
|
488
1549
|
}
|
|
489
|
-
const hints = [
|
|
490
|
-
|
|
491
|
-
|
|
1550
|
+
const hints = [];
|
|
1551
|
+
const modern = opts.protocol === "auto" || opts.protocol === "modern";
|
|
1552
|
+
if (modern) {
|
|
1553
|
+
const refused = [];
|
|
1554
|
+
for (const [header, value] of [
|
|
1555
|
+
["MCP-Protocol-Version", MCP_MODERN_PROTOCOL_VERSION],
|
|
1556
|
+
[MCP_MODERN_REQUEST_HEADERS[0], "ping"],
|
|
1557
|
+
[MCP_MODERN_REQUEST_HEADERS[1], "cors-check"]
|
|
1558
|
+
]) {
|
|
1559
|
+
try {
|
|
1560
|
+
await fetchFn(url, {
|
|
1561
|
+
method: "POST",
|
|
1562
|
+
headers: { "content-type": "application/json", [header]: value },
|
|
1563
|
+
body
|
|
1564
|
+
});
|
|
1565
|
+
} catch {
|
|
1566
|
+
refused.push(header);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
if (refused.length > 0) {
|
|
1570
|
+
hints.push(
|
|
1571
|
+
`a plain request to ${url} succeeded (HTTP ${plain.status}), but one carrying ${refused.join(" / ")} was blocked: the server's Access-Control-Allow-Headers does not list ${refused.length === 1 ? "it" : "them"}. The ${MCP_MODERN_PROTOCOL_VERSION} revision of the protocol (protocol: '${opts.protocol}') sends MCP-Protocol-Version, ${MCP_MODERN_REQUEST_HEADERS.join(" and ")} on every request: add ${refused.join(", ")} to Access-Control-Allow-Headers, alongside Content-Type and Authorization (and any Mcp-Param-* header the server's tools declare).`
|
|
1572
|
+
);
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
if (hints.length === 0) {
|
|
1576
|
+
hints.push(
|
|
1577
|
+
`a plain request to ${url} succeeded (HTTP ${plain.status}) but the transport's did not, so the origin is allowed and a request HEADER is being refused. Add MCP-Protocol-Version (required on every request after initialize) and Last-Event-ID to the server's Access-Control-Allow-Headers, alongside Content-Type, Authorization and mcp-session-id.` + (modern ? ` With protocol: '${opts.protocol}', ${MCP_MODERN_REQUEST_HEADERS.join(" and ")} too.` : "")
|
|
1578
|
+
);
|
|
1579
|
+
}
|
|
492
1580
|
if (plain.status === 401 && !plain.headers.get("www-authenticate")) {
|
|
493
1581
|
hints.push(
|
|
494
1582
|
"The server also answers 401 without exposing WWW-Authenticate: add it to Access-Control-Expose-Headers, or a browser client cannot read the challenge and OAuth discovery never starts."
|
|
@@ -496,22 +1584,39 @@ var diagnoseMcpCors = async (url, fetchFn = globalThis.fetch) => {
|
|
|
496
1584
|
}
|
|
497
1585
|
return hints.join(" ");
|
|
498
1586
|
};
|
|
1587
|
+
var NAMES_REFUSED_HEADERS = /was blocked: the server's Access-Control-Allow-Headers/;
|
|
499
1588
|
var warnTruncated = (log, name) => log(
|
|
500
1589
|
"warn",
|
|
501
1590
|
`[mcp] ${name}: tools/list still paginating after ${MAX_TOOL_LIST_PAGES} pages; the rest of the tools are not mounted`
|
|
502
1591
|
);
|
|
503
|
-
var openConnection = async (name, cfg, opts, log) => {
|
|
1592
|
+
var openConnection = async (name, cfg, opts, log, elicitation) => {
|
|
504
1593
|
let client;
|
|
1594
|
+
let listener;
|
|
505
1595
|
let timedOut = false;
|
|
506
1596
|
const timeoutMs = cfg.connectTimeoutMs ?? opts.connectTimeoutMs ?? 3e4;
|
|
507
|
-
const
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
1597
|
+
const probe = { blocked: false };
|
|
1598
|
+
const attempt = connectAndList(
|
|
1599
|
+
name,
|
|
1600
|
+
cfg,
|
|
1601
|
+
opts,
|
|
1602
|
+
log,
|
|
1603
|
+
probe,
|
|
1604
|
+
(c) => {
|
|
1605
|
+
client = c;
|
|
1606
|
+
if (timedOut) void c.close().catch(() => {
|
|
1607
|
+
});
|
|
1608
|
+
},
|
|
1609
|
+
(l) => {
|
|
1610
|
+
listener = l;
|
|
1611
|
+
if (timedOut) l.stop();
|
|
1612
|
+
},
|
|
1613
|
+
elicitation
|
|
1614
|
+
);
|
|
512
1615
|
attempt.then(
|
|
513
1616
|
(r) => {
|
|
514
|
-
if (timedOut)
|
|
1617
|
+
if (!timedOut) return;
|
|
1618
|
+
r.listener?.stop();
|
|
1619
|
+
void r.client?.close().catch(() => {
|
|
515
1620
|
});
|
|
516
1621
|
},
|
|
517
1622
|
() => {
|
|
@@ -521,13 +1626,26 @@ var openConnection = async (name, cfg, opts, log) => {
|
|
|
521
1626
|
return await withTimeout(attempt, timeoutMs, "connect");
|
|
522
1627
|
} catch (err) {
|
|
523
1628
|
if (err instanceof ConnectTimeoutError) timedOut = true;
|
|
1629
|
+
listener?.stop();
|
|
524
1630
|
if (client) await client.close().catch(() => {
|
|
525
1631
|
});
|
|
526
1632
|
const needsAuthorization = err instanceof UnauthorizedError;
|
|
527
1633
|
let message = err instanceof Error ? err.message : String(err);
|
|
528
|
-
if (
|
|
529
|
-
|
|
530
|
-
|
|
1634
|
+
if (cfg.protocol === "modern" && isSdkError(err, SdkErrorCode.EraNegotiationFailed)) {
|
|
1635
|
+
message = `${message} - ${MCP_MODERN_REFUSED_HINT}`;
|
|
1636
|
+
}
|
|
1637
|
+
if (!needsAuthorization && !(err instanceof ConnectTimeoutError)) {
|
|
1638
|
+
if (isNetworkLevelFailure(err)) {
|
|
1639
|
+
const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, {
|
|
1640
|
+
protocol: probe.mode
|
|
1641
|
+
}).catch(() => void 0);
|
|
1642
|
+
if (hint) message = `${message} - ${hint}`;
|
|
1643
|
+
} else if (probe.blocked) {
|
|
1644
|
+
const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, {
|
|
1645
|
+
protocol: probe.mode
|
|
1646
|
+
}).catch(() => void 0);
|
|
1647
|
+
if (hint && NAMES_REFUSED_HEADERS.test(hint)) message = `${message} - ${hint}`;
|
|
1648
|
+
}
|
|
531
1649
|
}
|
|
532
1650
|
log(
|
|
533
1651
|
"error",
|
|
@@ -536,7 +1654,29 @@ var openConnection = async (name, cfg, opts, log) => {
|
|
|
536
1654
|
return { name, error: message, needsAuthorization };
|
|
537
1655
|
}
|
|
538
1656
|
};
|
|
539
|
-
var
|
|
1657
|
+
var listenForToolChanges = async (name, client, log, announce, onListener, skills) => {
|
|
1658
|
+
if (!client.getServerCapabilities()?.tools?.listChanged) {
|
|
1659
|
+
log("info", `[mcp] ${name}: the server does not announce tool list changes`);
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
const resources = skills && client.getServerCapabilities()?.resources?.listChanged === true;
|
|
1663
|
+
const listener = createMcpListenSupervisor({
|
|
1664
|
+
server: name,
|
|
1665
|
+
listen: (signal) => client.listen(
|
|
1666
|
+
{ toolsListChanged: true, ...resources ? { resourcesListChanged: true } : {} },
|
|
1667
|
+
{ timeout: MCP_LISTEN_ACK_TIMEOUT_MS, signal }
|
|
1668
|
+
),
|
|
1669
|
+
log,
|
|
1670
|
+
// Changes made while no stream was open: the path a notice takes, so the host
|
|
1671
|
+
// sees what a notice causes.
|
|
1672
|
+
onResubscribed: announce
|
|
1673
|
+
});
|
|
1674
|
+
onListener(listener);
|
|
1675
|
+
await listener.start();
|
|
1676
|
+
};
|
|
1677
|
+
var connectAndList = async (name, cfg, opts, log, probe, onClient, onListener, elicitation) => {
|
|
1678
|
+
const mode = mcpProtocolMode(cfg.protocol, name);
|
|
1679
|
+
probe.mode = mode;
|
|
540
1680
|
if (cfg.headers && cfg.getHeaders) {
|
|
541
1681
|
throw new Error(`MCP server "${name}": specify either headers or getHeaders, not both`);
|
|
542
1682
|
}
|
|
@@ -568,33 +1708,222 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
|
|
|
568
1708
|
fetch: cfg.authProvider && asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog) || cfg.fetch,
|
|
569
1709
|
reconnectionOptions: { ...DEFAULT_RECONNECTION, ...cfg.reconnection }
|
|
570
1710
|
});
|
|
571
|
-
|
|
1711
|
+
let probing = mode !== "legacy";
|
|
1712
|
+
transport.onerror = (err) => {
|
|
1713
|
+
if (!probing) {
|
|
1714
|
+
log("warn", `[mcp] ${name}: transport error - ${err.message}`);
|
|
1715
|
+
return;
|
|
1716
|
+
}
|
|
1717
|
+
if (isNetworkLevelFailure(err)) probe.blocked = true;
|
|
1718
|
+
log("info", `[mcp] ${name}: version probe (server/discover) - ${err.message}`);
|
|
1719
|
+
};
|
|
572
1720
|
transport.onclose = () => log("info", `[mcp] ${name}: transport closed`);
|
|
573
1721
|
const enterprise = cfg.authProvider ? asEnterpriseProvider(cfg.authProvider) : void 0;
|
|
1722
|
+
const negotiation = mcpVersionNegotiation(mode);
|
|
1723
|
+
const apps = mcpAppsModeOf(cfg.apps, opts.apps) === "on";
|
|
1724
|
+
const skillsSetting = mcpSkillsSettingOf(cfg.skills, name);
|
|
1725
|
+
const skillsWanted = skillsSetting.on && mode !== "legacy";
|
|
1726
|
+
if (skillsSetting.on && mode === "legacy") {
|
|
1727
|
+
log(
|
|
1728
|
+
"warn",
|
|
1729
|
+
`[mcp] ${name}: skills: true needs protocol 'auto' or 'modern' (the Skills extension is written against 2026-07-28); no skills are requested`
|
|
1730
|
+
);
|
|
1731
|
+
}
|
|
1732
|
+
const clientOptions = enterprise || negotiation || elicitation || apps || skillsWanted ? {
|
|
1733
|
+
// An extension is opt-in: it is declared only by the client that uses
|
|
1734
|
+
// it. So is elicitation: without `onElicitation` no capability is
|
|
1735
|
+
// declared, and a server cannot ask. MCP Apps: only with `apps`.
|
|
1736
|
+
...enterprise || elicitation || apps || skillsWanted ? {
|
|
1737
|
+
capabilities: {
|
|
1738
|
+
...enterprise || apps || skillsWanted ? {
|
|
1739
|
+
extensions: {
|
|
1740
|
+
...enterprise ? { [enterprise.extension]: {} } : {},
|
|
1741
|
+
...apps ? { [MCP_APPS_EXTENSION]: { mimeTypes: [MCP_APP_MIME_TYPE] } } : {},
|
|
1742
|
+
...skillsWanted ? { [MCP_SKILLS_EXTENSION]: {} } : {}
|
|
1743
|
+
}
|
|
1744
|
+
} : {},
|
|
1745
|
+
...elicitation ? { elicitation: elicitation.capability } : {}
|
|
1746
|
+
}
|
|
1747
|
+
} : {},
|
|
1748
|
+
...negotiation ? {
|
|
1749
|
+
versionNegotiation: negotiation,
|
|
1750
|
+
// 2026-07-28: an `input_required` result is NOT answered and the
|
|
1751
|
+
// call is NOT sent again by the SDK (its default would try
|
|
1752
|
+
// both). Without `onElicitation` it fails the tool call; with
|
|
1753
|
+
// it, `execute` answers it through the session, which keeps
|
|
1754
|
+
// the caps the SDK's own loop does not have.
|
|
1755
|
+
inputRequired: { autoFulfill: false }
|
|
1756
|
+
} : {}
|
|
1757
|
+
} : void 0;
|
|
574
1758
|
const client = new Client(
|
|
575
1759
|
{ name: opts.clientName ?? "agent-web", version: opts.clientVersion ?? "0.0.0" },
|
|
576
|
-
|
|
577
|
-
enterprise ? { capabilities: { extensions: { [enterprise.extension]: {} } } } : void 0
|
|
1760
|
+
clientOptions
|
|
578
1761
|
);
|
|
1762
|
+
if (elicitation) {
|
|
1763
|
+
client.setRequestHandler(
|
|
1764
|
+
"elicitation/create",
|
|
1765
|
+
(request) => elicitation.onRequest(request.params)
|
|
1766
|
+
);
|
|
1767
|
+
}
|
|
579
1768
|
onClient(client);
|
|
580
1769
|
await client.connect(transport);
|
|
1770
|
+
probing = false;
|
|
1771
|
+
const era = client.getProtocolEra() ?? "legacy";
|
|
1772
|
+
const version = client.getNegotiatedProtocolVersion() ?? "";
|
|
1773
|
+
if (mode !== "legacy") {
|
|
1774
|
+
log(
|
|
1775
|
+
"info",
|
|
1776
|
+
`[mcp] ${name}: protocol ${version} (${era === "modern" ? "modern: stateless, no session" : "legacy: the initialize handshake"}; configured '${mode}')`
|
|
1777
|
+
);
|
|
1778
|
+
if (era === "legacy" && probe.blocked) {
|
|
1779
|
+
const hint = await diagnoseMcpCors(cfg.url, cfg.fetch, { protocol: mode }).catch(
|
|
1780
|
+
() => void 0
|
|
1781
|
+
);
|
|
1782
|
+
log(
|
|
1783
|
+
"warn",
|
|
1784
|
+
`[mcp] ${name}: the version probe (server/discover) was blocked before it reached the server, so the connection uses ${version}${hint && NAMES_REFUSED_HEADERS.test(hint) ? ` - ${hint}` : ""}`
|
|
1785
|
+
);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
let skills;
|
|
1789
|
+
if (skillsWanted) {
|
|
1790
|
+
if (era !== "modern") {
|
|
1791
|
+
log(
|
|
1792
|
+
"info",
|
|
1793
|
+
`[mcp] ${name}: skills: true, but the connection uses ${version} - the Skills extension needs 2026-07-28; no skills`
|
|
1794
|
+
);
|
|
1795
|
+
} else if (!client.getServerCapabilities()?.extensions?.[MCP_SKILLS_EXTENSION]) {
|
|
1796
|
+
log("info", `[mcp] ${name}: the server does not offer skills (${MCP_SKILLS_EXTENSION})`);
|
|
1797
|
+
} else {
|
|
1798
|
+
const { SkillsClient } = await import("@modelcontextprotocol/client/ext/skills");
|
|
1799
|
+
skills = createMcpSkillCatalog(
|
|
1800
|
+
name,
|
|
1801
|
+
new SkillsClient(client, { skipInvalid: true }),
|
|
1802
|
+
(level, message) => log(level, message),
|
|
1803
|
+
skillsSetting.consent ? { consent: skillsSetting.consent } : {}
|
|
1804
|
+
);
|
|
1805
|
+
await skills.refresh();
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
let listener;
|
|
581
1809
|
if (opts.onToolsChanged) {
|
|
582
1810
|
const notify = opts.onToolsChanged;
|
|
583
|
-
|
|
1811
|
+
const announce = () => notify(name);
|
|
1812
|
+
client.setNotificationHandler("notifications/tools/list_changed", announce);
|
|
1813
|
+
if (skills) client.setNotificationHandler("notifications/resources/list_changed", announce);
|
|
1814
|
+
if (era === "modern") {
|
|
1815
|
+
await listenForToolChanges(
|
|
1816
|
+
name,
|
|
1817
|
+
client,
|
|
1818
|
+
log,
|
|
1819
|
+
announce,
|
|
1820
|
+
(l) => {
|
|
1821
|
+
listener = l;
|
|
1822
|
+
onListener(l);
|
|
1823
|
+
},
|
|
1824
|
+
Boolean(skills)
|
|
1825
|
+
);
|
|
1826
|
+
}
|
|
584
1827
|
}
|
|
585
1828
|
const listed = await listAllTools(client, () => warnTruncated(log, name));
|
|
586
|
-
return {
|
|
1829
|
+
return {
|
|
1830
|
+
name,
|
|
1831
|
+
client,
|
|
1832
|
+
listed,
|
|
1833
|
+
...listener ? { listener } : {},
|
|
1834
|
+
instructions: cleanMcpInstructions(client.getInstructions()),
|
|
1835
|
+
protocol: { version, era },
|
|
1836
|
+
...skills ? { skills } : {}
|
|
1837
|
+
};
|
|
587
1838
|
};
|
|
588
1839
|
var connectMcpHttp = async (servers, opts = {}) => {
|
|
589
1840
|
const log = opts.onLog ?? (() => {
|
|
590
1841
|
});
|
|
1842
|
+
const elicitationOptions = resolveMcpElicitationOptions(opts.elicitation);
|
|
1843
|
+
const elicitationDeps = opts.onElicitation ? { handler: opts.onElicitation, options: elicitationOptions, log } : void 0;
|
|
1844
|
+
const elicitationSessions = /* @__PURE__ */ new Map();
|
|
1845
|
+
const elicitationSessionOf = (name) => {
|
|
1846
|
+
if (!elicitationDeps) return void 0;
|
|
1847
|
+
let session = elicitationSessions.get(name);
|
|
1848
|
+
if (!session) {
|
|
1849
|
+
session = createMcpElicitationSession(name, elicitationDeps);
|
|
1850
|
+
elicitationSessions.set(name, session);
|
|
1851
|
+
}
|
|
1852
|
+
return session;
|
|
1853
|
+
};
|
|
591
1854
|
const clients = /* @__PURE__ */ new Map();
|
|
592
1855
|
const tools = {};
|
|
593
1856
|
const catalog = [];
|
|
594
1857
|
const results = [];
|
|
595
1858
|
const instructions = [];
|
|
596
1859
|
const instructionsOf = /* @__PURE__ */ new Map();
|
|
1860
|
+
const protocols = [];
|
|
1861
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
597
1862
|
const mountedKeys = /* @__PURE__ */ new Map();
|
|
1863
|
+
const skillCatalogs = /* @__PURE__ */ new Map();
|
|
1864
|
+
const appsModes = new Map(
|
|
1865
|
+
Object.entries(servers).map(([name, cfg]) => [name, mcpAppsModeOf(cfg.apps, opts.apps)])
|
|
1866
|
+
);
|
|
1867
|
+
const appsOn = [...appsModes.values()].includes("on");
|
|
1868
|
+
const appToolsOf = /* @__PURE__ */ new Map();
|
|
1869
|
+
const appResources = /* @__PURE__ */ new Map();
|
|
1870
|
+
let appEventSeq = 0;
|
|
1871
|
+
const requestToolCall = async (name, client, key, toolName, args, options) => {
|
|
1872
|
+
const elicitation = elicitationSessionOf(name);
|
|
1873
|
+
try {
|
|
1874
|
+
if (elicitation) {
|
|
1875
|
+
const call = options;
|
|
1876
|
+
const run = call?.agentRun;
|
|
1877
|
+
const signal = call?.abortSignal ?? run?.signal;
|
|
1878
|
+
const emit = run?.emit;
|
|
1879
|
+
const step = run?.step;
|
|
1880
|
+
const helper = run?.subagent ?? call?.subagentCall;
|
|
1881
|
+
const counter = call?.subagentCall?.elicitations ?? run?.elicitations;
|
|
1882
|
+
const pause = run?.clock?.pause ?? call?.subagentCall?.pause;
|
|
1883
|
+
const era = client.getProtocolEra() ?? "legacy";
|
|
1884
|
+
const info = {
|
|
1885
|
+
tool: key,
|
|
1886
|
+
toolName,
|
|
1887
|
+
...signal ? { signal } : {},
|
|
1888
|
+
...emit ? {
|
|
1889
|
+
emit: (event) => emit(
|
|
1890
|
+
event.type === "mcp.elicitation-requested" && step ? { ...event, step } : event
|
|
1891
|
+
)
|
|
1892
|
+
} : {},
|
|
1893
|
+
...run?.runId ? { runId: run.runId } : {},
|
|
1894
|
+
...helper ? { subagent: { id: helper.id, depth: helper.depth } } : {},
|
|
1895
|
+
...counter ? { run: counter } : {},
|
|
1896
|
+
...pause ? { pause } : {}
|
|
1897
|
+
};
|
|
1898
|
+
return await elicitation.call(
|
|
1899
|
+
era,
|
|
1900
|
+
info,
|
|
1901
|
+
(leg) => client.request(
|
|
1902
|
+
{
|
|
1903
|
+
method: "tools/call",
|
|
1904
|
+
params: { name: toolName, arguments: args, ...leg.retry }
|
|
1905
|
+
},
|
|
1906
|
+
{
|
|
1907
|
+
...leg.signal ? { signal: leg.signal } : {},
|
|
1908
|
+
...leg.ownTimeout ? { timeout: MAX_TIMER_MS } : {},
|
|
1909
|
+
// Hand an `input_required` result back instead of failing
|
|
1910
|
+
// on it: the session answers it.
|
|
1911
|
+
...era === "modern" ? { allowInputRequired: true } : {}
|
|
1912
|
+
}
|
|
1913
|
+
)
|
|
1914
|
+
);
|
|
1915
|
+
}
|
|
1916
|
+
return await client.request(
|
|
1917
|
+
{ method: "tools/call", params: { name: toolName, arguments: args } },
|
|
1918
|
+
options?.abortSignal ? { signal: options.abortSignal } : void 0
|
|
1919
|
+
);
|
|
1920
|
+
} catch (err) {
|
|
1921
|
+
if (isSdkError(err, SdkErrorCode.UnsupportedResultType)) {
|
|
1922
|
+
throw new Error(mcpInputRequiredMessage(toolName));
|
|
1923
|
+
}
|
|
1924
|
+
throw err;
|
|
1925
|
+
}
|
|
1926
|
+
};
|
|
598
1927
|
const mountTools = (name, client, listed) => {
|
|
599
1928
|
const prefix = `${sanitizeName(name)}__`;
|
|
600
1929
|
for (const k of mountedKeys.get(name) ?? []) {
|
|
@@ -604,10 +1933,41 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
604
1933
|
if (catalog[i].server === name) catalog.splice(i, 1);
|
|
605
1934
|
}
|
|
606
1935
|
const keys = [];
|
|
1936
|
+
const appTools = /* @__PURE__ */ new Map();
|
|
607
1937
|
let schemaValidator;
|
|
608
1938
|
let mounted = 0;
|
|
1939
|
+
const appsMode = appsModes.get(name) ?? "off";
|
|
609
1940
|
for (const t of listed) {
|
|
610
1941
|
const prefixed = prefix + sanitizeName(t.name);
|
|
1942
|
+
const ui = appsMode !== "off" ? mcpAppToolMeta(t) : void 0;
|
|
1943
|
+
if (appsMode === "on" && ui?.refusedUri !== void 0) {
|
|
1944
|
+
log(
|
|
1945
|
+
"warn",
|
|
1946
|
+
`[mcp] ${name}: tool "${t.name}" declares an app that is not a ui:// URI (${ui.refusedUri}); ignored`
|
|
1947
|
+
);
|
|
1948
|
+
}
|
|
1949
|
+
if (ui && !ui.visibility.includes("model")) {
|
|
1950
|
+
if (appsMode === "declined") {
|
|
1951
|
+
log(
|
|
1952
|
+
"info",
|
|
1953
|
+
`[mcp] ${name}: tool "${t.name}" is for its app only, and apps are off for this server; not mounted`
|
|
1954
|
+
);
|
|
1955
|
+
continue;
|
|
1956
|
+
}
|
|
1957
|
+
if (ui.visibility.includes("app")) {
|
|
1958
|
+
appTools.set(t.name, {
|
|
1959
|
+
name: t.name,
|
|
1960
|
+
key: prefixed,
|
|
1961
|
+
description: t.description ?? "",
|
|
1962
|
+
inputSchema: t.inputSchema,
|
|
1963
|
+
readOnly: t.annotations?.readOnlyHint === true,
|
|
1964
|
+
visibility: ui.visibility,
|
|
1965
|
+
...ui.resourceUri ? { resourceUri: ui.resourceUri } : {}
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1968
|
+
log("info", `[mcp] ${name}: tool "${t.name}" is for its app only; not mounted`);
|
|
1969
|
+
continue;
|
|
1970
|
+
}
|
|
611
1971
|
if (prefixed.length > MAX_TOOL_NAME_LEN) {
|
|
612
1972
|
log(
|
|
613
1973
|
"warn",
|
|
@@ -625,6 +1985,18 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
625
1985
|
}
|
|
626
1986
|
const description = t.description ?? "";
|
|
627
1987
|
const readOnly = t.annotations?.readOnlyHint === true;
|
|
1988
|
+
const appUri = appsMode === "on" ? ui?.resourceUri : void 0;
|
|
1989
|
+
if (appsMode === "on" && ui?.visibility.includes("app")) {
|
|
1990
|
+
appTools.set(t.name, {
|
|
1991
|
+
name: t.name,
|
|
1992
|
+
key,
|
|
1993
|
+
description,
|
|
1994
|
+
inputSchema: t.inputSchema,
|
|
1995
|
+
readOnly,
|
|
1996
|
+
visibility: ui.visibility,
|
|
1997
|
+
...appUri ? { resourceUri: appUri } : {}
|
|
1998
|
+
});
|
|
1999
|
+
}
|
|
628
2000
|
let outputValidator;
|
|
629
2001
|
const outputValidatorOf = () => {
|
|
630
2002
|
if (!t.outputSchema || outputValidator) return outputValidator;
|
|
@@ -645,13 +2017,32 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
645
2017
|
inputSchema: jsonSchema(t.inputSchema),
|
|
646
2018
|
execute: async (args, options) => {
|
|
647
2019
|
const validate = outputValidatorOf();
|
|
648
|
-
const res = await
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
2020
|
+
const res = await requestToolCall(
|
|
2021
|
+
name,
|
|
2022
|
+
client,
|
|
2023
|
+
key,
|
|
2024
|
+
t.name,
|
|
2025
|
+
args ?? {},
|
|
2026
|
+
options
|
|
654
2027
|
);
|
|
2028
|
+
if (appUri) {
|
|
2029
|
+
const run = options?.agentRun;
|
|
2030
|
+
const emit = run?.emit;
|
|
2031
|
+
if (emit) {
|
|
2032
|
+
const result = mcpAppToolResultOf(res);
|
|
2033
|
+
emit({
|
|
2034
|
+
type: "mcp.app",
|
|
2035
|
+
id: `mcp-app-${Date.now().toString(36)}-${appEventSeq += 1}`,
|
|
2036
|
+
server: name,
|
|
2037
|
+
tool: key,
|
|
2038
|
+
toolName: t.name,
|
|
2039
|
+
resourceUri: appUri,
|
|
2040
|
+
input: args ?? {},
|
|
2041
|
+
...result ? { result } : {},
|
|
2042
|
+
...run?.step ? { step: run.step } : {}
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
655
2046
|
let schemaNote;
|
|
656
2047
|
const violation = validate && outputSchemaViolation(t.name, res, validate);
|
|
657
2048
|
if (violation) {
|
|
@@ -674,15 +2065,29 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
674
2065
|
});
|
|
675
2066
|
if (readOnly) tools[key].readOnly = true;
|
|
676
2067
|
markMcpTool(tools[key], name, instructionsOf.get(name));
|
|
677
|
-
|
|
2068
|
+
const skillSource = skillCatalogs.get(name)?.source;
|
|
2069
|
+
if (skillSource) markMcpSkills(tools[key], skillSource);
|
|
2070
|
+
catalog.push({
|
|
2071
|
+
name: key,
|
|
2072
|
+
description,
|
|
2073
|
+
server: name,
|
|
2074
|
+
...readOnly ? { readOnly } : {},
|
|
2075
|
+
...appUri ? { app: appUri } : {}
|
|
2076
|
+
});
|
|
678
2077
|
keys.push(key);
|
|
679
2078
|
mounted += 1;
|
|
680
2079
|
}
|
|
681
2080
|
mountedKeys.set(name, keys);
|
|
2081
|
+
if (appsMode === "on") {
|
|
2082
|
+
appToolsOf.set(name, appTools);
|
|
2083
|
+
appResources.delete(name);
|
|
2084
|
+
}
|
|
682
2085
|
log("info", `[mcp] ${name}: ${mounted} tools mounted`);
|
|
683
2086
|
};
|
|
684
2087
|
const connects = await Promise.all(
|
|
685
|
-
Object.entries(servers).map(
|
|
2088
|
+
Object.entries(servers).map(
|
|
2089
|
+
([name, cfg]) => openConnection(name, cfg, opts, log, elicitationSessionOf(name))
|
|
2090
|
+
)
|
|
686
2091
|
);
|
|
687
2092
|
for (const server of connects) {
|
|
688
2093
|
if (!server.client || !server.listed) {
|
|
@@ -695,6 +2100,7 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
695
2100
|
continue;
|
|
696
2101
|
}
|
|
697
2102
|
clients.set(server.name, server.client);
|
|
2103
|
+
if (server.listener) listeners.set(server.name, server.listener);
|
|
698
2104
|
if (server.instructions) {
|
|
699
2105
|
log(
|
|
700
2106
|
"info",
|
|
@@ -703,22 +2109,116 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
703
2109
|
instructions.push({ server: server.name, instructions: server.instructions });
|
|
704
2110
|
instructionsOf.set(server.name, server.instructions);
|
|
705
2111
|
}
|
|
2112
|
+
if (server.protocol) protocols.push({ server: server.name, ...server.protocol });
|
|
2113
|
+
if (server.skills) skillCatalogs.set(server.name, server.skills);
|
|
706
2114
|
mountTools(server.name, server.client, server.listed);
|
|
707
2115
|
results.push({ name: server.name, connected: true });
|
|
708
2116
|
}
|
|
2117
|
+
const connectedClient = (server) => {
|
|
2118
|
+
const client = clients.get(server);
|
|
2119
|
+
if (!client) throw new Error(`MCP server "${server}" is not connected`);
|
|
2120
|
+
return client;
|
|
2121
|
+
};
|
|
2122
|
+
const apps = appsOn ? {
|
|
2123
|
+
readUiResource: (server, uri, readOptions) => {
|
|
2124
|
+
let client;
|
|
2125
|
+
try {
|
|
2126
|
+
client = connectedClient(server);
|
|
2127
|
+
} catch (err) {
|
|
2128
|
+
return Promise.reject(err);
|
|
2129
|
+
}
|
|
2130
|
+
const declared = [...appToolsOf.get(server)?.values() ?? []].some(
|
|
2131
|
+
(t) => t.resourceUri === uri
|
|
2132
|
+
);
|
|
2133
|
+
if (!declared) {
|
|
2134
|
+
return Promise.reject(
|
|
2135
|
+
new Error(`no tool of MCP server "${server}" declares the app ${uri}`)
|
|
2136
|
+
);
|
|
2137
|
+
}
|
|
2138
|
+
let cache = appResources.get(server);
|
|
2139
|
+
if (!cache) {
|
|
2140
|
+
cache = /* @__PURE__ */ new Map();
|
|
2141
|
+
appResources.set(server, cache);
|
|
2142
|
+
}
|
|
2143
|
+
const cached = cache.get(uri);
|
|
2144
|
+
if (cached) return cached;
|
|
2145
|
+
const reading = client.request(
|
|
2146
|
+
{ method: "resources/read", params: { uri } },
|
|
2147
|
+
readOptions?.signal ? { signal: readOptions.signal } : void 0
|
|
2148
|
+
).then((result) => {
|
|
2149
|
+
const resource = mcpAppResourceOf(server, uri, result);
|
|
2150
|
+
log("info", `[mcp] ${server}: app ${uri} - ${describeMcpAppPolicy(resource)}`);
|
|
2151
|
+
return resource;
|
|
2152
|
+
});
|
|
2153
|
+
reading.catch(() => {
|
|
2154
|
+
if (appResources.get(server)?.get(uri) === reading) cache.delete(uri);
|
|
2155
|
+
});
|
|
2156
|
+
cache.set(uri, reading);
|
|
2157
|
+
return reading;
|
|
2158
|
+
},
|
|
2159
|
+
appTool: (server, toolName) => {
|
|
2160
|
+
const tool = appToolsOf.get(server)?.get(toolName);
|
|
2161
|
+
return tool ? { ...tool, visibility: [...tool.visibility] } : void 0;
|
|
2162
|
+
},
|
|
2163
|
+
readResource: async (server, uri, readOptions) => {
|
|
2164
|
+
const client = connectedClient(server);
|
|
2165
|
+
if (!appToolsOf.has(server)) {
|
|
2166
|
+
throw new Error(`MCP Apps are off for the MCP server "${server}"`);
|
|
2167
|
+
}
|
|
2168
|
+
if (typeof uri !== "string" || uri.length === 0 || uri.length > 2048 || // eslint-disable-next-line no-control-regex
|
|
2169
|
+
/[\u0000-\u001f\u007f\s]/.test(uri)) {
|
|
2170
|
+
throw new Error("a resource URI is one line of at most 2048 characters");
|
|
2171
|
+
}
|
|
2172
|
+
log("info", `[mcp] ${server}: an app's download reads ${uri.slice(0, 200)}`);
|
|
2173
|
+
const result = await client.request(
|
|
2174
|
+
{ method: "resources/read", params: { uri } },
|
|
2175
|
+
readOptions?.signal ? { signal: readOptions.signal } : void 0
|
|
2176
|
+
);
|
|
2177
|
+
return mcpAppDownloadOf(uri, result, readOptions?.maxBytes ?? MCP_APP_MAX_DOWNLOAD_BYTES);
|
|
2178
|
+
},
|
|
2179
|
+
callAppTool: async (server, toolName, args, callOptions) => {
|
|
2180
|
+
const client = connectedClient(server);
|
|
2181
|
+
const tool = appToolsOf.get(server)?.get(toolName);
|
|
2182
|
+
if (!tool) {
|
|
2183
|
+
throw new Error(`MCP server "${server}" has no tool "${toolName}" that an app may call`);
|
|
2184
|
+
}
|
|
2185
|
+
if (typeof args !== "object" || args === null || Array.isArray(args)) {
|
|
2186
|
+
throw new Error(`the arguments of "${toolName}" must be an object`);
|
|
2187
|
+
}
|
|
2188
|
+
log("info", `[mcp] ${server}: an app called ${toolName}`);
|
|
2189
|
+
const res = await requestToolCall(
|
|
2190
|
+
server,
|
|
2191
|
+
client,
|
|
2192
|
+
tool.key,
|
|
2193
|
+
toolName,
|
|
2194
|
+
args,
|
|
2195
|
+
callOptions?.signal ? { abortSignal: callOptions.signal } : void 0
|
|
2196
|
+
);
|
|
2197
|
+
return mcpAppToolResultOf(res) ?? {
|
|
2198
|
+
content: [{ type: "text", text: "The result was too large to hand to the app." }],
|
|
2199
|
+
isError: true
|
|
2200
|
+
};
|
|
2201
|
+
}
|
|
2202
|
+
} : void 0;
|
|
709
2203
|
return {
|
|
710
2204
|
tools,
|
|
711
2205
|
catalog,
|
|
712
2206
|
results,
|
|
713
2207
|
instructions,
|
|
2208
|
+
protocols,
|
|
714
2209
|
refreshServer: async (name) => {
|
|
715
2210
|
const client = clients.get(name);
|
|
716
2211
|
if (!client) throw new Error(`MCP server "${name}" is not connected`);
|
|
2212
|
+
await skillCatalogs.get(name)?.refresh();
|
|
717
2213
|
mountTools(name, client, await listAllTools(client, () => warnTruncated(log, name)));
|
|
718
2214
|
},
|
|
719
2215
|
close: async () => {
|
|
2216
|
+
for (const listener of listeners.values()) listener.stop();
|
|
2217
|
+
listeners.clear();
|
|
2218
|
+
appResources.clear();
|
|
720
2219
|
await Promise.allSettled([...clients.values()].map((c) => c.close()));
|
|
721
|
-
}
|
|
2220
|
+
},
|
|
2221
|
+
...apps ? { apps } : {}
|
|
722
2222
|
};
|
|
723
2223
|
};
|
|
724
2224
|
|
|
@@ -1475,8 +2975,21 @@ export {
|
|
|
1475
2975
|
BrowserOAuthProvider,
|
|
1476
2976
|
ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,
|
|
1477
2977
|
EnterpriseOAuthError,
|
|
2978
|
+
MCP_APPS_EXTENSION,
|
|
2979
|
+
MCP_APP_DEFAULT_VISIBILITY,
|
|
2980
|
+
MCP_APP_MAX_DOMAINS,
|
|
2981
|
+
MCP_APP_MAX_DOWNLOAD_BYTES,
|
|
2982
|
+
MCP_APP_MAX_HTML_CHARS,
|
|
2983
|
+
MCP_APP_MAX_RESULT_CHARS,
|
|
2984
|
+
MCP_APP_MIME_TYPE,
|
|
2985
|
+
MCP_ELICITATION_MAX_PER_RUN,
|
|
2986
|
+
MCP_ELICITATION_MAX_PER_TOOL_CALL,
|
|
2987
|
+
MCP_ELICITATION_TIMEOUT_MS,
|
|
1478
2988
|
MCP_INSTRUCTIONS_MAX_CHARS_PER_SERVER,
|
|
1479
2989
|
MCP_INSTRUCTIONS_MAX_CHARS_TOTAL,
|
|
2990
|
+
MCP_MODERN_PROTOCOL_VERSION,
|
|
2991
|
+
MCP_MODERN_REQUEST_HEADERS,
|
|
2992
|
+
McpAppResourceError,
|
|
1480
2993
|
MemoryOAuthStorage,
|
|
1481
2994
|
UnauthorizedError2 as UnauthorizedError,
|
|
1482
2995
|
VaultOAuthStorage,
|
|
@@ -1487,7 +3000,19 @@ export {
|
|
|
1487
3000
|
diagnoseMcpCors,
|
|
1488
3001
|
finishMcpOAuth,
|
|
1489
3002
|
flattenContent,
|
|
3003
|
+
isMcpAppMimeType,
|
|
3004
|
+
isMcpAppUri,
|
|
3005
|
+
mcpAppCspOf,
|
|
3006
|
+
mcpAppDownloadOf,
|
|
3007
|
+
mcpAppOrigin,
|
|
3008
|
+
mcpAppPermissionsOf,
|
|
3009
|
+
mcpAppResourceOf,
|
|
3010
|
+
mcpAppToolMeta,
|
|
3011
|
+
mcpAppToolResultOf,
|
|
3012
|
+
mcpAppsModeOf,
|
|
3013
|
+
normalizeMcpElicitationSchema,
|
|
1490
3014
|
readOAuthCallback,
|
|
1491
|
-
renderMcpInstructions
|
|
3015
|
+
renderMcpInstructions,
|
|
3016
|
+
validateMcpElicitationContent
|
|
1492
3017
|
};
|
|
1493
3018
|
//# sourceMappingURL=mcp.js.map
|