x402-proxy 0.10.7 → 0.10.9

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.
Files changed (90) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +7 -1
  3. package/dist/Credential-COZQnr1-.js +2055 -0
  4. package/dist/Mcp-CrCEqLqO.js +10 -0
  5. package/dist/Sse-ChldYgU7.js +9742 -0
  6. package/dist/Sse-kCB38G56.js +16482 -0
  7. package/dist/accounts-DsuvWwph.js +232 -0
  8. package/dist/accounts-DzvAlQRn.js +5 -0
  9. package/dist/accounts-IG-Cmrwy.js +229 -0
  10. package/dist/api-CUzmQvTQ.js +2802 -0
  11. package/dist/auth-DTzQmnZ_.js +1196 -0
  12. package/dist/bin/cli.js +585 -242
  13. package/dist/ccip-Bx-zoUCJ.js +240 -0
  14. package/dist/ccip-C2k1DD1T.js +153 -0
  15. package/dist/ccip-C6CQOJYv.js +152 -0
  16. package/dist/ccip-RZzsZ5Mv.js +156 -0
  17. package/dist/chain-CafcHffR.js +1997 -0
  18. package/dist/chain-DwfP5RGZ.js +1968 -0
  19. package/dist/chunk-DBEY4PJZ.js +16 -0
  20. package/dist/chunk-DjEMn6fM.js +36 -0
  21. package/dist/client-Blw2V7LF.js +657 -0
  22. package/dist/client-C37gWJOZ.js +102 -0
  23. package/dist/client-CEc4NYAA.js +6388 -0
  24. package/dist/client-CVDTUY0l.js +5152 -0
  25. package/dist/config-BUQsit4s.js +3 -0
  26. package/dist/config-DR1Fs_wL.js +6600 -0
  27. package/dist/{config-D9wIR3xc.js → config-rvKA3SYT.js} +10 -5
  28. package/dist/decodeFunctionData-DuFcwhC_.js +4510 -0
  29. package/dist/decodeFunctionData-JPOUdvil.js +4394 -0
  30. package/dist/derive-DNUl8LU9.js +9109 -0
  31. package/dist/dist-C2YO6HSQ.js +6581 -0
  32. package/dist/dist-DM5_F3r5.js +4 -0
  33. package/dist/dist-DxJCYyL5.js +1388 -0
  34. package/dist/hashTypedData-BHmP9dBd.js +859 -0
  35. package/dist/hashTypedData-CtEdfx4y.js +846 -0
  36. package/dist/helpers-CuUSw-tH.js +7125 -0
  37. package/dist/hmac-59IlS_by.js +648 -0
  38. package/dist/http-BAtucMbS.js +2060 -0
  39. package/dist/index.d.ts +1903 -9
  40. package/dist/index.js +18006 -50
  41. package/dist/index.node-CxkL0OFh.js +3592 -0
  42. package/dist/index.node-DvmeuZBj.js +3 -0
  43. package/dist/isAddressEqual-BLrd1Hg1.js +9 -0
  44. package/dist/isAddressEqual-DsAqfQOD.js +10 -0
  45. package/dist/localBatchGatewayRequest-C-RPJyDO.js +6260 -0
  46. package/dist/localBatchGatewayRequest-DOdQ9bR7.js +93 -0
  47. package/dist/localBatchGatewayRequest-DQkbZaSy.js +6261 -0
  48. package/dist/parseUnits-CApwcKSD.js +49 -0
  49. package/dist/parseUnits-cMO2udMe.js +48 -0
  50. package/dist/schemas-BxMFYNbH.js +1270 -0
  51. package/dist/secp256k1-BZpiyffY.js +2525 -0
  52. package/dist/secp256k1-BjenrLl5.js +1877 -0
  53. package/dist/secp256k1-CLPUX17u.js +3 -0
  54. package/dist/sendRawTransactionSync-DvSkhZtW.js +3612 -0
  55. package/dist/server-CSq0IuUq.js +565 -0
  56. package/dist/setup-BY4J49Lv.js +1110 -0
  57. package/dist/setup-wMOAgrsN.js +3 -0
  58. package/dist/sha256-FAs0qeni.js +17 -0
  59. package/dist/sha3-CYkWM8Xa.js +195 -0
  60. package/dist/sha3-DbMJRJ3C.js +194 -0
  61. package/dist/sse-B4LLqBQm.js +408 -0
  62. package/dist/status-Bu23RjW6.js +3 -0
  63. package/dist/{status-DihAcUSC.js → status-X21VnGUO.js} +16 -15
  64. package/dist/stdio-BADqxZdZ.js +85 -0
  65. package/dist/streamableHttp-BHkJypcI.js +358 -0
  66. package/dist/tempo-3nttrxgQ.js +17 -0
  67. package/dist/tempo-DER0P-ul.js +18 -0
  68. package/dist/types-BEKUz-Mf.js +1240 -0
  69. package/dist/types-DatK5vR5.js +3 -0
  70. package/dist/utils-BYjkXZDF.js +444 -0
  71. package/dist/utils-SeGHMW9O.js +445 -0
  72. package/dist/wallet-DKVlrR1S.js +3 -0
  73. package/dist/wallet-DSyht15_.js +17759 -0
  74. package/package.json +18 -71
  75. package/dist/config-B_upkJeK.js +0 -66
  76. package/dist/config-Be35NM5s.js +0 -3
  77. package/dist/config-J1m-CWXT.js +0 -27
  78. package/dist/derive-CL6e8K0Z.js +0 -81
  79. package/dist/openclaw/plugin.d.ts +0 -15
  80. package/dist/openclaw/plugin.js +0 -2067
  81. package/dist/openclaw.plugin.json +0 -93
  82. package/dist/setup-CNyMLnM-.js +0 -197
  83. package/dist/setup-DTIxPe58.js +0 -3
  84. package/dist/status-DZlJ4pS7.js +0 -3
  85. package/dist/wallet-B0S-rma9.js +0 -544
  86. package/dist/wallet-DBrVZJqe.js +0 -3
  87. package/openclaw.plugin.json +0 -93
  88. package/skills/SKILL.md +0 -183
  89. package/skills/references/library.md +0 -85
  90. package/skills/references/openclaw-plugin.md +0 -145
@@ -0,0 +1,657 @@
1
+ #!/usr/bin/env node
2
+ import { a as mergeCapabilities, c as safeParse, i as Protocol, n as assertToolsCallTaskCapability, o as getObjectShape, r as AjvJsonSchemaValidator, s as isZ4Schema, t as assertClientRequestTaskCapability } from "./helpers-CuUSw-tH.js";
3
+ import { An as ToolListChangedNotificationSchema, C as CreateTaskResultSchema, D as ElicitRequestSchema, F as ErrorCode, Ft as PromptListChangedNotificationSchema, Ht as ReadResourceResultSchema, J as InitializeResultSchema, Jt as ResourceListChangedNotificationSchema, N as EmptyResultSchema, R as GetPromptResultSchema, S as CreateMessageResultWithToolsSchema, _ as CompleteResultSchema, an as SUPPORTED_PROTOCOL_VERSIONS, at as ListPromptsResultSchema, b as CreateMessageRequestSchema, c as CallToolResultSchema, ht as ListToolsResultSchema, k as ElicitResultSchema, lt as ListResourcesResultSchema, rt as ListChangedOptionsBaseSchema, st as ListResourceTemplatesResultSchema, tt as LATEST_PROTOCOL_VERSION, x as CreateMessageResultSchema, yt as McpError } from "./types-BEKUz-Mf.js";
4
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
5
+ /**
6
+ * Experimental client task features for MCP SDK.
7
+ * WARNING: These APIs are experimental and may change without notice.
8
+ *
9
+ * @experimental
10
+ */
11
+ /**
12
+ * Experimental task features for MCP clients.
13
+ *
14
+ * Access via `client.experimental.tasks`:
15
+ * ```typescript
16
+ * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });
17
+ * const task = await client.experimental.tasks.getTask(taskId);
18
+ * ```
19
+ *
20
+ * @experimental
21
+ */
22
+ var ExperimentalClientTasks = class {
23
+ constructor(_client) {
24
+ this._client = _client;
25
+ }
26
+ /**
27
+ * Calls a tool and returns an AsyncGenerator that yields response messages.
28
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
29
+ *
30
+ * This method provides streaming access to tool execution, allowing you to
31
+ * observe intermediate task status updates for long-running tool calls.
32
+ * Automatically validates structured output if the tool has an outputSchema.
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
37
+ * for await (const message of stream) {
38
+ * switch (message.type) {
39
+ * case 'taskCreated':
40
+ * console.log('Tool execution started:', message.task.taskId);
41
+ * break;
42
+ * case 'taskStatus':
43
+ * console.log('Tool status:', message.task.status);
44
+ * break;
45
+ * case 'result':
46
+ * console.log('Tool result:', message.result);
47
+ * break;
48
+ * case 'error':
49
+ * console.error('Tool error:', message.error);
50
+ * break;
51
+ * }
52
+ * }
53
+ * ```
54
+ *
55
+ * @param params - Tool call parameters (name and arguments)
56
+ * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
57
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
58
+ * @returns AsyncGenerator that yields ResponseMessage objects
59
+ *
60
+ * @experimental
61
+ */
62
+ async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
63
+ const clientInternal = this._client;
64
+ const optionsWithTask = {
65
+ ...options,
66
+ task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
67
+ };
68
+ const stream = clientInternal.requestStream({
69
+ method: "tools/call",
70
+ params
71
+ }, resultSchema, optionsWithTask);
72
+ const validator = clientInternal.getToolOutputValidator(params.name);
73
+ for await (const message of stream) {
74
+ if (message.type === "result" && validator) {
75
+ const result = message.result;
76
+ if (!result.structuredContent && !result.isError) {
77
+ yield {
78
+ type: "error",
79
+ error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
80
+ };
81
+ return;
82
+ }
83
+ if (result.structuredContent) try {
84
+ const validationResult = validator(result.structuredContent);
85
+ if (!validationResult.valid) {
86
+ yield {
87
+ type: "error",
88
+ error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
89
+ };
90
+ return;
91
+ }
92
+ } catch (error) {
93
+ if (error instanceof McpError) {
94
+ yield {
95
+ type: "error",
96
+ error
97
+ };
98
+ return;
99
+ }
100
+ yield {
101
+ type: "error",
102
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
103
+ };
104
+ return;
105
+ }
106
+ }
107
+ yield message;
108
+ }
109
+ }
110
+ /**
111
+ * Gets the current status of a task.
112
+ *
113
+ * @param taskId - The task identifier
114
+ * @param options - Optional request options
115
+ * @returns The task status
116
+ *
117
+ * @experimental
118
+ */
119
+ async getTask(taskId, options) {
120
+ return this._client.getTask({ taskId }, options);
121
+ }
122
+ /**
123
+ * Retrieves the result of a completed task.
124
+ *
125
+ * @param taskId - The task identifier
126
+ * @param resultSchema - Zod schema for validating the result
127
+ * @param options - Optional request options
128
+ * @returns The task result
129
+ *
130
+ * @experimental
131
+ */
132
+ async getTaskResult(taskId, resultSchema, options) {
133
+ return this._client.getTaskResult({ taskId }, resultSchema, options);
134
+ }
135
+ /**
136
+ * Lists tasks with optional pagination.
137
+ *
138
+ * @param cursor - Optional pagination cursor
139
+ * @param options - Optional request options
140
+ * @returns List of tasks with optional next cursor
141
+ *
142
+ * @experimental
143
+ */
144
+ async listTasks(cursor, options) {
145
+ return this._client.listTasks(cursor ? { cursor } : void 0, options);
146
+ }
147
+ /**
148
+ * Cancels a running task.
149
+ *
150
+ * @param taskId - The task identifier
151
+ * @param options - Optional request options
152
+ *
153
+ * @experimental
154
+ */
155
+ async cancelTask(taskId, options) {
156
+ return this._client.cancelTask({ taskId }, options);
157
+ }
158
+ /**
159
+ * Sends a request and returns an AsyncGenerator that yields response messages.
160
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
161
+ *
162
+ * This method provides streaming access to request processing, allowing you to
163
+ * observe intermediate task status updates for task-augmented requests.
164
+ *
165
+ * @param request - The request to send
166
+ * @param resultSchema - Zod schema for validating the result
167
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
168
+ * @returns AsyncGenerator that yields ResponseMessage objects
169
+ *
170
+ * @experimental
171
+ */
172
+ requestStream(request, resultSchema, options) {
173
+ return this._client.requestStream(request, resultSchema, options);
174
+ }
175
+ };
176
+ //#endregion
177
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
178
+ /**
179
+ * Elicitation default application helper. Applies defaults to the data based on the schema.
180
+ *
181
+ * @param schema - The schema to apply defaults to.
182
+ * @param data - The data to apply defaults to.
183
+ */
184
+ function applyElicitationDefaults(schema, data) {
185
+ if (!schema || data === null || typeof data !== "object") return;
186
+ if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
187
+ const obj = data;
188
+ const props = schema.properties;
189
+ for (const key of Object.keys(props)) {
190
+ const propSchema = props[key];
191
+ if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) obj[key] = propSchema.default;
192
+ if (obj[key] !== void 0) applyElicitationDefaults(propSchema, obj[key]);
193
+ }
194
+ }
195
+ if (Array.isArray(schema.anyOf)) {
196
+ for (const sub of schema.anyOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data);
197
+ }
198
+ if (Array.isArray(schema.oneOf)) {
199
+ for (const sub of schema.oneOf) if (typeof sub !== "boolean") applyElicitationDefaults(sub, data);
200
+ }
201
+ }
202
+ /**
203
+ * Determines which elicitation modes are supported based on declared client capabilities.
204
+ *
205
+ * According to the spec:
206
+ * - An empty elicitation capability object defaults to form mode support (backwards compatibility)
207
+ * - URL mode is only supported if explicitly declared
208
+ *
209
+ * @param capabilities - The client's elicitation capabilities
210
+ * @returns An object indicating which modes are supported
211
+ */
212
+ function getSupportedElicitationModes(capabilities) {
213
+ if (!capabilities) return {
214
+ supportsFormMode: false,
215
+ supportsUrlMode: false
216
+ };
217
+ const hasFormCapability = capabilities.form !== void 0;
218
+ const hasUrlCapability = capabilities.url !== void 0;
219
+ return {
220
+ supportsFormMode: hasFormCapability || !hasFormCapability && !hasUrlCapability,
221
+ supportsUrlMode: hasUrlCapability
222
+ };
223
+ }
224
+ /**
225
+ * An MCP client on top of a pluggable transport.
226
+ *
227
+ * The client will automatically begin the initialization flow with the server when connect() is called.
228
+ *
229
+ * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
230
+ *
231
+ * ```typescript
232
+ * // Custom schemas
233
+ * const CustomRequestSchema = RequestSchema.extend({...})
234
+ * const CustomNotificationSchema = NotificationSchema.extend({...})
235
+ * const CustomResultSchema = ResultSchema.extend({...})
236
+ *
237
+ * // Type aliases
238
+ * type CustomRequest = z.infer<typeof CustomRequestSchema>
239
+ * type CustomNotification = z.infer<typeof CustomNotificationSchema>
240
+ * type CustomResult = z.infer<typeof CustomResultSchema>
241
+ *
242
+ * // Create typed client
243
+ * const client = new Client<CustomRequest, CustomNotification, CustomResult>({
244
+ * name: "CustomClient",
245
+ * version: "1.0.0"
246
+ * })
247
+ * ```
248
+ */
249
+ var Client = class extends Protocol {
250
+ /**
251
+ * Initializes this client with the given name and version information.
252
+ */
253
+ constructor(_clientInfo, options) {
254
+ super(options);
255
+ this._clientInfo = _clientInfo;
256
+ this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
257
+ this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
258
+ this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
259
+ this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
260
+ this._capabilities = options?.capabilities ?? {};
261
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
262
+ if (options?.listChanged) this._pendingListChangedConfig = options.listChanged;
263
+ }
264
+ /**
265
+ * Set up handlers for list changed notifications based on config and server capabilities.
266
+ * This should only be called after initialization when server capabilities are known.
267
+ * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
268
+ * @internal
269
+ */
270
+ _setupListChangedHandlers(config) {
271
+ if (config.tools && this._serverCapabilities?.tools?.listChanged) this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
272
+ return (await this.listTools()).tools;
273
+ });
274
+ if (config.prompts && this._serverCapabilities?.prompts?.listChanged) this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
275
+ return (await this.listPrompts()).prompts;
276
+ });
277
+ if (config.resources && this._serverCapabilities?.resources?.listChanged) this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
278
+ return (await this.listResources()).resources;
279
+ });
280
+ }
281
+ /**
282
+ * Access experimental features.
283
+ *
284
+ * WARNING: These APIs are experimental and may change without notice.
285
+ *
286
+ * @experimental
287
+ */
288
+ get experimental() {
289
+ if (!this._experimental) this._experimental = { tasks: new ExperimentalClientTasks(this) };
290
+ return this._experimental;
291
+ }
292
+ /**
293
+ * Registers new capabilities. This can only be called before connecting to a transport.
294
+ *
295
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
296
+ */
297
+ registerCapabilities(capabilities) {
298
+ if (this.transport) throw new Error("Cannot register capabilities after connecting to transport");
299
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
300
+ }
301
+ /**
302
+ * Override request handler registration to enforce client-side validation for elicitation.
303
+ */
304
+ setRequestHandler(requestSchema, handler) {
305
+ const methodSchema = getObjectShape(requestSchema)?.method;
306
+ if (!methodSchema) throw new Error("Schema is missing a method literal");
307
+ let methodValue;
308
+ if (isZ4Schema(methodSchema)) {
309
+ const v4Schema = methodSchema;
310
+ methodValue = (v4Schema._zod?.def)?.value ?? v4Schema.value;
311
+ } else {
312
+ const v3Schema = methodSchema;
313
+ methodValue = v3Schema._def?.value ?? v3Schema.value;
314
+ }
315
+ if (typeof methodValue !== "string") throw new Error("Schema method literal must be a string");
316
+ const method = methodValue;
317
+ if (method === "elicitation/create") {
318
+ const wrappedHandler = async (request, extra) => {
319
+ const validatedRequest = safeParse(ElicitRequestSchema, request);
320
+ if (!validatedRequest.success) {
321
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
322
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
323
+ }
324
+ const { params } = validatedRequest.data;
325
+ params.mode = params.mode ?? "form";
326
+ const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
327
+ if (params.mode === "form" && !supportsFormMode) throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
328
+ if (params.mode === "url" && !supportsUrlMode) throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
329
+ const result = await Promise.resolve(handler(request, extra));
330
+ if (params.task) {
331
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
332
+ if (!taskValidationResult.success) {
333
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
334
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
335
+ }
336
+ return taskValidationResult.data;
337
+ }
338
+ const validationResult = safeParse(ElicitResultSchema, result);
339
+ if (!validationResult.success) {
340
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
341
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
342
+ }
343
+ const validatedResult = validationResult.data;
344
+ const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
345
+ if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
346
+ if (this._capabilities.elicitation?.form?.applyDefaults) try {
347
+ applyElicitationDefaults(requestedSchema, validatedResult.content);
348
+ } catch {}
349
+ }
350
+ return validatedResult;
351
+ };
352
+ return super.setRequestHandler(requestSchema, wrappedHandler);
353
+ }
354
+ if (method === "sampling/createMessage") {
355
+ const wrappedHandler = async (request, extra) => {
356
+ const validatedRequest = safeParse(CreateMessageRequestSchema, request);
357
+ if (!validatedRequest.success) {
358
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
359
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
360
+ }
361
+ const { params } = validatedRequest.data;
362
+ const result = await Promise.resolve(handler(request, extra));
363
+ if (params.task) {
364
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
365
+ if (!taskValidationResult.success) {
366
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
367
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
368
+ }
369
+ return taskValidationResult.data;
370
+ }
371
+ const validationResult = safeParse(params.tools || params.toolChoice ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema, result);
372
+ if (!validationResult.success) {
373
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
374
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
375
+ }
376
+ return validationResult.data;
377
+ };
378
+ return super.setRequestHandler(requestSchema, wrappedHandler);
379
+ }
380
+ return super.setRequestHandler(requestSchema, handler);
381
+ }
382
+ assertCapability(capability, method) {
383
+ if (!this._serverCapabilities?.[capability]) throw new Error(`Server does not support ${capability} (required for ${method})`);
384
+ }
385
+ async connect(transport, options) {
386
+ await super.connect(transport);
387
+ if (transport.sessionId !== void 0) return;
388
+ try {
389
+ const result = await this.request({
390
+ method: "initialize",
391
+ params: {
392
+ protocolVersion: LATEST_PROTOCOL_VERSION,
393
+ capabilities: this._capabilities,
394
+ clientInfo: this._clientInfo
395
+ }
396
+ }, InitializeResultSchema, options);
397
+ if (result === void 0) throw new Error(`Server sent invalid initialize result: ${result}`);
398
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
399
+ this._serverCapabilities = result.capabilities;
400
+ this._serverVersion = result.serverInfo;
401
+ if (transport.setProtocolVersion) transport.setProtocolVersion(result.protocolVersion);
402
+ this._instructions = result.instructions;
403
+ await this.notification({ method: "notifications/initialized" });
404
+ if (this._pendingListChangedConfig) {
405
+ this._setupListChangedHandlers(this._pendingListChangedConfig);
406
+ this._pendingListChangedConfig = void 0;
407
+ }
408
+ } catch (error) {
409
+ this.close();
410
+ throw error;
411
+ }
412
+ }
413
+ /**
414
+ * After initialization has completed, this will be populated with the server's reported capabilities.
415
+ */
416
+ getServerCapabilities() {
417
+ return this._serverCapabilities;
418
+ }
419
+ /**
420
+ * After initialization has completed, this will be populated with information about the server's name and version.
421
+ */
422
+ getServerVersion() {
423
+ return this._serverVersion;
424
+ }
425
+ /**
426
+ * After initialization has completed, this may be populated with information about the server's instructions.
427
+ */
428
+ getInstructions() {
429
+ return this._instructions;
430
+ }
431
+ assertCapabilityForMethod(method) {
432
+ switch (method) {
433
+ case "logging/setLevel":
434
+ if (!this._serverCapabilities?.logging) throw new Error(`Server does not support logging (required for ${method})`);
435
+ break;
436
+ case "prompts/get":
437
+ case "prompts/list":
438
+ if (!this._serverCapabilities?.prompts) throw new Error(`Server does not support prompts (required for ${method})`);
439
+ break;
440
+ case "resources/list":
441
+ case "resources/templates/list":
442
+ case "resources/read":
443
+ case "resources/subscribe":
444
+ case "resources/unsubscribe":
445
+ if (!this._serverCapabilities?.resources) throw new Error(`Server does not support resources (required for ${method})`);
446
+ if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) throw new Error(`Server does not support resource subscriptions (required for ${method})`);
447
+ break;
448
+ case "tools/call":
449
+ case "tools/list":
450
+ if (!this._serverCapabilities?.tools) throw new Error(`Server does not support tools (required for ${method})`);
451
+ break;
452
+ case "completion/complete":
453
+ if (!this._serverCapabilities?.completions) throw new Error(`Server does not support completions (required for ${method})`);
454
+ break;
455
+ case "initialize": break;
456
+ case "ping": break;
457
+ }
458
+ }
459
+ assertNotificationCapability(method) {
460
+ switch (method) {
461
+ case "notifications/roots/list_changed":
462
+ if (!this._capabilities.roots?.listChanged) throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
463
+ break;
464
+ case "notifications/initialized": break;
465
+ case "notifications/cancelled": break;
466
+ case "notifications/progress": break;
467
+ }
468
+ }
469
+ assertRequestHandlerCapability(method) {
470
+ if (!this._capabilities) return;
471
+ switch (method) {
472
+ case "sampling/createMessage":
473
+ if (!this._capabilities.sampling) throw new Error(`Client does not support sampling capability (required for ${method})`);
474
+ break;
475
+ case "elicitation/create":
476
+ if (!this._capabilities.elicitation) throw new Error(`Client does not support elicitation capability (required for ${method})`);
477
+ break;
478
+ case "roots/list":
479
+ if (!this._capabilities.roots) throw new Error(`Client does not support roots capability (required for ${method})`);
480
+ break;
481
+ case "tasks/get":
482
+ case "tasks/list":
483
+ case "tasks/result":
484
+ case "tasks/cancel":
485
+ if (!this._capabilities.tasks) throw new Error(`Client does not support tasks capability (required for ${method})`);
486
+ break;
487
+ case "ping": break;
488
+ }
489
+ }
490
+ assertTaskCapability(method) {
491
+ assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
492
+ }
493
+ assertTaskHandlerCapability(method) {
494
+ if (!this._capabilities) return;
495
+ assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
496
+ }
497
+ async ping(options) {
498
+ return this.request({ method: "ping" }, EmptyResultSchema, options);
499
+ }
500
+ async complete(params, options) {
501
+ return this.request({
502
+ method: "completion/complete",
503
+ params
504
+ }, CompleteResultSchema, options);
505
+ }
506
+ async setLoggingLevel(level, options) {
507
+ return this.request({
508
+ method: "logging/setLevel",
509
+ params: { level }
510
+ }, EmptyResultSchema, options);
511
+ }
512
+ async getPrompt(params, options) {
513
+ return this.request({
514
+ method: "prompts/get",
515
+ params
516
+ }, GetPromptResultSchema, options);
517
+ }
518
+ async listPrompts(params, options) {
519
+ return this.request({
520
+ method: "prompts/list",
521
+ params
522
+ }, ListPromptsResultSchema, options);
523
+ }
524
+ async listResources(params, options) {
525
+ return this.request({
526
+ method: "resources/list",
527
+ params
528
+ }, ListResourcesResultSchema, options);
529
+ }
530
+ async listResourceTemplates(params, options) {
531
+ return this.request({
532
+ method: "resources/templates/list",
533
+ params
534
+ }, ListResourceTemplatesResultSchema, options);
535
+ }
536
+ async readResource(params, options) {
537
+ return this.request({
538
+ method: "resources/read",
539
+ params
540
+ }, ReadResourceResultSchema, options);
541
+ }
542
+ async subscribeResource(params, options) {
543
+ return this.request({
544
+ method: "resources/subscribe",
545
+ params
546
+ }, EmptyResultSchema, options);
547
+ }
548
+ async unsubscribeResource(params, options) {
549
+ return this.request({
550
+ method: "resources/unsubscribe",
551
+ params
552
+ }, EmptyResultSchema, options);
553
+ }
554
+ /**
555
+ * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
556
+ *
557
+ * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
558
+ */
559
+ async callTool(params, resultSchema = CallToolResultSchema, options) {
560
+ if (this.isToolTaskRequired(params.name)) throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
561
+ const result = await this.request({
562
+ method: "tools/call",
563
+ params
564
+ }, resultSchema, options);
565
+ const validator = this.getToolOutputValidator(params.name);
566
+ if (validator) {
567
+ if (!result.structuredContent && !result.isError) throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
568
+ if (result.structuredContent) try {
569
+ const validationResult = validator(result.structuredContent);
570
+ if (!validationResult.valid) throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
571
+ } catch (error) {
572
+ if (error instanceof McpError) throw error;
573
+ throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
574
+ }
575
+ }
576
+ return result;
577
+ }
578
+ isToolTask(toolName) {
579
+ if (!this._serverCapabilities?.tasks?.requests?.tools?.call) return false;
580
+ return this._cachedKnownTaskTools.has(toolName);
581
+ }
582
+ /**
583
+ * Check if a tool requires task-based execution.
584
+ * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
585
+ */
586
+ isToolTaskRequired(toolName) {
587
+ return this._cachedRequiredTaskTools.has(toolName);
588
+ }
589
+ /**
590
+ * Cache validators for tool output schemas.
591
+ * Called after listTools() to pre-compile validators for better performance.
592
+ */
593
+ cacheToolMetadata(tools) {
594
+ this._cachedToolOutputValidators.clear();
595
+ this._cachedKnownTaskTools.clear();
596
+ this._cachedRequiredTaskTools.clear();
597
+ for (const tool of tools) {
598
+ if (tool.outputSchema) {
599
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
600
+ this._cachedToolOutputValidators.set(tool.name, toolValidator);
601
+ }
602
+ const taskSupport = tool.execution?.taskSupport;
603
+ if (taskSupport === "required" || taskSupport === "optional") this._cachedKnownTaskTools.add(tool.name);
604
+ if (taskSupport === "required") this._cachedRequiredTaskTools.add(tool.name);
605
+ }
606
+ }
607
+ /**
608
+ * Get cached validator for a tool
609
+ */
610
+ getToolOutputValidator(toolName) {
611
+ return this._cachedToolOutputValidators.get(toolName);
612
+ }
613
+ async listTools(params, options) {
614
+ const result = await this.request({
615
+ method: "tools/list",
616
+ params
617
+ }, ListToolsResultSchema, options);
618
+ this.cacheToolMetadata(result.tools);
619
+ return result;
620
+ }
621
+ /**
622
+ * Set up a single list changed handler.
623
+ * @internal
624
+ */
625
+ _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
626
+ const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
627
+ if (!parseResult.success) throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
628
+ if (typeof options.onChanged !== "function") throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
629
+ const { autoRefresh, debounceMs } = parseResult.data;
630
+ const { onChanged } = options;
631
+ const refresh = async () => {
632
+ if (!autoRefresh) {
633
+ onChanged(null, null);
634
+ return;
635
+ }
636
+ try {
637
+ onChanged(null, await fetcher());
638
+ } catch (e) {
639
+ onChanged(e instanceof Error ? e : new Error(String(e)), null);
640
+ }
641
+ };
642
+ const handler = () => {
643
+ if (debounceMs) {
644
+ const existingTimer = this._listChangedDebounceTimers.get(listType);
645
+ if (existingTimer) clearTimeout(existingTimer);
646
+ const timer = setTimeout(refresh, debounceMs);
647
+ this._listChangedDebounceTimers.set(listType, timer);
648
+ } else refresh();
649
+ };
650
+ this.setNotificationHandler(notificationSchema, handler);
651
+ }
652
+ async sendRootsListChanged() {
653
+ return this.notification({ method: "notifications/roots/list_changed" });
654
+ }
655
+ };
656
+ //#endregion
657
+ export { Client };