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,565 @@
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 { C as CreateTaskResultSchema, F as ErrorCode, N as EmptyResultSchema, S as CreateMessageResultWithToolsSchema, Y as InitializedNotificationSchema, an as SUPPORTED_PROTOCOL_VERSIONS, c as CallToolResultSchema, dt as ListRootsResultSchema, fn as SetLevelRequestSchema, gt as LoggingLevelSchema, k as ElicitResultSchema, q as InitializeRequestSchema, s as CallToolRequestSchema, 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/server.js
5
+ /**
6
+ * Experimental server 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 low-level MCP servers.
13
+ *
14
+ * Access via `server.experimental.tasks`:
15
+ * ```typescript
16
+ * const stream = server.experimental.tasks.requestStream(request, schema, options);
17
+ * ```
18
+ *
19
+ * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead.
20
+ *
21
+ * @experimental
22
+ */
23
+ var ExperimentalServerTasks = class {
24
+ constructor(_server) {
25
+ this._server = _server;
26
+ }
27
+ /**
28
+ * Sends a request and returns an AsyncGenerator that yields response messages.
29
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
30
+ *
31
+ * This method provides streaming access to request processing, allowing you to
32
+ * observe intermediate task status updates for task-augmented requests.
33
+ *
34
+ * @param request - The request to send
35
+ * @param resultSchema - Zod schema for validating the result
36
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
37
+ * @returns AsyncGenerator that yields ResponseMessage objects
38
+ *
39
+ * @experimental
40
+ */
41
+ requestStream(request, resultSchema, options) {
42
+ return this._server.requestStream(request, resultSchema, options);
43
+ }
44
+ /**
45
+ * Sends a sampling request and returns an AsyncGenerator that yields response messages.
46
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
47
+ *
48
+ * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
49
+ * before the final result.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const stream = server.experimental.tasks.createMessageStream({
54
+ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
55
+ * maxTokens: 100
56
+ * }, {
57
+ * onprogress: (progress) => {
58
+ * // Handle streaming tokens via progress notifications
59
+ * console.log('Progress:', progress.message);
60
+ * }
61
+ * });
62
+ *
63
+ * for await (const message of stream) {
64
+ * switch (message.type) {
65
+ * case 'taskCreated':
66
+ * console.log('Task created:', message.task.taskId);
67
+ * break;
68
+ * case 'taskStatus':
69
+ * console.log('Task status:', message.task.status);
70
+ * break;
71
+ * case 'result':
72
+ * console.log('Final result:', message.result);
73
+ * break;
74
+ * case 'error':
75
+ * console.error('Error:', message.error);
76
+ * break;
77
+ * }
78
+ * }
79
+ * ```
80
+ *
81
+ * @param params - The sampling request parameters
82
+ * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
83
+ * @returns AsyncGenerator that yields ResponseMessage objects
84
+ *
85
+ * @experimental
86
+ */
87
+ createMessageStream(params, options) {
88
+ const clientCapabilities = this._server.getClientCapabilities();
89
+ if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) throw new Error("Client does not support sampling tools capability.");
90
+ if (params.messages.length > 0) {
91
+ const lastMessage = params.messages[params.messages.length - 1];
92
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
93
+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");
94
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
95
+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
96
+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
97
+ if (hasToolResults) {
98
+ if (lastContent.some((c) => c.type !== "tool_result")) throw new Error("The last message must contain only tool_result content if any is present");
99
+ if (!hasPreviousToolUse) throw new Error("tool_result blocks are not matching any tool_use from the previous message");
100
+ }
101
+ if (hasPreviousToolUse) {
102
+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
103
+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
104
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
105
+ }
106
+ }
107
+ return this.requestStream({
108
+ method: "sampling/createMessage",
109
+ params
110
+ }, CreateMessageResultSchema, options);
111
+ }
112
+ /**
113
+ * Sends an elicitation request and returns an AsyncGenerator that yields response messages.
114
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
115
+ *
116
+ * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
117
+ * and 'taskStatus' messages before the final result.
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * const stream = server.experimental.tasks.elicitInputStream({
122
+ * mode: 'url',
123
+ * message: 'Please authenticate',
124
+ * elicitationId: 'auth-123',
125
+ * url: 'https://example.com/auth'
126
+ * }, {
127
+ * task: { ttl: 300000 } // Task-augmented for long-running auth flow
128
+ * });
129
+ *
130
+ * for await (const message of stream) {
131
+ * switch (message.type) {
132
+ * case 'taskCreated':
133
+ * console.log('Task created:', message.task.taskId);
134
+ * break;
135
+ * case 'taskStatus':
136
+ * console.log('Task status:', message.task.status);
137
+ * break;
138
+ * case 'result':
139
+ * console.log('User action:', message.result.action);
140
+ * break;
141
+ * case 'error':
142
+ * console.error('Error:', message.error);
143
+ * break;
144
+ * }
145
+ * }
146
+ * ```
147
+ *
148
+ * @param params - The elicitation request parameters
149
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
150
+ * @returns AsyncGenerator that yields ResponseMessage objects
151
+ *
152
+ * @experimental
153
+ */
154
+ elicitInputStream(params, options) {
155
+ const clientCapabilities = this._server.getClientCapabilities();
156
+ const mode = params.mode ?? "form";
157
+ switch (mode) {
158
+ case "url":
159
+ if (!clientCapabilities?.elicitation?.url) throw new Error("Client does not support url elicitation.");
160
+ break;
161
+ case "form":
162
+ if (!clientCapabilities?.elicitation?.form) throw new Error("Client does not support form elicitation.");
163
+ break;
164
+ }
165
+ const normalizedParams = mode === "form" && params.mode === void 0 ? {
166
+ ...params,
167
+ mode: "form"
168
+ } : params;
169
+ return this.requestStream({
170
+ method: "elicitation/create",
171
+ params: normalizedParams
172
+ }, ElicitResultSchema, options);
173
+ }
174
+ /**
175
+ * Gets the current status of a task.
176
+ *
177
+ * @param taskId - The task identifier
178
+ * @param options - Optional request options
179
+ * @returns The task status
180
+ *
181
+ * @experimental
182
+ */
183
+ async getTask(taskId, options) {
184
+ return this._server.getTask({ taskId }, options);
185
+ }
186
+ /**
187
+ * Retrieves the result of a completed task.
188
+ *
189
+ * @param taskId - The task identifier
190
+ * @param resultSchema - Zod schema for validating the result
191
+ * @param options - Optional request options
192
+ * @returns The task result
193
+ *
194
+ * @experimental
195
+ */
196
+ async getTaskResult(taskId, resultSchema, options) {
197
+ return this._server.getTaskResult({ taskId }, resultSchema, options);
198
+ }
199
+ /**
200
+ * Lists tasks with optional pagination.
201
+ *
202
+ * @param cursor - Optional pagination cursor
203
+ * @param options - Optional request options
204
+ * @returns List of tasks with optional next cursor
205
+ *
206
+ * @experimental
207
+ */
208
+ async listTasks(cursor, options) {
209
+ return this._server.listTasks(cursor ? { cursor } : void 0, options);
210
+ }
211
+ /**
212
+ * Cancels a running task.
213
+ *
214
+ * @param taskId - The task identifier
215
+ * @param options - Optional request options
216
+ *
217
+ * @experimental
218
+ */
219
+ async cancelTask(taskId, options) {
220
+ return this._server.cancelTask({ taskId }, options);
221
+ }
222
+ };
223
+ //#endregion
224
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.28.0_zod@4.3.6/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
225
+ /**
226
+ * An MCP server on top of a pluggable transport.
227
+ *
228
+ * This server will automatically respond to the initialization flow as initiated from the client.
229
+ *
230
+ * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
231
+ *
232
+ * ```typescript
233
+ * // Custom schemas
234
+ * const CustomRequestSchema = RequestSchema.extend({...})
235
+ * const CustomNotificationSchema = NotificationSchema.extend({...})
236
+ * const CustomResultSchema = ResultSchema.extend({...})
237
+ *
238
+ * // Type aliases
239
+ * type CustomRequest = z.infer<typeof CustomRequestSchema>
240
+ * type CustomNotification = z.infer<typeof CustomNotificationSchema>
241
+ * type CustomResult = z.infer<typeof CustomResultSchema>
242
+ *
243
+ * // Create typed server
244
+ * const server = new Server<CustomRequest, CustomNotification, CustomResult>({
245
+ * name: "CustomServer",
246
+ * version: "1.0.0"
247
+ * })
248
+ * ```
249
+ * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.
250
+ */
251
+ var Server = class extends Protocol {
252
+ /**
253
+ * Initializes this server with the given name and version information.
254
+ */
255
+ constructor(_serverInfo, options) {
256
+ super(options);
257
+ this._serverInfo = _serverInfo;
258
+ this._loggingLevels = /* @__PURE__ */ new Map();
259
+ this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));
260
+ this.isMessageIgnored = (level, sessionId) => {
261
+ const currentLevel = this._loggingLevels.get(sessionId);
262
+ return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
263
+ };
264
+ this._capabilities = options?.capabilities ?? {};
265
+ this._instructions = options?.instructions;
266
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
267
+ this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
268
+ this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
269
+ if (this._capabilities.logging) this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
270
+ const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
271
+ const { level } = request.params;
272
+ const parseResult = LoggingLevelSchema.safeParse(level);
273
+ if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data);
274
+ return {};
275
+ });
276
+ }
277
+ /**
278
+ * Access experimental features.
279
+ *
280
+ * WARNING: These APIs are experimental and may change without notice.
281
+ *
282
+ * @experimental
283
+ */
284
+ get experimental() {
285
+ if (!this._experimental) this._experimental = { tasks: new ExperimentalServerTasks(this) };
286
+ return this._experimental;
287
+ }
288
+ /**
289
+ * Registers new capabilities. This can only be called before connecting to a transport.
290
+ *
291
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
292
+ */
293
+ registerCapabilities(capabilities) {
294
+ if (this.transport) throw new Error("Cannot register capabilities after connecting to transport");
295
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
296
+ }
297
+ /**
298
+ * Override request handler registration to enforce server-side validation for tools/call.
299
+ */
300
+ setRequestHandler(requestSchema, handler) {
301
+ const methodSchema = getObjectShape(requestSchema)?.method;
302
+ if (!methodSchema) throw new Error("Schema is missing a method literal");
303
+ let methodValue;
304
+ if (isZ4Schema(methodSchema)) {
305
+ const v4Schema = methodSchema;
306
+ methodValue = (v4Schema._zod?.def)?.value ?? v4Schema.value;
307
+ } else {
308
+ const v3Schema = methodSchema;
309
+ methodValue = v3Schema._def?.value ?? v3Schema.value;
310
+ }
311
+ if (typeof methodValue !== "string") throw new Error("Schema method literal must be a string");
312
+ if (methodValue === "tools/call") {
313
+ const wrappedHandler = async (request, extra) => {
314
+ const validatedRequest = safeParse(CallToolRequestSchema, request);
315
+ if (!validatedRequest.success) {
316
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
317
+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
318
+ }
319
+ const { params } = validatedRequest.data;
320
+ const result = await Promise.resolve(handler(request, extra));
321
+ if (params.task) {
322
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
323
+ if (!taskValidationResult.success) {
324
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
325
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
326
+ }
327
+ return taskValidationResult.data;
328
+ }
329
+ const validationResult = safeParse(CallToolResultSchema, result);
330
+ if (!validationResult.success) {
331
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
332
+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
333
+ }
334
+ return validationResult.data;
335
+ };
336
+ return super.setRequestHandler(requestSchema, wrappedHandler);
337
+ }
338
+ return super.setRequestHandler(requestSchema, handler);
339
+ }
340
+ assertCapabilityForMethod(method) {
341
+ switch (method) {
342
+ case "sampling/createMessage":
343
+ if (!this._clientCapabilities?.sampling) throw new Error(`Client does not support sampling (required for ${method})`);
344
+ break;
345
+ case "elicitation/create":
346
+ if (!this._clientCapabilities?.elicitation) throw new Error(`Client does not support elicitation (required for ${method})`);
347
+ break;
348
+ case "roots/list":
349
+ if (!this._clientCapabilities?.roots) throw new Error(`Client does not support listing roots (required for ${method})`);
350
+ break;
351
+ case "ping": break;
352
+ }
353
+ }
354
+ assertNotificationCapability(method) {
355
+ switch (method) {
356
+ case "notifications/message":
357
+ if (!this._capabilities.logging) throw new Error(`Server does not support logging (required for ${method})`);
358
+ break;
359
+ case "notifications/resources/updated":
360
+ case "notifications/resources/list_changed":
361
+ if (!this._capabilities.resources) throw new Error(`Server does not support notifying about resources (required for ${method})`);
362
+ break;
363
+ case "notifications/tools/list_changed":
364
+ if (!this._capabilities.tools) throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
365
+ break;
366
+ case "notifications/prompts/list_changed":
367
+ if (!this._capabilities.prompts) throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
368
+ break;
369
+ case "notifications/elicitation/complete":
370
+ if (!this._clientCapabilities?.elicitation?.url) throw new Error(`Client does not support URL elicitation (required for ${method})`);
371
+ break;
372
+ case "notifications/cancelled": break;
373
+ case "notifications/progress": break;
374
+ }
375
+ }
376
+ assertRequestHandlerCapability(method) {
377
+ if (!this._capabilities) return;
378
+ switch (method) {
379
+ case "completion/complete":
380
+ if (!this._capabilities.completions) throw new Error(`Server does not support completions (required for ${method})`);
381
+ break;
382
+ case "logging/setLevel":
383
+ if (!this._capabilities.logging) throw new Error(`Server does not support logging (required for ${method})`);
384
+ break;
385
+ case "prompts/get":
386
+ case "prompts/list":
387
+ if (!this._capabilities.prompts) throw new Error(`Server does not support prompts (required for ${method})`);
388
+ break;
389
+ case "resources/list":
390
+ case "resources/templates/list":
391
+ case "resources/read":
392
+ if (!this._capabilities.resources) throw new Error(`Server does not support resources (required for ${method})`);
393
+ break;
394
+ case "tools/call":
395
+ case "tools/list":
396
+ if (!this._capabilities.tools) throw new Error(`Server does not support tools (required for ${method})`);
397
+ break;
398
+ case "tasks/get":
399
+ case "tasks/list":
400
+ case "tasks/result":
401
+ case "tasks/cancel":
402
+ if (!this._capabilities.tasks) throw new Error(`Server does not support tasks capability (required for ${method})`);
403
+ break;
404
+ case "ping":
405
+ case "initialize": break;
406
+ }
407
+ }
408
+ assertTaskCapability(method) {
409
+ assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");
410
+ }
411
+ assertTaskHandlerCapability(method) {
412
+ if (!this._capabilities) return;
413
+ assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
414
+ }
415
+ async _oninitialize(request) {
416
+ const requestedVersion = request.params.protocolVersion;
417
+ this._clientCapabilities = request.params.capabilities;
418
+ this._clientVersion = request.params.clientInfo;
419
+ return {
420
+ protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION,
421
+ capabilities: this.getCapabilities(),
422
+ serverInfo: this._serverInfo,
423
+ ...this._instructions && { instructions: this._instructions }
424
+ };
425
+ }
426
+ /**
427
+ * After initialization has completed, this will be populated with the client's reported capabilities.
428
+ */
429
+ getClientCapabilities() {
430
+ return this._clientCapabilities;
431
+ }
432
+ /**
433
+ * After initialization has completed, this will be populated with information about the client's name and version.
434
+ */
435
+ getClientVersion() {
436
+ return this._clientVersion;
437
+ }
438
+ getCapabilities() {
439
+ return this._capabilities;
440
+ }
441
+ async ping() {
442
+ return this.request({ method: "ping" }, EmptyResultSchema);
443
+ }
444
+ async createMessage(params, options) {
445
+ if (params.tools || params.toolChoice) {
446
+ if (!this._clientCapabilities?.sampling?.tools) throw new Error("Client does not support sampling tools capability.");
447
+ }
448
+ if (params.messages.length > 0) {
449
+ const lastMessage = params.messages[params.messages.length - 1];
450
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
451
+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");
452
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
453
+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
454
+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
455
+ if (hasToolResults) {
456
+ if (lastContent.some((c) => c.type !== "tool_result")) throw new Error("The last message must contain only tool_result content if any is present");
457
+ if (!hasPreviousToolUse) throw new Error("tool_result blocks are not matching any tool_use from the previous message");
458
+ }
459
+ if (hasPreviousToolUse) {
460
+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
461
+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
462
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
463
+ }
464
+ }
465
+ if (params.tools) return this.request({
466
+ method: "sampling/createMessage",
467
+ params
468
+ }, CreateMessageResultWithToolsSchema, options);
469
+ return this.request({
470
+ method: "sampling/createMessage",
471
+ params
472
+ }, CreateMessageResultSchema, options);
473
+ }
474
+ /**
475
+ * Creates an elicitation request for the given parameters.
476
+ * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
477
+ * @param params The parameters for the elicitation request.
478
+ * @param options Optional request options.
479
+ * @returns The result of the elicitation request.
480
+ */
481
+ async elicitInput(params, options) {
482
+ switch (params.mode ?? "form") {
483
+ case "url": {
484
+ if (!this._clientCapabilities?.elicitation?.url) throw new Error("Client does not support url elicitation.");
485
+ const urlParams = params;
486
+ return this.request({
487
+ method: "elicitation/create",
488
+ params: urlParams
489
+ }, ElicitResultSchema, options);
490
+ }
491
+ case "form": {
492
+ if (!this._clientCapabilities?.elicitation?.form) throw new Error("Client does not support form elicitation.");
493
+ const formParams = params.mode === "form" ? params : {
494
+ ...params,
495
+ mode: "form"
496
+ };
497
+ const result = await this.request({
498
+ method: "elicitation/create",
499
+ params: formParams
500
+ }, ElicitResultSchema, options);
501
+ if (result.action === "accept" && result.content && formParams.requestedSchema) try {
502
+ const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);
503
+ if (!validationResult.valid) throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
504
+ } catch (error) {
505
+ if (error instanceof McpError) throw error;
506
+ throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);
507
+ }
508
+ return result;
509
+ }
510
+ }
511
+ }
512
+ /**
513
+ * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
514
+ * notification for the specified elicitation ID.
515
+ *
516
+ * @param elicitationId The ID of the elicitation to mark as complete.
517
+ * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
518
+ * @returns A function that emits the completion notification when awaited.
519
+ */
520
+ createElicitationCompletionNotifier(elicitationId, options) {
521
+ if (!this._clientCapabilities?.elicitation?.url) throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
522
+ return () => this.notification({
523
+ method: "notifications/elicitation/complete",
524
+ params: { elicitationId }
525
+ }, options);
526
+ }
527
+ async listRoots(params, options) {
528
+ return this.request({
529
+ method: "roots/list",
530
+ params
531
+ }, ListRootsResultSchema, options);
532
+ }
533
+ /**
534
+ * Sends a logging message to the client, if connected.
535
+ * Note: You only need to send the parameters object, not the entire JSON RPC message
536
+ * @see LoggingMessageNotification
537
+ * @param params
538
+ * @param sessionId optional for stateless and backward compatibility
539
+ */
540
+ async sendLoggingMessage(params, sessionId) {
541
+ if (this._capabilities.logging) {
542
+ if (!this.isMessageIgnored(params.level, sessionId)) return this.notification({
543
+ method: "notifications/message",
544
+ params
545
+ });
546
+ }
547
+ }
548
+ async sendResourceUpdated(params) {
549
+ return this.notification({
550
+ method: "notifications/resources/updated",
551
+ params
552
+ });
553
+ }
554
+ async sendResourceListChanged() {
555
+ return this.notification({ method: "notifications/resources/list_changed" });
556
+ }
557
+ async sendToolListChanged() {
558
+ return this.notification({ method: "notifications/tools/list_changed" });
559
+ }
560
+ async sendPromptListChanged() {
561
+ return this.notification({ method: "notifications/prompts/list_changed" });
562
+ }
563
+ };
564
+ //#endregion
565
+ export { Server };