codeden 0.6.1 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-NOTICES.txt +187 -0
- package/dist/cli.js +1 -1
- package/dist/drizzle/20261112095507_inbox_notify/migration.sql +1 -0
- package/dist/drizzle/20261112095507_inbox_notify/snapshot.json +3514 -0
- package/dist/drizzle/20261112140714_turn_fork_point/migration.sql +1 -0
- package/dist/drizzle/20261112140714_turn_fork_point/snapshot.json +3524 -0
- package/dist/{main-BTA6NERX.js → main-Bx58CdV4.js} +6343 -14677
- package/dist/main-Bx58CdV4.js.map +1 -0
- package/dist/{main-DgIYOEGD.js → main-CMt4z1Z9.js} +2 -2
- package/dist/{main-DgIYOEGD.js.map → main-CMt4z1Z9.js.map} +1 -1
- package/dist/mediaType-BCz-hbZl.js +9731 -0
- package/dist/mediaType-BCz-hbZl.js.map +1 -0
- package/dist/{runner-C59QJvYP.js → runner-CiaiUWOE.js} +1367 -13438
- package/dist/runner-CiaiUWOE.js.map +1 -0
- package/dist/runner.js +1 -1
- package/dist/server-test-b0hHPqXb.js +3766 -0
- package/dist/server-test-b0hHPqXb.js.map +1 -0
- package/dist/tree-31WAOm5k.js +13481 -0
- package/dist/tree-31WAOm5k.js.map +1 -0
- package/dist/web/assets/{core-BE80EdZx.js → core-FqX7NQzW.js} +1 -1
- package/dist/web/assets/engine-oniguruma-C5UP18m1.js +1 -0
- package/dist/web/assets/{highlighted-body-JLMTFACH-DKf-ZukU.js → highlighted-body-JLMTFACH-BMKFJRL-.js} +1 -1
- package/dist/web/assets/{highlights-CXgTTgn7.js → highlights-9yuGk1pg.js} +1 -1
- package/dist/web/assets/index-C3QkKvUn.js +942 -0
- package/dist/web/assets/index-CmllrYFx.css +1 -0
- package/dist/web/assets/langs-DfCgj44a.js +1 -0
- package/dist/web/assets/mermaid-WFAXDIZX-zTA5f8lD.js +1 -0
- package/dist/web/assets/{shiki-BoVdalr2.js → shiki-Qa-y3xHo.js} +2 -2
- package/dist/web/assets/{stream-tokenizer-Ccxf5ToF.js → stream-tokenizer-VL43-ily.js} +1 -1
- package/dist/web/assets/{themes-C9K67wea.js → themes-Di4DO5zr.js} +2 -2
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/main-BTA6NERX.js.map +0 -1
- package/dist/runner-C59QJvYP.js.map +0 -1
- package/dist/web/assets/engine-oniguruma-CYbHTBkj.js +0 -1
- package/dist/web/assets/index-Bq-TWYoS.css +0 -1
- package/dist/web/assets/index-Cr_5sx1k.js +0 -937
- package/dist/web/assets/langs-2fbnR5VK.js +0 -1
- package/dist/web/assets/mermaid-WFAXDIZX-VZd02gKu.js +0 -1
|
@@ -0,0 +1,3766 @@
|
|
|
1
|
+
import { n as __require, r as __toESM, t as __commonJSMin } from "./rolldown-runtime-DegdyBIC.js";
|
|
2
|
+
import { Fr as any, Gr as object, Hr as literal, Ir as array, Lr as boolean, Qr as url, Ur as looseObject, Wr as number$1, Yr as string, a as childEnv, dr as MCP_TEST_STDERR_LIMIT, jr as number, r as killTreeAndOrphans, ri as NEVER, ur as MCP_TEST_ERROR_LIMIT } from "./tree-31WAOm5k.js";
|
|
3
|
+
import { B as ToolListChangedNotificationSchema, D as ListPromptsResultSchema, E as ListChangedOptionsBaseSchema, F as PromptListChangedNotificationSchema, G as isJSONRPCResultResponse, H as isInitializedNotification, I as ReadResourceResultSchema, J as safeParse, K as getLiteralValue, L as ResourceListChangedNotificationSchema, M as ListToolsResultSchema, O as ListResourceTemplatesResultSchema, P as McpError, R as SUPPORTED_PROTOCOL_VERSIONS, S as InitializeResultSchema, T as LATEST_PROTOCOL_VERSION, W as isJSONRPCRequest, _ as ElicitResultSchema, a as AjvJsonSchemaValidator, b as GetPromptResultSchema, d as CreateMessageRequestSchema, f as CreateMessageResultSchema, g as ElicitRequestSchema, i as assertToolsCallTaskCapability, k as ListResourcesResultSchema, l as CallToolResultSchema, m as CreateTaskResultSchema, n as mediaTypeEssence, o as Protocol, p as CreateMessageResultWithToolsSchema, q as getObjectShape, r as assertClientRequestTaskCapability, s as mergeCapabilities, u as CompleteResultSchema, v as EmptyResultSchema, w as JSONRPCMessageSchema, y as ErrorCode } from "./mediaType-BCz-hbZl.js";
|
|
4
|
+
import { existsSync, statSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
// ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/compat.js
|
|
7
|
+
/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */
|
|
8
|
+
const ZodIssueCode = {
|
|
9
|
+
invalid_type: "invalid_type",
|
|
10
|
+
too_big: "too_big",
|
|
11
|
+
too_small: "too_small",
|
|
12
|
+
invalid_format: "invalid_format",
|
|
13
|
+
not_multiple_of: "not_multiple_of",
|
|
14
|
+
unrecognized_keys: "unrecognized_keys",
|
|
15
|
+
invalid_union: "invalid_union",
|
|
16
|
+
invalid_key: "invalid_key",
|
|
17
|
+
invalid_element: "invalid_element",
|
|
18
|
+
invalid_value: "invalid_value",
|
|
19
|
+
custom: "custom"
|
|
20
|
+
};
|
|
21
|
+
/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */
|
|
22
|
+
var ZodFirstPartyTypeKind;
|
|
23
|
+
ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
|
|
24
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
|
|
25
|
+
/**
|
|
26
|
+
* Experimental client task features for MCP SDK.
|
|
27
|
+
* WARNING: These APIs are experimental and may change without notice.
|
|
28
|
+
*
|
|
29
|
+
* @experimental
|
|
30
|
+
*/
|
|
31
|
+
/**
|
|
32
|
+
* Experimental task features for MCP clients.
|
|
33
|
+
*
|
|
34
|
+
* Access via `client.experimental.tasks`:
|
|
35
|
+
* ```typescript
|
|
36
|
+
* const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });
|
|
37
|
+
* const task = await client.experimental.tasks.getTask(taskId);
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* @experimental
|
|
41
|
+
*/
|
|
42
|
+
var ExperimentalClientTasks = class {
|
|
43
|
+
constructor(_client) {
|
|
44
|
+
this._client = _client;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Calls a tool and returns an AsyncGenerator that yields response messages.
|
|
48
|
+
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
49
|
+
*
|
|
50
|
+
* This method provides streaming access to tool execution, allowing you to
|
|
51
|
+
* observe intermediate task status updates for long-running tool calls.
|
|
52
|
+
* Automatically validates structured output if the tool has an outputSchema.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```typescript
|
|
56
|
+
* const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
|
|
57
|
+
* for await (const message of stream) {
|
|
58
|
+
* switch (message.type) {
|
|
59
|
+
* case 'taskCreated':
|
|
60
|
+
* console.log('Tool execution started:', message.task.taskId);
|
|
61
|
+
* break;
|
|
62
|
+
* case 'taskStatus':
|
|
63
|
+
* console.log('Tool status:', message.task.status);
|
|
64
|
+
* break;
|
|
65
|
+
* case 'result':
|
|
66
|
+
* console.log('Tool result:', message.result);
|
|
67
|
+
* break;
|
|
68
|
+
* case 'error':
|
|
69
|
+
* console.error('Tool error:', message.error);
|
|
70
|
+
* break;
|
|
71
|
+
* }
|
|
72
|
+
* }
|
|
73
|
+
* ```
|
|
74
|
+
*
|
|
75
|
+
* @param params - Tool call parameters (name and arguments)
|
|
76
|
+
* @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
|
|
77
|
+
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
|
78
|
+
* @returns AsyncGenerator that yields ResponseMessage objects
|
|
79
|
+
*
|
|
80
|
+
* @experimental
|
|
81
|
+
*/
|
|
82
|
+
async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
|
|
83
|
+
const clientInternal = this._client;
|
|
84
|
+
const optionsWithTask = {
|
|
85
|
+
...options,
|
|
86
|
+
task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
|
|
87
|
+
};
|
|
88
|
+
const stream = clientInternal.requestStream({
|
|
89
|
+
method: "tools/call",
|
|
90
|
+
params
|
|
91
|
+
}, resultSchema, optionsWithTask);
|
|
92
|
+
const validator = clientInternal.getToolOutputValidator(params.name);
|
|
93
|
+
for await (const message of stream) {
|
|
94
|
+
if (message.type === "result" && validator) {
|
|
95
|
+
const result = message.result;
|
|
96
|
+
if (!result.structuredContent && !result.isError) {
|
|
97
|
+
yield {
|
|
98
|
+
type: "error",
|
|
99
|
+
error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
|
|
100
|
+
};
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (result.structuredContent) try {
|
|
104
|
+
const validationResult = validator(result.structuredContent);
|
|
105
|
+
if (!validationResult.valid) {
|
|
106
|
+
yield {
|
|
107
|
+
type: "error",
|
|
108
|
+
error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
|
|
109
|
+
};
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (error instanceof McpError) {
|
|
114
|
+
yield {
|
|
115
|
+
type: "error",
|
|
116
|
+
error
|
|
117
|
+
};
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
yield {
|
|
121
|
+
type: "error",
|
|
122
|
+
error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
|
|
123
|
+
};
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
yield message;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Gets the current status of a task.
|
|
132
|
+
*
|
|
133
|
+
* @param taskId - The task identifier
|
|
134
|
+
* @param options - Optional request options
|
|
135
|
+
* @returns The task status
|
|
136
|
+
*
|
|
137
|
+
* @experimental
|
|
138
|
+
*/
|
|
139
|
+
async getTask(taskId, options) {
|
|
140
|
+
return this._client.getTask({ taskId }, options);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Retrieves the result of a completed task.
|
|
144
|
+
*
|
|
145
|
+
* @param taskId - The task identifier
|
|
146
|
+
* @param resultSchema - Zod schema for validating the result
|
|
147
|
+
* @param options - Optional request options
|
|
148
|
+
* @returns The task result
|
|
149
|
+
*
|
|
150
|
+
* @experimental
|
|
151
|
+
*/
|
|
152
|
+
async getTaskResult(taskId, resultSchema, options) {
|
|
153
|
+
return this._client.getTaskResult({ taskId }, resultSchema, options);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Lists tasks with optional pagination.
|
|
157
|
+
*
|
|
158
|
+
* @param cursor - Optional pagination cursor
|
|
159
|
+
* @param options - Optional request options
|
|
160
|
+
* @returns List of tasks with optional next cursor
|
|
161
|
+
*
|
|
162
|
+
* @experimental
|
|
163
|
+
*/
|
|
164
|
+
async listTasks(cursor, options) {
|
|
165
|
+
return this._client.listTasks(cursor ? { cursor } : void 0, options);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Cancels a running task.
|
|
169
|
+
*
|
|
170
|
+
* @param taskId - The task identifier
|
|
171
|
+
* @param options - Optional request options
|
|
172
|
+
*
|
|
173
|
+
* @experimental
|
|
174
|
+
*/
|
|
175
|
+
async cancelTask(taskId, options) {
|
|
176
|
+
return this._client.cancelTask({ taskId }, options);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Sends a request and returns an AsyncGenerator that yields response messages.
|
|
180
|
+
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
181
|
+
*
|
|
182
|
+
* This method provides streaming access to request processing, allowing you to
|
|
183
|
+
* observe intermediate task status updates for task-augmented requests.
|
|
184
|
+
*
|
|
185
|
+
* @param request - The request to send
|
|
186
|
+
* @param resultSchema - Zod schema for validating the result
|
|
187
|
+
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
|
188
|
+
* @returns AsyncGenerator that yields ResponseMessage objects
|
|
189
|
+
*
|
|
190
|
+
* @experimental
|
|
191
|
+
*/
|
|
192
|
+
requestStream(request, resultSchema, options) {
|
|
193
|
+
return this._client.requestStream(request, resultSchema, options);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
|
|
197
|
+
/**
|
|
198
|
+
* Elicitation default application helper. Applies defaults to the data based on the schema.
|
|
199
|
+
*
|
|
200
|
+
* @param schema - The schema to apply defaults to.
|
|
201
|
+
* @param data - The data to apply defaults to.
|
|
202
|
+
*/
|
|
203
|
+
function applyElicitationDefaults(schema, data) {
|
|
204
|
+
if (!schema || data === null || typeof data !== "object") return;
|
|
205
|
+
if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
|
|
206
|
+
const obj = data;
|
|
207
|
+
const props = schema.properties;
|
|
208
|
+
for (const key of Object.keys(props)) {
|
|
209
|
+
const propSchema = props[key];
|
|
210
|
+
if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) obj[key] = propSchema.default;
|
|
211
|
+
if (obj[key] !== void 0) applyElicitationDefaults(propSchema, obj[key]);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (Array.isArray(schema.anyOf)) {
|
|
215
|
+
for (const sub of schema.anyOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data);
|
|
216
|
+
}
|
|
217
|
+
if (Array.isArray(schema.oneOf)) {
|
|
218
|
+
for (const sub of schema.oneOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Determines which elicitation modes are supported based on declared client capabilities.
|
|
223
|
+
*
|
|
224
|
+
* According to the spec:
|
|
225
|
+
* - An empty elicitation capability object defaults to form mode support (backwards compatibility)
|
|
226
|
+
* - URL mode is only supported if explicitly declared
|
|
227
|
+
*
|
|
228
|
+
* @param capabilities - The client's elicitation capabilities
|
|
229
|
+
* @returns An object indicating which modes are supported
|
|
230
|
+
*/
|
|
231
|
+
function getSupportedElicitationModes(capabilities) {
|
|
232
|
+
if (!capabilities) return {
|
|
233
|
+
supportsFormMode: false,
|
|
234
|
+
supportsUrlMode: false
|
|
235
|
+
};
|
|
236
|
+
const hasFormCapability = capabilities.form !== void 0;
|
|
237
|
+
const hasUrlCapability = capabilities.url !== void 0;
|
|
238
|
+
return {
|
|
239
|
+
supportsFormMode: hasFormCapability || !hasFormCapability && !hasUrlCapability,
|
|
240
|
+
supportsUrlMode: hasUrlCapability
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* An MCP client on top of a pluggable transport.
|
|
245
|
+
*
|
|
246
|
+
* The client will automatically begin the initialization flow with the server when connect() is called.
|
|
247
|
+
*
|
|
248
|
+
* To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
|
|
249
|
+
*
|
|
250
|
+
* ```typescript
|
|
251
|
+
* // Custom schemas
|
|
252
|
+
* const CustomRequestSchema = RequestSchema.extend({...})
|
|
253
|
+
* const CustomNotificationSchema = NotificationSchema.extend({...})
|
|
254
|
+
* const CustomResultSchema = ResultSchema.extend({...})
|
|
255
|
+
*
|
|
256
|
+
* // Type aliases
|
|
257
|
+
* type CustomRequest = z.infer<typeof CustomRequestSchema>
|
|
258
|
+
* type CustomNotification = z.infer<typeof CustomNotificationSchema>
|
|
259
|
+
* type CustomResult = z.infer<typeof CustomResultSchema>
|
|
260
|
+
*
|
|
261
|
+
* // Create typed client
|
|
262
|
+
* const client = new Client<CustomRequest, CustomNotification, CustomResult>({
|
|
263
|
+
* name: "CustomClient",
|
|
264
|
+
* version: "1.0.0"
|
|
265
|
+
* })
|
|
266
|
+
* ```
|
|
267
|
+
*/
|
|
268
|
+
var Client = class extends Protocol {
|
|
269
|
+
/**
|
|
270
|
+
* Initializes this client with the given name and version information.
|
|
271
|
+
*/
|
|
272
|
+
constructor(_clientInfo, options) {
|
|
273
|
+
super(options);
|
|
274
|
+
this._clientInfo = _clientInfo;
|
|
275
|
+
this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
|
|
276
|
+
this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
|
|
277
|
+
this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
|
|
278
|
+
this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
|
|
279
|
+
this._capabilities = options?.capabilities ?? {};
|
|
280
|
+
this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
|
|
281
|
+
if (options?.listChanged) this._pendingListChangedConfig = options.listChanged;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Set up handlers for list changed notifications based on config and server capabilities.
|
|
285
|
+
* This should only be called after initialization when server capabilities are known.
|
|
286
|
+
* Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
|
|
287
|
+
* @internal
|
|
288
|
+
*/
|
|
289
|
+
_setupListChangedHandlers(config) {
|
|
290
|
+
if (config.tools && this._serverCapabilities?.tools?.listChanged) this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
|
|
291
|
+
return (await this.listTools()).tools;
|
|
292
|
+
});
|
|
293
|
+
if (config.prompts && this._serverCapabilities?.prompts?.listChanged) this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
|
|
294
|
+
return (await this.listPrompts()).prompts;
|
|
295
|
+
});
|
|
296
|
+
if (config.resources && this._serverCapabilities?.resources?.listChanged) this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
|
|
297
|
+
return (await this.listResources()).resources;
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Access experimental features.
|
|
302
|
+
*
|
|
303
|
+
* WARNING: These APIs are experimental and may change without notice.
|
|
304
|
+
*
|
|
305
|
+
* @experimental
|
|
306
|
+
*/
|
|
307
|
+
get experimental() {
|
|
308
|
+
if (!this._experimental) this._experimental = { tasks: new ExperimentalClientTasks(this) };
|
|
309
|
+
return this._experimental;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Registers new capabilities. This can only be called before connecting to a transport.
|
|
313
|
+
*
|
|
314
|
+
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
|
|
315
|
+
*/
|
|
316
|
+
registerCapabilities(capabilities) {
|
|
317
|
+
if (this.transport) throw new Error("Cannot register capabilities after connecting to transport");
|
|
318
|
+
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Override request handler registration to enforce client-side validation for elicitation.
|
|
322
|
+
*/
|
|
323
|
+
setRequestHandler(requestSchema, handler) {
|
|
324
|
+
const methodSchema = getObjectShape(requestSchema)?.method;
|
|
325
|
+
if (!methodSchema) throw new Error("Schema is missing a method literal");
|
|
326
|
+
const methodValue = getLiteralValue(methodSchema);
|
|
327
|
+
if (typeof methodValue !== "string") throw new Error("Schema method literal must be a string");
|
|
328
|
+
const method = methodValue;
|
|
329
|
+
if (method === "elicitation/create") {
|
|
330
|
+
const wrappedHandler = async (request, extra) => {
|
|
331
|
+
const validatedRequest = safeParse(ElicitRequestSchema, request);
|
|
332
|
+
if (!validatedRequest.success) {
|
|
333
|
+
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
|
|
334
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
|
|
335
|
+
}
|
|
336
|
+
const { params } = validatedRequest.data;
|
|
337
|
+
params.mode = params.mode ?? "form";
|
|
338
|
+
const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
|
|
339
|
+
if (params.mode === "form" && !supportsFormMode) throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
|
|
340
|
+
if (params.mode === "url" && !supportsUrlMode) throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
|
|
341
|
+
const result = await Promise.resolve(handler(request, extra));
|
|
342
|
+
if (params.task) {
|
|
343
|
+
const taskValidationResult = safeParse(CreateTaskResultSchema, result);
|
|
344
|
+
if (!taskValidationResult.success) {
|
|
345
|
+
const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
|
|
346
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
|
|
347
|
+
}
|
|
348
|
+
return taskValidationResult.data;
|
|
349
|
+
}
|
|
350
|
+
const validationResult = safeParse(ElicitResultSchema, result);
|
|
351
|
+
if (!validationResult.success) {
|
|
352
|
+
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
|
|
353
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
|
|
354
|
+
}
|
|
355
|
+
const validatedResult = validationResult.data;
|
|
356
|
+
const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
|
|
357
|
+
if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
|
|
358
|
+
if (this._capabilities.elicitation?.form?.applyDefaults) try {
|
|
359
|
+
applyElicitationDefaults(requestedSchema, validatedResult.content);
|
|
360
|
+
} catch {}
|
|
361
|
+
}
|
|
362
|
+
return validatedResult;
|
|
363
|
+
};
|
|
364
|
+
return super.setRequestHandler(requestSchema, wrappedHandler);
|
|
365
|
+
}
|
|
366
|
+
if (method === "sampling/createMessage") {
|
|
367
|
+
const wrappedHandler = async (request, extra) => {
|
|
368
|
+
const validatedRequest = safeParse(CreateMessageRequestSchema, request);
|
|
369
|
+
if (!validatedRequest.success) {
|
|
370
|
+
const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
|
|
371
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
|
|
372
|
+
}
|
|
373
|
+
const { params } = validatedRequest.data;
|
|
374
|
+
const result = await Promise.resolve(handler(request, extra));
|
|
375
|
+
if (params.task) {
|
|
376
|
+
const taskValidationResult = safeParse(CreateTaskResultSchema, result);
|
|
377
|
+
if (!taskValidationResult.success) {
|
|
378
|
+
const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
|
|
379
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
|
|
380
|
+
}
|
|
381
|
+
return taskValidationResult.data;
|
|
382
|
+
}
|
|
383
|
+
const resultSchema = params.tools || params.toolChoice ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
|
|
384
|
+
const validationResult = safeParse(resultSchema, result);
|
|
385
|
+
if (!validationResult.success) {
|
|
386
|
+
const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
|
|
387
|
+
throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
|
|
388
|
+
}
|
|
389
|
+
return validationResult.data;
|
|
390
|
+
};
|
|
391
|
+
return super.setRequestHandler(requestSchema, wrappedHandler);
|
|
392
|
+
}
|
|
393
|
+
return super.setRequestHandler(requestSchema, handler);
|
|
394
|
+
}
|
|
395
|
+
assertCapability(capability, method) {
|
|
396
|
+
if (!this._serverCapabilities?.[capability]) throw new Error(`Server does not support ${capability} (required for ${method})`);
|
|
397
|
+
}
|
|
398
|
+
async connect(transport, options) {
|
|
399
|
+
await super.connect(transport);
|
|
400
|
+
if (transport.sessionId !== void 0) return;
|
|
401
|
+
try {
|
|
402
|
+
const result = await this.request({
|
|
403
|
+
method: "initialize",
|
|
404
|
+
params: {
|
|
405
|
+
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
406
|
+
capabilities: this._capabilities,
|
|
407
|
+
clientInfo: this._clientInfo
|
|
408
|
+
}
|
|
409
|
+
}, InitializeResultSchema, options);
|
|
410
|
+
if (result === void 0) throw new Error(`Server sent invalid initialize result: ${result}`);
|
|
411
|
+
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
|
|
412
|
+
this._serverCapabilities = result.capabilities;
|
|
413
|
+
this._serverVersion = result.serverInfo;
|
|
414
|
+
if (transport.setProtocolVersion) transport.setProtocolVersion(result.protocolVersion);
|
|
415
|
+
this._instructions = result.instructions;
|
|
416
|
+
await this.notification({ method: "notifications/initialized" });
|
|
417
|
+
if (this._pendingListChangedConfig) {
|
|
418
|
+
this._setupListChangedHandlers(this._pendingListChangedConfig);
|
|
419
|
+
this._pendingListChangedConfig = void 0;
|
|
420
|
+
}
|
|
421
|
+
} catch (error) {
|
|
422
|
+
this.close();
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* After initialization has completed, this will be populated with the server's reported capabilities.
|
|
428
|
+
*/
|
|
429
|
+
getServerCapabilities() {
|
|
430
|
+
return this._serverCapabilities;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* After initialization has completed, this will be populated with information about the server's name and version.
|
|
434
|
+
*/
|
|
435
|
+
getServerVersion() {
|
|
436
|
+
return this._serverVersion;
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* After initialization has completed, this may be populated with information about the server's instructions.
|
|
440
|
+
*/
|
|
441
|
+
getInstructions() {
|
|
442
|
+
return this._instructions;
|
|
443
|
+
}
|
|
444
|
+
assertCapabilityForMethod(method) {
|
|
445
|
+
switch (method) {
|
|
446
|
+
case "logging/setLevel":
|
|
447
|
+
if (!this._serverCapabilities?.logging) throw new Error(`Server does not support logging (required for ${method})`);
|
|
448
|
+
break;
|
|
449
|
+
case "prompts/get":
|
|
450
|
+
case "prompts/list":
|
|
451
|
+
if (!this._serverCapabilities?.prompts) throw new Error(`Server does not support prompts (required for ${method})`);
|
|
452
|
+
break;
|
|
453
|
+
case "resources/list":
|
|
454
|
+
case "resources/templates/list":
|
|
455
|
+
case "resources/read":
|
|
456
|
+
case "resources/subscribe":
|
|
457
|
+
case "resources/unsubscribe":
|
|
458
|
+
if (!this._serverCapabilities?.resources) throw new Error(`Server does not support resources (required for ${method})`);
|
|
459
|
+
if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) throw new Error(`Server does not support resource subscriptions (required for ${method})`);
|
|
460
|
+
break;
|
|
461
|
+
case "tools/call":
|
|
462
|
+
case "tools/list":
|
|
463
|
+
if (!this._serverCapabilities?.tools) throw new Error(`Server does not support tools (required for ${method})`);
|
|
464
|
+
break;
|
|
465
|
+
case "completion/complete": if (!this._serverCapabilities?.completions) throw new Error(`Server does not support completions (required for ${method})`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
assertNotificationCapability(method) {
|
|
469
|
+
switch (method) {
|
|
470
|
+
case "notifications/roots/list_changed": if (!this._capabilities.roots?.listChanged) throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
assertRequestHandlerCapability(method) {
|
|
474
|
+
if (!this._capabilities) return;
|
|
475
|
+
switch (method) {
|
|
476
|
+
case "sampling/createMessage":
|
|
477
|
+
if (!this._capabilities.sampling) throw new Error(`Client does not support sampling capability (required for ${method})`);
|
|
478
|
+
break;
|
|
479
|
+
case "elicitation/create":
|
|
480
|
+
if (!this._capabilities.elicitation) throw new Error(`Client does not support elicitation capability (required for ${method})`);
|
|
481
|
+
break;
|
|
482
|
+
case "roots/list":
|
|
483
|
+
if (!this._capabilities.roots) throw new Error(`Client does not support roots capability (required for ${method})`);
|
|
484
|
+
break;
|
|
485
|
+
case "tasks/get":
|
|
486
|
+
case "tasks/list":
|
|
487
|
+
case "tasks/result":
|
|
488
|
+
case "tasks/cancel": if (!this._capabilities.tasks) throw new Error(`Client does not support tasks capability (required for ${method})`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
assertTaskCapability(method) {
|
|
492
|
+
assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
|
|
493
|
+
}
|
|
494
|
+
assertTaskHandlerCapability(method) {
|
|
495
|
+
if (!this._capabilities) return;
|
|
496
|
+
assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
|
|
497
|
+
}
|
|
498
|
+
async ping(options) {
|
|
499
|
+
return this.request({ method: "ping" }, EmptyResultSchema, options);
|
|
500
|
+
}
|
|
501
|
+
async complete(params, options) {
|
|
502
|
+
return this.request({
|
|
503
|
+
method: "completion/complete",
|
|
504
|
+
params
|
|
505
|
+
}, CompleteResultSchema, options);
|
|
506
|
+
}
|
|
507
|
+
async setLoggingLevel(level, options) {
|
|
508
|
+
return this.request({
|
|
509
|
+
method: "logging/setLevel",
|
|
510
|
+
params: { level }
|
|
511
|
+
}, EmptyResultSchema, options);
|
|
512
|
+
}
|
|
513
|
+
async getPrompt(params, options) {
|
|
514
|
+
return this.request({
|
|
515
|
+
method: "prompts/get",
|
|
516
|
+
params
|
|
517
|
+
}, GetPromptResultSchema, options);
|
|
518
|
+
}
|
|
519
|
+
async listPrompts(params, options) {
|
|
520
|
+
return this.request({
|
|
521
|
+
method: "prompts/list",
|
|
522
|
+
params
|
|
523
|
+
}, ListPromptsResultSchema, options);
|
|
524
|
+
}
|
|
525
|
+
async listResources(params, options) {
|
|
526
|
+
return this.request({
|
|
527
|
+
method: "resources/list",
|
|
528
|
+
params
|
|
529
|
+
}, ListResourcesResultSchema, options);
|
|
530
|
+
}
|
|
531
|
+
async listResourceTemplates(params, options) {
|
|
532
|
+
return this.request({
|
|
533
|
+
method: "resources/templates/list",
|
|
534
|
+
params
|
|
535
|
+
}, ListResourceTemplatesResultSchema, options);
|
|
536
|
+
}
|
|
537
|
+
async readResource(params, options) {
|
|
538
|
+
return this.request({
|
|
539
|
+
method: "resources/read",
|
|
540
|
+
params
|
|
541
|
+
}, ReadResourceResultSchema, options);
|
|
542
|
+
}
|
|
543
|
+
async subscribeResource(params, options) {
|
|
544
|
+
return this.request({
|
|
545
|
+
method: "resources/subscribe",
|
|
546
|
+
params
|
|
547
|
+
}, EmptyResultSchema, options);
|
|
548
|
+
}
|
|
549
|
+
async unsubscribeResource(params, options) {
|
|
550
|
+
return this.request({
|
|
551
|
+
method: "resources/unsubscribe",
|
|
552
|
+
params
|
|
553
|
+
}, EmptyResultSchema, options);
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
|
|
557
|
+
*
|
|
558
|
+
* For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
|
|
559
|
+
*/
|
|
560
|
+
async callTool(params, resultSchema = CallToolResultSchema, options) {
|
|
561
|
+
if (this.isToolTaskRequired(params.name)) throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
|
|
562
|
+
const result = await this.request({
|
|
563
|
+
method: "tools/call",
|
|
564
|
+
params
|
|
565
|
+
}, resultSchema, options);
|
|
566
|
+
const validator = this.getToolOutputValidator(params.name);
|
|
567
|
+
if (validator) {
|
|
568
|
+
if (!result.structuredContent && !result.isError) throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
|
|
569
|
+
if (result.structuredContent) try {
|
|
570
|
+
const validationResult = validator(result.structuredContent);
|
|
571
|
+
if (!validationResult.valid) throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
|
|
572
|
+
} catch (error) {
|
|
573
|
+
if (error instanceof McpError) throw error;
|
|
574
|
+
throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return result;
|
|
578
|
+
}
|
|
579
|
+
isToolTask(toolName) {
|
|
580
|
+
if (!this._serverCapabilities?.tasks?.requests?.tools?.call) return false;
|
|
581
|
+
return this._cachedKnownTaskTools.has(toolName);
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Check if a tool requires task-based execution.
|
|
585
|
+
* Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
|
|
586
|
+
*/
|
|
587
|
+
isToolTaskRequired(toolName) {
|
|
588
|
+
return this._cachedRequiredTaskTools.has(toolName);
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Cache validators for tool output schemas.
|
|
592
|
+
* Called after listTools() to pre-compile validators for better performance.
|
|
593
|
+
*/
|
|
594
|
+
cacheToolMetadata(tools) {
|
|
595
|
+
this._cachedToolOutputValidators.clear();
|
|
596
|
+
this._cachedKnownTaskTools.clear();
|
|
597
|
+
this._cachedRequiredTaskTools.clear();
|
|
598
|
+
for (const tool of tools) {
|
|
599
|
+
if (tool.outputSchema) {
|
|
600
|
+
const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
|
|
601
|
+
this._cachedToolOutputValidators.set(tool.name, toolValidator);
|
|
602
|
+
}
|
|
603
|
+
const taskSupport = tool.execution?.taskSupport;
|
|
604
|
+
if (taskSupport === "required" || taskSupport === "optional") this._cachedKnownTaskTools.add(tool.name);
|
|
605
|
+
if (taskSupport === "required") this._cachedRequiredTaskTools.add(tool.name);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Get cached validator for a tool
|
|
610
|
+
*/
|
|
611
|
+
getToolOutputValidator(toolName) {
|
|
612
|
+
return this._cachedToolOutputValidators.get(toolName);
|
|
613
|
+
}
|
|
614
|
+
async listTools(params, options) {
|
|
615
|
+
const result = await this.request({
|
|
616
|
+
method: "tools/list",
|
|
617
|
+
params
|
|
618
|
+
}, ListToolsResultSchema, options);
|
|
619
|
+
this.cacheToolMetadata(result.tools);
|
|
620
|
+
return result;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Set up a single list changed handler.
|
|
624
|
+
* @internal
|
|
625
|
+
*/
|
|
626
|
+
_setupListChangedHandler(listType, notificationSchema, options, fetcher) {
|
|
627
|
+
const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
|
|
628
|
+
if (!parseResult.success) throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
|
|
629
|
+
if (typeof options.onChanged !== "function") throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
|
|
630
|
+
const { autoRefresh, debounceMs } = parseResult.data;
|
|
631
|
+
const { onChanged } = options;
|
|
632
|
+
const refresh = async () => {
|
|
633
|
+
if (!autoRefresh) {
|
|
634
|
+
onChanged(null, null);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
try {
|
|
638
|
+
const items = await fetcher();
|
|
639
|
+
onChanged(null, items);
|
|
640
|
+
} catch (e) {
|
|
641
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
642
|
+
onChanged(error, null);
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
const handler = () => {
|
|
646
|
+
if (debounceMs) {
|
|
647
|
+
const existingTimer = this._listChangedDebounceTimers.get(listType);
|
|
648
|
+
if (existingTimer) clearTimeout(existingTimer);
|
|
649
|
+
const timer = setTimeout(refresh, debounceMs);
|
|
650
|
+
this._listChangedDebounceTimers.set(listType, timer);
|
|
651
|
+
} else refresh();
|
|
652
|
+
};
|
|
653
|
+
this.setNotificationHandler(notificationSchema, handler);
|
|
654
|
+
}
|
|
655
|
+
async sendRootsListChanged() {
|
|
656
|
+
return this.notification({ method: "notifications/roots/list_changed" });
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
// ../../node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/index.js
|
|
660
|
+
var ParseError = class extends Error {
|
|
661
|
+
constructor(message, options) {
|
|
662
|
+
super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
const LF = 10;
|
|
666
|
+
const CR = 13;
|
|
667
|
+
const SPACE = 32;
|
|
668
|
+
function noop(_arg) {}
|
|
669
|
+
function createParser(config) {
|
|
670
|
+
if (typeof config == "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
|
|
671
|
+
const { onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize } = config, pendingFragments = [];
|
|
672
|
+
let pendingFragmentsLength = 0, isFirstChunk = !0, id, data = "", dataLines = 0, eventType, terminated = !1;
|
|
673
|
+
function feed(chunk) {
|
|
674
|
+
if (terminated) throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
|
|
675
|
+
if (isFirstChunk && (isFirstChunk = !1, chunk.charCodeAt(0) === 239 && chunk.charCodeAt(1) === 187 && chunk.charCodeAt(2) === 191 && (chunk = chunk.slice(3))), pendingFragments.length === 0) {
|
|
676
|
+
const trailing2 = processLines(chunk);
|
|
677
|
+
trailing2 !== "" && (pendingFragments.push(trailing2), pendingFragmentsLength = trailing2.length), checkBufferSize();
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (chunk.indexOf(`
|
|
681
|
+
`) === -1 && chunk.indexOf("\r") === -1) {
|
|
682
|
+
pendingFragments.push(chunk), pendingFragmentsLength += chunk.length, checkBufferSize();
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
pendingFragments.push(chunk);
|
|
686
|
+
const input = pendingFragments.join("");
|
|
687
|
+
pendingFragments.length = 0, pendingFragmentsLength = 0;
|
|
688
|
+
const trailing = processLines(input);
|
|
689
|
+
trailing !== "" && (pendingFragments.push(trailing), pendingFragmentsLength = trailing.length), checkBufferSize();
|
|
690
|
+
}
|
|
691
|
+
function checkBufferSize() {
|
|
692
|
+
maxBufferSize !== void 0 && (pendingFragmentsLength + data.length <= maxBufferSize || (terminated = !0, pendingFragments.length = 0, pendingFragmentsLength = 0, id = void 0, data = "", dataLines = 0, eventType = void 0, onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { type: "max-buffer-size-exceeded" }))));
|
|
693
|
+
}
|
|
694
|
+
function processLines(chunk) {
|
|
695
|
+
let searchIndex = 0;
|
|
696
|
+
if (chunk.indexOf("\r") === -1) {
|
|
697
|
+
let lfIndex = chunk.indexOf(`
|
|
698
|
+
`, searchIndex);
|
|
699
|
+
for (; lfIndex !== -1;) {
|
|
700
|
+
if (searchIndex === lfIndex) {
|
|
701
|
+
dataLines > 0 && onEvent({
|
|
702
|
+
id,
|
|
703
|
+
event: eventType,
|
|
704
|
+
data
|
|
705
|
+
}), id = void 0, data = "", dataLines = 0, eventType = void 0, searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
|
|
706
|
+
`, searchIndex);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
const firstCharCode = chunk.charCodeAt(searchIndex);
|
|
710
|
+
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
|
|
711
|
+
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5, value = chunk.slice(valueStart, lfIndex);
|
|
712
|
+
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
|
|
713
|
+
onEvent({
|
|
714
|
+
id,
|
|
715
|
+
event: eventType,
|
|
716
|
+
data: value
|
|
717
|
+
}), id = void 0, data = "", eventType = void 0, searchIndex = lfIndex + 2, lfIndex = chunk.indexOf(`
|
|
718
|
+
`, searchIndex);
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
data = dataLines === 0 ? value : `${data}
|
|
722
|
+
${value}`, dataLines++;
|
|
723
|
+
} else isEventPrefix(chunk, searchIndex, firstCharCode) ? eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0 : parseLine(chunk, searchIndex, lfIndex);
|
|
724
|
+
searchIndex = lfIndex + 1, lfIndex = chunk.indexOf(`
|
|
725
|
+
`, searchIndex);
|
|
726
|
+
}
|
|
727
|
+
return chunk.slice(searchIndex);
|
|
728
|
+
}
|
|
729
|
+
for (; searchIndex < chunk.length;) {
|
|
730
|
+
const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
|
|
731
|
+
`, searchIndex);
|
|
732
|
+
let lineEnd = -1;
|
|
733
|
+
if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = crIndex < lfIndex ? crIndex : lfIndex : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) break;
|
|
734
|
+
parseLine(chunk, searchIndex, lineEnd), searchIndex = lineEnd + 1, chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF && searchIndex++;
|
|
735
|
+
}
|
|
736
|
+
return chunk.slice(searchIndex);
|
|
737
|
+
}
|
|
738
|
+
function parseLine(chunk, start, end) {
|
|
739
|
+
if (start === end) {
|
|
740
|
+
dispatchEvent();
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const firstCharCode = chunk.charCodeAt(start);
|
|
744
|
+
if (isDataPrefix(chunk, start, firstCharCode)) {
|
|
745
|
+
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5, value2 = chunk.slice(valueStart, end);
|
|
746
|
+
data = dataLines === 0 ? value2 : `${data}
|
|
747
|
+
${value2}`, dataLines++;
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
if (isEventPrefix(chunk, start, firstCharCode)) {
|
|
751
|
+
eventType = chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || void 0;
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
|
|
755
|
+
const value2 = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
|
|
756
|
+
value2.includes("\0") || (id = value2);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (firstCharCode === 58) {
|
|
760
|
+
if (onComment) {
|
|
761
|
+
const line2 = chunk.slice(start, end);
|
|
762
|
+
onComment(line2.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
|
|
763
|
+
}
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
const line = chunk.slice(start, end), fieldSeparatorIndex = line.indexOf(":");
|
|
767
|
+
if (fieldSeparatorIndex === -1) {
|
|
768
|
+
processField(line, "", line);
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const field = line.slice(0, fieldSeparatorIndex), offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
|
|
772
|
+
processField(field, line.slice(fieldSeparatorIndex + offset), line);
|
|
773
|
+
}
|
|
774
|
+
function processField(field, value, line) {
|
|
775
|
+
switch (field) {
|
|
776
|
+
case "event":
|
|
777
|
+
eventType = value || void 0;
|
|
778
|
+
break;
|
|
779
|
+
case "data":
|
|
780
|
+
data = dataLines === 0 ? value : `${data}
|
|
781
|
+
${value}`, dataLines++;
|
|
782
|
+
break;
|
|
783
|
+
case "id":
|
|
784
|
+
value.includes("\0") || (id = value);
|
|
785
|
+
break;
|
|
786
|
+
case "retry":
|
|
787
|
+
/^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
788
|
+
type: "invalid-retry",
|
|
789
|
+
value,
|
|
790
|
+
line
|
|
791
|
+
}));
|
|
792
|
+
break;
|
|
793
|
+
default: onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, {
|
|
794
|
+
type: "unknown-field",
|
|
795
|
+
field,
|
|
796
|
+
value,
|
|
797
|
+
line
|
|
798
|
+
}));
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
function dispatchEvent() {
|
|
802
|
+
dataLines > 0 && onEvent({
|
|
803
|
+
id,
|
|
804
|
+
event: eventType,
|
|
805
|
+
data
|
|
806
|
+
}), id = void 0, data = "", dataLines = 0, eventType = void 0;
|
|
807
|
+
}
|
|
808
|
+
function reset(options = {}) {
|
|
809
|
+
if (options.consume && pendingFragments.length > 0) {
|
|
810
|
+
const incompleteLine = pendingFragments.join("");
|
|
811
|
+
parseLine(incompleteLine, 0, incompleteLine.length);
|
|
812
|
+
}
|
|
813
|
+
isFirstChunk = !0, id = void 0, data = "", dataLines = 0, eventType = void 0, pendingFragments.length = 0, pendingFragmentsLength = 0, terminated = !1;
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
feed,
|
|
817
|
+
reset
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
function isDataPrefix(chunk, i, firstCharCode) {
|
|
821
|
+
return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
|
|
822
|
+
}
|
|
823
|
+
function isEventPrefix(chunk, i, firstCharCode) {
|
|
824
|
+
return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
|
|
825
|
+
}
|
|
826
|
+
// ../../node_modules/.pnpm/eventsource@3.0.7/node_modules/eventsource/dist/index.js
|
|
827
|
+
var ErrorEvent = class extends Event {
|
|
828
|
+
/**
|
|
829
|
+
* Constructs a new `ErrorEvent` instance. This is typically not called directly,
|
|
830
|
+
* but rather emitted by the `EventSource` object when an error occurs.
|
|
831
|
+
*
|
|
832
|
+
* @param type - The type of the event (should be "error")
|
|
833
|
+
* @param errorEventInitDict - Optional properties to include in the error event
|
|
834
|
+
*/
|
|
835
|
+
constructor(type, errorEventInitDict) {
|
|
836
|
+
var _a, _b;
|
|
837
|
+
super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0;
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
|
|
841
|
+
* when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
|
|
842
|
+
* we explicitly include the properties in the `inspect` method.
|
|
843
|
+
*
|
|
844
|
+
* This is automatically called by Node.js when you `console.log` an instance of this class.
|
|
845
|
+
*
|
|
846
|
+
* @param _depth - The current depth
|
|
847
|
+
* @param options - The options passed to `util.inspect`
|
|
848
|
+
* @param inspect - The inspect function to use (prevents having to import it from `util`)
|
|
849
|
+
* @returns A string representation of the error
|
|
850
|
+
*/
|
|
851
|
+
[Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
|
|
852
|
+
return inspect(inspectableError(this), options);
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
|
|
856
|
+
* when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
|
|
857
|
+
* we explicitly include the properties in the `inspect` method.
|
|
858
|
+
*
|
|
859
|
+
* This is automatically called by Deno when you `console.log` an instance of this class.
|
|
860
|
+
*
|
|
861
|
+
* @param inspect - The inspect function to use (prevents having to import it from `util`)
|
|
862
|
+
* @param options - The options passed to `Deno.inspect`
|
|
863
|
+
* @returns A string representation of the error
|
|
864
|
+
*/
|
|
865
|
+
[Symbol.for("Deno.customInspect")](inspect, options) {
|
|
866
|
+
return inspect(inspectableError(this), options);
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
function syntaxError(message) {
|
|
870
|
+
const DomException = globalThis.DOMException;
|
|
871
|
+
return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
|
|
872
|
+
}
|
|
873
|
+
function flattenError(err) {
|
|
874
|
+
return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`;
|
|
875
|
+
}
|
|
876
|
+
function inspectableError(err) {
|
|
877
|
+
return {
|
|
878
|
+
type: err.type,
|
|
879
|
+
message: err.message,
|
|
880
|
+
code: err.code,
|
|
881
|
+
defaultPrevented: err.defaultPrevented,
|
|
882
|
+
cancelable: err.cancelable,
|
|
883
|
+
timeStamp: err.timeStamp
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
var __typeError = (msg) => {
|
|
887
|
+
throw TypeError(msg);
|
|
888
|
+
};
|
|
889
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
890
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
891
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
892
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
893
|
+
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
|
|
894
|
+
var _readyState;
|
|
895
|
+
var _url;
|
|
896
|
+
var _redirectUrl;
|
|
897
|
+
var _withCredentials;
|
|
898
|
+
var _fetch;
|
|
899
|
+
var _reconnectInterval;
|
|
900
|
+
var _reconnectTimer;
|
|
901
|
+
var _lastEventId;
|
|
902
|
+
var _controller;
|
|
903
|
+
var _parser;
|
|
904
|
+
var _onError;
|
|
905
|
+
var _onMessage;
|
|
906
|
+
var _onOpen;
|
|
907
|
+
var _EventSource_instances;
|
|
908
|
+
var connect_fn;
|
|
909
|
+
var _onFetchResponse;
|
|
910
|
+
var _onFetchError;
|
|
911
|
+
var getRequestOptions_fn;
|
|
912
|
+
var _onEvent;
|
|
913
|
+
var _onRetryChange;
|
|
914
|
+
var failConnection_fn;
|
|
915
|
+
var scheduleReconnect_fn;
|
|
916
|
+
var _reconnect;
|
|
917
|
+
var EventSource = class extends EventTarget {
|
|
918
|
+
constructor(url, eventSourceInitDict) {
|
|
919
|
+
var _a, _b;
|
|
920
|
+
super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => {
|
|
921
|
+
var _a2;
|
|
922
|
+
__privateGet(this, _parser).reset();
|
|
923
|
+
const { body, redirected, status, headers } = response;
|
|
924
|
+
if (status === 204) {
|
|
925
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) {
|
|
929
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
|
|
933
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid content type, expected \"text/event-stream\"", status);
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
if (__privateGet(this, _readyState) === this.CLOSED) return;
|
|
937
|
+
__privateSet(this, _readyState, this.OPEN);
|
|
938
|
+
const openEvent = new Event("open");
|
|
939
|
+
if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
|
|
940
|
+
__privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const decoder = new TextDecoder(), reader = body.getReader();
|
|
944
|
+
let open = !0;
|
|
945
|
+
do {
|
|
946
|
+
const { done, value } = await reader.read();
|
|
947
|
+
value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
|
|
948
|
+
} while (open);
|
|
949
|
+
}), __privateAdd(this, _onFetchError, (err) => {
|
|
950
|
+
__privateSet(this, _controller, void 0), err.name !== "AbortError" && err.type !== "aborted" && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err));
|
|
951
|
+
}), __privateAdd(this, _onEvent, (event) => {
|
|
952
|
+
typeof event.id == "string" && __privateSet(this, _lastEventId, event.id);
|
|
953
|
+
const messageEvent = new MessageEvent(event.event || "message", {
|
|
954
|
+
data: event.data,
|
|
955
|
+
origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin,
|
|
956
|
+
lastEventId: event.id || ""
|
|
957
|
+
});
|
|
958
|
+
__privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
|
|
959
|
+
}), __privateAdd(this, _onRetryChange, (value) => {
|
|
960
|
+
__privateSet(this, _reconnectInterval, value);
|
|
961
|
+
}), __privateAdd(this, _reconnect, () => {
|
|
962
|
+
__privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
|
|
963
|
+
});
|
|
964
|
+
try {
|
|
965
|
+
if (url instanceof URL) __privateSet(this, _url, url);
|
|
966
|
+
else if (typeof url == "string") __privateSet(this, _url, new URL(url, getBaseURL()));
|
|
967
|
+
else throw new Error("Invalid URL");
|
|
968
|
+
} catch {
|
|
969
|
+
throw syntaxError("An invalid or illegal string was specified");
|
|
970
|
+
}
|
|
971
|
+
__privateSet(this, _parser, createParser({
|
|
972
|
+
onEvent: __privateGet(this, _onEvent),
|
|
973
|
+
onRetry: __privateGet(this, _onRetryChange)
|
|
974
|
+
})), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
|
|
975
|
+
}
|
|
976
|
+
/**
|
|
977
|
+
* Returns the state of this EventSource object's connection. It can have the values described below.
|
|
978
|
+
*
|
|
979
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
|
|
980
|
+
*
|
|
981
|
+
* Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
|
|
982
|
+
* defined in the TypeScript `dom` library.
|
|
983
|
+
*
|
|
984
|
+
* @public
|
|
985
|
+
*/
|
|
986
|
+
get readyState() {
|
|
987
|
+
return __privateGet(this, _readyState);
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Returns the URL providing the event stream.
|
|
991
|
+
*
|
|
992
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
|
|
993
|
+
*
|
|
994
|
+
* @public
|
|
995
|
+
*/
|
|
996
|
+
get url() {
|
|
997
|
+
return __privateGet(this, _url).href;
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
|
|
1001
|
+
*
|
|
1002
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
|
|
1003
|
+
*/
|
|
1004
|
+
get withCredentials() {
|
|
1005
|
+
return __privateGet(this, _withCredentials);
|
|
1006
|
+
}
|
|
1007
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
|
|
1008
|
+
get onerror() {
|
|
1009
|
+
return __privateGet(this, _onError);
|
|
1010
|
+
}
|
|
1011
|
+
set onerror(value) {
|
|
1012
|
+
__privateSet(this, _onError, value);
|
|
1013
|
+
}
|
|
1014
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
|
|
1015
|
+
get onmessage() {
|
|
1016
|
+
return __privateGet(this, _onMessage);
|
|
1017
|
+
}
|
|
1018
|
+
set onmessage(value) {
|
|
1019
|
+
__privateSet(this, _onMessage, value);
|
|
1020
|
+
}
|
|
1021
|
+
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
|
|
1022
|
+
get onopen() {
|
|
1023
|
+
return __privateGet(this, _onOpen);
|
|
1024
|
+
}
|
|
1025
|
+
set onopen(value) {
|
|
1026
|
+
__privateSet(this, _onOpen, value);
|
|
1027
|
+
}
|
|
1028
|
+
addEventListener(type, listener, options) {
|
|
1029
|
+
const listen = listener;
|
|
1030
|
+
super.addEventListener(type, listen, options);
|
|
1031
|
+
}
|
|
1032
|
+
removeEventListener(type, listener, options) {
|
|
1033
|
+
const listen = listener;
|
|
1034
|
+
super.removeEventListener(type, listen, options);
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
|
|
1038
|
+
*
|
|
1039
|
+
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
|
|
1040
|
+
*
|
|
1041
|
+
* @public
|
|
1042
|
+
*/
|
|
1043
|
+
close() {
|
|
1044
|
+
__privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0));
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), connect_fn = function() {
|
|
1048
|
+
__privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError));
|
|
1049
|
+
}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), getRequestOptions_fn = function() {
|
|
1050
|
+
var _a;
|
|
1051
|
+
const init = {
|
|
1052
|
+
mode: "cors",
|
|
1053
|
+
redirect: "follow",
|
|
1054
|
+
headers: {
|
|
1055
|
+
Accept: "text/event-stream",
|
|
1056
|
+
...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0
|
|
1057
|
+
},
|
|
1058
|
+
cache: "no-store",
|
|
1059
|
+
signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal
|
|
1060
|
+
};
|
|
1061
|
+
return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
|
|
1062
|
+
}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), failConnection_fn = function(message, code) {
|
|
1063
|
+
var _a;
|
|
1064
|
+
__privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED);
|
|
1065
|
+
const errorEvent = new ErrorEvent("error", {
|
|
1066
|
+
code,
|
|
1067
|
+
message
|
|
1068
|
+
});
|
|
1069
|
+
(_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent);
|
|
1070
|
+
}, scheduleReconnect_fn = function(message, code) {
|
|
1071
|
+
var _a;
|
|
1072
|
+
if (__privateGet(this, _readyState) === this.CLOSED) return;
|
|
1073
|
+
__privateSet(this, _readyState, this.CONNECTING);
|
|
1074
|
+
const errorEvent = new ErrorEvent("error", {
|
|
1075
|
+
code,
|
|
1076
|
+
message
|
|
1077
|
+
});
|
|
1078
|
+
(_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval)));
|
|
1079
|
+
}, _reconnect = /* @__PURE__ */ new WeakMap(), EventSource.CONNECTING = 0, EventSource.OPEN = 1, EventSource.CLOSED = 2;
|
|
1080
|
+
function getBaseURL() {
|
|
1081
|
+
const doc = "document" in globalThis ? globalThis.document : void 0;
|
|
1082
|
+
return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
|
|
1083
|
+
}
|
|
1084
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
|
|
1085
|
+
/**
|
|
1086
|
+
* Normalizes HeadersInit to a plain Record<string, string> for manipulation.
|
|
1087
|
+
* Handles Headers objects, arrays of tuples, and plain objects.
|
|
1088
|
+
*/
|
|
1089
|
+
function normalizeHeaders(headers) {
|
|
1090
|
+
if (!headers) return {};
|
|
1091
|
+
if (headers instanceof Headers) return Object.fromEntries(headers.entries());
|
|
1092
|
+
if (Array.isArray(headers)) return Object.fromEntries(headers);
|
|
1093
|
+
return { ...headers };
|
|
1094
|
+
}
|
|
1095
|
+
/**
|
|
1096
|
+
* Creates a fetch function that includes base RequestInit options.
|
|
1097
|
+
* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.
|
|
1098
|
+
*
|
|
1099
|
+
* @param baseFetch - The base fetch function to wrap (defaults to global fetch)
|
|
1100
|
+
* @param baseInit - The base RequestInit to merge with each request
|
|
1101
|
+
* @returns A wrapped fetch function that merges base options with call-specific options
|
|
1102
|
+
*/
|
|
1103
|
+
function createFetchWithInit(baseFetch = fetch, baseInit) {
|
|
1104
|
+
if (!baseInit) return baseFetch;
|
|
1105
|
+
return async (url, init) => {
|
|
1106
|
+
return baseFetch(url, {
|
|
1107
|
+
...baseInit,
|
|
1108
|
+
...init,
|
|
1109
|
+
headers: init?.headers ? {
|
|
1110
|
+
...normalizeHeaders(baseInit.headers),
|
|
1111
|
+
...normalizeHeaders(init.headers)
|
|
1112
|
+
} : baseInit.headers
|
|
1113
|
+
});
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
const MAX_REDIRECTS = 5;
|
|
1117
|
+
const REDIRECT_STATUSES = [
|
|
1118
|
+
301,
|
|
1119
|
+
302,
|
|
1120
|
+
303,
|
|
1121
|
+
307,
|
|
1122
|
+
308
|
|
1123
|
+
];
|
|
1124
|
+
/** @internal Whether `to` has the scheme, host and port of `from`, or is its https form with both on default ports. */
|
|
1125
|
+
function isWithinOrigin(from, to) {
|
|
1126
|
+
if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) return true;
|
|
1127
|
+
return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
|
|
1128
|
+
}
|
|
1129
|
+
function redirectTarget(response, requestUrl) {
|
|
1130
|
+
const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
|
|
1131
|
+
try {
|
|
1132
|
+
return location ? new URL(location, requestUrl) : void 0;
|
|
1133
|
+
} catch {
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
/** @internal Follows the redirect in `response` while it stays within the origin of `url`; undefined when `response` is to be used as is. */
|
|
1138
|
+
function followWithinOrigin(baseFetch, url, init, response, followed = 0) {
|
|
1139
|
+
const target = redirectTarget(response, url);
|
|
1140
|
+
const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
|
|
1141
|
+
if (!target || followed === MAX_REDIRECTS || !keepsMethod) return;
|
|
1142
|
+
const from = new URL(url);
|
|
1143
|
+
if ((target.username || target.password) && (target.username !== from.username || target.password !== from.password) || !isWithinOrigin(from, target)) return;
|
|
1144
|
+
return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, {
|
|
1145
|
+
...init,
|
|
1146
|
+
redirect: "manual"
|
|
1147
|
+
})).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
|
|
1148
|
+
}
|
|
1149
|
+
const followingFetches = /* @__PURE__ */ new WeakSet();
|
|
1150
|
+
/** @internal Wraps a fetch for `redirectPolicy: 'follow'`: `fetchWithinOrigin` returns the result as it is, so redirects are left to the fetch. */
|
|
1151
|
+
function fetchLeavingRedirects(baseFetch) {
|
|
1152
|
+
const following = (url, init) => (baseFetch ?? fetch)(url, init);
|
|
1153
|
+
followingFetches.add(following);
|
|
1154
|
+
return following;
|
|
1155
|
+
}
|
|
1156
|
+
/** @internal Wraps a fetch so it follows a redirect only within the request's origin; any other redirect response is returned as is. */
|
|
1157
|
+
function fetchWithinOrigin(baseFetch = fetch) {
|
|
1158
|
+
if (followingFetches.has(baseFetch)) return baseFetch;
|
|
1159
|
+
return (url, init) => {
|
|
1160
|
+
if (init?.redirect === "error" || init?.redirect === "manual") return baseFetch(url, init);
|
|
1161
|
+
return Promise.resolve(baseFetch(url, {
|
|
1162
|
+
...init,
|
|
1163
|
+
redirect: "manual"
|
|
1164
|
+
})).then((response) => followWithinOrigin(baseFetch, url, init, response) ?? response);
|
|
1165
|
+
};
|
|
1166
|
+
}
|
|
1167
|
+
/** @internal Describes a redirect that `fetchWithinOrigin` returned unfollowed, naming its target without userinfo, query or fragment. */
|
|
1168
|
+
function unfollowedRedirect(response, requestUrl) {
|
|
1169
|
+
if (response.type === "opaqueredirect") return "Redirect not followed: this runtime does not expose the redirect target";
|
|
1170
|
+
const from = response.url || requestUrl;
|
|
1171
|
+
const target = redirectTarget(response, from);
|
|
1172
|
+
if (!target) return;
|
|
1173
|
+
target.username = target.password = target.search = target.hash = "";
|
|
1174
|
+
if (target.protocol === "http:" && new URL(from).protocol === "https:") {
|
|
1175
|
+
target.protocol = "https:";
|
|
1176
|
+
return `Redirect to plain http not followed; try ${target.href} instead`;
|
|
1177
|
+
}
|
|
1178
|
+
return `Redirect to ${target.href} not followed`;
|
|
1179
|
+
}
|
|
1180
|
+
// ../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
|
|
1181
|
+
let crypto;
|
|
1182
|
+
crypto = globalThis.crypto?.webcrypto ?? globalThis.crypto ?? import("node:crypto").then((m) => m.webcrypto);
|
|
1183
|
+
/**
|
|
1184
|
+
* Creates an array of length `size` of random bytes
|
|
1185
|
+
* @param size
|
|
1186
|
+
* @returns Array of random ints (0 to 255)
|
|
1187
|
+
*/
|
|
1188
|
+
async function getRandomValues(size) {
|
|
1189
|
+
return (await crypto).getRandomValues(new Uint8Array(size));
|
|
1190
|
+
}
|
|
1191
|
+
/** Generate cryptographically strong random string
|
|
1192
|
+
* @param size The desired length of the string
|
|
1193
|
+
* @returns The random string
|
|
1194
|
+
*/
|
|
1195
|
+
async function random(size) {
|
|
1196
|
+
const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
|
|
1197
|
+
const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % 66;
|
|
1198
|
+
let result = "";
|
|
1199
|
+
while (result.length < size) {
|
|
1200
|
+
const randomBytes = await getRandomValues(size - result.length);
|
|
1201
|
+
for (const randomByte of randomBytes) if (randomByte < evenDistCutoff) result += mask[randomByte % 66];
|
|
1202
|
+
}
|
|
1203
|
+
return result;
|
|
1204
|
+
}
|
|
1205
|
+
/** Generate a PKCE challenge verifier
|
|
1206
|
+
* @param length Length of the verifier
|
|
1207
|
+
* @returns A random verifier `length` characters long
|
|
1208
|
+
*/
|
|
1209
|
+
async function generateVerifier(length) {
|
|
1210
|
+
return await random(length);
|
|
1211
|
+
}
|
|
1212
|
+
/** Generate a PKCE code challenge from a code verifier
|
|
1213
|
+
* @param code_verifier
|
|
1214
|
+
* @returns The base64 url encoded code challenge
|
|
1215
|
+
*/
|
|
1216
|
+
async function generateChallenge(code_verifier) {
|
|
1217
|
+
const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
|
|
1218
|
+
return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
|
|
1219
|
+
}
|
|
1220
|
+
/** Generate a PKCE challenge pair
|
|
1221
|
+
* @param length Length of the verifer (between 43-128). Defaults to 43.
|
|
1222
|
+
* @returns PKCE challenge pair
|
|
1223
|
+
*/
|
|
1224
|
+
async function pkceChallenge(length) {
|
|
1225
|
+
if (!length) length = 43;
|
|
1226
|
+
if (length < 43 || length > 128) throw `Expected a length between 43 and 128. Received ${length}.`;
|
|
1227
|
+
const verifier = await generateVerifier(length);
|
|
1228
|
+
return {
|
|
1229
|
+
code_verifier: verifier,
|
|
1230
|
+
code_challenge: await generateChallenge(verifier)
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
|
|
1234
|
+
/**
|
|
1235
|
+
* Reusable URL validation that disallows javascript: scheme
|
|
1236
|
+
*/
|
|
1237
|
+
const SafeUrlSchema = url().superRefine((val, ctx) => {
|
|
1238
|
+
if (!URL.canParse(val)) {
|
|
1239
|
+
ctx.addIssue({
|
|
1240
|
+
code: ZodIssueCode.custom,
|
|
1241
|
+
message: "URL must be parseable",
|
|
1242
|
+
fatal: true
|
|
1243
|
+
});
|
|
1244
|
+
return NEVER;
|
|
1245
|
+
}
|
|
1246
|
+
}).refine((url) => {
|
|
1247
|
+
const u = new URL(url);
|
|
1248
|
+
return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
|
|
1249
|
+
}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
|
|
1250
|
+
/**
|
|
1251
|
+
* RFC 9728 OAuth Protected Resource Metadata
|
|
1252
|
+
*/
|
|
1253
|
+
const OAuthProtectedResourceMetadataSchema = looseObject({
|
|
1254
|
+
resource: string().url(),
|
|
1255
|
+
authorization_servers: array(SafeUrlSchema).optional(),
|
|
1256
|
+
jwks_uri: string().url().optional(),
|
|
1257
|
+
scopes_supported: array(string()).optional(),
|
|
1258
|
+
bearer_methods_supported: array(string()).optional(),
|
|
1259
|
+
resource_signing_alg_values_supported: array(string()).optional(),
|
|
1260
|
+
resource_name: string().optional(),
|
|
1261
|
+
resource_documentation: string().optional(),
|
|
1262
|
+
resource_policy_uri: string().url().optional(),
|
|
1263
|
+
resource_tos_uri: string().url().optional(),
|
|
1264
|
+
tls_client_certificate_bound_access_tokens: boolean().optional(),
|
|
1265
|
+
authorization_details_types_supported: array(string()).optional(),
|
|
1266
|
+
dpop_signing_alg_values_supported: array(string()).optional(),
|
|
1267
|
+
dpop_bound_access_tokens_required: boolean().optional()
|
|
1268
|
+
});
|
|
1269
|
+
/**
|
|
1270
|
+
* RFC 8414 OAuth 2.0 Authorization Server Metadata
|
|
1271
|
+
*/
|
|
1272
|
+
const OAuthMetadataSchema = looseObject({
|
|
1273
|
+
issuer: string(),
|
|
1274
|
+
authorization_endpoint: SafeUrlSchema,
|
|
1275
|
+
token_endpoint: SafeUrlSchema,
|
|
1276
|
+
registration_endpoint: SafeUrlSchema.optional(),
|
|
1277
|
+
scopes_supported: array(string()).optional(),
|
|
1278
|
+
response_types_supported: array(string()),
|
|
1279
|
+
response_modes_supported: array(string()).optional(),
|
|
1280
|
+
grant_types_supported: array(string()).optional(),
|
|
1281
|
+
token_endpoint_auth_methods_supported: array(string()).optional(),
|
|
1282
|
+
token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
1283
|
+
service_documentation: SafeUrlSchema.optional(),
|
|
1284
|
+
revocation_endpoint: SafeUrlSchema.optional(),
|
|
1285
|
+
revocation_endpoint_auth_methods_supported: array(string()).optional(),
|
|
1286
|
+
revocation_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
1287
|
+
introspection_endpoint: string().optional(),
|
|
1288
|
+
introspection_endpoint_auth_methods_supported: array(string()).optional(),
|
|
1289
|
+
introspection_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
1290
|
+
code_challenge_methods_supported: array(string()).optional(),
|
|
1291
|
+
client_id_metadata_document_supported: boolean().optional()
|
|
1292
|
+
});
|
|
1293
|
+
/**
|
|
1294
|
+
* OpenID Connect Discovery 1.0 Provider Metadata
|
|
1295
|
+
* see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
|
|
1296
|
+
*/
|
|
1297
|
+
const OpenIdProviderMetadataSchema = looseObject({
|
|
1298
|
+
issuer: string(),
|
|
1299
|
+
authorization_endpoint: SafeUrlSchema,
|
|
1300
|
+
token_endpoint: SafeUrlSchema,
|
|
1301
|
+
userinfo_endpoint: SafeUrlSchema.optional(),
|
|
1302
|
+
jwks_uri: SafeUrlSchema,
|
|
1303
|
+
registration_endpoint: SafeUrlSchema.optional(),
|
|
1304
|
+
scopes_supported: array(string()).optional(),
|
|
1305
|
+
response_types_supported: array(string()),
|
|
1306
|
+
response_modes_supported: array(string()).optional(),
|
|
1307
|
+
grant_types_supported: array(string()).optional(),
|
|
1308
|
+
acr_values_supported: array(string()).optional(),
|
|
1309
|
+
subject_types_supported: array(string()),
|
|
1310
|
+
id_token_signing_alg_values_supported: array(string()),
|
|
1311
|
+
id_token_encryption_alg_values_supported: array(string()).optional(),
|
|
1312
|
+
id_token_encryption_enc_values_supported: array(string()).optional(),
|
|
1313
|
+
userinfo_signing_alg_values_supported: array(string()).optional(),
|
|
1314
|
+
userinfo_encryption_alg_values_supported: array(string()).optional(),
|
|
1315
|
+
userinfo_encryption_enc_values_supported: array(string()).optional(),
|
|
1316
|
+
request_object_signing_alg_values_supported: array(string()).optional(),
|
|
1317
|
+
request_object_encryption_alg_values_supported: array(string()).optional(),
|
|
1318
|
+
request_object_encryption_enc_values_supported: array(string()).optional(),
|
|
1319
|
+
token_endpoint_auth_methods_supported: array(string()).optional(),
|
|
1320
|
+
token_endpoint_auth_signing_alg_values_supported: array(string()).optional(),
|
|
1321
|
+
display_values_supported: array(string()).optional(),
|
|
1322
|
+
claim_types_supported: array(string()).optional(),
|
|
1323
|
+
claims_supported: array(string()).optional(),
|
|
1324
|
+
service_documentation: string().optional(),
|
|
1325
|
+
claims_locales_supported: array(string()).optional(),
|
|
1326
|
+
ui_locales_supported: array(string()).optional(),
|
|
1327
|
+
claims_parameter_supported: boolean().optional(),
|
|
1328
|
+
request_parameter_supported: boolean().optional(),
|
|
1329
|
+
request_uri_parameter_supported: boolean().optional(),
|
|
1330
|
+
require_request_uri_registration: boolean().optional(),
|
|
1331
|
+
op_policy_uri: SafeUrlSchema.optional(),
|
|
1332
|
+
op_tos_uri: SafeUrlSchema.optional(),
|
|
1333
|
+
client_id_metadata_document_supported: boolean().optional()
|
|
1334
|
+
});
|
|
1335
|
+
/**
|
|
1336
|
+
* OpenID Connect Discovery metadata that may include OAuth 2.0 fields
|
|
1337
|
+
* This schema represents the real-world scenario where OIDC providers
|
|
1338
|
+
* return a mix of OpenID Connect and OAuth 2.0 metadata fields
|
|
1339
|
+
*/
|
|
1340
|
+
const OpenIdProviderDiscoveryMetadataSchema = object({
|
|
1341
|
+
...OpenIdProviderMetadataSchema.shape,
|
|
1342
|
+
...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape
|
|
1343
|
+
});
|
|
1344
|
+
/**
|
|
1345
|
+
* OAuth 2.1 token response
|
|
1346
|
+
*/
|
|
1347
|
+
const OAuthTokensSchema = object({
|
|
1348
|
+
access_token: string(),
|
|
1349
|
+
id_token: string().optional(),
|
|
1350
|
+
token_type: string(),
|
|
1351
|
+
expires_in: number().optional(),
|
|
1352
|
+
scope: string().optional(),
|
|
1353
|
+
refresh_token: string().optional(),
|
|
1354
|
+
/**
|
|
1355
|
+
* Not part of the wire format: the authorization server this value was obtained from, added by
|
|
1356
|
+
* the client's `auth()` before it is stored and compared when it is read back.
|
|
1357
|
+
*/
|
|
1358
|
+
issuer: string().optional().catch(void 0)
|
|
1359
|
+
}).strip();
|
|
1360
|
+
/**
|
|
1361
|
+
* OAuth 2.1 error response
|
|
1362
|
+
*/
|
|
1363
|
+
const OAuthErrorResponseSchema = object({
|
|
1364
|
+
error: string(),
|
|
1365
|
+
error_description: string().optional(),
|
|
1366
|
+
error_uri: string().optional()
|
|
1367
|
+
});
|
|
1368
|
+
/**
|
|
1369
|
+
* Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri
|
|
1370
|
+
*/
|
|
1371
|
+
const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
|
|
1372
|
+
/**
|
|
1373
|
+
* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata
|
|
1374
|
+
*/
|
|
1375
|
+
const OAuthClientMetadataSchema = object({
|
|
1376
|
+
redirect_uris: array(SafeUrlSchema),
|
|
1377
|
+
token_endpoint_auth_method: string().optional(),
|
|
1378
|
+
grant_types: array(string()).optional(),
|
|
1379
|
+
response_types: array(string()).optional(),
|
|
1380
|
+
client_name: string().optional(),
|
|
1381
|
+
client_uri: SafeUrlSchema.optional(),
|
|
1382
|
+
logo_uri: OptionalSafeUrlSchema,
|
|
1383
|
+
scope: string().optional(),
|
|
1384
|
+
contacts: array(string()).optional(),
|
|
1385
|
+
tos_uri: OptionalSafeUrlSchema,
|
|
1386
|
+
policy_uri: string().optional(),
|
|
1387
|
+
jwks_uri: SafeUrlSchema.optional(),
|
|
1388
|
+
jwks: any().optional(),
|
|
1389
|
+
software_id: string().optional(),
|
|
1390
|
+
software_version: string().optional(),
|
|
1391
|
+
software_statement: string().optional()
|
|
1392
|
+
}).strip();
|
|
1393
|
+
/**
|
|
1394
|
+
* RFC 7591 OAuth 2.0 Dynamic Client Registration client information
|
|
1395
|
+
*/
|
|
1396
|
+
const OAuthClientInformationSchema = object({
|
|
1397
|
+
client_id: string(),
|
|
1398
|
+
client_secret: string().optional(),
|
|
1399
|
+
client_id_issued_at: number$1().optional(),
|
|
1400
|
+
client_secret_expires_at: number$1().optional(),
|
|
1401
|
+
/**
|
|
1402
|
+
* Not part of the wire format: the authorization server this value was obtained from, added by
|
|
1403
|
+
* the client's `auth()` before it is stored and compared when it is read back.
|
|
1404
|
+
*/
|
|
1405
|
+
issuer: string().optional().catch(void 0)
|
|
1406
|
+
}).strip();
|
|
1407
|
+
/**
|
|
1408
|
+
* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)
|
|
1409
|
+
*/
|
|
1410
|
+
const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
|
|
1411
|
+
object({
|
|
1412
|
+
error: string(),
|
|
1413
|
+
error_description: string().optional()
|
|
1414
|
+
}).strip();
|
|
1415
|
+
object({
|
|
1416
|
+
token: string(),
|
|
1417
|
+
token_type_hint: string().optional()
|
|
1418
|
+
}).strip();
|
|
1419
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
|
|
1420
|
+
/**
|
|
1421
|
+
* Utilities for handling OAuth resource URIs.
|
|
1422
|
+
*/
|
|
1423
|
+
/**
|
|
1424
|
+
* Converts a server URL to a resource URL by removing the fragment.
|
|
1425
|
+
* RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component".
|
|
1426
|
+
* Keeps everything else unchanged (scheme, domain, port, path, query).
|
|
1427
|
+
*/
|
|
1428
|
+
function resourceUrlFromServerUrl(url) {
|
|
1429
|
+
const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
|
|
1430
|
+
resourceURL.hash = "";
|
|
1431
|
+
return resourceURL;
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* Checks if a requested resource URL matches a configured resource URL.
|
|
1435
|
+
* A requested resource matches if it has the same scheme, domain, port,
|
|
1436
|
+
* and its path starts with the configured resource's path.
|
|
1437
|
+
*
|
|
1438
|
+
* @param requestedResource The resource URL being requested
|
|
1439
|
+
* @param configuredResource The resource URL that has been configured
|
|
1440
|
+
* @returns true if the requested resource matches the configured resource, false otherwise
|
|
1441
|
+
*/
|
|
1442
|
+
function checkResourceAllowed({ requestedResource, configuredResource }) {
|
|
1443
|
+
const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
|
|
1444
|
+
const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
|
|
1445
|
+
if (requested.origin !== configured.origin) return false;
|
|
1446
|
+
if (requested.pathname.length < configured.pathname.length) return false;
|
|
1447
|
+
const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
|
|
1448
|
+
const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
|
|
1449
|
+
return requestedPath.startsWith(configuredPath);
|
|
1450
|
+
}
|
|
1451
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
|
|
1452
|
+
/**
|
|
1453
|
+
* Base class for all OAuth errors
|
|
1454
|
+
*/
|
|
1455
|
+
var OAuthError = class extends Error {
|
|
1456
|
+
constructor(message, errorUri) {
|
|
1457
|
+
super(message);
|
|
1458
|
+
this.errorUri = errorUri;
|
|
1459
|
+
this.name = this.constructor.name;
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Converts the error to a standard OAuth error response object
|
|
1463
|
+
*/
|
|
1464
|
+
toResponseObject() {
|
|
1465
|
+
const response = {
|
|
1466
|
+
error: this.errorCode,
|
|
1467
|
+
error_description: this.message
|
|
1468
|
+
};
|
|
1469
|
+
if (this.errorUri) response.error_uri = this.errorUri;
|
|
1470
|
+
return response;
|
|
1471
|
+
}
|
|
1472
|
+
get errorCode() {
|
|
1473
|
+
return this.constructor.errorCode;
|
|
1474
|
+
}
|
|
1475
|
+
};
|
|
1476
|
+
/**
|
|
1477
|
+
* Invalid request error - The request is missing a required parameter,
|
|
1478
|
+
* includes an invalid parameter value, includes a parameter more than once,
|
|
1479
|
+
* or is otherwise malformed.
|
|
1480
|
+
*/
|
|
1481
|
+
var InvalidRequestError = class extends OAuthError {};
|
|
1482
|
+
InvalidRequestError.errorCode = "invalid_request";
|
|
1483
|
+
/**
|
|
1484
|
+
* Invalid client error - Client authentication failed (e.g., unknown client, no client
|
|
1485
|
+
* authentication included, or unsupported authentication method).
|
|
1486
|
+
*/
|
|
1487
|
+
var InvalidClientError = class extends OAuthError {};
|
|
1488
|
+
InvalidClientError.errorCode = "invalid_client";
|
|
1489
|
+
/**
|
|
1490
|
+
* Invalid grant error - The provided authorization grant or refresh token is
|
|
1491
|
+
* invalid, expired, revoked, does not match the redirection URI used in the
|
|
1492
|
+
* authorization request, or was issued to another client.
|
|
1493
|
+
*/
|
|
1494
|
+
var InvalidGrantError = class extends OAuthError {};
|
|
1495
|
+
InvalidGrantError.errorCode = "invalid_grant";
|
|
1496
|
+
/**
|
|
1497
|
+
* Unauthorized client error - The authenticated client is not authorized to use
|
|
1498
|
+
* this authorization grant type.
|
|
1499
|
+
*/
|
|
1500
|
+
var UnauthorizedClientError = class extends OAuthError {};
|
|
1501
|
+
UnauthorizedClientError.errorCode = "unauthorized_client";
|
|
1502
|
+
/**
|
|
1503
|
+
* Unsupported grant type error - The authorization grant type is not supported
|
|
1504
|
+
* by the authorization server.
|
|
1505
|
+
*/
|
|
1506
|
+
var UnsupportedGrantTypeError = class extends OAuthError {};
|
|
1507
|
+
UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
|
|
1508
|
+
/**
|
|
1509
|
+
* Invalid scope error - The requested scope is invalid, unknown, malformed, or
|
|
1510
|
+
* exceeds the scope granted by the resource owner.
|
|
1511
|
+
*/
|
|
1512
|
+
var InvalidScopeError = class extends OAuthError {};
|
|
1513
|
+
InvalidScopeError.errorCode = "invalid_scope";
|
|
1514
|
+
/**
|
|
1515
|
+
* Access denied error - The resource owner or authorization server denied the request.
|
|
1516
|
+
*/
|
|
1517
|
+
var AccessDeniedError = class extends OAuthError {};
|
|
1518
|
+
AccessDeniedError.errorCode = "access_denied";
|
|
1519
|
+
/**
|
|
1520
|
+
* Server error - The authorization server encountered an unexpected condition
|
|
1521
|
+
* that prevented it from fulfilling the request.
|
|
1522
|
+
*/
|
|
1523
|
+
var ServerError = class extends OAuthError {};
|
|
1524
|
+
ServerError.errorCode = "server_error";
|
|
1525
|
+
/**
|
|
1526
|
+
* Temporarily unavailable error - The authorization server is currently unable to
|
|
1527
|
+
* handle the request due to a temporary overloading or maintenance of the server.
|
|
1528
|
+
*/
|
|
1529
|
+
var TemporarilyUnavailableError = class extends OAuthError {};
|
|
1530
|
+
TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
|
|
1531
|
+
/**
|
|
1532
|
+
* Unsupported response type error - The authorization server does not support
|
|
1533
|
+
* obtaining an authorization code using this method.
|
|
1534
|
+
*/
|
|
1535
|
+
var UnsupportedResponseTypeError = class extends OAuthError {};
|
|
1536
|
+
UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
|
|
1537
|
+
/**
|
|
1538
|
+
* Unsupported token type error - The authorization server does not support
|
|
1539
|
+
* the requested token type.
|
|
1540
|
+
*/
|
|
1541
|
+
var UnsupportedTokenTypeError = class extends OAuthError {};
|
|
1542
|
+
UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
|
|
1543
|
+
/**
|
|
1544
|
+
* Invalid token error - The access token provided is expired, revoked, malformed,
|
|
1545
|
+
* or invalid for other reasons.
|
|
1546
|
+
*/
|
|
1547
|
+
var InvalidTokenError = class extends OAuthError {};
|
|
1548
|
+
InvalidTokenError.errorCode = "invalid_token";
|
|
1549
|
+
/**
|
|
1550
|
+
* Method not allowed error - The HTTP method used is not allowed for this endpoint.
|
|
1551
|
+
* (Custom, non-standard error)
|
|
1552
|
+
*/
|
|
1553
|
+
var MethodNotAllowedError = class extends OAuthError {};
|
|
1554
|
+
MethodNotAllowedError.errorCode = "method_not_allowed";
|
|
1555
|
+
/**
|
|
1556
|
+
* Too many requests error - Rate limit exceeded.
|
|
1557
|
+
* (Custom, non-standard error based on RFC 6585)
|
|
1558
|
+
*/
|
|
1559
|
+
var TooManyRequestsError = class extends OAuthError {};
|
|
1560
|
+
TooManyRequestsError.errorCode = "too_many_requests";
|
|
1561
|
+
/**
|
|
1562
|
+
* Invalid client metadata error - The client metadata is invalid.
|
|
1563
|
+
* (Custom error for dynamic client registration - RFC 7591)
|
|
1564
|
+
*/
|
|
1565
|
+
var InvalidClientMetadataError = class extends OAuthError {};
|
|
1566
|
+
InvalidClientMetadataError.errorCode = "invalid_client_metadata";
|
|
1567
|
+
/**
|
|
1568
|
+
* Insufficient scope error - The request requires higher privileges than provided by the access token.
|
|
1569
|
+
*/
|
|
1570
|
+
var InsufficientScopeError = class extends OAuthError {};
|
|
1571
|
+
InsufficientScopeError.errorCode = "insufficient_scope";
|
|
1572
|
+
/**
|
|
1573
|
+
* Invalid target error - The requested resource is invalid, missing, unknown, or malformed.
|
|
1574
|
+
* (Custom error for resource indicators - RFC 8707)
|
|
1575
|
+
*/
|
|
1576
|
+
var InvalidTargetError = class extends OAuthError {};
|
|
1577
|
+
InvalidTargetError.errorCode = "invalid_target";
|
|
1578
|
+
/**
|
|
1579
|
+
* A full list of all OAuthErrors, enabling parsing from error responses
|
|
1580
|
+
*/
|
|
1581
|
+
const OAUTH_ERRORS = {
|
|
1582
|
+
[InvalidRequestError.errorCode]: InvalidRequestError,
|
|
1583
|
+
[InvalidClientError.errorCode]: InvalidClientError,
|
|
1584
|
+
[InvalidGrantError.errorCode]: InvalidGrantError,
|
|
1585
|
+
[UnauthorizedClientError.errorCode]: UnauthorizedClientError,
|
|
1586
|
+
[UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
|
|
1587
|
+
[InvalidScopeError.errorCode]: InvalidScopeError,
|
|
1588
|
+
[AccessDeniedError.errorCode]: AccessDeniedError,
|
|
1589
|
+
[ServerError.errorCode]: ServerError,
|
|
1590
|
+
[TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
|
|
1591
|
+
[UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
|
|
1592
|
+
[UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
|
|
1593
|
+
[InvalidTokenError.errorCode]: InvalidTokenError,
|
|
1594
|
+
[MethodNotAllowedError.errorCode]: MethodNotAllowedError,
|
|
1595
|
+
[TooManyRequestsError.errorCode]: TooManyRequestsError,
|
|
1596
|
+
[InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
|
|
1597
|
+
[InsufficientScopeError.errorCode]: InsufficientScopeError,
|
|
1598
|
+
[InvalidTargetError.errorCode]: InvalidTargetError
|
|
1599
|
+
};
|
|
1600
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
|
|
1601
|
+
var UnauthorizedError = class extends Error {
|
|
1602
|
+
constructor(message) {
|
|
1603
|
+
super(message ?? "Unauthorized");
|
|
1604
|
+
}
|
|
1605
|
+
};
|
|
1606
|
+
function isClientAuthMethod(method) {
|
|
1607
|
+
return [
|
|
1608
|
+
"client_secret_basic",
|
|
1609
|
+
"client_secret_post",
|
|
1610
|
+
"none"
|
|
1611
|
+
].includes(method);
|
|
1612
|
+
}
|
|
1613
|
+
const AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
|
|
1614
|
+
const AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
|
|
1615
|
+
/**
|
|
1616
|
+
* Determines the best client authentication method to use based on server support and client configuration.
|
|
1617
|
+
*
|
|
1618
|
+
* Priority order (highest to lowest):
|
|
1619
|
+
* 1. client_secret_basic (if client secret is available)
|
|
1620
|
+
* 2. client_secret_post (if client secret is available)
|
|
1621
|
+
* 3. none (for public clients)
|
|
1622
|
+
*
|
|
1623
|
+
* @param clientInformation - OAuth client information containing credentials
|
|
1624
|
+
* @param supportedMethods - Authentication methods supported by the authorization server
|
|
1625
|
+
* @returns The selected authentication method
|
|
1626
|
+
*/
|
|
1627
|
+
function selectClientAuthMethod(clientInformation, supportedMethods) {
|
|
1628
|
+
const hasClientSecret = clientInformation.client_secret !== void 0;
|
|
1629
|
+
if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) return clientInformation.token_endpoint_auth_method;
|
|
1630
|
+
if (supportedMethods.length === 0) return hasClientSecret ? "client_secret_basic" : "none";
|
|
1631
|
+
if (hasClientSecret && supportedMethods.includes("client_secret_basic")) return "client_secret_basic";
|
|
1632
|
+
if (hasClientSecret && supportedMethods.includes("client_secret_post")) return "client_secret_post";
|
|
1633
|
+
if (supportedMethods.includes("none")) return "none";
|
|
1634
|
+
return hasClientSecret ? "client_secret_post" : "none";
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Applies client authentication to the request based on the specified method.
|
|
1638
|
+
*
|
|
1639
|
+
* Implements OAuth 2.1 client authentication methods:
|
|
1640
|
+
* - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1)
|
|
1641
|
+
* - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1)
|
|
1642
|
+
* - none: Public client authentication (RFC 6749 Section 2.1)
|
|
1643
|
+
*
|
|
1644
|
+
* @param method - The authentication method to use
|
|
1645
|
+
* @param clientInformation - OAuth client information containing credentials
|
|
1646
|
+
* @param headers - HTTP headers object to modify
|
|
1647
|
+
* @param params - URL search parameters to modify
|
|
1648
|
+
* @throws {Error} When required credentials are missing
|
|
1649
|
+
*/
|
|
1650
|
+
function applyClientAuthentication(method, clientInformation, headers, params) {
|
|
1651
|
+
const { client_id, client_secret } = clientInformation;
|
|
1652
|
+
switch (method) {
|
|
1653
|
+
case "client_secret_basic":
|
|
1654
|
+
applyBasicAuth(client_id, client_secret, headers);
|
|
1655
|
+
return;
|
|
1656
|
+
case "client_secret_post":
|
|
1657
|
+
applyPostAuth(client_id, client_secret, params);
|
|
1658
|
+
return;
|
|
1659
|
+
case "none":
|
|
1660
|
+
applyPublicAuth(client_id, params);
|
|
1661
|
+
return;
|
|
1662
|
+
default: throw new Error(`Unsupported client authentication method: ${method}`);
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* Applies HTTP Basic authentication (RFC 6749 Section 2.3.1)
|
|
1667
|
+
*/
|
|
1668
|
+
function applyBasicAuth(clientId, clientSecret, headers) {
|
|
1669
|
+
if (!clientSecret) throw new Error("client_secret_basic authentication requires a client_secret");
|
|
1670
|
+
const credentials = btoa(`${clientId}:${clientSecret}`);
|
|
1671
|
+
headers.set("Authorization", `Basic ${credentials}`);
|
|
1672
|
+
}
|
|
1673
|
+
/**
|
|
1674
|
+
* Applies POST body authentication (RFC 6749 Section 2.3.1)
|
|
1675
|
+
*/
|
|
1676
|
+
function applyPostAuth(clientId, clientSecret, params) {
|
|
1677
|
+
params.set("client_id", clientId);
|
|
1678
|
+
if (clientSecret) params.set("client_secret", clientSecret);
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* Applies public client authentication (RFC 6749 Section 2.1)
|
|
1682
|
+
*/
|
|
1683
|
+
function applyPublicAuth(clientId, params) {
|
|
1684
|
+
params.set("client_id", clientId);
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Parses an OAuth error response from a string or Response object.
|
|
1688
|
+
*
|
|
1689
|
+
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
|
|
1690
|
+
* and an instance of the appropriate OAuthError subclass will be returned.
|
|
1691
|
+
* If parsing fails, it falls back to a generic ServerError that includes
|
|
1692
|
+
* the response status (if available) and original content.
|
|
1693
|
+
*
|
|
1694
|
+
* @param input - A Response object or string containing the error response
|
|
1695
|
+
* @returns A Promise that resolves to an OAuthError instance
|
|
1696
|
+
*/
|
|
1697
|
+
async function parseErrorResponse(input) {
|
|
1698
|
+
const statusCode = input instanceof Response ? input.status : void 0;
|
|
1699
|
+
const body = input instanceof Response ? await input.text() : input;
|
|
1700
|
+
try {
|
|
1701
|
+
const { error, error_description, error_uri } = OAuthErrorResponseSchema.parse(JSON.parse(body));
|
|
1702
|
+
return new (OAUTH_ERRORS[error] || ServerError)(error_description || "", error_uri);
|
|
1703
|
+
} catch (error) {
|
|
1704
|
+
const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
|
|
1705
|
+
return new ServerError(`${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`);
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
/**
|
|
1709
|
+
* Compares two authorization server identifiers, tolerating a single trailing `/`
|
|
1710
|
+
* difference (`String(new URL(...))` is slash-suffixed, advertised values often are not).
|
|
1711
|
+
*/
|
|
1712
|
+
function issuersMatch(a, b) {
|
|
1713
|
+
let [x, y] = [a, b];
|
|
1714
|
+
try {
|
|
1715
|
+
[x, y] = [new URL(a).href, new URL(b).href];
|
|
1716
|
+
} catch {}
|
|
1717
|
+
return x === y || x.endsWith("/") && x.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x;
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* {@linkcode auth} stamps everything it passes to `saveClientInformation` / `saveTokens` with
|
|
1721
|
+
* `issuer`, the authorization server URL used for discovery. This returns `stored` unless its
|
|
1722
|
+
* stamp names a different authorization server, in which case the caller behaves as if nothing
|
|
1723
|
+
* were stored. A value without a stamp (saved by an earlier version) is returned as-is, and
|
|
1724
|
+
* is stamped once this authorization server has accepted it.
|
|
1725
|
+
*/
|
|
1726
|
+
function discardIfIssuerMismatch(stored, issuer) {
|
|
1727
|
+
if (!stored) return void 0;
|
|
1728
|
+
if (typeof stored.issuer !== "string") return stored.issuer == null ? stored : {
|
|
1729
|
+
...stored,
|
|
1730
|
+
issuer: void 0
|
|
1731
|
+
};
|
|
1732
|
+
return issuersMatch(stored.issuer, issuer) ? stored : void 0;
|
|
1733
|
+
}
|
|
1734
|
+
const TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
|
|
1735
|
+
const RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
|
|
1736
|
+
function boundElsewhereError(stored, issuer) {
|
|
1737
|
+
return /* @__PURE__ */ new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`);
|
|
1738
|
+
}
|
|
1739
|
+
/**
|
|
1740
|
+
* Orchestrates the full auth flow with a server.
|
|
1741
|
+
*
|
|
1742
|
+
* This can be used as a single entry point for all authorization functionality,
|
|
1743
|
+
* instead of linking together the other lower-level functions in this module.
|
|
1744
|
+
*/
|
|
1745
|
+
async function auth(provider, options) {
|
|
1746
|
+
try {
|
|
1747
|
+
return await authInternal(provider, options);
|
|
1748
|
+
} catch (error) {
|
|
1749
|
+
if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) {
|
|
1750
|
+
await provider.invalidateCredentials?.("all");
|
|
1751
|
+
return await authInternal(provider, options);
|
|
1752
|
+
} else if (error instanceof InvalidGrantError) {
|
|
1753
|
+
await provider.invalidateCredentials?.("tokens");
|
|
1754
|
+
return await authInternal(provider, options);
|
|
1755
|
+
}
|
|
1756
|
+
throw error;
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
|
|
1760
|
+
const cachedState = await provider.discoveryState?.();
|
|
1761
|
+
let resourceMetadata;
|
|
1762
|
+
let authorizationServerUrl;
|
|
1763
|
+
let metadata;
|
|
1764
|
+
let effectiveResourceMetadataUrl = resourceMetadataUrl;
|
|
1765
|
+
if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
|
|
1766
|
+
if (cachedState?.authorizationServerUrl) {
|
|
1767
|
+
authorizationServerUrl = cachedState.authorizationServerUrl;
|
|
1768
|
+
resourceMetadata = cachedState.resourceMetadata;
|
|
1769
|
+
metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
|
|
1770
|
+
if (!resourceMetadata) try {
|
|
1771
|
+
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
|
|
1772
|
+
} catch {}
|
|
1773
|
+
if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) await provider.saveDiscoveryState?.({
|
|
1774
|
+
authorizationServerUrl: String(authorizationServerUrl),
|
|
1775
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
|
|
1776
|
+
resourceMetadata,
|
|
1777
|
+
authorizationServerMetadata: metadata
|
|
1778
|
+
});
|
|
1779
|
+
} else {
|
|
1780
|
+
const serverInfo = await discoverOAuthServerInfo(serverUrl, {
|
|
1781
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl,
|
|
1782
|
+
fetchFn
|
|
1783
|
+
});
|
|
1784
|
+
authorizationServerUrl = serverInfo.authorizationServerUrl;
|
|
1785
|
+
metadata = serverInfo.authorizationServerMetadata;
|
|
1786
|
+
resourceMetadata = serverInfo.resourceMetadata;
|
|
1787
|
+
await provider.saveDiscoveryState?.({
|
|
1788
|
+
authorizationServerUrl: String(authorizationServerUrl),
|
|
1789
|
+
resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
|
|
1790
|
+
resourceMetadata,
|
|
1791
|
+
authorizationServerMetadata: metadata
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
const issuer = String(authorizationServerUrl);
|
|
1795
|
+
const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
|
|
1796
|
+
const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
|
|
1797
|
+
const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
|
|
1798
|
+
const storedClientInformation = await Promise.resolve(provider.clientInformation());
|
|
1799
|
+
let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
|
|
1800
|
+
const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
|
|
1801
|
+
if (storedClientInformation && !clientInformation && !canRegisterAgain) throw boundElsewhereError(storedClientInformation, issuer);
|
|
1802
|
+
const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
|
|
1803
|
+
const bindClientInformation = async () => {
|
|
1804
|
+
try {
|
|
1805
|
+
if (unstampedClientInformation) await provider.saveClientInformation?.({
|
|
1806
|
+
...unstampedClientInformation,
|
|
1807
|
+
issuer
|
|
1808
|
+
});
|
|
1809
|
+
} catch {}
|
|
1810
|
+
};
|
|
1811
|
+
if (!clientInformation) {
|
|
1812
|
+
if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code");
|
|
1813
|
+
const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
|
|
1814
|
+
const clientMetadataUrl = provider.clientMetadataUrl;
|
|
1815
|
+
if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
|
|
1816
|
+
if (supportsUrlBasedClientId && clientMetadataUrl) {
|
|
1817
|
+
clientInformation = {
|
|
1818
|
+
client_id: clientMetadataUrl,
|
|
1819
|
+
issuer
|
|
1820
|
+
};
|
|
1821
|
+
await provider.saveClientInformation?.(clientInformation);
|
|
1822
|
+
} else {
|
|
1823
|
+
if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration");
|
|
1824
|
+
clientInformation = {
|
|
1825
|
+
...await registerClient(authorizationServerUrl, {
|
|
1826
|
+
metadata,
|
|
1827
|
+
clientMetadata: provider.clientMetadata,
|
|
1828
|
+
scope: resolvedScope,
|
|
1829
|
+
fetchFn
|
|
1830
|
+
}),
|
|
1831
|
+
issuer
|
|
1832
|
+
};
|
|
1833
|
+
await provider.saveClientInformation(clientInformation);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
const nonInteractiveFlow = !provider.redirectUrl;
|
|
1837
|
+
if (authorizationCode !== void 0 || nonInteractiveFlow) {
|
|
1838
|
+
const tokens = await fetchToken(provider, authorizationServerUrl, {
|
|
1839
|
+
metadata,
|
|
1840
|
+
resource,
|
|
1841
|
+
authorizationCode,
|
|
1842
|
+
fetchFn
|
|
1843
|
+
});
|
|
1844
|
+
await bindClientInformation();
|
|
1845
|
+
await provider.saveTokens({
|
|
1846
|
+
...tokens,
|
|
1847
|
+
issuer
|
|
1848
|
+
});
|
|
1849
|
+
return "AUTHORIZED";
|
|
1850
|
+
}
|
|
1851
|
+
const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
|
|
1852
|
+
if (tokens?.refresh_token && tokens.issuer == null) console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");
|
|
1853
|
+
if (tokens?.refresh_token) try {
|
|
1854
|
+
const newTokens = await refreshAuthorization(authorizationServerUrl, {
|
|
1855
|
+
metadata,
|
|
1856
|
+
clientInformation,
|
|
1857
|
+
refreshToken: tokens.refresh_token,
|
|
1858
|
+
resource,
|
|
1859
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
1860
|
+
fetchFn
|
|
1861
|
+
});
|
|
1862
|
+
await bindClientInformation();
|
|
1863
|
+
await provider.saveTokens({
|
|
1864
|
+
...newTokens,
|
|
1865
|
+
issuer
|
|
1866
|
+
});
|
|
1867
|
+
return "AUTHORIZED";
|
|
1868
|
+
} catch (error) {
|
|
1869
|
+
if (!(error instanceof OAuthError) || error instanceof ServerError) {} else throw error;
|
|
1870
|
+
}
|
|
1871
|
+
const state = provider.state ? await provider.state() : void 0;
|
|
1872
|
+
const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
|
|
1873
|
+
metadata,
|
|
1874
|
+
clientInformation,
|
|
1875
|
+
state,
|
|
1876
|
+
redirectUrl: provider.redirectUrl,
|
|
1877
|
+
scope: resolvedScope,
|
|
1878
|
+
resource
|
|
1879
|
+
});
|
|
1880
|
+
await provider.saveCodeVerifier(codeVerifier);
|
|
1881
|
+
await provider.redirectToAuthorization(authorizationUrl);
|
|
1882
|
+
return "REDIRECT";
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* SEP-991: URL-based Client IDs
|
|
1886
|
+
* Validate that the client_id is a valid URL with https scheme
|
|
1887
|
+
*/
|
|
1888
|
+
function isHttpsUrl(value) {
|
|
1889
|
+
if (!value) return false;
|
|
1890
|
+
try {
|
|
1891
|
+
const url = new URL(value);
|
|
1892
|
+
return url.protocol === "https:" && url.pathname !== "/";
|
|
1893
|
+
} catch {
|
|
1894
|
+
return false;
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
/**
|
|
1898
|
+
* Selects the RFC 8707 resource indicator for an MCP server: the provider's
|
|
1899
|
+
* {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when
|
|
1900
|
+
* implemented, otherwise the protected resource metadata's `resource` (checked against the
|
|
1901
|
+
* server URL with `checkResourceAllowed`), or `undefined` when there is no metadata.
|
|
1902
|
+
*
|
|
1903
|
+
* The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has
|
|
1904
|
+
* the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string
|
|
1905
|
+
* verbatim instead of this URL's `href` (#1968); callers that emit the `resource`
|
|
1906
|
+
* parameter themselves should do the same.
|
|
1907
|
+
*/
|
|
1908
|
+
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
|
|
1909
|
+
const defaultResource = resourceUrlFromServerUrl(serverUrl);
|
|
1910
|
+
if (provider.validateResourceURL) return await provider.validateResourceURL(defaultResource, resourceMetadata?.resource);
|
|
1911
|
+
if (!resourceMetadata) return;
|
|
1912
|
+
if (!checkResourceAllowed({
|
|
1913
|
+
requestedResource: defaultResource,
|
|
1914
|
+
configuredResource: resourceMetadata.resource
|
|
1915
|
+
})) throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
|
|
1916
|
+
return new URL(resourceMetadata.resource);
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* Extract resource_metadata, scope, and error from WWW-Authenticate header.
|
|
1920
|
+
*/
|
|
1921
|
+
function extractWWWAuthenticateParams(res) {
|
|
1922
|
+
const authenticateHeader = res.headers.get("WWW-Authenticate");
|
|
1923
|
+
if (!authenticateHeader) return {};
|
|
1924
|
+
const [type, scheme] = authenticateHeader.split(" ");
|
|
1925
|
+
if (type.toLowerCase() !== "bearer" || !scheme) return {};
|
|
1926
|
+
const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
|
|
1927
|
+
let resourceMetadataUrl;
|
|
1928
|
+
if (resourceMetadataMatch) try {
|
|
1929
|
+
resourceMetadataUrl = new URL(resourceMetadataMatch);
|
|
1930
|
+
} catch {}
|
|
1931
|
+
const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
|
|
1932
|
+
const error = extractFieldFromWwwAuth(res, "error") || void 0;
|
|
1933
|
+
return {
|
|
1934
|
+
resourceMetadataUrl,
|
|
1935
|
+
scope,
|
|
1936
|
+
error
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1939
|
+
/**
|
|
1940
|
+
* Extracts a specific field's value from the WWW-Authenticate header string.
|
|
1941
|
+
*
|
|
1942
|
+
* @param response The HTTP response object containing the headers.
|
|
1943
|
+
* @param fieldName The name of the field to extract (e.g., "realm", "nonce").
|
|
1944
|
+
* @returns The field value
|
|
1945
|
+
*/
|
|
1946
|
+
function extractFieldFromWwwAuth(response, fieldName) {
|
|
1947
|
+
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
1948
|
+
if (!wwwAuthHeader) return null;
|
|
1949
|
+
const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
|
|
1950
|
+
const match = wwwAuthHeader.match(pattern);
|
|
1951
|
+
if (match) return match[1] || match[2];
|
|
1952
|
+
return null;
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
|
|
1956
|
+
*
|
|
1957
|
+
* If the server returns a 404 for the well-known endpoint, this function will
|
|
1958
|
+
* return `undefined`. Any other errors will be thrown as exceptions.
|
|
1959
|
+
*/
|
|
1960
|
+
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
|
|
1961
|
+
const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
|
|
1962
|
+
protocolVersion: opts?.protocolVersion,
|
|
1963
|
+
metadataUrl: opts?.resourceMetadataUrl
|
|
1964
|
+
});
|
|
1965
|
+
if (!response || response.status === 404) {
|
|
1966
|
+
await response?.body?.cancel();
|
|
1967
|
+
throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
|
|
1968
|
+
}
|
|
1969
|
+
if (!response.ok) {
|
|
1970
|
+
await response.body?.cancel();
|
|
1971
|
+
throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
|
|
1972
|
+
}
|
|
1973
|
+
return OAuthProtectedResourceMetadataSchema.parse(await response.json());
|
|
1974
|
+
}
|
|
1975
|
+
/**
|
|
1976
|
+
* Helper function to handle fetch with CORS retry logic
|
|
1977
|
+
*/
|
|
1978
|
+
async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
|
|
1979
|
+
try {
|
|
1980
|
+
return await fetchWithinOrigin(fetchFn)(url, { headers });
|
|
1981
|
+
} catch (error) {
|
|
1982
|
+
if (error instanceof TypeError) {
|
|
1983
|
+
if (headers) return fetchWithCorsRetry(url, void 0, fetchFn);
|
|
1984
|
+
else return;
|
|
1985
|
+
}
|
|
1986
|
+
throw error;
|
|
1987
|
+
}
|
|
1988
|
+
}
|
|
1989
|
+
/**
|
|
1990
|
+
* Constructs the well-known path for auth-related metadata discovery
|
|
1991
|
+
*/
|
|
1992
|
+
function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
|
|
1993
|
+
if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
|
|
1994
|
+
return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Tries to discover OAuth metadata at a specific URL
|
|
1998
|
+
*/
|
|
1999
|
+
async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
|
|
2000
|
+
return await fetchWithCorsRetry(url, { "MCP-Protocol-Version": protocolVersion }, fetchFn);
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Determines if fallback to root discovery should be attempted
|
|
2004
|
+
*/
|
|
2005
|
+
function shouldAttemptFallback(response, pathname) {
|
|
2006
|
+
return !response || !response.ok && response.status < 500 && pathname !== "/";
|
|
2007
|
+
}
|
|
2008
|
+
/**
|
|
2009
|
+
* Generic function for discovering OAuth metadata with fallback support
|
|
2010
|
+
*/
|
|
2011
|
+
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
|
|
2012
|
+
const issuer = new URL(serverUrl);
|
|
2013
|
+
const protocolVersion = opts?.protocolVersion ?? "2025-11-25";
|
|
2014
|
+
let url;
|
|
2015
|
+
if (opts?.metadataUrl) url = new URL(opts.metadataUrl);
|
|
2016
|
+
else {
|
|
2017
|
+
const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
|
|
2018
|
+
url = new URL(wellKnownPath, opts?.metadataServerUrl ?? issuer);
|
|
2019
|
+
url.search = issuer.search;
|
|
2020
|
+
}
|
|
2021
|
+
let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn);
|
|
2022
|
+
if (!opts?.metadataUrl && shouldAttemptFallback(response, issuer.pathname)) response = await tryMetadataDiscovery(new URL(`/.well-known/${wellKnownType}`, issuer), protocolVersion, fetchFn);
|
|
2023
|
+
return response;
|
|
2024
|
+
}
|
|
2025
|
+
/**
|
|
2026
|
+
* Builds a list of discovery URLs to try for authorization server metadata.
|
|
2027
|
+
* URLs are returned in priority order:
|
|
2028
|
+
* 1. OAuth metadata at the given URL
|
|
2029
|
+
* 2. OIDC metadata endpoints at the given URL
|
|
2030
|
+
*/
|
|
2031
|
+
function buildDiscoveryUrls(authorizationServerUrl) {
|
|
2032
|
+
const url = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
|
|
2033
|
+
const hasPath = url.pathname !== "/";
|
|
2034
|
+
const urlsToTry = [];
|
|
2035
|
+
if (!hasPath) {
|
|
2036
|
+
urlsToTry.push({
|
|
2037
|
+
url: new URL("/.well-known/oauth-authorization-server", url.origin),
|
|
2038
|
+
type: "oauth"
|
|
2039
|
+
});
|
|
2040
|
+
urlsToTry.push({
|
|
2041
|
+
url: new URL(`/.well-known/openid-configuration`, url.origin),
|
|
2042
|
+
type: "oidc"
|
|
2043
|
+
});
|
|
2044
|
+
return urlsToTry;
|
|
2045
|
+
}
|
|
2046
|
+
let pathname = url.pathname;
|
|
2047
|
+
if (pathname.endsWith("/")) pathname = pathname.slice(0, -1);
|
|
2048
|
+
urlsToTry.push({
|
|
2049
|
+
url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin),
|
|
2050
|
+
type: "oauth"
|
|
2051
|
+
});
|
|
2052
|
+
urlsToTry.push({
|
|
2053
|
+
url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin),
|
|
2054
|
+
type: "oidc"
|
|
2055
|
+
});
|
|
2056
|
+
urlsToTry.push({
|
|
2057
|
+
url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin),
|
|
2058
|
+
type: "oidc"
|
|
2059
|
+
});
|
|
2060
|
+
return urlsToTry;
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
|
|
2064
|
+
* and OpenID Connect Discovery 1.0 specifications.
|
|
2065
|
+
*
|
|
2066
|
+
* This function implements a fallback strategy for authorization server discovery:
|
|
2067
|
+
* 1. Attempts RFC 8414 OAuth metadata discovery first
|
|
2068
|
+
* 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
|
|
2069
|
+
*
|
|
2070
|
+
* @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
|
|
2071
|
+
* protected resource metadata, or the MCP server's URL if the
|
|
2072
|
+
* metadata was not found.
|
|
2073
|
+
* @param options - Configuration options
|
|
2074
|
+
* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
|
|
2075
|
+
* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
|
|
2076
|
+
* @returns Promise resolving to authorization server metadata, or undefined if discovery fails
|
|
2077
|
+
*/
|
|
2078
|
+
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
|
|
2079
|
+
const headers = {
|
|
2080
|
+
"MCP-Protocol-Version": protocolVersion,
|
|
2081
|
+
Accept: "application/json"
|
|
2082
|
+
};
|
|
2083
|
+
const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
|
|
2084
|
+
for (const { url: endpointUrl, type } of urlsToTry) {
|
|
2085
|
+
const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
|
|
2086
|
+
if (!response)
|
|
2087
|
+
/**
|
|
2088
|
+
* CORS error occurred - don't throw as the endpoint may not allow CORS,
|
|
2089
|
+
* continue trying other possible endpoints
|
|
2090
|
+
*/
|
|
2091
|
+
continue;
|
|
2092
|
+
if (!response.ok) {
|
|
2093
|
+
await response.body?.cancel();
|
|
2094
|
+
if (response.status < 500) continue;
|
|
2095
|
+
throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
|
|
2096
|
+
}
|
|
2097
|
+
if (type === "oauth") return OAuthMetadataSchema.parse(await response.json());
|
|
2098
|
+
else return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Discovers the authorization server for an MCP server following
|
|
2103
|
+
* {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected
|
|
2104
|
+
* Resource Metadata), with fallback to treating the server URL as the
|
|
2105
|
+
* authorization server.
|
|
2106
|
+
*
|
|
2107
|
+
* This function combines two discovery steps into one call:
|
|
2108
|
+
* 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the
|
|
2109
|
+
* authorization server URL (RFC 9728).
|
|
2110
|
+
* 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).
|
|
2111
|
+
*
|
|
2112
|
+
* Use this when you need the authorization server metadata for operations outside the
|
|
2113
|
+
* {@linkcode auth} orchestrator, such as token refresh or token revocation.
|
|
2114
|
+
*
|
|
2115
|
+
* @param serverUrl - The MCP resource server URL
|
|
2116
|
+
* @param opts - Optional configuration
|
|
2117
|
+
* @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint
|
|
2118
|
+
* @param opts.fetchFn - Custom fetch function for HTTP requests
|
|
2119
|
+
* @returns Authorization server URL, metadata, and resource metadata (if available)
|
|
2120
|
+
*/
|
|
2121
|
+
async function discoverOAuthServerInfo(serverUrl, opts) {
|
|
2122
|
+
let resourceMetadata;
|
|
2123
|
+
let authorizationServerUrl;
|
|
2124
|
+
try {
|
|
2125
|
+
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
|
|
2126
|
+
if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) authorizationServerUrl = resourceMetadata.authorization_servers[0];
|
|
2127
|
+
} catch {}
|
|
2128
|
+
if (!authorizationServerUrl) authorizationServerUrl = String(new URL("/", serverUrl));
|
|
2129
|
+
const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
|
|
2130
|
+
return {
|
|
2131
|
+
authorizationServerUrl,
|
|
2132
|
+
authorizationServerMetadata,
|
|
2133
|
+
resourceMetadata
|
|
2134
|
+
};
|
|
2135
|
+
}
|
|
2136
|
+
function resourceIndicatorToString(resource) {
|
|
2137
|
+
return typeof resource === "string" ? resource : resource.href;
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
|
|
2141
|
+
*/
|
|
2142
|
+
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
|
|
2143
|
+
let authorizationUrl;
|
|
2144
|
+
if (metadata) {
|
|
2145
|
+
authorizationUrl = new URL(metadata.authorization_endpoint);
|
|
2146
|
+
if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
|
|
2147
|
+
if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
|
|
2148
|
+
} else authorizationUrl = new URL("/authorize", authorizationServerUrl);
|
|
2149
|
+
const challenge = await pkceChallenge();
|
|
2150
|
+
const codeVerifier = challenge.code_verifier;
|
|
2151
|
+
const codeChallenge = challenge.code_challenge;
|
|
2152
|
+
authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
|
|
2153
|
+
authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
|
|
2154
|
+
authorizationUrl.searchParams.set("code_challenge", codeChallenge);
|
|
2155
|
+
authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
|
|
2156
|
+
authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
|
|
2157
|
+
if (state) authorizationUrl.searchParams.set("state", state);
|
|
2158
|
+
if (scope) authorizationUrl.searchParams.set("scope", scope);
|
|
2159
|
+
if (scope?.includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent");
|
|
2160
|
+
if (resource) authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
|
|
2161
|
+
return {
|
|
2162
|
+
authorizationUrl,
|
|
2163
|
+
codeVerifier
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
/**
|
|
2167
|
+
* Prepares token request parameters for an authorization code exchange.
|
|
2168
|
+
*
|
|
2169
|
+
* This is the default implementation used by fetchToken when the provider
|
|
2170
|
+
* doesn't implement prepareTokenRequest.
|
|
2171
|
+
*
|
|
2172
|
+
* @param authorizationCode - The authorization code received from the authorization endpoint
|
|
2173
|
+
* @param codeVerifier - The PKCE code verifier
|
|
2174
|
+
* @param redirectUri - The redirect URI used in the authorization request
|
|
2175
|
+
* @returns URLSearchParams for the authorization_code grant
|
|
2176
|
+
*/
|
|
2177
|
+
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
|
|
2178
|
+
return new URLSearchParams({
|
|
2179
|
+
grant_type: "authorization_code",
|
|
2180
|
+
code: authorizationCode,
|
|
2181
|
+
code_verifier: codeVerifier,
|
|
2182
|
+
redirect_uri: String(redirectUri)
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
/**
|
|
2186
|
+
* Internal helper to execute a token request with the given parameters.
|
|
2187
|
+
* Used by exchangeAuthorization, refreshAuthorization, and fetchToken.
|
|
2188
|
+
*/
|
|
2189
|
+
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
|
|
2190
|
+
const tokenUrl = metadata?.token_endpoint ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
|
|
2191
|
+
const headers = new Headers({
|
|
2192
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
2193
|
+
Accept: "application/json"
|
|
2194
|
+
});
|
|
2195
|
+
if (resource) tokenRequestParams.set("resource", resourceIndicatorToString(resource));
|
|
2196
|
+
if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
|
|
2197
|
+
else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams);
|
|
2198
|
+
const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
|
|
2199
|
+
method: "POST",
|
|
2200
|
+
headers,
|
|
2201
|
+
body: tokenRequestParams
|
|
2202
|
+
});
|
|
2203
|
+
if (!response.ok) throw await parseErrorResponse(response);
|
|
2204
|
+
return TokenResponseSchema.parse(await response.json());
|
|
2205
|
+
}
|
|
2206
|
+
/**
|
|
2207
|
+
* Exchange a refresh token for an updated access token.
|
|
2208
|
+
*
|
|
2209
|
+
* Supports multiple client authentication methods as specified in OAuth 2.1:
|
|
2210
|
+
* - Automatically selects the best authentication method based on server support
|
|
2211
|
+
* - Preserves the original refresh token if a new one is not returned
|
|
2212
|
+
*
|
|
2213
|
+
* @param authorizationServerUrl - The authorization server's base URL
|
|
2214
|
+
* @param options - Configuration object containing client info, refresh token, etc.
|
|
2215
|
+
* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
|
|
2216
|
+
* @throws {Error} When token refresh fails or authentication is invalid
|
|
2217
|
+
*/
|
|
2218
|
+
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
|
|
2219
|
+
return {
|
|
2220
|
+
refresh_token: refreshToken,
|
|
2221
|
+
...await executeTokenRequest(authorizationServerUrl, {
|
|
2222
|
+
metadata,
|
|
2223
|
+
tokenRequestParams: new URLSearchParams({
|
|
2224
|
+
grant_type: "refresh_token",
|
|
2225
|
+
refresh_token: refreshToken
|
|
2226
|
+
}),
|
|
2227
|
+
clientInformation,
|
|
2228
|
+
addClientAuthentication,
|
|
2229
|
+
resource,
|
|
2230
|
+
fetchFn
|
|
2231
|
+
})
|
|
2232
|
+
};
|
|
2233
|
+
}
|
|
2234
|
+
/**
|
|
2235
|
+
* Unified token fetching that works with any grant type via provider.prepareTokenRequest().
|
|
2236
|
+
*
|
|
2237
|
+
* This function provides a single entry point for obtaining tokens regardless of the
|
|
2238
|
+
* OAuth grant type. The provider's prepareTokenRequest() method determines which grant
|
|
2239
|
+
* to use and supplies the grant-specific parameters.
|
|
2240
|
+
*
|
|
2241
|
+
* @param provider - OAuth client provider that implements prepareTokenRequest()
|
|
2242
|
+
* @param authorizationServerUrl - The authorization server's base URL
|
|
2243
|
+
* @param options - Configuration for the token request
|
|
2244
|
+
* @returns Promise resolving to OAuth tokens
|
|
2245
|
+
* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
|
|
2246
|
+
*
|
|
2247
|
+
* @example
|
|
2248
|
+
* // Provider for client_credentials:
|
|
2249
|
+
* class MyProvider implements OAuthClientProvider {
|
|
2250
|
+
* prepareTokenRequest(scope) {
|
|
2251
|
+
* const params = new URLSearchParams({ grant_type: 'client_credentials' });
|
|
2252
|
+
* if (scope) params.set('scope', scope);
|
|
2253
|
+
* return params;
|
|
2254
|
+
* }
|
|
2255
|
+
* // ... other methods
|
|
2256
|
+
* }
|
|
2257
|
+
*
|
|
2258
|
+
* const tokens = await fetchToken(provider, authServerUrl, { metadata });
|
|
2259
|
+
*/
|
|
2260
|
+
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
|
|
2261
|
+
const readClientInformation = async () => {
|
|
2262
|
+
const storedClientInformation = await provider.clientInformation();
|
|
2263
|
+
const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
|
|
2264
|
+
if (storedClientInformation && !checked) throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
|
|
2265
|
+
return checked;
|
|
2266
|
+
};
|
|
2267
|
+
let clientInformation = await readClientInformation();
|
|
2268
|
+
const scope = provider.clientMetadata.scope;
|
|
2269
|
+
let tokenRequestParams;
|
|
2270
|
+
if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(scope);
|
|
2271
|
+
if (!tokenRequestParams) {
|
|
2272
|
+
if (!authorizationCode) throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
|
|
2273
|
+
if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow");
|
|
2274
|
+
tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl);
|
|
2275
|
+
}
|
|
2276
|
+
clientInformation ?? (clientInformation = await readClientInformation());
|
|
2277
|
+
return executeTokenRequest(authorizationServerUrl, {
|
|
2278
|
+
metadata,
|
|
2279
|
+
tokenRequestParams,
|
|
2280
|
+
clientInformation,
|
|
2281
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
2282
|
+
resource,
|
|
2283
|
+
fetchFn
|
|
2284
|
+
});
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
|
|
2288
|
+
*
|
|
2289
|
+
* If `scope` is provided, it overrides `clientMetadata.scope` in the registration
|
|
2290
|
+
* request body. This allows callers to apply the Scope Selection Strategy (SEP-835)
|
|
2291
|
+
* consistently across both DCR and the subsequent authorization request.
|
|
2292
|
+
*/
|
|
2293
|
+
async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
|
|
2294
|
+
let registrationUrl;
|
|
2295
|
+
if (metadata) {
|
|
2296
|
+
if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration");
|
|
2297
|
+
registrationUrl = new URL(metadata.registration_endpoint);
|
|
2298
|
+
} else registrationUrl = new URL("/register", authorizationServerUrl);
|
|
2299
|
+
const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
|
|
2300
|
+
method: "POST",
|
|
2301
|
+
headers: { "Content-Type": "application/json" },
|
|
2302
|
+
body: JSON.stringify({
|
|
2303
|
+
...clientMetadata,
|
|
2304
|
+
...scope !== void 0 ? { scope } : {}
|
|
2305
|
+
})
|
|
2306
|
+
});
|
|
2307
|
+
if (!response.ok) throw await parseErrorResponse(response);
|
|
2308
|
+
return RegistrationResponseSchema.parse(await response.json());
|
|
2309
|
+
}
|
|
2310
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
|
|
2311
|
+
var SseError = class extends Error {
|
|
2312
|
+
constructor(code, message, event) {
|
|
2313
|
+
super(`SSE error: ${message}`);
|
|
2314
|
+
this.code = code;
|
|
2315
|
+
this.event = event;
|
|
2316
|
+
}
|
|
2317
|
+
};
|
|
2318
|
+
/**
|
|
2319
|
+
* Client transport for SSE: this will connect to a server using Server-Sent Events for receiving
|
|
2320
|
+
* messages and make separate POST requests for sending messages.
|
|
2321
|
+
* @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period.
|
|
2322
|
+
*/
|
|
2323
|
+
var SSEClientTransport = class {
|
|
2324
|
+
constructor(url, opts) {
|
|
2325
|
+
this._url = url;
|
|
2326
|
+
this._resourceMetadataUrl = void 0;
|
|
2327
|
+
this._scope = void 0;
|
|
2328
|
+
this._eventSourceInit = opts?.eventSourceInit;
|
|
2329
|
+
this._requestInit = opts?.requestInit;
|
|
2330
|
+
this._authProvider = opts?.authProvider;
|
|
2331
|
+
this._fetch = opts?.fetch;
|
|
2332
|
+
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
2333
|
+
this._followRedirects = opts?.redirectPolicy === "follow";
|
|
2334
|
+
if (this._followRedirects) {
|
|
2335
|
+
this._fetch = fetchLeavingRedirects(this._fetch);
|
|
2336
|
+
this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
/** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
|
|
2340
|
+
_unfollowedRedirect(response, url) {
|
|
2341
|
+
const text = unfollowedRedirect(response, url);
|
|
2342
|
+
return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
|
|
2343
|
+
}
|
|
2344
|
+
async _authThenStart() {
|
|
2345
|
+
if (!this._authProvider) throw new UnauthorizedError("No auth provider");
|
|
2346
|
+
let result;
|
|
2347
|
+
try {
|
|
2348
|
+
result = await auth(this._authProvider, {
|
|
2349
|
+
serverUrl: this._url,
|
|
2350
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2351
|
+
scope: this._scope,
|
|
2352
|
+
fetchFn: this._fetchWithInit
|
|
2353
|
+
});
|
|
2354
|
+
} catch (error) {
|
|
2355
|
+
this.onerror?.(error);
|
|
2356
|
+
throw error;
|
|
2357
|
+
}
|
|
2358
|
+
if (result !== "AUTHORIZED") throw new UnauthorizedError();
|
|
2359
|
+
return await this._startOrAuth();
|
|
2360
|
+
}
|
|
2361
|
+
async _commonHeaders() {
|
|
2362
|
+
const headers = {};
|
|
2363
|
+
if (this._authProvider) {
|
|
2364
|
+
const tokens = await this._authProvider.tokens();
|
|
2365
|
+
if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
2366
|
+
}
|
|
2367
|
+
if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion;
|
|
2368
|
+
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
2369
|
+
return new Headers({
|
|
2370
|
+
...headers,
|
|
2371
|
+
...extraHeaders
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
_startOrAuth() {
|
|
2375
|
+
const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
|
|
2376
|
+
const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
|
|
2377
|
+
let redirect;
|
|
2378
|
+
return new Promise((resolve, reject) => {
|
|
2379
|
+
this._eventSource = new EventSource(this._url.href, {
|
|
2380
|
+
...this._eventSourceInit,
|
|
2381
|
+
fetch: async (url, init) => {
|
|
2382
|
+
const headers = await this._commonHeaders();
|
|
2383
|
+
headers.set("Accept", "text/event-stream");
|
|
2384
|
+
const response = await fetchImpl(url, {
|
|
2385
|
+
...init,
|
|
2386
|
+
headers
|
|
2387
|
+
});
|
|
2388
|
+
redirect = this._unfollowedRedirect(response, url);
|
|
2389
|
+
if (response.status === 401 && response.headers.has("www-authenticate")) {
|
|
2390
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
2391
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
2392
|
+
this._scope = scope;
|
|
2393
|
+
}
|
|
2394
|
+
return response;
|
|
2395
|
+
}
|
|
2396
|
+
});
|
|
2397
|
+
this._abortController = new AbortController();
|
|
2398
|
+
this._eventSource.onerror = (event) => {
|
|
2399
|
+
if (event.code === 401 && this._authProvider) {
|
|
2400
|
+
this._authThenStart().then(resolve, reject);
|
|
2401
|
+
return;
|
|
2402
|
+
}
|
|
2403
|
+
const error = new SseError(event.code, redirect ?? event.message, event);
|
|
2404
|
+
reject(error);
|
|
2405
|
+
this.onerror?.(error);
|
|
2406
|
+
};
|
|
2407
|
+
this._eventSource.onopen = () => {};
|
|
2408
|
+
this._eventSource.addEventListener("endpoint", (event) => {
|
|
2409
|
+
const messageEvent = event;
|
|
2410
|
+
try {
|
|
2411
|
+
this._endpoint = new URL(messageEvent.data, this._url);
|
|
2412
|
+
if (this._endpoint.origin !== this._url.origin) throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
|
|
2413
|
+
} catch (error) {
|
|
2414
|
+
reject(error);
|
|
2415
|
+
this.onerror?.(error);
|
|
2416
|
+
this.close();
|
|
2417
|
+
return;
|
|
2418
|
+
}
|
|
2419
|
+
resolve();
|
|
2420
|
+
});
|
|
2421
|
+
this._eventSource.onmessage = (event) => {
|
|
2422
|
+
const messageEvent = event;
|
|
2423
|
+
let message;
|
|
2424
|
+
try {
|
|
2425
|
+
message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
|
|
2426
|
+
} catch (error) {
|
|
2427
|
+
this.onerror?.(error);
|
|
2428
|
+
return;
|
|
2429
|
+
}
|
|
2430
|
+
this.onmessage?.(message);
|
|
2431
|
+
};
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
async start() {
|
|
2435
|
+
if (this._eventSource) throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
2436
|
+
return await this._startOrAuth();
|
|
2437
|
+
}
|
|
2438
|
+
/**
|
|
2439
|
+
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
2440
|
+
*/
|
|
2441
|
+
async finishAuth(authorizationCode) {
|
|
2442
|
+
if (!this._authProvider) throw new UnauthorizedError("No auth provider");
|
|
2443
|
+
if (await auth(this._authProvider, {
|
|
2444
|
+
serverUrl: this._url,
|
|
2445
|
+
authorizationCode,
|
|
2446
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2447
|
+
scope: this._scope,
|
|
2448
|
+
fetchFn: this._fetchWithInit
|
|
2449
|
+
}) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize");
|
|
2450
|
+
}
|
|
2451
|
+
async close() {
|
|
2452
|
+
this._abortController?.abort();
|
|
2453
|
+
this._eventSource?.close();
|
|
2454
|
+
this.onclose?.();
|
|
2455
|
+
}
|
|
2456
|
+
async send(message) {
|
|
2457
|
+
if (!this._endpoint) throw new Error("Not connected");
|
|
2458
|
+
try {
|
|
2459
|
+
const headers = await this._commonHeaders();
|
|
2460
|
+
headers.set("content-type", "application/json");
|
|
2461
|
+
const init = {
|
|
2462
|
+
...this._requestInit,
|
|
2463
|
+
method: "POST",
|
|
2464
|
+
headers,
|
|
2465
|
+
body: JSON.stringify(message),
|
|
2466
|
+
signal: this._abortController?.signal
|
|
2467
|
+
};
|
|
2468
|
+
const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
|
|
2469
|
+
if (!response.ok) {
|
|
2470
|
+
const text = await response.text().catch(() => null);
|
|
2471
|
+
if (response.status === 401 && this._authProvider) {
|
|
2472
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
2473
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
2474
|
+
this._scope = scope;
|
|
2475
|
+
if (await auth(this._authProvider, {
|
|
2476
|
+
serverUrl: this._url,
|
|
2477
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2478
|
+
scope: this._scope,
|
|
2479
|
+
fetchFn: this._fetchWithInit
|
|
2480
|
+
}) !== "AUTHORIZED") throw new UnauthorizedError();
|
|
2481
|
+
return this.send(message);
|
|
2482
|
+
}
|
|
2483
|
+
throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text}`);
|
|
2484
|
+
}
|
|
2485
|
+
await response.body?.cancel();
|
|
2486
|
+
} catch (error) {
|
|
2487
|
+
this.onerror?.(error);
|
|
2488
|
+
throw error;
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
setProtocolVersion(version) {
|
|
2492
|
+
this._protocolVersion = version;
|
|
2493
|
+
}
|
|
2494
|
+
};
|
|
2495
|
+
// ../../node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/stream.js
|
|
2496
|
+
var EventSourceParserStream = class extends TransformStream {
|
|
2497
|
+
constructor({ onError, onRetry, onComment, maxBufferSize } = {}) {
|
|
2498
|
+
let parser;
|
|
2499
|
+
super({
|
|
2500
|
+
start(controller) {
|
|
2501
|
+
parser = createParser({
|
|
2502
|
+
onEvent: (event) => {
|
|
2503
|
+
controller.enqueue(event);
|
|
2504
|
+
},
|
|
2505
|
+
onError(error) {
|
|
2506
|
+
typeof onError == "function" && onError(error), (onError === "terminate" || error.type === "max-buffer-size-exceeded") && controller.error(error);
|
|
2507
|
+
},
|
|
2508
|
+
onRetry,
|
|
2509
|
+
onComment,
|
|
2510
|
+
maxBufferSize
|
|
2511
|
+
});
|
|
2512
|
+
},
|
|
2513
|
+
transform(chunk) {
|
|
2514
|
+
parser.feed(chunk);
|
|
2515
|
+
}
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
};
|
|
2519
|
+
// ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@4.6.7/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
|
|
2520
|
+
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
|
|
2521
|
+
initialReconnectionDelay: 1e3,
|
|
2522
|
+
maxReconnectionDelay: 3e4,
|
|
2523
|
+
reconnectionDelayGrowFactor: 1.5,
|
|
2524
|
+
maxRetries: 2
|
|
2525
|
+
};
|
|
2526
|
+
var StreamableHTTPError = class extends Error {
|
|
2527
|
+
constructor(code, message) {
|
|
2528
|
+
super(`Streamable HTTP error: ${message}`);
|
|
2529
|
+
this.code = code;
|
|
2530
|
+
}
|
|
2531
|
+
};
|
|
2532
|
+
/**
|
|
2533
|
+
* Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.
|
|
2534
|
+
* It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events
|
|
2535
|
+
* for receiving messages.
|
|
2536
|
+
*/
|
|
2537
|
+
var StreamableHTTPClientTransport = class {
|
|
2538
|
+
constructor(url, opts) {
|
|
2539
|
+
this._hasCompletedAuthFlow = false;
|
|
2540
|
+
this._url = url;
|
|
2541
|
+
this._resourceMetadataUrl = void 0;
|
|
2542
|
+
this._scope = void 0;
|
|
2543
|
+
this._requestInit = opts?.requestInit;
|
|
2544
|
+
this._authProvider = opts?.authProvider;
|
|
2545
|
+
this._fetch = opts?.fetch;
|
|
2546
|
+
this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
|
|
2547
|
+
this._followRedirects = opts?.redirectPolicy === "follow";
|
|
2548
|
+
if (this._followRedirects) {
|
|
2549
|
+
this._fetch = fetchLeavingRedirects(this._fetch);
|
|
2550
|
+
this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
|
|
2551
|
+
}
|
|
2552
|
+
this._sessionId = opts?.sessionId;
|
|
2553
|
+
this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
|
|
2554
|
+
}
|
|
2555
|
+
/** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
|
|
2556
|
+
_unfollowedRedirect(response, url) {
|
|
2557
|
+
const text = unfollowedRedirect(response, url);
|
|
2558
|
+
return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
|
|
2559
|
+
}
|
|
2560
|
+
async _authThenStart() {
|
|
2561
|
+
if (!this._authProvider) throw new UnauthorizedError("No auth provider");
|
|
2562
|
+
let result;
|
|
2563
|
+
try {
|
|
2564
|
+
result = await auth(this._authProvider, {
|
|
2565
|
+
serverUrl: this._url,
|
|
2566
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2567
|
+
scope: this._scope,
|
|
2568
|
+
fetchFn: this._fetchWithInit
|
|
2569
|
+
});
|
|
2570
|
+
} catch (error) {
|
|
2571
|
+
this.onerror?.(error);
|
|
2572
|
+
throw error;
|
|
2573
|
+
}
|
|
2574
|
+
if (result !== "AUTHORIZED") throw new UnauthorizedError();
|
|
2575
|
+
return await this._startOrAuthSse({ resumptionToken: void 0 });
|
|
2576
|
+
}
|
|
2577
|
+
async _commonHeaders() {
|
|
2578
|
+
const headers = {};
|
|
2579
|
+
if (this._authProvider) {
|
|
2580
|
+
const tokens = await this._authProvider.tokens();
|
|
2581
|
+
if (tokens) headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
2582
|
+
}
|
|
2583
|
+
if (this._sessionId) headers["mcp-session-id"] = this._sessionId;
|
|
2584
|
+
if (this._protocolVersion) headers["mcp-protocol-version"] = this._protocolVersion;
|
|
2585
|
+
const extraHeaders = normalizeHeaders(this._requestInit?.headers);
|
|
2586
|
+
return new Headers({
|
|
2587
|
+
...headers,
|
|
2588
|
+
...extraHeaders
|
|
2589
|
+
});
|
|
2590
|
+
}
|
|
2591
|
+
async _startOrAuthSse(options) {
|
|
2592
|
+
const { resumptionToken } = options;
|
|
2593
|
+
try {
|
|
2594
|
+
const headers = await this._commonHeaders();
|
|
2595
|
+
headers.set("Accept", "text/event-stream");
|
|
2596
|
+
if (resumptionToken) headers.set("last-event-id", resumptionToken);
|
|
2597
|
+
const fetchFn = this._fetch ?? fetch;
|
|
2598
|
+
const init = {
|
|
2599
|
+
method: "GET",
|
|
2600
|
+
headers,
|
|
2601
|
+
signal: this._abortController?.signal
|
|
2602
|
+
};
|
|
2603
|
+
let response = await fetchFn(this._url, this._followRedirects ? init : {
|
|
2604
|
+
...init,
|
|
2605
|
+
redirect: "manual"
|
|
2606
|
+
});
|
|
2607
|
+
const followed = this._followRedirects ? void 0 : followWithinOrigin(fetchFn, this._url, init, response);
|
|
2608
|
+
if (followed) response = await followed;
|
|
2609
|
+
if (!response.ok) {
|
|
2610
|
+
await response.body?.cancel();
|
|
2611
|
+
if (response.status === 401 && this._authProvider) return await this._authThenStart();
|
|
2612
|
+
if (response.status === 405) return;
|
|
2613
|
+
throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
|
|
2614
|
+
}
|
|
2615
|
+
this._handleSseStream(response.body, options, true);
|
|
2616
|
+
} catch (error) {
|
|
2617
|
+
this.onerror?.(error);
|
|
2618
|
+
throw error;
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
/**
|
|
2622
|
+
* Calculates the next reconnection delay using backoff algorithm
|
|
2623
|
+
*
|
|
2624
|
+
* @param attempt Current reconnection attempt count for the specific stream
|
|
2625
|
+
* @returns Time to wait in milliseconds before next reconnection attempt
|
|
2626
|
+
*/
|
|
2627
|
+
_getNextReconnectionDelay(attempt) {
|
|
2628
|
+
if (this._serverRetryMs !== void 0) return this._serverRetryMs;
|
|
2629
|
+
const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
|
|
2630
|
+
const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
|
|
2631
|
+
const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
|
|
2632
|
+
return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Schedule a reconnection attempt using server-provided retry interval or backoff
|
|
2636
|
+
*
|
|
2637
|
+
* @param lastEventId The ID of the last received event for resumability
|
|
2638
|
+
* @param attemptCount Current reconnection attempt count for this specific stream
|
|
2639
|
+
*/
|
|
2640
|
+
_scheduleReconnection(options, attemptCount = 0) {
|
|
2641
|
+
const maxRetries = this._reconnectionOptions.maxRetries;
|
|
2642
|
+
if (attemptCount >= maxRetries) {
|
|
2643
|
+
this.onerror?.(/* @__PURE__ */ new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
|
|
2644
|
+
return;
|
|
2645
|
+
}
|
|
2646
|
+
const delay = this._getNextReconnectionDelay(attemptCount);
|
|
2647
|
+
this._reconnectionTimeout = setTimeout(() => {
|
|
2648
|
+
this._startOrAuthSse(options).catch((error) => {
|
|
2649
|
+
this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
|
|
2650
|
+
this._scheduleReconnection(options, attemptCount + 1);
|
|
2651
|
+
});
|
|
2652
|
+
}, delay);
|
|
2653
|
+
}
|
|
2654
|
+
_handleSseStream(stream, options, isReconnectable) {
|
|
2655
|
+
if (!stream) return;
|
|
2656
|
+
const { onresumptiontoken, replayMessageId } = options;
|
|
2657
|
+
let lastEventId;
|
|
2658
|
+
let hasPrimingEvent = false;
|
|
2659
|
+
let receivedResponse = false;
|
|
2660
|
+
const processStream = async () => {
|
|
2661
|
+
try {
|
|
2662
|
+
const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({ onRetry: (retryMs) => {
|
|
2663
|
+
this._serverRetryMs = retryMs;
|
|
2664
|
+
} })).getReader();
|
|
2665
|
+
while (true) {
|
|
2666
|
+
const { value: event, done } = await reader.read();
|
|
2667
|
+
if (done) break;
|
|
2668
|
+
if (event.id) {
|
|
2669
|
+
lastEventId = event.id;
|
|
2670
|
+
hasPrimingEvent = true;
|
|
2671
|
+
onresumptiontoken?.(event.id);
|
|
2672
|
+
}
|
|
2673
|
+
if (!event.data) continue;
|
|
2674
|
+
if (!event.event || event.event === "message") try {
|
|
2675
|
+
const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
|
|
2676
|
+
if (isJSONRPCResultResponse(message)) {
|
|
2677
|
+
receivedResponse = true;
|
|
2678
|
+
if (replayMessageId !== void 0) message.id = replayMessageId;
|
|
2679
|
+
}
|
|
2680
|
+
this.onmessage?.(message);
|
|
2681
|
+
} catch (error) {
|
|
2682
|
+
this.onerror?.(error);
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2685
|
+
if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted) this._scheduleReconnection({
|
|
2686
|
+
resumptionToken: lastEventId,
|
|
2687
|
+
onresumptiontoken,
|
|
2688
|
+
replayMessageId
|
|
2689
|
+
}, 0);
|
|
2690
|
+
} catch (error) {
|
|
2691
|
+
this.onerror?.(/* @__PURE__ */ new Error(`SSE stream disconnected: ${error}`));
|
|
2692
|
+
if ((isReconnectable || hasPrimingEvent) && !receivedResponse && this._abortController && !this._abortController.signal.aborted) try {
|
|
2693
|
+
this._scheduleReconnection({
|
|
2694
|
+
resumptionToken: lastEventId,
|
|
2695
|
+
onresumptiontoken,
|
|
2696
|
+
replayMessageId
|
|
2697
|
+
}, 0);
|
|
2698
|
+
} catch (error) {
|
|
2699
|
+
this.onerror?.(/* @__PURE__ */ new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`));
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
};
|
|
2703
|
+
processStream();
|
|
2704
|
+
}
|
|
2705
|
+
async start() {
|
|
2706
|
+
if (this._abortController) throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
|
|
2707
|
+
this._abortController = new AbortController();
|
|
2708
|
+
}
|
|
2709
|
+
/**
|
|
2710
|
+
* Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
|
|
2711
|
+
*/
|
|
2712
|
+
async finishAuth(authorizationCode) {
|
|
2713
|
+
if (!this._authProvider) throw new UnauthorizedError("No auth provider");
|
|
2714
|
+
if (await auth(this._authProvider, {
|
|
2715
|
+
serverUrl: this._url,
|
|
2716
|
+
authorizationCode,
|
|
2717
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2718
|
+
scope: this._scope,
|
|
2719
|
+
fetchFn: this._fetchWithInit
|
|
2720
|
+
}) !== "AUTHORIZED") throw new UnauthorizedError("Failed to authorize");
|
|
2721
|
+
}
|
|
2722
|
+
async close() {
|
|
2723
|
+
if (this._reconnectionTimeout) {
|
|
2724
|
+
clearTimeout(this._reconnectionTimeout);
|
|
2725
|
+
this._reconnectionTimeout = void 0;
|
|
2726
|
+
}
|
|
2727
|
+
this._abortController?.abort();
|
|
2728
|
+
this.onclose?.();
|
|
2729
|
+
}
|
|
2730
|
+
async send(message, options) {
|
|
2731
|
+
try {
|
|
2732
|
+
const { resumptionToken, onresumptiontoken } = options || {};
|
|
2733
|
+
if (resumptionToken) {
|
|
2734
|
+
this._startOrAuthSse({
|
|
2735
|
+
resumptionToken,
|
|
2736
|
+
replayMessageId: isJSONRPCRequest(message) ? message.id : void 0
|
|
2737
|
+
}).catch((err) => this.onerror?.(err));
|
|
2738
|
+
return;
|
|
2739
|
+
}
|
|
2740
|
+
const headers = await this._commonHeaders();
|
|
2741
|
+
headers.set("content-type", "application/json");
|
|
2742
|
+
headers.set("accept", "application/json, text/event-stream");
|
|
2743
|
+
const init = {
|
|
2744
|
+
...this._requestInit,
|
|
2745
|
+
method: "POST",
|
|
2746
|
+
headers,
|
|
2747
|
+
body: JSON.stringify(message),
|
|
2748
|
+
signal: this._abortController?.signal
|
|
2749
|
+
};
|
|
2750
|
+
const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
|
|
2751
|
+
const sessionId = response.headers.get("mcp-session-id");
|
|
2752
|
+
if (sessionId) this._sessionId = sessionId;
|
|
2753
|
+
if (!response.ok) {
|
|
2754
|
+
const text = await response.text().catch(() => null);
|
|
2755
|
+
if (response.status === 401 && this._authProvider) {
|
|
2756
|
+
if (this._hasCompletedAuthFlow) throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
|
|
2757
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
2758
|
+
this._resourceMetadataUrl = resourceMetadataUrl;
|
|
2759
|
+
this._scope = scope;
|
|
2760
|
+
if (await auth(this._authProvider, {
|
|
2761
|
+
serverUrl: this._url,
|
|
2762
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2763
|
+
scope: this._scope,
|
|
2764
|
+
fetchFn: this._fetchWithInit
|
|
2765
|
+
}) !== "AUTHORIZED") throw new UnauthorizedError();
|
|
2766
|
+
this._hasCompletedAuthFlow = true;
|
|
2767
|
+
return this.send(message);
|
|
2768
|
+
}
|
|
2769
|
+
if (response.status === 403 && this._authProvider) {
|
|
2770
|
+
const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response);
|
|
2771
|
+
if (error === "insufficient_scope") {
|
|
2772
|
+
const wwwAuthHeader = response.headers.get("WWW-Authenticate");
|
|
2773
|
+
if (this._lastUpscopingHeader === wwwAuthHeader) throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
|
|
2774
|
+
if (scope) this._scope = scope;
|
|
2775
|
+
if (resourceMetadataUrl) this._resourceMetadataUrl = resourceMetadataUrl;
|
|
2776
|
+
this._lastUpscopingHeader = wwwAuthHeader ?? void 0;
|
|
2777
|
+
if (await auth(this._authProvider, {
|
|
2778
|
+
serverUrl: this._url,
|
|
2779
|
+
resourceMetadataUrl: this._resourceMetadataUrl,
|
|
2780
|
+
scope: this._scope,
|
|
2781
|
+
fetchFn: this._fetch
|
|
2782
|
+
}) !== "AUTHORIZED") throw new UnauthorizedError();
|
|
2783
|
+
return this.send(message);
|
|
2784
|
+
}
|
|
2785
|
+
}
|
|
2786
|
+
throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${this._unfollowedRedirect(response, this._url) ?? text}`);
|
|
2787
|
+
}
|
|
2788
|
+
this._hasCompletedAuthFlow = false;
|
|
2789
|
+
this._lastUpscopingHeader = void 0;
|
|
2790
|
+
if (response.status === 202) {
|
|
2791
|
+
await response.body?.cancel();
|
|
2792
|
+
if (isInitializedNotification(message)) this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => this.onerror?.(err));
|
|
2793
|
+
return;
|
|
2794
|
+
}
|
|
2795
|
+
const hasRequests = (Array.isArray(message) ? message : [message]).filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
|
|
2796
|
+
const contentType = response.headers.get("content-type");
|
|
2797
|
+
const responseMediaType = mediaTypeEssence(contentType);
|
|
2798
|
+
if (hasRequests) {
|
|
2799
|
+
if (responseMediaType === "text/event-stream") this._handleSseStream(response.body, { onresumptiontoken }, false);
|
|
2800
|
+
else if (responseMediaType === "application/json") {
|
|
2801
|
+
const data = await response.json();
|
|
2802
|
+
const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
|
|
2803
|
+
for (const msg of responseMessages) this.onmessage?.(msg);
|
|
2804
|
+
} else {
|
|
2805
|
+
await response.body?.cancel();
|
|
2806
|
+
throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
|
|
2807
|
+
}
|
|
2808
|
+
} else await response.body?.cancel();
|
|
2809
|
+
} catch (error) {
|
|
2810
|
+
this.onerror?.(error);
|
|
2811
|
+
throw error;
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
get sessionId() {
|
|
2815
|
+
return this._sessionId;
|
|
2816
|
+
}
|
|
2817
|
+
/**
|
|
2818
|
+
* Terminates the current session by sending a DELETE request to the server.
|
|
2819
|
+
*
|
|
2820
|
+
* Clients that no longer need a particular session
|
|
2821
|
+
* (e.g., because the user is leaving the client application) SHOULD send an
|
|
2822
|
+
* HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
|
|
2823
|
+
* terminate the session.
|
|
2824
|
+
*
|
|
2825
|
+
* The server MAY respond with HTTP 405 Method Not Allowed, indicating that
|
|
2826
|
+
* the server does not allow clients to terminate sessions.
|
|
2827
|
+
*/
|
|
2828
|
+
async terminateSession() {
|
|
2829
|
+
if (!this._sessionId) return;
|
|
2830
|
+
try {
|
|
2831
|
+
const headers = await this._commonHeaders();
|
|
2832
|
+
const init = {
|
|
2833
|
+
...this._requestInit,
|
|
2834
|
+
method: "DELETE",
|
|
2835
|
+
headers,
|
|
2836
|
+
signal: this._abortController?.signal
|
|
2837
|
+
};
|
|
2838
|
+
const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
|
|
2839
|
+
await response.body?.cancel();
|
|
2840
|
+
if (!response.ok && response.status !== 405) throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
|
|
2841
|
+
this._sessionId = void 0;
|
|
2842
|
+
} catch (error) {
|
|
2843
|
+
this.onerror?.(error);
|
|
2844
|
+
throw error;
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
setProtocolVersion(version) {
|
|
2848
|
+
this._protocolVersion = version;
|
|
2849
|
+
}
|
|
2850
|
+
get protocolVersion() {
|
|
2851
|
+
return this._protocolVersion;
|
|
2852
|
+
}
|
|
2853
|
+
/**
|
|
2854
|
+
* Resume an SSE stream from a previous event ID.
|
|
2855
|
+
* Opens a GET SSE connection with Last-Event-ID header to replay missed events.
|
|
2856
|
+
*
|
|
2857
|
+
* @param lastEventId The event ID to resume from
|
|
2858
|
+
* @param options Optional callback to receive new resumption tokens
|
|
2859
|
+
*/
|
|
2860
|
+
async resumeStream(lastEventId, options) {
|
|
2861
|
+
await this._startOrAuthSse({
|
|
2862
|
+
resumptionToken: lastEventId,
|
|
2863
|
+
onresumptiontoken: options?.onresumptiontoken
|
|
2864
|
+
});
|
|
2865
|
+
}
|
|
2866
|
+
};
|
|
2867
|
+
// ../runner/src/mcp/resolve-spec.ts
|
|
2868
|
+
/** A `${VAR}` without a default named a variable that is not set. */
|
|
2869
|
+
var MissingEnvError = class extends Error {
|
|
2870
|
+
names;
|
|
2871
|
+
constructor(names) {
|
|
2872
|
+
super(names.length === 1 ? `Environment variable ${names[0]} is not set` : `Environment variables ${names.join(", ")} are not set`);
|
|
2873
|
+
this.names = names;
|
|
2874
|
+
this.name = "MissingEnvError";
|
|
2875
|
+
}
|
|
2876
|
+
};
|
|
2877
|
+
const PLACEHOLDER = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
|
|
2878
|
+
/**
|
|
2879
|
+
* Expand `${VAR}` and `${VAR:-default}` the way Claude Code does in its MCP config: an unset
|
|
2880
|
+
* variable takes the default, and one without a default is collected into `missing`.
|
|
2881
|
+
*/
|
|
2882
|
+
function expandEnvVars(value, env, missing) {
|
|
2883
|
+
return value.replace(PLACEHOLDER, (match, name, fallback) => {
|
|
2884
|
+
const set = env[name];
|
|
2885
|
+
if (set !== void 0) return set;
|
|
2886
|
+
if (fallback !== void 0) return fallback;
|
|
2887
|
+
missing.add(name);
|
|
2888
|
+
return match;
|
|
2889
|
+
});
|
|
2890
|
+
}
|
|
2891
|
+
const mapValues = (o, f) => Object.fromEntries(Object.entries(o ?? {}).map(([k, v]) => [k, f(v)]));
|
|
2892
|
+
/**
|
|
2893
|
+
* Set a header, replacing every copy of it under any casing. HTTP header names are
|
|
2894
|
+
* case-insensitive, and two spellings (`authorization` and `Authorization`) would otherwise
|
|
2895
|
+
* be sent as one header with both values joined, such as an invalid `Bearer a, Bearer b`.
|
|
2896
|
+
*/
|
|
2897
|
+
function setHeader(headers, name, value) {
|
|
2898
|
+
const lower = name.toLowerCase();
|
|
2899
|
+
for (const existing of Object.keys(headers)) if (existing.toLowerCase() === lower) delete headers[existing];
|
|
2900
|
+
headers[name] = value;
|
|
2901
|
+
}
|
|
2902
|
+
/**
|
|
2903
|
+
* Apply the environment to a spec as the provider would before starting it.
|
|
2904
|
+
* - `expandEnv` (Claude): `${VAR}` placeholders in the command, args, env, URL and headers.
|
|
2905
|
+
* - Codex: `bearerTokenEnvVar` becomes an `Authorization: Bearer` header, and the native
|
|
2906
|
+
* `env_http_headers` table (header name -> variable name) adds headers from set variables.
|
|
2907
|
+
* Header names are matched case-insensitively and one value wins, in this order: the
|
|
2908
|
+
* bearer-token variable, then `env_http_headers`, then the headers themselves (the last
|
|
2909
|
+
* spelling in the file when the same header appears twice there).
|
|
2910
|
+
* Throws `MissingEnvError` naming every variable that is required but not set.
|
|
2911
|
+
*/
|
|
2912
|
+
function resolveMcpSpec(spec, opts) {
|
|
2913
|
+
const missing = /* @__PURE__ */ new Set();
|
|
2914
|
+
const x = (v) => opts.expandEnv ? expandEnvVars(v, opts.env, missing) : v;
|
|
2915
|
+
let resolved;
|
|
2916
|
+
if (spec.type === "stdio") resolved = {
|
|
2917
|
+
type: "stdio",
|
|
2918
|
+
command: x(spec.command),
|
|
2919
|
+
args: (spec.args ?? []).map(x),
|
|
2920
|
+
env: mapValues(spec.env, x),
|
|
2921
|
+
cwd: spec.cwd ? x(spec.cwd) : void 0
|
|
2922
|
+
};
|
|
2923
|
+
else {
|
|
2924
|
+
const url = x(spec.url);
|
|
2925
|
+
const headers = {};
|
|
2926
|
+
for (const [name, value] of Object.entries(spec.headers ?? {})) setHeader(headers, name, x(value));
|
|
2927
|
+
const envHeaders = spec.extra?.env_http_headers;
|
|
2928
|
+
if (envHeaders && typeof envHeaders === "object" && !Array.isArray(envHeaders)) for (const [header, variable] of Object.entries(envHeaders)) {
|
|
2929
|
+
const value = typeof variable === "string" ? opts.env[variable] : void 0;
|
|
2930
|
+
if (value !== void 0) setHeader(headers, header, value);
|
|
2931
|
+
}
|
|
2932
|
+
if (spec.bearerTokenEnvVar) {
|
|
2933
|
+
const token = opts.env[spec.bearerTokenEnvVar];
|
|
2934
|
+
if (token === void 0) missing.add(spec.bearerTokenEnvVar);
|
|
2935
|
+
else setHeader(headers, "Authorization", `Bearer ${token}`);
|
|
2936
|
+
}
|
|
2937
|
+
resolved = {
|
|
2938
|
+
type: spec.type,
|
|
2939
|
+
url,
|
|
2940
|
+
headers
|
|
2941
|
+
};
|
|
2942
|
+
}
|
|
2943
|
+
if (missing.size > 0) throw new MissingEnvError([...missing]);
|
|
2944
|
+
return resolved;
|
|
2945
|
+
}
|
|
2946
|
+
// ../runner/src/mcp/stdio-env.ts
|
|
2947
|
+
/** Variables Codex passes from its own environment to every local stdio server, on POSIX. */
|
|
2948
|
+
const CODEX_POSIX_DEFAULTS = [
|
|
2949
|
+
"HOME",
|
|
2950
|
+
"LOGNAME",
|
|
2951
|
+
"PATH",
|
|
2952
|
+
"SHELL",
|
|
2953
|
+
"USER",
|
|
2954
|
+
"__CF_USER_TEXT_ENCODING",
|
|
2955
|
+
"LANG",
|
|
2956
|
+
"LC_ALL",
|
|
2957
|
+
"TERM",
|
|
2958
|
+
"TMPDIR",
|
|
2959
|
+
"TZ"
|
|
2960
|
+
];
|
|
2961
|
+
/** The same on Windows. */
|
|
2962
|
+
const CODEX_WINDOWS_DEFAULTS = [
|
|
2963
|
+
"PATH",
|
|
2964
|
+
"PATHEXT",
|
|
2965
|
+
"SHELL",
|
|
2966
|
+
"COMSPEC",
|
|
2967
|
+
"SYSTEMROOT",
|
|
2968
|
+
"WINDIR",
|
|
2969
|
+
"SYSTEMDRIVE",
|
|
2970
|
+
"USERNAME",
|
|
2971
|
+
"USERDOMAIN",
|
|
2972
|
+
"USERPROFILE",
|
|
2973
|
+
"HOMEDRIVE",
|
|
2974
|
+
"HOMEPATH",
|
|
2975
|
+
"PROGRAMFILES",
|
|
2976
|
+
"PROGRAMFILES(X86)",
|
|
2977
|
+
"PROGRAMW6432",
|
|
2978
|
+
"PROGRAMDATA",
|
|
2979
|
+
"LOCALAPPDATA",
|
|
2980
|
+
"APPDATA",
|
|
2981
|
+
"TEMP",
|
|
2982
|
+
"TMP",
|
|
2983
|
+
"TMPDIR",
|
|
2984
|
+
"POWERSHELL",
|
|
2985
|
+
"PWSH"
|
|
2986
|
+
];
|
|
2987
|
+
/** CA bundle variables Codex also passes on when they are set and not empty. */
|
|
2988
|
+
const CODEX_CA_VARS = [
|
|
2989
|
+
"CODEX_CA_CERTIFICATE",
|
|
2990
|
+
"SSL_CERT_FILE",
|
|
2991
|
+
"REQUESTS_CA_BUNDLE",
|
|
2992
|
+
"CURL_CA_BUNDLE",
|
|
2993
|
+
"NODE_EXTRA_CA_CERTS",
|
|
2994
|
+
"GIT_SSL_CAINFO",
|
|
2995
|
+
"CARGO_HTTP_CAINFO",
|
|
2996
|
+
"PIP_CERT",
|
|
2997
|
+
"BUNDLE_SSL_CA_CERT",
|
|
2998
|
+
"npm_config_cafile",
|
|
2999
|
+
"NPM_CONFIG_CAFILE"
|
|
3000
|
+
];
|
|
3001
|
+
/** Added to a failed `allowlist` test of a stdio server that started. */
|
|
3002
|
+
const ALLOWLIST_NOTE = "Codex starts a stdio server with only a few variables from your environment (PATH, HOME or USERPROFILE, the temp folder and the like), the names listed in its env_vars and its env table. If the server needs another variable, such as a token, add its name to the server's env_vars in ~/.codex/config.toml.";
|
|
3003
|
+
/**
|
|
3004
|
+
* Names in Codex's native `env_vars` list (kept in a spec's `extra`): plain names, or
|
|
3005
|
+
* `{ name, source }` tables. A `source = "remote"` entry is read on a remote machine, never
|
|
3006
|
+
* from the local environment, so it is left out.
|
|
3007
|
+
*/
|
|
3008
|
+
function codexEnvVarNames(extra) {
|
|
3009
|
+
const list = extra?.env_vars;
|
|
3010
|
+
if (!Array.isArray(list)) return [];
|
|
3011
|
+
return list.flatMap((entry) => {
|
|
3012
|
+
if (typeof entry === "string") return [entry];
|
|
3013
|
+
if (typeof entry !== "object" || entry === null) return [];
|
|
3014
|
+
const { name, source } = entry;
|
|
3015
|
+
return typeof name === "string" && source !== "remote" ? [name] : [];
|
|
3016
|
+
});
|
|
3017
|
+
}
|
|
3018
|
+
/**
|
|
3019
|
+
* The environment a stdio server starts with in a connection test (`McpStdioEnv`). `base` is
|
|
3020
|
+
* the runner's environment (minus CodeDen's secrets); the server's own `env` always wins.
|
|
3021
|
+
* Variable names are matched ignoring case on Windows, as the OS does.
|
|
3022
|
+
*/
|
|
3023
|
+
function stdioServerEnv(opts) {
|
|
3024
|
+
const windows = (opts.platform ?? process.platform) === "win32";
|
|
3025
|
+
const fold = (name) => windows ? name.toUpperCase() : name;
|
|
3026
|
+
const out = {};
|
|
3027
|
+
const set = (name, value) => {
|
|
3028
|
+
if (windows) {
|
|
3029
|
+
for (const key of Object.keys(out)) if (fold(key) === fold(name)) delete out[key];
|
|
3030
|
+
}
|
|
3031
|
+
out[name] = value;
|
|
3032
|
+
};
|
|
3033
|
+
if (opts.policy === "inherit") Object.assign(out, opts.base);
|
|
3034
|
+
else {
|
|
3035
|
+
const byName = new Map(Object.entries(opts.base).map(([k, v]) => [fold(k), v]));
|
|
3036
|
+
const defaults = windows ? CODEX_WINDOWS_DEFAULTS : CODEX_POSIX_DEFAULTS;
|
|
3037
|
+
for (const name of [...defaults, ...opts.envVars]) {
|
|
3038
|
+
const value = byName.get(fold(name));
|
|
3039
|
+
if (value !== void 0) set(name, value);
|
|
3040
|
+
}
|
|
3041
|
+
for (const name of CODEX_CA_VARS) {
|
|
3042
|
+
const value = byName.get(fold(name));
|
|
3043
|
+
if (value) set(name, value);
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
for (const [name, value] of Object.entries(opts.serverEnv)) set(name, value);
|
|
3047
|
+
return out;
|
|
3048
|
+
}
|
|
3049
|
+
/**
|
|
3050
|
+
* Buffers a continuous stdio stream into discrete JSON-RPC messages.
|
|
3051
|
+
*/
|
|
3052
|
+
var ReadBuffer = class {
|
|
3053
|
+
constructor(options) {
|
|
3054
|
+
this._maxBufferSize = options?.maxBufferSize ?? 10485760;
|
|
3055
|
+
}
|
|
3056
|
+
append(chunk) {
|
|
3057
|
+
if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) {
|
|
3058
|
+
this.clear();
|
|
3059
|
+
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
3060
|
+
}
|
|
3061
|
+
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
3062
|
+
}
|
|
3063
|
+
readMessage() {
|
|
3064
|
+
if (!this._buffer) return null;
|
|
3065
|
+
const index = this._buffer.indexOf("\n");
|
|
3066
|
+
if (index === -1) return null;
|
|
3067
|
+
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
|
|
3068
|
+
this._buffer = this._buffer.subarray(index + 1);
|
|
3069
|
+
return deserializeMessage(line);
|
|
3070
|
+
}
|
|
3071
|
+
clear() {
|
|
3072
|
+
this._buffer = void 0;
|
|
3073
|
+
}
|
|
3074
|
+
};
|
|
3075
|
+
function deserializeMessage(line) {
|
|
3076
|
+
return JSONRPCMessageSchema.parse(JSON.parse(line));
|
|
3077
|
+
}
|
|
3078
|
+
function serializeMessage(message) {
|
|
3079
|
+
return JSON.stringify(message) + "\n";
|
|
3080
|
+
}
|
|
3081
|
+
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js
|
|
3082
|
+
var require_windows = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3083
|
+
module.exports = isexe;
|
|
3084
|
+
isexe.sync = sync;
|
|
3085
|
+
var fs = __require("fs");
|
|
3086
|
+
function checkPathExt(path, options) {
|
|
3087
|
+
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
|
|
3088
|
+
if (!pathext) return true;
|
|
3089
|
+
pathext = pathext.split(";");
|
|
3090
|
+
if (pathext.indexOf("") !== -1) return true;
|
|
3091
|
+
for (var i = 0; i < pathext.length; i++) {
|
|
3092
|
+
var p = pathext[i].toLowerCase();
|
|
3093
|
+
if (p && path.substr(-p.length).toLowerCase() === p) return true;
|
|
3094
|
+
}
|
|
3095
|
+
return false;
|
|
3096
|
+
}
|
|
3097
|
+
function checkStat(stat, path, options) {
|
|
3098
|
+
if (!stat.isSymbolicLink() && !stat.isFile()) return false;
|
|
3099
|
+
return checkPathExt(path, options);
|
|
3100
|
+
}
|
|
3101
|
+
function isexe(path, options, cb) {
|
|
3102
|
+
fs.stat(path, function(er, stat) {
|
|
3103
|
+
cb(er, er ? false : checkStat(stat, path, options));
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
function sync(path, options) {
|
|
3107
|
+
return checkStat(fs.statSync(path), path, options);
|
|
3108
|
+
}
|
|
3109
|
+
}));
|
|
3110
|
+
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js
|
|
3111
|
+
var require_mode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3112
|
+
module.exports = isexe;
|
|
3113
|
+
isexe.sync = sync;
|
|
3114
|
+
var fs = __require("fs");
|
|
3115
|
+
function isexe(path, options, cb) {
|
|
3116
|
+
fs.stat(path, function(er, stat) {
|
|
3117
|
+
cb(er, er ? false : checkStat(stat, options));
|
|
3118
|
+
});
|
|
3119
|
+
}
|
|
3120
|
+
function sync(path, options) {
|
|
3121
|
+
return checkStat(fs.statSync(path), options);
|
|
3122
|
+
}
|
|
3123
|
+
function checkStat(stat, options) {
|
|
3124
|
+
return stat.isFile() && checkMode(stat, options);
|
|
3125
|
+
}
|
|
3126
|
+
function checkMode(stat, options) {
|
|
3127
|
+
var mod = stat.mode;
|
|
3128
|
+
var uid = stat.uid;
|
|
3129
|
+
var gid = stat.gid;
|
|
3130
|
+
var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
|
|
3131
|
+
var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
|
|
3132
|
+
var u = parseInt("100", 8);
|
|
3133
|
+
var g = parseInt("010", 8);
|
|
3134
|
+
var o = parseInt("001", 8);
|
|
3135
|
+
var ug = u | g;
|
|
3136
|
+
return mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
|
|
3137
|
+
}
|
|
3138
|
+
}));
|
|
3139
|
+
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
|
|
3140
|
+
var require_isexe = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3141
|
+
__require("fs");
|
|
3142
|
+
var core;
|
|
3143
|
+
if (process.platform === "win32" || global.TESTING_WINDOWS) core = require_windows();
|
|
3144
|
+
else core = require_mode();
|
|
3145
|
+
module.exports = isexe;
|
|
3146
|
+
isexe.sync = sync;
|
|
3147
|
+
function isexe(path, options, cb) {
|
|
3148
|
+
if (typeof options === "function") {
|
|
3149
|
+
cb = options;
|
|
3150
|
+
options = {};
|
|
3151
|
+
}
|
|
3152
|
+
if (!cb) {
|
|
3153
|
+
if (typeof Promise !== "function") throw new TypeError("callback not provided");
|
|
3154
|
+
return new Promise(function(resolve, reject) {
|
|
3155
|
+
isexe(path, options || {}, function(er, is) {
|
|
3156
|
+
if (er) reject(er);
|
|
3157
|
+
else resolve(is);
|
|
3158
|
+
});
|
|
3159
|
+
});
|
|
3160
|
+
}
|
|
3161
|
+
core(path, options || {}, function(er, is) {
|
|
3162
|
+
if (er) {
|
|
3163
|
+
if (er.code === "EACCES" || options && options.ignoreErrors) {
|
|
3164
|
+
er = null;
|
|
3165
|
+
is = false;
|
|
3166
|
+
}
|
|
3167
|
+
}
|
|
3168
|
+
cb(er, is);
|
|
3169
|
+
});
|
|
3170
|
+
}
|
|
3171
|
+
function sync(path, options) {
|
|
3172
|
+
try {
|
|
3173
|
+
return core.sync(path, options || {});
|
|
3174
|
+
} catch (er) {
|
|
3175
|
+
if (options && options.ignoreErrors || er.code === "EACCES") return false;
|
|
3176
|
+
else throw er;
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
3179
|
+
}));
|
|
3180
|
+
// ../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js
|
|
3181
|
+
var require_which = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3182
|
+
const isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
|
|
3183
|
+
const path = __require("path");
|
|
3184
|
+
const COLON = isWindows ? ";" : ":";
|
|
3185
|
+
const isexe = require_isexe();
|
|
3186
|
+
const getNotFoundError = (cmd) => Object.assign(/* @__PURE__ */ new Error(`not found: ${cmd}`), { code: "ENOENT" });
|
|
3187
|
+
const getPathInfo = (cmd, opt) => {
|
|
3188
|
+
const colon = opt.colon || COLON;
|
|
3189
|
+
const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [...isWindows ? [process.cwd()] : [], ...(opt.path || process.env.PATH ||
|
|
3190
|
+
/* istanbul ignore next: very unusual */ "").split(colon)];
|
|
3191
|
+
const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
|
|
3192
|
+
const pathExt = isWindows ? pathExtExe.split(colon) : [""];
|
|
3193
|
+
if (isWindows) {
|
|
3194
|
+
if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") pathExt.unshift("");
|
|
3195
|
+
}
|
|
3196
|
+
return {
|
|
3197
|
+
pathEnv,
|
|
3198
|
+
pathExt,
|
|
3199
|
+
pathExtExe
|
|
3200
|
+
};
|
|
3201
|
+
};
|
|
3202
|
+
const which = (cmd, opt, cb) => {
|
|
3203
|
+
if (typeof opt === "function") {
|
|
3204
|
+
cb = opt;
|
|
3205
|
+
opt = {};
|
|
3206
|
+
}
|
|
3207
|
+
if (!opt) opt = {};
|
|
3208
|
+
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
3209
|
+
const found = [];
|
|
3210
|
+
const step = (i) => new Promise((resolve, reject) => {
|
|
3211
|
+
if (i === pathEnv.length) return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd));
|
|
3212
|
+
const ppRaw = pathEnv[i];
|
|
3213
|
+
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
3214
|
+
const pCmd = path.join(pathPart, cmd);
|
|
3215
|
+
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
3216
|
+
resolve(subStep(p, i, 0));
|
|
3217
|
+
});
|
|
3218
|
+
const subStep = (p, i, ii) => new Promise((resolve, reject) => {
|
|
3219
|
+
if (ii === pathExt.length) return resolve(step(i + 1));
|
|
3220
|
+
const ext = pathExt[ii];
|
|
3221
|
+
isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
|
|
3222
|
+
if (!er && is) {
|
|
3223
|
+
if (opt.all) found.push(p + ext);
|
|
3224
|
+
else return resolve(p + ext);
|
|
3225
|
+
}
|
|
3226
|
+
return resolve(subStep(p, i, ii + 1));
|
|
3227
|
+
});
|
|
3228
|
+
});
|
|
3229
|
+
return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
|
|
3230
|
+
};
|
|
3231
|
+
const whichSync = (cmd, opt) => {
|
|
3232
|
+
opt = opt || {};
|
|
3233
|
+
const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
|
|
3234
|
+
const found = [];
|
|
3235
|
+
for (let i = 0; i < pathEnv.length; i++) {
|
|
3236
|
+
const ppRaw = pathEnv[i];
|
|
3237
|
+
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
3238
|
+
const pCmd = path.join(pathPart, cmd);
|
|
3239
|
+
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
3240
|
+
for (let j = 0; j < pathExt.length; j++) {
|
|
3241
|
+
const cur = p + pathExt[j];
|
|
3242
|
+
try {
|
|
3243
|
+
if (isexe.sync(cur, { pathExt: pathExtExe })) {
|
|
3244
|
+
if (opt.all) found.push(cur);
|
|
3245
|
+
else return cur;
|
|
3246
|
+
}
|
|
3247
|
+
} catch (ex) {}
|
|
3248
|
+
}
|
|
3249
|
+
}
|
|
3250
|
+
if (opt.all && found.length) return found;
|
|
3251
|
+
if (opt.nothrow) return null;
|
|
3252
|
+
throw getNotFoundError(cmd);
|
|
3253
|
+
};
|
|
3254
|
+
module.exports = which;
|
|
3255
|
+
which.sync = whichSync;
|
|
3256
|
+
}));
|
|
3257
|
+
// ../../node_modules/.pnpm/path-key@3.1.1/node_modules/path-key/index.js
|
|
3258
|
+
var require_path_key = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3259
|
+
const pathKey = (options = {}) => {
|
|
3260
|
+
const environment = options.env || process.env;
|
|
3261
|
+
if ((options.platform || process.platform) !== "win32") return "PATH";
|
|
3262
|
+
return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
|
|
3263
|
+
};
|
|
3264
|
+
module.exports = pathKey;
|
|
3265
|
+
module.exports.default = pathKey;
|
|
3266
|
+
}));
|
|
3267
|
+
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js
|
|
3268
|
+
var require_resolveCommand = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3269
|
+
const path = __require("path");
|
|
3270
|
+
const which = require_which();
|
|
3271
|
+
const getPathKey = require_path_key();
|
|
3272
|
+
function resolveCommandAttempt(parsed, withoutPathExt) {
|
|
3273
|
+
const env = parsed.options.env || process.env;
|
|
3274
|
+
const cwd = process.cwd();
|
|
3275
|
+
const hasCustomCwd = parsed.options.cwd != null;
|
|
3276
|
+
const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
|
|
3277
|
+
if (shouldSwitchCwd) try {
|
|
3278
|
+
process.chdir(parsed.options.cwd);
|
|
3279
|
+
} catch (err) {}
|
|
3280
|
+
let resolved;
|
|
3281
|
+
try {
|
|
3282
|
+
resolved = which.sync(parsed.command, {
|
|
3283
|
+
path: env[getPathKey({ env })],
|
|
3284
|
+
pathExt: withoutPathExt ? path.delimiter : void 0
|
|
3285
|
+
});
|
|
3286
|
+
} catch (e) {} finally {
|
|
3287
|
+
if (shouldSwitchCwd) process.chdir(cwd);
|
|
3288
|
+
}
|
|
3289
|
+
if (resolved) resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
|
|
3290
|
+
return resolved;
|
|
3291
|
+
}
|
|
3292
|
+
function resolveCommand(parsed) {
|
|
3293
|
+
return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
|
|
3294
|
+
}
|
|
3295
|
+
module.exports = resolveCommand;
|
|
3296
|
+
}));
|
|
3297
|
+
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/escape.js
|
|
3298
|
+
var require_escape = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3299
|
+
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
|
|
3300
|
+
function escapeCommand(arg) {
|
|
3301
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
3302
|
+
return arg;
|
|
3303
|
+
}
|
|
3304
|
+
function escapeArgument(arg, doubleEscapeMetaChars) {
|
|
3305
|
+
arg = `${arg}`;
|
|
3306
|
+
arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
|
|
3307
|
+
arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
|
|
3308
|
+
arg = `"${arg}"`;
|
|
3309
|
+
arg = arg.replace(metaCharsRegExp, "^$1");
|
|
3310
|
+
if (doubleEscapeMetaChars) arg = arg.replace(metaCharsRegExp, "^$1");
|
|
3311
|
+
return arg;
|
|
3312
|
+
}
|
|
3313
|
+
module.exports.command = escapeCommand;
|
|
3314
|
+
module.exports.argument = escapeArgument;
|
|
3315
|
+
}));
|
|
3316
|
+
// ../../node_modules/.pnpm/shebang-regex@3.0.0/node_modules/shebang-regex/index.js
|
|
3317
|
+
var require_shebang_regex = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3318
|
+
module.exports = /^#!(.*)/;
|
|
3319
|
+
}));
|
|
3320
|
+
// ../../node_modules/.pnpm/shebang-command@2.0.0/node_modules/shebang-command/index.js
|
|
3321
|
+
var require_shebang_command = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3322
|
+
const shebangRegex = require_shebang_regex();
|
|
3323
|
+
module.exports = (string = "") => {
|
|
3324
|
+
const match = string.match(shebangRegex);
|
|
3325
|
+
if (!match) return null;
|
|
3326
|
+
const [path, argument] = match[0].replace(/#! ?/, "").split(" ");
|
|
3327
|
+
const binary = path.split("/").pop();
|
|
3328
|
+
if (binary === "env") return argument;
|
|
3329
|
+
return argument ? `${binary} ${argument}` : binary;
|
|
3330
|
+
};
|
|
3331
|
+
}));
|
|
3332
|
+
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js
|
|
3333
|
+
var require_readShebang = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3334
|
+
const fs = __require("fs");
|
|
3335
|
+
const shebangCommand = require_shebang_command();
|
|
3336
|
+
function readShebang(command) {
|
|
3337
|
+
const size = 150;
|
|
3338
|
+
const buffer = Buffer.alloc(size);
|
|
3339
|
+
let fd;
|
|
3340
|
+
try {
|
|
3341
|
+
fd = fs.openSync(command, "r");
|
|
3342
|
+
fs.readSync(fd, buffer, 0, size, 0);
|
|
3343
|
+
fs.closeSync(fd);
|
|
3344
|
+
} catch (e) {}
|
|
3345
|
+
return shebangCommand(buffer.toString());
|
|
3346
|
+
}
|
|
3347
|
+
module.exports = readShebang;
|
|
3348
|
+
}));
|
|
3349
|
+
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js
|
|
3350
|
+
var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3351
|
+
const path = __require("path");
|
|
3352
|
+
const resolveCommand = require_resolveCommand();
|
|
3353
|
+
const escape = require_escape();
|
|
3354
|
+
const readShebang = require_readShebang();
|
|
3355
|
+
const isWin = process.platform === "win32";
|
|
3356
|
+
const isExecutableRegExp = /\.(?:com|exe)$/i;
|
|
3357
|
+
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
|
|
3358
|
+
function detectShebang(parsed) {
|
|
3359
|
+
parsed.file = resolveCommand(parsed);
|
|
3360
|
+
const shebang = parsed.file && readShebang(parsed.file);
|
|
3361
|
+
if (shebang) {
|
|
3362
|
+
parsed.args.unshift(parsed.file);
|
|
3363
|
+
parsed.command = shebang;
|
|
3364
|
+
return resolveCommand(parsed);
|
|
3365
|
+
}
|
|
3366
|
+
return parsed.file;
|
|
3367
|
+
}
|
|
3368
|
+
function parseNonShell(parsed) {
|
|
3369
|
+
if (!isWin) return parsed;
|
|
3370
|
+
const commandFile = detectShebang(parsed);
|
|
3371
|
+
const needsShell = !isExecutableRegExp.test(commandFile);
|
|
3372
|
+
if (parsed.options.forceShell || needsShell) {
|
|
3373
|
+
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
|
|
3374
|
+
parsed.command = path.normalize(parsed.command);
|
|
3375
|
+
parsed.command = escape.command(parsed.command);
|
|
3376
|
+
parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
|
|
3377
|
+
parsed.args = [
|
|
3378
|
+
"/d",
|
|
3379
|
+
"/s",
|
|
3380
|
+
"/c",
|
|
3381
|
+
`"${[parsed.command].concat(parsed.args).join(" ")}"`
|
|
3382
|
+
];
|
|
3383
|
+
parsed.command = process.env.comspec || "cmd.exe";
|
|
3384
|
+
parsed.options.windowsVerbatimArguments = true;
|
|
3385
|
+
}
|
|
3386
|
+
return parsed;
|
|
3387
|
+
}
|
|
3388
|
+
function parse(command, args, options) {
|
|
3389
|
+
if (args && !Array.isArray(args)) {
|
|
3390
|
+
options = args;
|
|
3391
|
+
args = null;
|
|
3392
|
+
}
|
|
3393
|
+
args = args ? args.slice(0) : [];
|
|
3394
|
+
options = Object.assign({}, options);
|
|
3395
|
+
const parsed = {
|
|
3396
|
+
command,
|
|
3397
|
+
args,
|
|
3398
|
+
options,
|
|
3399
|
+
file: void 0,
|
|
3400
|
+
original: {
|
|
3401
|
+
command,
|
|
3402
|
+
args
|
|
3403
|
+
}
|
|
3404
|
+
};
|
|
3405
|
+
return options.shell ? parsed : parseNonShell(parsed);
|
|
3406
|
+
}
|
|
3407
|
+
module.exports = parse;
|
|
3408
|
+
}));
|
|
3409
|
+
// ../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/enoent.js
|
|
3410
|
+
var require_enoent = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3411
|
+
const isWin = process.platform === "win32";
|
|
3412
|
+
function notFoundError(original, syscall) {
|
|
3413
|
+
return Object.assign(/* @__PURE__ */ new Error(`${syscall} ${original.command} ENOENT`), {
|
|
3414
|
+
code: "ENOENT",
|
|
3415
|
+
errno: "ENOENT",
|
|
3416
|
+
syscall: `${syscall} ${original.command}`,
|
|
3417
|
+
path: original.command,
|
|
3418
|
+
spawnargs: original.args
|
|
3419
|
+
});
|
|
3420
|
+
}
|
|
3421
|
+
function hookChildProcess(cp, parsed) {
|
|
3422
|
+
if (!isWin) return;
|
|
3423
|
+
const originalEmit = cp.emit;
|
|
3424
|
+
cp.emit = function(name, arg1) {
|
|
3425
|
+
if (name === "exit") {
|
|
3426
|
+
const err = verifyENOENT(arg1, parsed);
|
|
3427
|
+
if (err) return originalEmit.call(cp, "error", err);
|
|
3428
|
+
}
|
|
3429
|
+
return originalEmit.apply(cp, arguments);
|
|
3430
|
+
};
|
|
3431
|
+
}
|
|
3432
|
+
function verifyENOENT(status, parsed) {
|
|
3433
|
+
if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawn");
|
|
3434
|
+
return null;
|
|
3435
|
+
}
|
|
3436
|
+
function verifyENOENTSync(status, parsed) {
|
|
3437
|
+
if (isWin && status === 1 && !parsed.file) return notFoundError(parsed.original, "spawnSync");
|
|
3438
|
+
return null;
|
|
3439
|
+
}
|
|
3440
|
+
module.exports = {
|
|
3441
|
+
hookChildProcess,
|
|
3442
|
+
verifyENOENT,
|
|
3443
|
+
verifyENOENTSync,
|
|
3444
|
+
notFoundError
|
|
3445
|
+
};
|
|
3446
|
+
}));
|
|
3447
|
+
// ../runner/src/mcp/stdio-transport.ts
|
|
3448
|
+
var import_cross_spawn = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
3449
|
+
const cp = __require("child_process");
|
|
3450
|
+
const parse = require_parse();
|
|
3451
|
+
const enoent = require_enoent();
|
|
3452
|
+
function spawn(command, args, options) {
|
|
3453
|
+
const parsed = parse(command, args, options);
|
|
3454
|
+
const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
|
|
3455
|
+
enoent.hookChildProcess(spawned, parsed);
|
|
3456
|
+
return spawned;
|
|
3457
|
+
}
|
|
3458
|
+
function spawnSync(command, args, options) {
|
|
3459
|
+
const parsed = parse(command, args, options);
|
|
3460
|
+
const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
|
|
3461
|
+
result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
|
|
3462
|
+
return result;
|
|
3463
|
+
}
|
|
3464
|
+
module.exports = spawn;
|
|
3465
|
+
module.exports.spawn = spawn;
|
|
3466
|
+
module.exports.sync = spawnSync;
|
|
3467
|
+
module.exports._parse = parse;
|
|
3468
|
+
module.exports._enoent = enoent;
|
|
3469
|
+
})))(), 1);
|
|
3470
|
+
/**
|
|
3471
|
+
* MCP over a child process's stdin and stdout, for connection tests (§12.4).
|
|
3472
|
+
*
|
|
3473
|
+
* It only talks to the process and never stops it: the test stops the whole tree it started,
|
|
3474
|
+
* on every path. So the pid is kept from spawn to the end, even after the process has exited
|
|
3475
|
+
* or the client has closed the transport, and on POSIX the process leads its own process
|
|
3476
|
+
* group, which still reaches what it started after it is gone. `cross-spawn` runs `.cmd`
|
|
3477
|
+
* shims such as `npx` on Windows.
|
|
3478
|
+
*/
|
|
3479
|
+
var McpStdioTransport = class {
|
|
3480
|
+
params;
|
|
3481
|
+
onclose;
|
|
3482
|
+
onerror;
|
|
3483
|
+
onmessage;
|
|
3484
|
+
/** The server process, from spawn on; null when it could not be started. */
|
|
3485
|
+
pid = null;
|
|
3486
|
+
child = null;
|
|
3487
|
+
buffer = new ReadBuffer();
|
|
3488
|
+
constructor(params) {
|
|
3489
|
+
this.params = params;
|
|
3490
|
+
}
|
|
3491
|
+
start() {
|
|
3492
|
+
if (this.child) throw new Error("Already started");
|
|
3493
|
+
const spawn = this.params.spawn ?? import_cross_spawn.default;
|
|
3494
|
+
return new Promise((resolve, reject) => {
|
|
3495
|
+
const child = spawn(this.params.command, this.params.args, {
|
|
3496
|
+
cwd: this.params.cwd,
|
|
3497
|
+
env: this.params.env,
|
|
3498
|
+
stdio: [
|
|
3499
|
+
"pipe",
|
|
3500
|
+
"pipe",
|
|
3501
|
+
"pipe"
|
|
3502
|
+
],
|
|
3503
|
+
windowsHide: true,
|
|
3504
|
+
detached: process.platform !== "win32"
|
|
3505
|
+
});
|
|
3506
|
+
this.child = child;
|
|
3507
|
+
child.once("error", (error) => {
|
|
3508
|
+
reject(error);
|
|
3509
|
+
this.onerror?.(error);
|
|
3510
|
+
});
|
|
3511
|
+
child.once("spawn", () => {
|
|
3512
|
+
this.pid = child.pid ?? null;
|
|
3513
|
+
resolve();
|
|
3514
|
+
});
|
|
3515
|
+
child.once("close", () => {
|
|
3516
|
+
this.child = null;
|
|
3517
|
+
this.onclose?.();
|
|
3518
|
+
});
|
|
3519
|
+
child.stdout?.on("data", (chunk) => this.read(chunk));
|
|
3520
|
+
child.stderr?.on("data", (chunk) => this.params.onStderr(chunk.toString("utf8")));
|
|
3521
|
+
for (const stream of [
|
|
3522
|
+
child.stdin,
|
|
3523
|
+
child.stdout,
|
|
3524
|
+
child.stderr
|
|
3525
|
+
]) stream?.on("error", (error) => this.onerror?.(error));
|
|
3526
|
+
});
|
|
3527
|
+
}
|
|
3528
|
+
send(message) {
|
|
3529
|
+
const stdin = this.child?.stdin;
|
|
3530
|
+
if (!stdin?.writable) return Promise.reject(/* @__PURE__ */ new Error("Not connected"));
|
|
3531
|
+
return new Promise((resolve, reject) => {
|
|
3532
|
+
stdin.write(serializeMessage(message), (error) => error ? reject(error) : resolve());
|
|
3533
|
+
});
|
|
3534
|
+
}
|
|
3535
|
+
/** Detach from the process; stopping it is the caller's job (see the class comment). */
|
|
3536
|
+
async close() {
|
|
3537
|
+
this.child = null;
|
|
3538
|
+
this.buffer.clear();
|
|
3539
|
+
}
|
|
3540
|
+
read(chunk) {
|
|
3541
|
+
try {
|
|
3542
|
+
this.buffer.append(chunk);
|
|
3543
|
+
} catch (error) {
|
|
3544
|
+
this.onerror?.(error);
|
|
3545
|
+
return;
|
|
3546
|
+
}
|
|
3547
|
+
for (;;) {
|
|
3548
|
+
let message;
|
|
3549
|
+
try {
|
|
3550
|
+
message = this.buffer.readMessage();
|
|
3551
|
+
} catch (error) {
|
|
3552
|
+
this.onerror?.(error);
|
|
3553
|
+
continue;
|
|
3554
|
+
}
|
|
3555
|
+
if (message === null) return;
|
|
3556
|
+
this.onmessage?.(message);
|
|
3557
|
+
}
|
|
3558
|
+
}
|
|
3559
|
+
};
|
|
3560
|
+
// ../runner/src/mcp/server-test.ts
|
|
3561
|
+
/** Keeps the last `limit` characters written to it. */
|
|
3562
|
+
var TailBuffer = class {
|
|
3563
|
+
limit;
|
|
3564
|
+
text = "";
|
|
3565
|
+
constructor(limit) {
|
|
3566
|
+
this.limit = limit;
|
|
3567
|
+
}
|
|
3568
|
+
append(chunk) {
|
|
3569
|
+
this.text = (this.text + chunk).slice(-this.limit * 2);
|
|
3570
|
+
}
|
|
3571
|
+
value() {
|
|
3572
|
+
const clean = this.text.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, "").trim();
|
|
3573
|
+
return clean ? clean.slice(-this.limit) : void 0;
|
|
3574
|
+
}
|
|
3575
|
+
};
|
|
3576
|
+
/**
|
|
3577
|
+
* Connect to an MCP server as an agent would (§12.4): start it (stdio) or reach its URL
|
|
3578
|
+
* (http/sse), run the `initialize` handshake and `tools/list`, then stop it. Never throws:
|
|
3579
|
+
* a server that fails is an `ok: false` result with the stage, the error and (stdio) the end
|
|
3580
|
+
* of its stderr.
|
|
3581
|
+
*/
|
|
3582
|
+
async function testMcpServer(opts) {
|
|
3583
|
+
const started = performance.now();
|
|
3584
|
+
const elapsed = () => Math.round(performance.now() - started);
|
|
3585
|
+
const timeoutMs = opts.timeoutMs ?? 6e4;
|
|
3586
|
+
const env = opts.env ?? childEnv();
|
|
3587
|
+
const stderr = new TailBuffer(MCP_TEST_STDERR_LIMIT);
|
|
3588
|
+
let stage = "start";
|
|
3589
|
+
let timedOut = false;
|
|
3590
|
+
let protocolVersion = null;
|
|
3591
|
+
let stdio = null;
|
|
3592
|
+
const stdioEnv = opts.stdioEnv ?? "inherit";
|
|
3593
|
+
const fail = (error) => {
|
|
3594
|
+
const tail = stderr.value();
|
|
3595
|
+
const note = stdioEnv === "allowlist" && opts.spec.type === "stdio" && stage !== "start" ? ALLOWLIST_NOTE : void 0;
|
|
3596
|
+
return {
|
|
3597
|
+
ok: false,
|
|
3598
|
+
durationMs: elapsed(),
|
|
3599
|
+
stage,
|
|
3600
|
+
error: describeError(error, {
|
|
3601
|
+
timedOut,
|
|
3602
|
+
timeoutMs,
|
|
3603
|
+
type: opts.spec.type
|
|
3604
|
+
}),
|
|
3605
|
+
timedOut,
|
|
3606
|
+
...tail ? { stderrTail: tail } : {},
|
|
3607
|
+
...note ? { note } : {}
|
|
3608
|
+
};
|
|
3609
|
+
};
|
|
3610
|
+
const client = new Client({
|
|
3611
|
+
name: "codeden-mcp-test",
|
|
3612
|
+
version: opts.clientVersion
|
|
3613
|
+
});
|
|
3614
|
+
try {
|
|
3615
|
+
const server = resolveMcpSpec(opts.spec, {
|
|
3616
|
+
expandEnv: opts.expandEnv,
|
|
3617
|
+
env
|
|
3618
|
+
});
|
|
3619
|
+
const cwd = (server.type === "stdio" ? server.cwd : void 0) ?? opts.cwd ?? homedir();
|
|
3620
|
+
const transport = createTransport(server, {
|
|
3621
|
+
cwd,
|
|
3622
|
+
env,
|
|
3623
|
+
stdioEnv,
|
|
3624
|
+
envVars: opts.spec.type === "stdio" ? codexEnvVarNames(opts.spec.extra) : [],
|
|
3625
|
+
platform: opts.platform,
|
|
3626
|
+
stderr,
|
|
3627
|
+
spawn: opts.spawn
|
|
3628
|
+
});
|
|
3629
|
+
const start = transport.start.bind(transport);
|
|
3630
|
+
transport.start = async () => {
|
|
3631
|
+
await start();
|
|
3632
|
+
stage = "connect";
|
|
3633
|
+
if (stdio?.pid) opts.supervisor?.adopt({
|
|
3634
|
+
pid: stdio.pid,
|
|
3635
|
+
label: "MCP server test",
|
|
3636
|
+
cwd
|
|
3637
|
+
});
|
|
3638
|
+
};
|
|
3639
|
+
const setVersion = transport.setProtocolVersion?.bind(transport);
|
|
3640
|
+
transport.setProtocolVersion = (version) => {
|
|
3641
|
+
protocolVersion = version;
|
|
3642
|
+
setVersion?.(version);
|
|
3643
|
+
};
|
|
3644
|
+
if (transport instanceof McpStdioTransport) stdio = transport;
|
|
3645
|
+
const { toolCount, morePages, tools } = await withTimeout((async () => {
|
|
3646
|
+
await client.connect(transport, { timeout: timeoutMs });
|
|
3647
|
+
stage = "list_tools";
|
|
3648
|
+
return listTools(client, timeoutMs);
|
|
3649
|
+
})(), timeoutMs, () => {
|
|
3650
|
+
timedOut = true;
|
|
3651
|
+
});
|
|
3652
|
+
const info = client.getServerVersion();
|
|
3653
|
+
return {
|
|
3654
|
+
ok: true,
|
|
3655
|
+
durationMs: elapsed(),
|
|
3656
|
+
server: {
|
|
3657
|
+
name: info?.name ?? "",
|
|
3658
|
+
version: info?.version ?? "",
|
|
3659
|
+
...info?.title ? { title: info.title } : {}
|
|
3660
|
+
},
|
|
3661
|
+
protocolVersion,
|
|
3662
|
+
toolCount,
|
|
3663
|
+
morePages,
|
|
3664
|
+
tools
|
|
3665
|
+
};
|
|
3666
|
+
} catch (error) {
|
|
3667
|
+
return fail(error);
|
|
3668
|
+
} finally {
|
|
3669
|
+
const stopTree = opts.stopTree ?? ((pid) => killTreeAndOrphans(pid, 1e3));
|
|
3670
|
+
await stop(client, stdio?.pid ?? null, stopTree);
|
|
3671
|
+
if (stdio?.pid) opts.supervisor?.release(stdio.pid);
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
function createTransport(server, ctx) {
|
|
3675
|
+
if (server.type === "stdio") {
|
|
3676
|
+
if (!existsSync(ctx.cwd) || !statSync(ctx.cwd).isDirectory()) throw new Error(`Working folder not found: ${ctx.cwd}`);
|
|
3677
|
+
return new McpStdioTransport({
|
|
3678
|
+
command: server.command,
|
|
3679
|
+
args: server.args,
|
|
3680
|
+
env: stdioServerEnv({
|
|
3681
|
+
policy: ctx.stdioEnv,
|
|
3682
|
+
base: ctx.env,
|
|
3683
|
+
serverEnv: server.env,
|
|
3684
|
+
envVars: ctx.envVars,
|
|
3685
|
+
platform: ctx.platform
|
|
3686
|
+
}),
|
|
3687
|
+
cwd: ctx.cwd,
|
|
3688
|
+
onStderr: (chunk) => ctx.stderr.append(chunk),
|
|
3689
|
+
spawn: ctx.spawn
|
|
3690
|
+
});
|
|
3691
|
+
}
|
|
3692
|
+
let url;
|
|
3693
|
+
try {
|
|
3694
|
+
url = new URL(server.url);
|
|
3695
|
+
} catch {
|
|
3696
|
+
throw new Error(`Not a valid URL: ${server.url}`);
|
|
3697
|
+
}
|
|
3698
|
+
const requestInit = { headers: server.headers };
|
|
3699
|
+
return server.type === "sse" ? new SSEClientTransport(url, { requestInit }) : new StreamableHTTPClientTransport(url, { requestInit });
|
|
3700
|
+
}
|
|
3701
|
+
/** Every page of `tools/list`, up to `MCP_TEST_MAX_PAGES`; `morePages` when it stopped early. */
|
|
3702
|
+
async function listTools(client, timeoutMs) {
|
|
3703
|
+
if (!client.getServerCapabilities()?.tools) return {
|
|
3704
|
+
toolCount: 0,
|
|
3705
|
+
morePages: false,
|
|
3706
|
+
tools: []
|
|
3707
|
+
};
|
|
3708
|
+
const tools = [];
|
|
3709
|
+
let toolCount = 0;
|
|
3710
|
+
let cursor;
|
|
3711
|
+
for (let page = 0; page < 100; page++) {
|
|
3712
|
+
const result = await client.listTools(cursor ? { cursor } : void 0, { timeout: timeoutMs });
|
|
3713
|
+
toolCount += result.tools.length;
|
|
3714
|
+
for (const tool of result.tools) {
|
|
3715
|
+
if (tools.length >= 500) break;
|
|
3716
|
+
tools.push({
|
|
3717
|
+
name: tool.name,
|
|
3718
|
+
...tool.title ? { title: tool.title } : {},
|
|
3719
|
+
...tool.description ? { description: tool.description.slice(0, 300) } : {}
|
|
3720
|
+
});
|
|
3721
|
+
}
|
|
3722
|
+
cursor = result.nextCursor;
|
|
3723
|
+
if (!cursor) break;
|
|
3724
|
+
}
|
|
3725
|
+
return {
|
|
3726
|
+
toolCount,
|
|
3727
|
+
morePages: cursor !== void 0,
|
|
3728
|
+
tools
|
|
3729
|
+
};
|
|
3730
|
+
}
|
|
3731
|
+
function withTimeout(work, ms, onTimeout) {
|
|
3732
|
+
work.catch(() => void 0);
|
|
3733
|
+
let timer;
|
|
3734
|
+
const timeout = new Promise((_, reject) => {
|
|
3735
|
+
timer = setTimeout(() => {
|
|
3736
|
+
onTimeout();
|
|
3737
|
+
reject(/* @__PURE__ */ new Error("timed out"));
|
|
3738
|
+
}, ms);
|
|
3739
|
+
});
|
|
3740
|
+
return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
|
|
3741
|
+
}
|
|
3742
|
+
/**
|
|
3743
|
+
* Stop the server on every path (success, failed handshake, timeout): the whole process tree
|
|
3744
|
+
* of the pid kept from spawn, including what it started and left behind (wrappers such as
|
|
3745
|
+
* `npx`, detached helpers), then the client.
|
|
3746
|
+
*/
|
|
3747
|
+
async function stop(client, pid, stopTree) {
|
|
3748
|
+
if (pid !== null) await stopTree(pid).catch(() => void 0);
|
|
3749
|
+
await client.close().catch(() => void 0);
|
|
3750
|
+
}
|
|
3751
|
+
function describeError(error, ctx) {
|
|
3752
|
+
let message;
|
|
3753
|
+
if (ctx.timedOut) message = `No answer within ${Math.round(ctx.timeoutMs / 1e3)} s; the server was stopped`;
|
|
3754
|
+
else if (error instanceof Error) {
|
|
3755
|
+
message = error.message;
|
|
3756
|
+
const code = error.code;
|
|
3757
|
+
if (ctx.type !== "stdio" && (code === 401 || /\b401\b/.test(message))) message = `Unauthorized (401): the server needs a sign-in, which the agent's CLI does and this test can't. ${message}`;
|
|
3758
|
+
const cause = error.cause;
|
|
3759
|
+
if (cause instanceof Error && !message.includes(cause.message)) message = `${message}: ${cause.message}`;
|
|
3760
|
+
if (/connection closed/i.test(message) && ctx.type === "stdio") message = `${message}. The server stopped before it answered`;
|
|
3761
|
+
} else message = String(error);
|
|
3762
|
+
return message.slice(0, MCP_TEST_ERROR_LIMIT);
|
|
3763
|
+
}
|
|
3764
|
+
export { testMcpServer };
|
|
3765
|
+
|
|
3766
|
+
//# sourceMappingURL=server-test-b0hHPqXb.js.map
|