kith-coord 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,708 @@
1
+ import { createRequire as __kithRequire } from 'node:module'; const require = __kithRequire(import.meta.url);
2
+ import {
3
+ AjvJsonSchemaValidator,
4
+ Protocol,
5
+ assertClientRequestTaskCapability,
6
+ assertToolsCallTaskCapability,
7
+ getLiteralValue,
8
+ getObjectShape,
9
+ mergeCapabilities,
10
+ safeParse
11
+ } from "./chunk-SAHFIOEQ.js";
12
+ import {
13
+ CallToolResultSchema,
14
+ CompleteResultSchema,
15
+ CreateMessageRequestSchema,
16
+ CreateMessageResultSchema,
17
+ CreateMessageResultWithToolsSchema,
18
+ CreateTaskResultSchema,
19
+ ElicitRequestSchema,
20
+ ElicitResultSchema,
21
+ EmptyResultSchema,
22
+ ErrorCode,
23
+ GetPromptResultSchema,
24
+ InitializeResultSchema,
25
+ LATEST_PROTOCOL_VERSION,
26
+ ListChangedOptionsBaseSchema,
27
+ ListPromptsResultSchema,
28
+ ListResourceTemplatesResultSchema,
29
+ ListResourcesResultSchema,
30
+ ListToolsResultSchema,
31
+ McpError,
32
+ PromptListChangedNotificationSchema,
33
+ ReadResourceResultSchema,
34
+ ResourceListChangedNotificationSchema,
35
+ SUPPORTED_PROTOCOL_VERSIONS,
36
+ ToolListChangedNotificationSchema
37
+ } from "./chunk-QLLTQNDL.js";
38
+ import "./chunk-WYEINJKJ.js";
39
+
40
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
41
+ var ExperimentalClientTasks = class {
42
+ constructor(_client) {
43
+ this._client = _client;
44
+ }
45
+ /**
46
+ * Calls a tool and returns an AsyncGenerator that yields response messages.
47
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
48
+ *
49
+ * This method provides streaming access to tool execution, allowing you to
50
+ * observe intermediate task status updates for long-running tool calls.
51
+ * Automatically validates structured output if the tool has an outputSchema.
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
56
+ * for await (const message of stream) {
57
+ * switch (message.type) {
58
+ * case 'taskCreated':
59
+ * console.log('Tool execution started:', message.task.taskId);
60
+ * break;
61
+ * case 'taskStatus':
62
+ * console.log('Tool status:', message.task.status);
63
+ * break;
64
+ * case 'result':
65
+ * console.log('Tool result:', message.result);
66
+ * break;
67
+ * case 'error':
68
+ * console.error('Tool error:', message.error);
69
+ * break;
70
+ * }
71
+ * }
72
+ * ```
73
+ *
74
+ * @param params - Tool call parameters (name and arguments)
75
+ * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
76
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
77
+ * @returns AsyncGenerator that yields ResponseMessage objects
78
+ *
79
+ * @experimental
80
+ */
81
+ async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
82
+ const clientInternal = this._client;
83
+ const optionsWithTask = {
84
+ ...options,
85
+ // We check if the tool is known to be a task during auto-configuration, but assume
86
+ // the caller knows what they're doing if they pass this explicitly
87
+ task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : void 0)
88
+ };
89
+ const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
90
+ const validator = clientInternal.getToolOutputValidator(params.name);
91
+ for await (const message of stream) {
92
+ if (message.type === "result" && validator) {
93
+ const result = message.result;
94
+ if (!result.structuredContent && !result.isError) {
95
+ yield {
96
+ type: "error",
97
+ error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
98
+ };
99
+ return;
100
+ }
101
+ if (result.structuredContent) {
102
+ try {
103
+ const validationResult = validator(result.structuredContent);
104
+ if (!validationResult.valid) {
105
+ yield {
106
+ type: "error",
107
+ error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
108
+ };
109
+ return;
110
+ }
111
+ } catch (error) {
112
+ if (error instanceof McpError) {
113
+ yield { type: "error", error };
114
+ return;
115
+ }
116
+ yield {
117
+ type: "error",
118
+ error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)
119
+ };
120
+ return;
121
+ }
122
+ }
123
+ }
124
+ yield message;
125
+ }
126
+ }
127
+ /**
128
+ * Gets the current status of a task.
129
+ *
130
+ * @param taskId - The task identifier
131
+ * @param options - Optional request options
132
+ * @returns The task status
133
+ *
134
+ * @experimental
135
+ */
136
+ async getTask(taskId, options) {
137
+ return this._client.getTask({ taskId }, options);
138
+ }
139
+ /**
140
+ * Retrieves the result of a completed task.
141
+ *
142
+ * @param taskId - The task identifier
143
+ * @param resultSchema - Zod schema for validating the result
144
+ * @param options - Optional request options
145
+ * @returns The task result
146
+ *
147
+ * @experimental
148
+ */
149
+ async getTaskResult(taskId, resultSchema, options) {
150
+ return this._client.getTaskResult({ taskId }, resultSchema, options);
151
+ }
152
+ /**
153
+ * Lists tasks with optional pagination.
154
+ *
155
+ * @param cursor - Optional pagination cursor
156
+ * @param options - Optional request options
157
+ * @returns List of tasks with optional next cursor
158
+ *
159
+ * @experimental
160
+ */
161
+ async listTasks(cursor, options) {
162
+ return this._client.listTasks(cursor ? { cursor } : void 0, options);
163
+ }
164
+ /**
165
+ * Cancels a running task.
166
+ *
167
+ * @param taskId - The task identifier
168
+ * @param options - Optional request options
169
+ *
170
+ * @experimental
171
+ */
172
+ async cancelTask(taskId, options) {
173
+ return this._client.cancelTask({ taskId }, options);
174
+ }
175
+ /**
176
+ * Sends a request and returns an AsyncGenerator that yields response messages.
177
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
178
+ *
179
+ * This method provides streaming access to request processing, allowing you to
180
+ * observe intermediate task status updates for task-augmented requests.
181
+ *
182
+ * @param request - The request to send
183
+ * @param resultSchema - Zod schema for validating the result
184
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
185
+ * @returns AsyncGenerator that yields ResponseMessage objects
186
+ *
187
+ * @experimental
188
+ */
189
+ requestStream(request, resultSchema, options) {
190
+ return this._client.requestStream(request, resultSchema, options);
191
+ }
192
+ };
193
+
194
+ // node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.2_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
195
+ function applyElicitationDefaults(schema, data) {
196
+ if (!schema || data === null || typeof data !== "object")
197
+ return;
198
+ if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
199
+ const obj = data;
200
+ const props = schema.properties;
201
+ for (const key of Object.keys(props)) {
202
+ const propSchema = props[key];
203
+ if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
204
+ obj[key] = propSchema.default;
205
+ }
206
+ if (obj[key] !== void 0) {
207
+ applyElicitationDefaults(propSchema, obj[key]);
208
+ }
209
+ }
210
+ }
211
+ if (Array.isArray(schema.anyOf)) {
212
+ for (const sub of schema.anyOf) {
213
+ if (typeof sub !== "boolean") {
214
+ applyElicitationDefaults(sub, data);
215
+ }
216
+ }
217
+ }
218
+ if (Array.isArray(schema.oneOf)) {
219
+ for (const sub of schema.oneOf) {
220
+ if (typeof sub !== "boolean") {
221
+ applyElicitationDefaults(sub, data);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ function getSupportedElicitationModes(capabilities) {
227
+ if (!capabilities) {
228
+ return { supportsFormMode: false, supportsUrlMode: false };
229
+ }
230
+ const hasFormCapability = capabilities.form !== void 0;
231
+ const hasUrlCapability = capabilities.url !== void 0;
232
+ const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
233
+ const supportsUrlMode = hasUrlCapability;
234
+ return { supportsFormMode, supportsUrlMode };
235
+ }
236
+ var Client = class extends Protocol {
237
+ /**
238
+ * Initializes this client with the given name and version information.
239
+ */
240
+ constructor(_clientInfo, options) {
241
+ super(options);
242
+ this._clientInfo = _clientInfo;
243
+ this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
244
+ this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
245
+ this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
246
+ this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
247
+ this._capabilities = options?.capabilities ?? {};
248
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
249
+ if (options?.listChanged) {
250
+ this._pendingListChangedConfig = options.listChanged;
251
+ }
252
+ }
253
+ /**
254
+ * Set up handlers for list changed notifications based on config and server capabilities.
255
+ * This should only be called after initialization when server capabilities are known.
256
+ * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
257
+ * @internal
258
+ */
259
+ _setupListChangedHandlers(config) {
260
+ if (config.tools && this._serverCapabilities?.tools?.listChanged) {
261
+ this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config.tools, async () => {
262
+ const result = await this.listTools();
263
+ return result.tools;
264
+ });
265
+ }
266
+ if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {
267
+ this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config.prompts, async () => {
268
+ const result = await this.listPrompts();
269
+ return result.prompts;
270
+ });
271
+ }
272
+ if (config.resources && this._serverCapabilities?.resources?.listChanged) {
273
+ this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config.resources, async () => {
274
+ const result = await this.listResources();
275
+ return result.resources;
276
+ });
277
+ }
278
+ }
279
+ /**
280
+ * Access experimental features.
281
+ *
282
+ * WARNING: These APIs are experimental and may change without notice.
283
+ *
284
+ * @experimental
285
+ */
286
+ get experimental() {
287
+ if (!this._experimental) {
288
+ this._experimental = {
289
+ tasks: new ExperimentalClientTasks(this)
290
+ };
291
+ }
292
+ return this._experimental;
293
+ }
294
+ /**
295
+ * Registers new capabilities. This can only be called before connecting to a transport.
296
+ *
297
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
298
+ */
299
+ registerCapabilities(capabilities) {
300
+ if (this.transport) {
301
+ throw new Error("Cannot register capabilities after connecting to transport");
302
+ }
303
+ this._capabilities = mergeCapabilities(this._capabilities, capabilities);
304
+ }
305
+ /**
306
+ * Override request handler registration to enforce client-side validation for elicitation.
307
+ */
308
+ setRequestHandler(requestSchema, handler) {
309
+ const shape = getObjectShape(requestSchema);
310
+ const methodSchema = shape?.method;
311
+ if (!methodSchema) {
312
+ throw new Error("Schema is missing a method literal");
313
+ }
314
+ const methodValue = getLiteralValue(methodSchema);
315
+ if (typeof methodValue !== "string") {
316
+ throw new Error("Schema method literal must be a string");
317
+ }
318
+ const method = methodValue;
319
+ if (method === "elicitation/create") {
320
+ const wrappedHandler = async (request, extra) => {
321
+ const validatedRequest = safeParse(ElicitRequestSchema, request);
322
+ if (!validatedRequest.success) {
323
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
324
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
325
+ }
326
+ const { params } = validatedRequest.data;
327
+ params.mode = params.mode ?? "form";
328
+ const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
329
+ if (params.mode === "form" && !supportsFormMode) {
330
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
331
+ }
332
+ if (params.mode === "url" && !supportsUrlMode) {
333
+ throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
334
+ }
335
+ const result = await Promise.resolve(handler(request, extra));
336
+ if (params.task) {
337
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
338
+ if (!taskValidationResult.success) {
339
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
340
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
341
+ }
342
+ return taskValidationResult.data;
343
+ }
344
+ const validationResult = safeParse(ElicitResultSchema, result);
345
+ if (!validationResult.success) {
346
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
347
+ throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
348
+ }
349
+ const validatedResult = validationResult.data;
350
+ const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
351
+ if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
352
+ if (this._capabilities.elicitation?.form?.applyDefaults) {
353
+ try {
354
+ applyElicitationDefaults(requestedSchema, validatedResult.content);
355
+ } catch {
356
+ }
357
+ }
358
+ }
359
+ return validatedResult;
360
+ };
361
+ return super.setRequestHandler(requestSchema, wrappedHandler);
362
+ }
363
+ if (method === "sampling/createMessage") {
364
+ const wrappedHandler = async (request, extra) => {
365
+ const validatedRequest = safeParse(CreateMessageRequestSchema, request);
366
+ if (!validatedRequest.success) {
367
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
368
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
369
+ }
370
+ const { params } = validatedRequest.data;
371
+ const result = await Promise.resolve(handler(request, extra));
372
+ if (params.task) {
373
+ const taskValidationResult = safeParse(CreateTaskResultSchema, result);
374
+ if (!taskValidationResult.success) {
375
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
376
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
377
+ }
378
+ return taskValidationResult.data;
379
+ }
380
+ const hasTools = params.tools || params.toolChoice;
381
+ const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
382
+ const validationResult = safeParse(resultSchema, result);
383
+ if (!validationResult.success) {
384
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
385
+ throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
386
+ }
387
+ return validationResult.data;
388
+ };
389
+ return super.setRequestHandler(requestSchema, wrappedHandler);
390
+ }
391
+ return super.setRequestHandler(requestSchema, handler);
392
+ }
393
+ assertCapability(capability, method) {
394
+ if (!this._serverCapabilities?.[capability]) {
395
+ throw new Error(`Server does not support ${capability} (required for ${method})`);
396
+ }
397
+ }
398
+ async connect(transport, options) {
399
+ await super.connect(transport);
400
+ if (transport.sessionId !== void 0) {
401
+ return;
402
+ }
403
+ try {
404
+ const result = await this.request({
405
+ method: "initialize",
406
+ params: {
407
+ protocolVersion: LATEST_PROTOCOL_VERSION,
408
+ capabilities: this._capabilities,
409
+ clientInfo: this._clientInfo
410
+ }
411
+ }, InitializeResultSchema, options);
412
+ if (result === void 0) {
413
+ throw new Error(`Server sent invalid initialize result: ${result}`);
414
+ }
415
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
416
+ throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
417
+ }
418
+ this._serverCapabilities = result.capabilities;
419
+ this._serverVersion = result.serverInfo;
420
+ if (transport.setProtocolVersion) {
421
+ transport.setProtocolVersion(result.protocolVersion);
422
+ }
423
+ this._instructions = result.instructions;
424
+ await this.notification({
425
+ method: "notifications/initialized"
426
+ });
427
+ if (this._pendingListChangedConfig) {
428
+ this._setupListChangedHandlers(this._pendingListChangedConfig);
429
+ this._pendingListChangedConfig = void 0;
430
+ }
431
+ } catch (error) {
432
+ void this.close();
433
+ throw error;
434
+ }
435
+ }
436
+ /**
437
+ * After initialization has completed, this will be populated with the server's reported capabilities.
438
+ */
439
+ getServerCapabilities() {
440
+ return this._serverCapabilities;
441
+ }
442
+ /**
443
+ * After initialization has completed, this will be populated with information about the server's name and version.
444
+ */
445
+ getServerVersion() {
446
+ return this._serverVersion;
447
+ }
448
+ /**
449
+ * After initialization has completed, this may be populated with information about the server's instructions.
450
+ */
451
+ getInstructions() {
452
+ return this._instructions;
453
+ }
454
+ assertCapabilityForMethod(method) {
455
+ switch (method) {
456
+ case "logging/setLevel":
457
+ if (!this._serverCapabilities?.logging) {
458
+ throw new Error(`Server does not support logging (required for ${method})`);
459
+ }
460
+ break;
461
+ case "prompts/get":
462
+ case "prompts/list":
463
+ if (!this._serverCapabilities?.prompts) {
464
+ throw new Error(`Server does not support prompts (required for ${method})`);
465
+ }
466
+ break;
467
+ case "resources/list":
468
+ case "resources/templates/list":
469
+ case "resources/read":
470
+ case "resources/subscribe":
471
+ case "resources/unsubscribe":
472
+ if (!this._serverCapabilities?.resources) {
473
+ throw new Error(`Server does not support resources (required for ${method})`);
474
+ }
475
+ if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
476
+ throw new Error(`Server does not support resource subscriptions (required for ${method})`);
477
+ }
478
+ break;
479
+ case "tools/call":
480
+ case "tools/list":
481
+ if (!this._serverCapabilities?.tools) {
482
+ throw new Error(`Server does not support tools (required for ${method})`);
483
+ }
484
+ break;
485
+ case "completion/complete":
486
+ if (!this._serverCapabilities?.completions) {
487
+ throw new Error(`Server does not support completions (required for ${method})`);
488
+ }
489
+ break;
490
+ case "initialize":
491
+ break;
492
+ case "ping":
493
+ break;
494
+ }
495
+ }
496
+ assertNotificationCapability(method) {
497
+ switch (method) {
498
+ case "notifications/roots/list_changed":
499
+ if (!this._capabilities.roots?.listChanged) {
500
+ throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
501
+ }
502
+ break;
503
+ case "notifications/initialized":
504
+ break;
505
+ case "notifications/cancelled":
506
+ break;
507
+ case "notifications/progress":
508
+ break;
509
+ }
510
+ }
511
+ assertRequestHandlerCapability(method) {
512
+ if (!this._capabilities) {
513
+ return;
514
+ }
515
+ switch (method) {
516
+ case "sampling/createMessage":
517
+ if (!this._capabilities.sampling) {
518
+ throw new Error(`Client does not support sampling capability (required for ${method})`);
519
+ }
520
+ break;
521
+ case "elicitation/create":
522
+ if (!this._capabilities.elicitation) {
523
+ throw new Error(`Client does not support elicitation capability (required for ${method})`);
524
+ }
525
+ break;
526
+ case "roots/list":
527
+ if (!this._capabilities.roots) {
528
+ throw new Error(`Client does not support roots capability (required for ${method})`);
529
+ }
530
+ break;
531
+ case "tasks/get":
532
+ case "tasks/list":
533
+ case "tasks/result":
534
+ case "tasks/cancel":
535
+ if (!this._capabilities.tasks) {
536
+ throw new Error(`Client does not support tasks capability (required for ${method})`);
537
+ }
538
+ break;
539
+ case "ping":
540
+ break;
541
+ }
542
+ }
543
+ assertTaskCapability(method) {
544
+ assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, "Server");
545
+ }
546
+ assertTaskHandlerCapability(method) {
547
+ if (!this._capabilities) {
548
+ return;
549
+ }
550
+ assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, "Client");
551
+ }
552
+ async ping(options) {
553
+ return this.request({ method: "ping" }, EmptyResultSchema, options);
554
+ }
555
+ async complete(params, options) {
556
+ return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
557
+ }
558
+ async setLoggingLevel(level, options) {
559
+ return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
560
+ }
561
+ async getPrompt(params, options) {
562
+ return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
563
+ }
564
+ async listPrompts(params, options) {
565
+ return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
566
+ }
567
+ async listResources(params, options) {
568
+ return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
569
+ }
570
+ async listResourceTemplates(params, options) {
571
+ return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
572
+ }
573
+ async readResource(params, options) {
574
+ return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
575
+ }
576
+ async subscribeResource(params, options) {
577
+ return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
578
+ }
579
+ async unsubscribeResource(params, options) {
580
+ return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
581
+ }
582
+ /**
583
+ * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
584
+ *
585
+ * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
586
+ */
587
+ async callTool(params, resultSchema = CallToolResultSchema, options) {
588
+ if (this.isToolTaskRequired(params.name)) {
589
+ throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
590
+ }
591
+ const result = await this.request({ method: "tools/call", params }, resultSchema, options);
592
+ const validator = this.getToolOutputValidator(params.name);
593
+ if (validator) {
594
+ if (!result.structuredContent && !result.isError) {
595
+ throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
596
+ }
597
+ if (result.structuredContent) {
598
+ try {
599
+ const validationResult = validator(result.structuredContent);
600
+ if (!validationResult.valid) {
601
+ throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
602
+ }
603
+ } catch (error) {
604
+ if (error instanceof McpError) {
605
+ throw error;
606
+ }
607
+ throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
608
+ }
609
+ }
610
+ }
611
+ return result;
612
+ }
613
+ isToolTask(toolName) {
614
+ if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {
615
+ return false;
616
+ }
617
+ return this._cachedKnownTaskTools.has(toolName);
618
+ }
619
+ /**
620
+ * Check if a tool requires task-based execution.
621
+ * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
622
+ */
623
+ isToolTaskRequired(toolName) {
624
+ return this._cachedRequiredTaskTools.has(toolName);
625
+ }
626
+ /**
627
+ * Cache validators for tool output schemas.
628
+ * Called after listTools() to pre-compile validators for better performance.
629
+ */
630
+ cacheToolMetadata(tools) {
631
+ this._cachedToolOutputValidators.clear();
632
+ this._cachedKnownTaskTools.clear();
633
+ this._cachedRequiredTaskTools.clear();
634
+ for (const tool of tools) {
635
+ if (tool.outputSchema) {
636
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
637
+ this._cachedToolOutputValidators.set(tool.name, toolValidator);
638
+ }
639
+ const taskSupport = tool.execution?.taskSupport;
640
+ if (taskSupport === "required" || taskSupport === "optional") {
641
+ this._cachedKnownTaskTools.add(tool.name);
642
+ }
643
+ if (taskSupport === "required") {
644
+ this._cachedRequiredTaskTools.add(tool.name);
645
+ }
646
+ }
647
+ }
648
+ /**
649
+ * Get cached validator for a tool
650
+ */
651
+ getToolOutputValidator(toolName) {
652
+ return this._cachedToolOutputValidators.get(toolName);
653
+ }
654
+ async listTools(params, options) {
655
+ const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
656
+ this.cacheToolMetadata(result.tools);
657
+ return result;
658
+ }
659
+ /**
660
+ * Set up a single list changed handler.
661
+ * @internal
662
+ */
663
+ _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
664
+ const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
665
+ if (!parseResult.success) {
666
+ throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
667
+ }
668
+ if (typeof options.onChanged !== "function") {
669
+ throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
670
+ }
671
+ const { autoRefresh, debounceMs } = parseResult.data;
672
+ const { onChanged } = options;
673
+ const refresh = async () => {
674
+ if (!autoRefresh) {
675
+ onChanged(null, null);
676
+ return;
677
+ }
678
+ try {
679
+ const items = await fetcher();
680
+ onChanged(null, items);
681
+ } catch (e) {
682
+ const error = e instanceof Error ? e : new Error(String(e));
683
+ onChanged(error, null);
684
+ }
685
+ };
686
+ const handler = () => {
687
+ if (debounceMs) {
688
+ const existingTimer = this._listChangedDebounceTimers.get(listType);
689
+ if (existingTimer) {
690
+ clearTimeout(existingTimer);
691
+ }
692
+ const timer = setTimeout(refresh, debounceMs);
693
+ this._listChangedDebounceTimers.set(listType, timer);
694
+ } else {
695
+ refresh();
696
+ }
697
+ };
698
+ this.setNotificationHandler(notificationSchema, handler);
699
+ }
700
+ async sendRootsListChanged() {
701
+ return this.notification({ method: "notifications/roots/list_changed" });
702
+ }
703
+ };
704
+ export {
705
+ Client,
706
+ getSupportedElicitationModes
707
+ };
708
+ //# sourceMappingURL=client-77BNXEAH.js.map