taskin 1.0.12 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -38,12 +38,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
38
38
  mod
39
39
  ));
40
40
 
41
- // ../../node_modules/.pnpm/tsup@8.5.0_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js
41
+ // ../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js
42
42
  import path from "path";
43
43
  import { fileURLToPath } from "url";
44
44
  var getFilename, getDirname, __dirname;
45
45
  var init_esm_shims = __esm({
46
- "../../node_modules/.pnpm/tsup@8.5.0_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js"() {
46
+ "../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js"() {
47
47
  "use strict";
48
48
  getFilename = () => fileURLToPath(import.meta.url);
49
49
  getDirname = () => path.dirname(getFilename());
@@ -106,9 +106,18 @@ async function fixTaskFile(filePath) {
106
106
  const content = await readFile(filePath, "utf-8");
107
107
  const locale = detectLocale(content);
108
108
  const i18n = getI18n(locale);
109
- const statusPattern = new RegExp(`##\\s*(?:Status|${i18n.status})\\s*\\n\\s*([^\\n\\r]+)`, "i");
110
- const typePattern = new RegExp(`##\\s*(?:Type|${i18n.type})\\s*\\n\\s*([^\\n\\r]+)`, "i");
111
- const assigneePattern = new RegExp(`##\\s*(?:Assignee|${i18n.assignee})\\s*\\n\\s*([^\\n\\r]+)`, "i");
109
+ const statusPattern = new RegExp(
110
+ `##\\s*(?:Status|${i18n.status})\\s*\\n\\s*([^\\n\\r]+)`,
111
+ "i"
112
+ );
113
+ const typePattern = new RegExp(
114
+ `##\\s*(?:Type|${i18n.type})\\s*\\n\\s*([^\\n\\r]+)`,
115
+ "i"
116
+ );
117
+ const assigneePattern = new RegExp(
118
+ `##\\s*(?:Assignee|${i18n.assignee})\\s*\\n\\s*([^\\n\\r]+)`,
119
+ "i"
120
+ );
112
121
  const hasSectionStatus = statusPattern.test(content);
113
122
  const hasSectionType = typePattern.test(content);
114
123
  const hasSectionAssignee = assigneePattern.test(content);
@@ -166,9 +175,18 @@ async function fixTaskFile(filePath) {
166
175
  }
167
176
  if (needsSpaceFix) {
168
177
  newContent = newContent.replace(/^(# .+)\n([^#\n])/m, "$1\n\n$2");
169
- newContent = newContent.replace(/^(Status|Tipo):\s*(.+?)(\s*)$/im, (_, key, value) => `${key}: ${value.trim()} `);
170
- newContent = newContent.replace(/^(Type|Tipo):\s*(.+?)(\s*)$/im, (_, key, value) => `${key}: ${value.trim()} `);
171
- newContent = newContent.replace(/^(Assignee|Responsável):\s*(.+?)(\s*)$/im, (_, key, value) => `${key}: ${value.trim()} `);
178
+ newContent = newContent.replace(
179
+ /^(Status|Tipo):\s*(.+?)(\s*)$/im,
180
+ (_, key, value) => `${key}: ${value.trim()} `
181
+ );
182
+ newContent = newContent.replace(
183
+ /^(Type|Tipo):\s*(.+?)(\s*)$/im,
184
+ (_, key, value) => `${key}: ${value.trim()} `
185
+ );
186
+ newContent = newContent.replace(
187
+ /^(Assignee|Responsável):\s*(.+?)(\s*)$/im,
188
+ (_, key, value) => `${key}: ${value.trim()} `
189
+ );
172
190
  wasModified = true;
173
191
  }
174
192
  if (wasModified) {
@@ -190,8 +208,14 @@ async function validateTaskFile(filePath) {
190
208
  const locale = detectLocale(content);
191
209
  const i18n = getI18n(locale);
192
210
  const hasTitleSection = lines.some((line) => line.trim().startsWith("# "));
193
- const inlineStatusPattern = new RegExp(`^(?:Status|${i18n.status}):\\s*.+$`, "im");
194
- const sectionStatusPattern = new RegExp(`##\\s*(?:Status|${i18n.status})`, "i");
211
+ const inlineStatusPattern = new RegExp(
212
+ `^(?:Status|${i18n.status}):\\s*.+$`,
213
+ "im"
214
+ );
215
+ const sectionStatusPattern = new RegExp(
216
+ `##\\s*(?:Status|${i18n.status})`,
217
+ "i"
218
+ );
195
219
  const hasInlineStatus = inlineStatusPattern.test(content);
196
220
  const hasSectionStatus = sectionStatusPattern.test(content);
197
221
  const hasDescriptionSection = content.includes("## Description") || content.includes("## Descri\xE7\xE3o");
@@ -205,7 +229,9 @@ async function validateTaskFile(filePath) {
205
229
  });
206
230
  }
207
231
  if (hasSectionStatus) {
208
- const statusLineIdx = lines.findIndex((line) => sectionStatusPattern.test(line.trim()));
232
+ const statusLineIdx = lines.findIndex(
233
+ (line) => sectionStatusPattern.test(line.trim())
234
+ );
209
235
  issues.push({
210
236
  file: filePath,
211
237
  line: statusLineIdx >= 0 ? statusLineIdx + 1 : void 0,
@@ -234,7 +260,9 @@ ${i18n.status}: <todo|in-progress|done>`
234
260
  "blocked",
235
261
  "canceled"
236
262
  ].includes(statusValue)) {
237
- const statusLineIdx = lines.findIndex((line) => inlineStatusPattern.test(line.trim()));
263
+ const statusLineIdx = lines.findIndex(
264
+ (line) => inlineStatusPattern.test(line.trim())
265
+ );
238
266
  issues.push({
239
267
  file: filePath,
240
268
  line: statusLineIdx >= 0 ? statusLineIdx + 1 : void 0,
@@ -281,9 +309,15 @@ ${i18n.status}: <todo|in-progress|done>`
281
309
  return issues;
282
310
  }
283
311
  function createLintResult(allIssues) {
284
- const errorCount = allIssues.filter((issue) => issue.severity === "error").length;
285
- const warningCount = allIssues.filter((issue) => issue.severity === "warning").length;
286
- const infoCount = allIssues.filter((issue) => issue.severity === "info").length;
312
+ const errorCount = allIssues.filter(
313
+ (issue) => issue.severity === "error"
314
+ ).length;
315
+ const warningCount = allIssues.filter(
316
+ (issue) => issue.severity === "warning"
317
+ ).length;
318
+ const infoCount = allIssues.filter(
319
+ (issue) => issue.severity === "info"
320
+ ).length;
287
321
  return {
288
322
  valid: errorCount === 0,
289
323
  issues: allIssues,
@@ -7156,7 +7190,9 @@ var FileSystemTaskProvider = class {
7156
7190
  }
7157
7191
  async findTask(taskId) {
7158
7192
  const files = await fs.readdir(this.tasksDirectory);
7159
- const taskFile = files.find((file) => file.startsWith(`task-${taskId}-`) && file.endsWith(".md"));
7193
+ const taskFile = files.find(
7194
+ (file) => file.startsWith(`task-${taskId}-`) && file.endsWith(".md")
7195
+ );
7160
7196
  if (!taskFile) {
7161
7197
  return void 0;
7162
7198
  }
@@ -7172,8 +7208,7 @@ var FileSystemTaskProvider = class {
7172
7208
  const escapedName = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7173
7209
  const rx = new RegExp(`^${escapedName}:\\s*(.+)$`, "im");
7174
7210
  const m = content.match(rx);
7175
- if (m)
7176
- return m[1].trim();
7211
+ if (m) return m[1].trim();
7177
7212
  }
7178
7213
  return null;
7179
7214
  };
@@ -7185,7 +7220,9 @@ var FileSystemTaskProvider = class {
7185
7220
  const assigneeValue = assigneeMatch.trim();
7186
7221
  assignee = this.userRegistry.resolveUser(assigneeValue);
7187
7222
  if (!assignee) {
7188
- console.warn(`[FS Provider] User "${assigneeValue}" not found in registry, creating temporary user`);
7223
+ console.warn(
7224
+ `[FS Provider] User "${assigneeValue}" not found in registry, creating temporary user`
7225
+ );
7189
7226
  assignee = this.userRegistry.createTemporaryUser(assigneeValue);
7190
7227
  }
7191
7228
  }
@@ -7203,7 +7240,9 @@ var FileSystemTaskProvider = class {
7203
7240
  }
7204
7241
  async updateTask(task) {
7205
7242
  const currentContent = await fs.readFile(task.filePath, "utf-8");
7206
- const hasSectionMetadata = /##\s*(Status|Type|Assignee)/i.test(currentContent);
7243
+ const hasSectionMetadata = /##\s*(Status|Type|Assignee)/i.test(
7244
+ currentContent
7245
+ );
7207
7246
  if (hasSectionMetadata) {
7208
7247
  const { fixTaskFile: fixTaskFile2 } = await Promise.resolve().then(() => (init_task_validator(), task_validator_exports));
7209
7248
  await fixTaskFile2(task.filePath);
@@ -7211,16 +7250,24 @@ var FileSystemTaskProvider = class {
7211
7250
  const content = await fs.readFile(task.filePath, "utf-8");
7212
7251
  let updatedContent;
7213
7252
  if (/^Status:\s*.+$/im.test(content)) {
7214
- updatedContent = content.replace(/^Status:\s*.+$/im, `Status: ${task.status} `);
7253
+ updatedContent = content.replace(
7254
+ /^Status:\s*.+$/im,
7255
+ `Status: ${task.status} `
7256
+ );
7215
7257
  } else {
7216
- updatedContent = content.replace(/(^#.*\n)/, `$1Status: ${task.status}
7217
- `);
7258
+ updatedContent = content.replace(
7259
+ /(^#.*\n)/,
7260
+ `$1Status: ${task.status}
7261
+ `
7262
+ );
7218
7263
  }
7219
7264
  await fs.writeFile(task.filePath, updatedContent, "utf-8");
7220
7265
  }
7221
7266
  async getAllTasks() {
7222
7267
  const files = await fs.readdir(this.tasksDirectory);
7223
- const taskFiles = files.filter((file) => file.startsWith("task-") && file.endsWith(".md"));
7268
+ const taskFiles = files.filter(
7269
+ (file) => file.startsWith("task-") && file.endsWith(".md")
7270
+ );
7224
7271
  const tasks = [];
7225
7272
  for (const file of taskFiles) {
7226
7273
  const filePath = path2.join(this.tasksDirectory, file);
@@ -7237,8 +7284,7 @@ var FileSystemTaskProvider = class {
7237
7284
  const escapedName = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7238
7285
  const rx = new RegExp(`^${escapedName}:\\s*(.+)$`, "im");
7239
7286
  const m = content.match(rx);
7240
- if (m)
7241
- return m[1].trim();
7287
+ if (m) return m[1].trim();
7242
7288
  }
7243
7289
  return null;
7244
7290
  };
@@ -8350,7 +8396,13 @@ async function finishTask(taskId, options) {
8350
8396
 
8351
8397
  // src/commands/init.ts
8352
8398
  init_esm_shims();
8353
- import { existsSync as existsSync4, mkdirSync, writeFileSync } from "fs";
8399
+ import {
8400
+ existsSync as existsSync4,
8401
+ mkdirSync,
8402
+ readFileSync,
8403
+ readdirSync,
8404
+ writeFileSync
8405
+ } from "fs";
8354
8406
  import inquirer from "inquirer";
8355
8407
  import { join } from "path";
8356
8408
 
@@ -8634,7 +8686,7 @@ async function initializeTaskin(options) {
8634
8686
  success(`\u2713 Created ${colors2.highlight(".taskin.json")}`);
8635
8687
  const gitignorePath = join(cwd, ".gitignore");
8636
8688
  if (existsSync4(gitignorePath)) {
8637
- const gitignoreContent = __require("fs").readFileSync(gitignorePath, "utf-8");
8689
+ const gitignoreContent = readFileSync(gitignorePath, "utf-8");
8638
8690
  if (!gitignoreContent.includes(".taskin.json")) {
8639
8691
  info("Adding .taskin.json to .gitignore...");
8640
8692
  writeFileSync(
@@ -8697,8 +8749,7 @@ async function setupFileSystemProvider(cwd) {
8697
8749
  info(`${colors2.highlight("TASKS/")} directory already exists`);
8698
8750
  success("\u2713 Directory is ready to use");
8699
8751
  }
8700
- const fs3 = __require("fs");
8701
- const existingTask001 = fs3.readdirSync(tasksDir).find(
8752
+ const existingTask001 = readdirSync(tasksDir).find(
8702
8753
  (file) => file.startsWith("task-001-") && file.endsWith(".md")
8703
8754
  );
8704
8755
  if (existingTask001) {
@@ -8926,67 +8977,173 @@ init_esm_shims();
8926
8977
  // ../task-server-mcp/dist/task-server-mcp.js
8927
8978
  init_esm_shims();
8928
8979
 
8929
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
8980
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
8981
+ init_esm_shims();
8982
+
8983
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
8930
8984
  init_esm_shims();
8931
8985
 
8932
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
8986
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
8933
8987
  init_esm_shims();
8988
+ import * as z3rt from "zod/v3";
8989
+ import * as z4mini from "zod/v4-mini";
8990
+ function isZ4Schema(s) {
8991
+ const schema = s;
8992
+ return !!schema._zod;
8993
+ }
8994
+ function safeParse2(schema, data) {
8995
+ if (isZ4Schema(schema)) {
8996
+ const result2 = z4mini.safeParse(schema, data);
8997
+ return result2;
8998
+ }
8999
+ const v3Schema = schema;
9000
+ const result = v3Schema.safeParse(data);
9001
+ return result;
9002
+ }
9003
+ function getObjectShape(schema) {
9004
+ if (!schema)
9005
+ return void 0;
9006
+ let rawShape;
9007
+ if (isZ4Schema(schema)) {
9008
+ const v4Schema = schema;
9009
+ rawShape = v4Schema._zod?.def?.shape;
9010
+ } else {
9011
+ const v3Schema = schema;
9012
+ rawShape = v3Schema.shape;
9013
+ }
9014
+ if (!rawShape)
9015
+ return void 0;
9016
+ if (typeof rawShape === "function") {
9017
+ try {
9018
+ return rawShape();
9019
+ } catch {
9020
+ return void 0;
9021
+ }
9022
+ }
9023
+ return rawShape;
9024
+ }
9025
+ function getLiteralValue(schema) {
9026
+ if (isZ4Schema(schema)) {
9027
+ const v4Schema = schema;
9028
+ const def2 = v4Schema._zod?.def;
9029
+ if (def2) {
9030
+ if (def2.value !== void 0)
9031
+ return def2.value;
9032
+ if (Array.isArray(def2.values) && def2.values.length > 0) {
9033
+ return def2.values[0];
9034
+ }
9035
+ }
9036
+ }
9037
+ const v3Schema = schema;
9038
+ const def = v3Schema._def;
9039
+ if (def) {
9040
+ if (def.value !== void 0)
9041
+ return def.value;
9042
+ if (Array.isArray(def.values) && def.values.length > 0) {
9043
+ return def.values[0];
9044
+ }
9045
+ }
9046
+ const directValue = schema.value;
9047
+ if (directValue !== void 0)
9048
+ return directValue;
9049
+ return void 0;
9050
+ }
8934
9051
 
8935
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
9052
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
8936
9053
  init_esm_shims();
8937
- import { z as z2 } from "zod";
8938
- var LATEST_PROTOCOL_VERSION = "2025-06-18";
8939
- var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-03-26", "2024-11-05", "2024-10-07"];
9054
+ import * as z2 from "zod/v4";
9055
+ var LATEST_PROTOCOL_VERSION = "2025-11-25";
9056
+ var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
9057
+ var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
8940
9058
  var JSONRPC_VERSION = "2.0";
9059
+ var AssertObjectSchema = z2.custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
8941
9060
  var ProgressTokenSchema = z2.union([z2.string(), z2.number().int()]);
8942
9061
  var CursorSchema = z2.string();
8943
- var RequestMetaSchema = z2.object({
9062
+ var TaskCreationParamsSchema = z2.looseObject({
9063
+ /**
9064
+ * Time in milliseconds to keep task results available after completion.
9065
+ * If null, the task has unlimited lifetime until manually cleaned up.
9066
+ */
9067
+ ttl: z2.union([z2.number(), z2.null()]).optional(),
9068
+ /**
9069
+ * Time in milliseconds to wait between task status requests.
9070
+ */
9071
+ pollInterval: z2.number().optional()
9072
+ });
9073
+ var TaskMetadataSchema = z2.object({
9074
+ ttl: z2.number().optional()
9075
+ });
9076
+ var RelatedTaskMetadataSchema = z2.object({
9077
+ taskId: z2.string()
9078
+ });
9079
+ var RequestMetaSchema = z2.looseObject({
8944
9080
  /**
8945
9081
  * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
8946
9082
  */
8947
- progressToken: z2.optional(ProgressTokenSchema)
8948
- }).passthrough();
9083
+ progressToken: ProgressTokenSchema.optional(),
9084
+ /**
9085
+ * If specified, this request is related to the provided task.
9086
+ */
9087
+ [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
9088
+ });
8949
9089
  var BaseRequestParamsSchema = z2.object({
8950
- _meta: z2.optional(RequestMetaSchema)
8951
- }).passthrough();
9090
+ /**
9091
+ * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
9092
+ */
9093
+ _meta: RequestMetaSchema.optional()
9094
+ });
9095
+ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
9096
+ /**
9097
+ * If specified, the caller is requesting task-augmented execution for this request.
9098
+ * The request will return a CreateTaskResult immediately, and the actual result can be
9099
+ * retrieved later via tasks/result.
9100
+ *
9101
+ * Task augmentation is subject to capability negotiation - receivers MUST declare support
9102
+ * for task augmentation of specific request types in their capabilities.
9103
+ */
9104
+ task: TaskMetadataSchema.optional()
9105
+ });
9106
+ var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
8952
9107
  var RequestSchema = z2.object({
8953
9108
  method: z2.string(),
8954
- params: z2.optional(BaseRequestParamsSchema)
9109
+ params: BaseRequestParamsSchema.loose().optional()
8955
9110
  });
8956
- var BaseNotificationParamsSchema = z2.object({
9111
+ var NotificationsParamsSchema = z2.object({
8957
9112
  /**
8958
9113
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
8959
9114
  * for notes on _meta usage.
8960
9115
  */
8961
- _meta: z2.optional(z2.object({}).passthrough())
8962
- }).passthrough();
9116
+ _meta: RequestMetaSchema.optional()
9117
+ });
8963
9118
  var NotificationSchema = z2.object({
8964
9119
  method: z2.string(),
8965
- params: z2.optional(BaseNotificationParamsSchema)
9120
+ params: NotificationsParamsSchema.loose().optional()
8966
9121
  });
8967
- var ResultSchema = z2.object({
9122
+ var ResultSchema = z2.looseObject({
8968
9123
  /**
8969
9124
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
8970
9125
  * for notes on _meta usage.
8971
9126
  */
8972
- _meta: z2.optional(z2.object({}).passthrough())
8973
- }).passthrough();
9127
+ _meta: RequestMetaSchema.optional()
9128
+ });
8974
9129
  var RequestIdSchema = z2.union([z2.string(), z2.number().int()]);
8975
9130
  var JSONRPCRequestSchema = z2.object({
8976
9131
  jsonrpc: z2.literal(JSONRPC_VERSION),
8977
- id: RequestIdSchema
8978
- }).merge(RequestSchema).strict();
9132
+ id: RequestIdSchema,
9133
+ ...RequestSchema.shape
9134
+ }).strict();
8979
9135
  var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
8980
9136
  var JSONRPCNotificationSchema = z2.object({
8981
- jsonrpc: z2.literal(JSONRPC_VERSION)
8982
- }).merge(NotificationSchema).strict();
9137
+ jsonrpc: z2.literal(JSONRPC_VERSION),
9138
+ ...NotificationSchema.shape
9139
+ }).strict();
8983
9140
  var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
8984
- var JSONRPCResponseSchema = z2.object({
9141
+ var JSONRPCResultResponseSchema = z2.object({
8985
9142
  jsonrpc: z2.literal(JSONRPC_VERSION),
8986
9143
  id: RequestIdSchema,
8987
9144
  result: ResultSchema
8988
9145
  }).strict();
8989
- var isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success;
9146
+ var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
8990
9147
  var ErrorCode;
8991
9148
  (function(ErrorCode2) {
8992
9149
  ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
@@ -8996,10 +9153,11 @@ var ErrorCode;
8996
9153
  ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
8997
9154
  ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
8998
9155
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
9156
+ ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
8999
9157
  })(ErrorCode || (ErrorCode = {}));
9000
- var JSONRPCErrorSchema = z2.object({
9158
+ var JSONRPCErrorResponseSchema = z2.object({
9001
9159
  jsonrpc: z2.literal(JSONRPC_VERSION),
9002
- id: RequestIdSchema,
9160
+ id: RequestIdSchema.optional(),
9003
9161
  error: z2.object({
9004
9162
  /**
9005
9163
  * The error type that occurred.
@@ -9012,26 +9170,33 @@ var JSONRPCErrorSchema = z2.object({
9012
9170
  /**
9013
9171
  * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
9014
9172
  */
9015
- data: z2.optional(z2.unknown())
9173
+ data: z2.unknown().optional()
9016
9174
  })
9017
9175
  }).strict();
9018
- var isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
9019
- var JSONRPCMessageSchema = z2.union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]);
9176
+ var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
9177
+ var JSONRPCMessageSchema = z2.union([
9178
+ JSONRPCRequestSchema,
9179
+ JSONRPCNotificationSchema,
9180
+ JSONRPCResultResponseSchema,
9181
+ JSONRPCErrorResponseSchema
9182
+ ]);
9183
+ var JSONRPCResponseSchema = z2.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
9020
9184
  var EmptyResultSchema = ResultSchema.strict();
9185
+ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
9186
+ /**
9187
+ * The ID of the request to cancel.
9188
+ *
9189
+ * This MUST correspond to the ID of a request previously issued in the same direction.
9190
+ */
9191
+ requestId: RequestIdSchema.optional(),
9192
+ /**
9193
+ * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
9194
+ */
9195
+ reason: z2.string().optional()
9196
+ });
9021
9197
  var CancelledNotificationSchema = NotificationSchema.extend({
9022
9198
  method: z2.literal("notifications/cancelled"),
9023
- params: BaseNotificationParamsSchema.extend({
9024
- /**
9025
- * The ID of the request to cancel.
9026
- *
9027
- * This MUST correspond to the ID of a request previously issued in the same direction.
9028
- */
9029
- requestId: RequestIdSchema,
9030
- /**
9031
- * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
9032
- */
9033
- reason: z2.string().optional()
9034
- })
9199
+ params: CancelledNotificationParamsSchema
9035
9200
  });
9036
9201
  var IconSchema = z2.object({
9037
9202
  /**
@@ -9041,15 +9206,23 @@ var IconSchema = z2.object({
9041
9206
  /**
9042
9207
  * Optional MIME type for the icon.
9043
9208
  */
9044
- mimeType: z2.optional(z2.string()),
9209
+ mimeType: z2.string().optional(),
9045
9210
  /**
9046
9211
  * Optional array of strings that specify sizes at which the icon can be used.
9047
9212
  * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
9048
9213
  *
9049
9214
  * If not provided, the client should assume that the icon can be used at any size.
9050
9215
  */
9051
- sizes: z2.optional(z2.array(z2.string()))
9052
- }).passthrough();
9216
+ sizes: z2.array(z2.string()).optional(),
9217
+ /**
9218
+ * Optional specifier for the theme this icon is designed for. `light` indicates
9219
+ * the icon is designed to be used with a light background, and `dark` indicates
9220
+ * the icon is designed to be used with a dark background.
9221
+ *
9222
+ * If not provided, the client should assume the icon can be used with any theme.
9223
+ */
9224
+ theme: z2.enum(["light", "dark"]).optional()
9225
+ });
9053
9226
  var IconsSchema = z2.object({
9054
9227
  /**
9055
9228
  * Optional set of sized icons that the client can display in a user interface.
@@ -9063,7 +9236,7 @@ var IconsSchema = z2.object({
9063
9236
  * - `image/webp` - WebP images (modern, efficient format)
9064
9237
  */
9065
9238
  icons: z2.array(IconSchema).optional()
9066
- }).passthrough();
9239
+ });
9067
9240
  var BaseMetadataSchema = z2.object({
9068
9241
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
9069
9242
  name: z2.string(),
@@ -9075,94 +9248,185 @@ var BaseMetadataSchema = z2.object({
9075
9248
  * where `annotations.title` should be given precedence over using `name`,
9076
9249
  * if present).
9077
9250
  */
9078
- title: z2.optional(z2.string())
9079
- }).passthrough();
9251
+ title: z2.string().optional()
9252
+ });
9080
9253
  var ImplementationSchema = BaseMetadataSchema.extend({
9254
+ ...BaseMetadataSchema.shape,
9255
+ ...IconsSchema.shape,
9081
9256
  version: z2.string(),
9082
9257
  /**
9083
9258
  * An optional URL of the website for this implementation.
9084
9259
  */
9085
- websiteUrl: z2.optional(z2.string())
9086
- }).merge(IconsSchema);
9260
+ websiteUrl: z2.string().optional(),
9261
+ /**
9262
+ * An optional human-readable description of what this implementation does.
9263
+ *
9264
+ * This can be used by clients or servers to provide context about their purpose
9265
+ * and capabilities. For example, a server might describe the types of resources
9266
+ * or tools it provides, while a client might describe its intended use case.
9267
+ */
9268
+ description: z2.string().optional()
9269
+ });
9270
+ var FormElicitationCapabilitySchema = z2.intersection(z2.object({
9271
+ applyDefaults: z2.boolean().optional()
9272
+ }), z2.record(z2.string(), z2.unknown()));
9273
+ var ElicitationCapabilitySchema = z2.preprocess((value) => {
9274
+ if (value && typeof value === "object" && !Array.isArray(value)) {
9275
+ if (Object.keys(value).length === 0) {
9276
+ return { form: {} };
9277
+ }
9278
+ }
9279
+ return value;
9280
+ }, z2.intersection(z2.object({
9281
+ form: FormElicitationCapabilitySchema.optional(),
9282
+ url: AssertObjectSchema.optional()
9283
+ }), z2.record(z2.string(), z2.unknown()).optional()));
9284
+ var ClientTasksCapabilitySchema = z2.looseObject({
9285
+ /**
9286
+ * Present if the client supports listing tasks.
9287
+ */
9288
+ list: AssertObjectSchema.optional(),
9289
+ /**
9290
+ * Present if the client supports cancelling tasks.
9291
+ */
9292
+ cancel: AssertObjectSchema.optional(),
9293
+ /**
9294
+ * Capabilities for task creation on specific request types.
9295
+ */
9296
+ requests: z2.looseObject({
9297
+ /**
9298
+ * Task support for sampling requests.
9299
+ */
9300
+ sampling: z2.looseObject({
9301
+ createMessage: AssertObjectSchema.optional()
9302
+ }).optional(),
9303
+ /**
9304
+ * Task support for elicitation requests.
9305
+ */
9306
+ elicitation: z2.looseObject({
9307
+ create: AssertObjectSchema.optional()
9308
+ }).optional()
9309
+ }).optional()
9310
+ });
9311
+ var ServerTasksCapabilitySchema = z2.looseObject({
9312
+ /**
9313
+ * Present if the server supports listing tasks.
9314
+ */
9315
+ list: AssertObjectSchema.optional(),
9316
+ /**
9317
+ * Present if the server supports cancelling tasks.
9318
+ */
9319
+ cancel: AssertObjectSchema.optional(),
9320
+ /**
9321
+ * Capabilities for task creation on specific request types.
9322
+ */
9323
+ requests: z2.looseObject({
9324
+ /**
9325
+ * Task support for tool requests.
9326
+ */
9327
+ tools: z2.looseObject({
9328
+ call: AssertObjectSchema.optional()
9329
+ }).optional()
9330
+ }).optional()
9331
+ });
9087
9332
  var ClientCapabilitiesSchema = z2.object({
9088
9333
  /**
9089
9334
  * Experimental, non-standard capabilities that the client supports.
9090
9335
  */
9091
- experimental: z2.optional(z2.object({}).passthrough()),
9336
+ experimental: z2.record(z2.string(), AssertObjectSchema).optional(),
9092
9337
  /**
9093
9338
  * Present if the client supports sampling from an LLM.
9094
9339
  */
9095
- sampling: z2.optional(z2.object({}).passthrough()),
9340
+ sampling: z2.object({
9341
+ /**
9342
+ * Present if the client supports context inclusion via includeContext parameter.
9343
+ * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
9344
+ */
9345
+ context: AssertObjectSchema.optional(),
9346
+ /**
9347
+ * Present if the client supports tool use via tools and toolChoice parameters.
9348
+ */
9349
+ tools: AssertObjectSchema.optional()
9350
+ }).optional(),
9096
9351
  /**
9097
9352
  * Present if the client supports eliciting user input.
9098
9353
  */
9099
- elicitation: z2.optional(z2.object({}).passthrough()),
9354
+ elicitation: ElicitationCapabilitySchema.optional(),
9100
9355
  /**
9101
9356
  * Present if the client supports listing roots.
9102
9357
  */
9103
- roots: z2.optional(z2.object({
9358
+ roots: z2.object({
9104
9359
  /**
9105
9360
  * Whether the client supports issuing notifications for changes to the roots list.
9106
9361
  */
9107
- listChanged: z2.optional(z2.boolean())
9108
- }).passthrough())
9109
- }).passthrough();
9362
+ listChanged: z2.boolean().optional()
9363
+ }).optional(),
9364
+ /**
9365
+ * Present if the client supports task creation.
9366
+ */
9367
+ tasks: ClientTasksCapabilitySchema.optional()
9368
+ });
9369
+ var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
9370
+ /**
9371
+ * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
9372
+ */
9373
+ protocolVersion: z2.string(),
9374
+ capabilities: ClientCapabilitiesSchema,
9375
+ clientInfo: ImplementationSchema
9376
+ });
9110
9377
  var InitializeRequestSchema = RequestSchema.extend({
9111
9378
  method: z2.literal("initialize"),
9112
- params: BaseRequestParamsSchema.extend({
9113
- /**
9114
- * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
9115
- */
9116
- protocolVersion: z2.string(),
9117
- capabilities: ClientCapabilitiesSchema,
9118
- clientInfo: ImplementationSchema
9119
- })
9379
+ params: InitializeRequestParamsSchema
9120
9380
  });
9121
9381
  var ServerCapabilitiesSchema = z2.object({
9122
9382
  /**
9123
9383
  * Experimental, non-standard capabilities that the server supports.
9124
9384
  */
9125
- experimental: z2.optional(z2.object({}).passthrough()),
9385
+ experimental: z2.record(z2.string(), AssertObjectSchema).optional(),
9126
9386
  /**
9127
9387
  * Present if the server supports sending log messages to the client.
9128
9388
  */
9129
- logging: z2.optional(z2.object({}).passthrough()),
9389
+ logging: AssertObjectSchema.optional(),
9130
9390
  /**
9131
9391
  * Present if the server supports sending completions to the client.
9132
9392
  */
9133
- completions: z2.optional(z2.object({}).passthrough()),
9393
+ completions: AssertObjectSchema.optional(),
9134
9394
  /**
9135
9395
  * Present if the server offers any prompt templates.
9136
9396
  */
9137
- prompts: z2.optional(z2.object({
9397
+ prompts: z2.object({
9138
9398
  /**
9139
9399
  * Whether this server supports issuing notifications for changes to the prompt list.
9140
9400
  */
9141
- listChanged: z2.optional(z2.boolean())
9142
- }).passthrough()),
9401
+ listChanged: z2.boolean().optional()
9402
+ }).optional(),
9143
9403
  /**
9144
9404
  * Present if the server offers any resources to read.
9145
9405
  */
9146
- resources: z2.optional(z2.object({
9406
+ resources: z2.object({
9147
9407
  /**
9148
9408
  * Whether this server supports clients subscribing to resource updates.
9149
9409
  */
9150
- subscribe: z2.optional(z2.boolean()),
9410
+ subscribe: z2.boolean().optional(),
9151
9411
  /**
9152
9412
  * Whether this server supports issuing notifications for changes to the resource list.
9153
9413
  */
9154
- listChanged: z2.optional(z2.boolean())
9155
- }).passthrough()),
9414
+ listChanged: z2.boolean().optional()
9415
+ }).optional(),
9156
9416
  /**
9157
9417
  * Present if the server offers any tools to call.
9158
9418
  */
9159
- tools: z2.optional(z2.object({
9419
+ tools: z2.object({
9160
9420
  /**
9161
9421
  * Whether this server supports issuing notifications for changes to the tool list.
9162
9422
  */
9163
- listChanged: z2.optional(z2.boolean())
9164
- }).passthrough())
9165
- }).passthrough();
9423
+ listChanged: z2.boolean().optional()
9424
+ }).optional(),
9425
+ /**
9426
+ * Present if the server supports task creation.
9427
+ */
9428
+ tasks: ServerTasksCapabilitySchema.optional()
9429
+ });
9166
9430
  var InitializeResultSchema = ResultSchema.extend({
9167
9431
  /**
9168
9432
  * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
@@ -9175,13 +9439,15 @@ var InitializeResultSchema = ResultSchema.extend({
9175
9439
  *
9176
9440
  * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
9177
9441
  */
9178
- instructions: z2.optional(z2.string())
9442
+ instructions: z2.string().optional()
9179
9443
  });
9180
9444
  var InitializedNotificationSchema = NotificationSchema.extend({
9181
- method: z2.literal("notifications/initialized")
9445
+ method: z2.literal("notifications/initialized"),
9446
+ params: NotificationsParamsSchema.optional()
9182
9447
  });
9183
9448
  var PingRequestSchema = RequestSchema.extend({
9184
- method: z2.literal("ping")
9449
+ method: z2.literal("ping"),
9450
+ params: BaseRequestParamsSchema.optional()
9185
9451
  });
9186
9452
  var ProgressSchema = z2.object({
9187
9453
  /**
@@ -9196,32 +9462,94 @@ var ProgressSchema = z2.object({
9196
9462
  * An optional message describing the current progress.
9197
9463
  */
9198
9464
  message: z2.optional(z2.string())
9199
- }).passthrough();
9465
+ });
9466
+ var ProgressNotificationParamsSchema = z2.object({
9467
+ ...NotificationsParamsSchema.shape,
9468
+ ...ProgressSchema.shape,
9469
+ /**
9470
+ * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
9471
+ */
9472
+ progressToken: ProgressTokenSchema
9473
+ });
9200
9474
  var ProgressNotificationSchema = NotificationSchema.extend({
9201
9475
  method: z2.literal("notifications/progress"),
9202
- params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
9203
- /**
9204
- * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
9205
- */
9206
- progressToken: ProgressTokenSchema
9207
- })
9476
+ params: ProgressNotificationParamsSchema
9477
+ });
9478
+ var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
9479
+ /**
9480
+ * An opaque token representing the current pagination position.
9481
+ * If provided, the server should return results starting after this cursor.
9482
+ */
9483
+ cursor: CursorSchema.optional()
9208
9484
  });
9209
9485
  var PaginatedRequestSchema = RequestSchema.extend({
9210
- params: BaseRequestParamsSchema.extend({
9211
- /**
9212
- * An opaque token representing the current pagination position.
9213
- * If provided, the server should return results starting after this cursor.
9214
- */
9215
- cursor: z2.optional(CursorSchema)
9216
- }).optional()
9486
+ params: PaginatedRequestParamsSchema.optional()
9217
9487
  });
9218
9488
  var PaginatedResultSchema = ResultSchema.extend({
9219
9489
  /**
9220
9490
  * An opaque token representing the pagination position after the last returned result.
9221
9491
  * If present, there may be more results available.
9222
9492
  */
9223
- nextCursor: z2.optional(CursorSchema)
9493
+ nextCursor: CursorSchema.optional()
9494
+ });
9495
+ var TaskStatusSchema = z2.enum(["working", "input_required", "completed", "failed", "cancelled"]);
9496
+ var TaskSchema = z2.object({
9497
+ taskId: z2.string(),
9498
+ status: TaskStatusSchema,
9499
+ /**
9500
+ * Time in milliseconds to keep task results available after completion.
9501
+ * If null, the task has unlimited lifetime until manually cleaned up.
9502
+ */
9503
+ ttl: z2.union([z2.number(), z2.null()]),
9504
+ /**
9505
+ * ISO 8601 timestamp when the task was created.
9506
+ */
9507
+ createdAt: z2.string(),
9508
+ /**
9509
+ * ISO 8601 timestamp when the task was last updated.
9510
+ */
9511
+ lastUpdatedAt: z2.string(),
9512
+ pollInterval: z2.optional(z2.number()),
9513
+ /**
9514
+ * Optional diagnostic message for failed tasks or other status information.
9515
+ */
9516
+ statusMessage: z2.optional(z2.string())
9517
+ });
9518
+ var CreateTaskResultSchema = ResultSchema.extend({
9519
+ task: TaskSchema
9520
+ });
9521
+ var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
9522
+ var TaskStatusNotificationSchema = NotificationSchema.extend({
9523
+ method: z2.literal("notifications/tasks/status"),
9524
+ params: TaskStatusNotificationParamsSchema
9525
+ });
9526
+ var GetTaskRequestSchema = RequestSchema.extend({
9527
+ method: z2.literal("tasks/get"),
9528
+ params: BaseRequestParamsSchema.extend({
9529
+ taskId: z2.string()
9530
+ })
9531
+ });
9532
+ var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
9533
+ var GetTaskPayloadRequestSchema = RequestSchema.extend({
9534
+ method: z2.literal("tasks/result"),
9535
+ params: BaseRequestParamsSchema.extend({
9536
+ taskId: z2.string()
9537
+ })
9538
+ });
9539
+ var GetTaskPayloadResultSchema = ResultSchema.loose();
9540
+ var ListTasksRequestSchema = PaginatedRequestSchema.extend({
9541
+ method: z2.literal("tasks/list")
9542
+ });
9543
+ var ListTasksResultSchema = PaginatedResultSchema.extend({
9544
+ tasks: z2.array(TaskSchema)
9224
9545
  });
9546
+ var CancelTaskRequestSchema = RequestSchema.extend({
9547
+ method: z2.literal("tasks/cancel"),
9548
+ params: BaseRequestParamsSchema.extend({
9549
+ taskId: z2.string()
9550
+ })
9551
+ });
9552
+ var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
9225
9553
  var ResourceContentsSchema = z2.object({
9226
9554
  /**
9227
9555
  * The URI of this resource.
@@ -9235,8 +9563,8 @@ var ResourceContentsSchema = z2.object({
9235
9563
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9236
9564
  * for notes on _meta usage.
9237
9565
  */
9238
- _meta: z2.optional(z2.object({}).passthrough())
9239
- }).passthrough();
9566
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9567
+ });
9240
9568
  var TextResourceContentsSchema = ResourceContentsSchema.extend({
9241
9569
  /**
9242
9570
  * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
@@ -9247,7 +9575,7 @@ var Base64Schema = z2.string().refine((val) => {
9247
9575
  try {
9248
9576
  atob(val);
9249
9577
  return true;
9250
- } catch (_a) {
9578
+ } catch {
9251
9579
  return false;
9252
9580
  }
9253
9581
  }, { message: "Invalid Base64 string" });
@@ -9257,7 +9585,24 @@ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
9257
9585
  */
9258
9586
  blob: Base64Schema
9259
9587
  });
9260
- var ResourceSchema = BaseMetadataSchema.extend({
9588
+ var RoleSchema = z2.enum(["user", "assistant"]);
9589
+ var AnnotationsSchema = z2.object({
9590
+ /**
9591
+ * Intended audience(s) for the resource.
9592
+ */
9593
+ audience: z2.array(RoleSchema).optional(),
9594
+ /**
9595
+ * Importance hint for the resource, from 0 (least) to 1 (most).
9596
+ */
9597
+ priority: z2.number().min(0).max(1).optional(),
9598
+ /**
9599
+ * ISO 8601 timestamp for the most recent modification.
9600
+ */
9601
+ lastModified: z2.iso.datetime({ offset: true }).optional()
9602
+ });
9603
+ var ResourceSchema = z2.object({
9604
+ ...BaseMetadataSchema.shape,
9605
+ ...IconsSchema.shape,
9261
9606
  /**
9262
9607
  * The URI of this resource.
9263
9608
  */
@@ -9272,13 +9617,19 @@ var ResourceSchema = BaseMetadataSchema.extend({
9272
9617
  * The MIME type of this resource, if known.
9273
9618
  */
9274
9619
  mimeType: z2.optional(z2.string()),
9620
+ /**
9621
+ * Optional annotations for the client.
9622
+ */
9623
+ annotations: AnnotationsSchema.optional(),
9275
9624
  /**
9276
9625
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9277
9626
  * for notes on _meta usage.
9278
9627
  */
9279
- _meta: z2.optional(z2.object({}).passthrough())
9280
- }).merge(IconsSchema);
9281
- var ResourceTemplateSchema = BaseMetadataSchema.extend({
9628
+ _meta: z2.optional(z2.looseObject({}))
9629
+ });
9630
+ var ResourceTemplateSchema = z2.object({
9631
+ ...BaseMetadataSchema.shape,
9632
+ ...IconsSchema.shape,
9282
9633
  /**
9283
9634
  * A URI template (according to RFC 6570) that can be used to construct resource URIs.
9284
9635
  */
@@ -9293,12 +9644,16 @@ var ResourceTemplateSchema = BaseMetadataSchema.extend({
9293
9644
  * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
9294
9645
  */
9295
9646
  mimeType: z2.optional(z2.string()),
9647
+ /**
9648
+ * Optional annotations for the client.
9649
+ */
9650
+ annotations: AnnotationsSchema.optional(),
9296
9651
  /**
9297
9652
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9298
9653
  * for notes on _meta usage.
9299
9654
  */
9300
- _meta: z2.optional(z2.object({}).passthrough())
9301
- }).merge(IconsSchema);
9655
+ _meta: z2.optional(z2.looseObject({}))
9656
+ });
9302
9657
  var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
9303
9658
  method: z2.literal("resources/list")
9304
9659
  });
@@ -9311,47 +9666,45 @@ var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
9311
9666
  var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
9312
9667
  resourceTemplates: z2.array(ResourceTemplateSchema)
9313
9668
  });
9669
+ var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
9670
+ /**
9671
+ * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
9672
+ *
9673
+ * @format uri
9674
+ */
9675
+ uri: z2.string()
9676
+ });
9677
+ var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
9314
9678
  var ReadResourceRequestSchema = RequestSchema.extend({
9315
9679
  method: z2.literal("resources/read"),
9316
- params: BaseRequestParamsSchema.extend({
9317
- /**
9318
- * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
9319
- */
9320
- uri: z2.string()
9321
- })
9680
+ params: ReadResourceRequestParamsSchema
9322
9681
  });
9323
9682
  var ReadResourceResultSchema = ResultSchema.extend({
9324
9683
  contents: z2.array(z2.union([TextResourceContentsSchema, BlobResourceContentsSchema]))
9325
9684
  });
9326
9685
  var ResourceListChangedNotificationSchema = NotificationSchema.extend({
9327
- method: z2.literal("notifications/resources/list_changed")
9686
+ method: z2.literal("notifications/resources/list_changed"),
9687
+ params: NotificationsParamsSchema.optional()
9328
9688
  });
9689
+ var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
9329
9690
  var SubscribeRequestSchema = RequestSchema.extend({
9330
9691
  method: z2.literal("resources/subscribe"),
9331
- params: BaseRequestParamsSchema.extend({
9332
- /**
9333
- * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it.
9334
- */
9335
- uri: z2.string()
9336
- })
9692
+ params: SubscribeRequestParamsSchema
9337
9693
  });
9694
+ var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
9338
9695
  var UnsubscribeRequestSchema = RequestSchema.extend({
9339
9696
  method: z2.literal("resources/unsubscribe"),
9340
- params: BaseRequestParamsSchema.extend({
9341
- /**
9342
- * The URI of the resource to unsubscribe from.
9343
- */
9344
- uri: z2.string()
9345
- })
9697
+ params: UnsubscribeRequestParamsSchema
9698
+ });
9699
+ var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
9700
+ /**
9701
+ * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
9702
+ */
9703
+ uri: z2.string()
9346
9704
  });
9347
9705
  var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
9348
9706
  method: z2.literal("notifications/resources/updated"),
9349
- params: BaseNotificationParamsSchema.extend({
9350
- /**
9351
- * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
9352
- */
9353
- uri: z2.string()
9354
- })
9707
+ params: ResourceUpdatedNotificationParamsSchema
9355
9708
  });
9356
9709
  var PromptArgumentSchema = z2.object({
9357
9710
  /**
@@ -9366,8 +9719,10 @@ var PromptArgumentSchema = z2.object({
9366
9719
  * Whether this argument must be provided.
9367
9720
  */
9368
9721
  required: z2.optional(z2.boolean())
9369
- }).passthrough();
9370
- var PromptSchema = BaseMetadataSchema.extend({
9722
+ });
9723
+ var PromptSchema = z2.object({
9724
+ ...BaseMetadataSchema.shape,
9725
+ ...IconsSchema.shape,
9371
9726
  /**
9372
9727
  * An optional description of what this prompt provides
9373
9728
  */
@@ -9380,26 +9735,27 @@ var PromptSchema = BaseMetadataSchema.extend({
9380
9735
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9381
9736
  * for notes on _meta usage.
9382
9737
  */
9383
- _meta: z2.optional(z2.object({}).passthrough())
9384
- }).merge(IconsSchema);
9738
+ _meta: z2.optional(z2.looseObject({}))
9739
+ });
9385
9740
  var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
9386
9741
  method: z2.literal("prompts/list")
9387
9742
  });
9388
9743
  var ListPromptsResultSchema = PaginatedResultSchema.extend({
9389
9744
  prompts: z2.array(PromptSchema)
9390
9745
  });
9746
+ var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
9747
+ /**
9748
+ * The name of the prompt or prompt template.
9749
+ */
9750
+ name: z2.string(),
9751
+ /**
9752
+ * Arguments to use for templating the prompt.
9753
+ */
9754
+ arguments: z2.record(z2.string(), z2.string()).optional()
9755
+ });
9391
9756
  var GetPromptRequestSchema = RequestSchema.extend({
9392
9757
  method: z2.literal("prompts/get"),
9393
- params: BaseRequestParamsSchema.extend({
9394
- /**
9395
- * The name of the prompt or prompt template.
9396
- */
9397
- name: z2.string(),
9398
- /**
9399
- * Arguments to use for templating the prompt.
9400
- */
9401
- arguments: z2.optional(z2.record(z2.string()))
9402
- })
9758
+ params: GetPromptRequestParamsSchema
9403
9759
  });
9404
9760
  var TextContentSchema = z2.object({
9405
9761
  type: z2.literal("text"),
@@ -9407,12 +9763,16 @@ var TextContentSchema = z2.object({
9407
9763
  * The text content of the message.
9408
9764
  */
9409
9765
  text: z2.string(),
9766
+ /**
9767
+ * Optional annotations for the client.
9768
+ */
9769
+ annotations: AnnotationsSchema.optional(),
9410
9770
  /**
9411
9771
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9412
9772
  * for notes on _meta usage.
9413
9773
  */
9414
- _meta: z2.optional(z2.object({}).passthrough())
9415
- }).passthrough();
9774
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9775
+ });
9416
9776
  var ImageContentSchema = z2.object({
9417
9777
  type: z2.literal("image"),
9418
9778
  /**
@@ -9423,12 +9783,16 @@ var ImageContentSchema = z2.object({
9423
9783
  * The MIME type of the image. Different providers may support different image types.
9424
9784
  */
9425
9785
  mimeType: z2.string(),
9786
+ /**
9787
+ * Optional annotations for the client.
9788
+ */
9789
+ annotations: AnnotationsSchema.optional(),
9426
9790
  /**
9427
9791
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9428
9792
  * for notes on _meta usage.
9429
9793
  */
9430
- _meta: z2.optional(z2.object({}).passthrough())
9431
- }).passthrough();
9794
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9795
+ });
9432
9796
  var AudioContentSchema = z2.object({
9433
9797
  type: z2.literal("audio"),
9434
9798
  /**
@@ -9439,21 +9803,52 @@ var AudioContentSchema = z2.object({
9439
9803
  * The MIME type of the audio. Different providers may support different audio types.
9440
9804
  */
9441
9805
  mimeType: z2.string(),
9806
+ /**
9807
+ * Optional annotations for the client.
9808
+ */
9809
+ annotations: AnnotationsSchema.optional(),
9810
+ /**
9811
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9812
+ * for notes on _meta usage.
9813
+ */
9814
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9815
+ });
9816
+ var ToolUseContentSchema = z2.object({
9817
+ type: z2.literal("tool_use"),
9818
+ /**
9819
+ * The name of the tool to invoke.
9820
+ * Must match a tool name from the request's tools array.
9821
+ */
9822
+ name: z2.string(),
9823
+ /**
9824
+ * Unique identifier for this tool call.
9825
+ * Used to correlate with ToolResultContent in subsequent messages.
9826
+ */
9827
+ id: z2.string(),
9828
+ /**
9829
+ * Arguments to pass to the tool.
9830
+ * Must conform to the tool's inputSchema.
9831
+ */
9832
+ input: z2.record(z2.string(), z2.unknown()),
9442
9833
  /**
9443
9834
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9444
9835
  * for notes on _meta usage.
9445
9836
  */
9446
- _meta: z2.optional(z2.object({}).passthrough())
9447
- }).passthrough();
9837
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9838
+ });
9448
9839
  var EmbeddedResourceSchema = z2.object({
9449
9840
  type: z2.literal("resource"),
9450
9841
  resource: z2.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
9842
+ /**
9843
+ * Optional annotations for the client.
9844
+ */
9845
+ annotations: AnnotationsSchema.optional(),
9451
9846
  /**
9452
9847
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9453
9848
  * for notes on _meta usage.
9454
9849
  */
9455
- _meta: z2.optional(z2.object({}).passthrough())
9456
- }).passthrough();
9850
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9851
+ });
9457
9852
  var ResourceLinkSchema = ResourceSchema.extend({
9458
9853
  type: z2.literal("resource_link")
9459
9854
  });
@@ -9465,30 +9860,31 @@ var ContentBlockSchema = z2.union([
9465
9860
  EmbeddedResourceSchema
9466
9861
  ]);
9467
9862
  var PromptMessageSchema = z2.object({
9468
- role: z2.enum(["user", "assistant"]),
9863
+ role: RoleSchema,
9469
9864
  content: ContentBlockSchema
9470
- }).passthrough();
9865
+ });
9471
9866
  var GetPromptResultSchema = ResultSchema.extend({
9472
9867
  /**
9473
9868
  * An optional description for the prompt.
9474
9869
  */
9475
- description: z2.optional(z2.string()),
9870
+ description: z2.string().optional(),
9476
9871
  messages: z2.array(PromptMessageSchema)
9477
9872
  });
9478
9873
  var PromptListChangedNotificationSchema = NotificationSchema.extend({
9479
- method: z2.literal("notifications/prompts/list_changed")
9874
+ method: z2.literal("notifications/prompts/list_changed"),
9875
+ params: NotificationsParamsSchema.optional()
9480
9876
  });
9481
9877
  var ToolAnnotationsSchema = z2.object({
9482
9878
  /**
9483
9879
  * A human-readable title for the tool.
9484
9880
  */
9485
- title: z2.optional(z2.string()),
9881
+ title: z2.string().optional(),
9486
9882
  /**
9487
9883
  * If true, the tool does not modify its environment.
9488
9884
  *
9489
9885
  * Default: false
9490
9886
  */
9491
- readOnlyHint: z2.optional(z2.boolean()),
9887
+ readOnlyHint: z2.boolean().optional(),
9492
9888
  /**
9493
9889
  * If true, the tool may perform destructive updates to its environment.
9494
9890
  * If false, the tool performs only additive updates.
@@ -9497,7 +9893,7 @@ var ToolAnnotationsSchema = z2.object({
9497
9893
  *
9498
9894
  * Default: true
9499
9895
  */
9500
- destructiveHint: z2.optional(z2.boolean()),
9896
+ destructiveHint: z2.boolean().optional(),
9501
9897
  /**
9502
9898
  * If true, calling the tool repeatedly with the same arguments
9503
9899
  * will have no additional effect on the its environment.
@@ -9506,7 +9902,7 @@ var ToolAnnotationsSchema = z2.object({
9506
9902
  *
9507
9903
  * Default: false
9508
9904
  */
9509
- idempotentHint: z2.optional(z2.boolean()),
9905
+ idempotentHint: z2.boolean().optional(),
9510
9906
  /**
9511
9907
  * If true, this tool may interact with an "open world" of external
9512
9908
  * entities. If false, the tool's domain of interaction is closed.
@@ -9515,40 +9911,59 @@ var ToolAnnotationsSchema = z2.object({
9515
9911
  *
9516
9912
  * Default: true
9517
9913
  */
9518
- openWorldHint: z2.optional(z2.boolean())
9519
- }).passthrough();
9520
- var ToolSchema = BaseMetadataSchema.extend({
9914
+ openWorldHint: z2.boolean().optional()
9915
+ });
9916
+ var ToolExecutionSchema = z2.object({
9917
+ /**
9918
+ * Indicates the tool's preference for task-augmented execution.
9919
+ * - "required": Clients MUST invoke the tool as a task
9920
+ * - "optional": Clients MAY invoke the tool as a task or normal request
9921
+ * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
9922
+ *
9923
+ * If not present, defaults to "forbidden".
9924
+ */
9925
+ taskSupport: z2.enum(["required", "optional", "forbidden"]).optional()
9926
+ });
9927
+ var ToolSchema = z2.object({
9928
+ ...BaseMetadataSchema.shape,
9929
+ ...IconsSchema.shape,
9521
9930
  /**
9522
9931
  * A human-readable description of the tool.
9523
9932
  */
9524
- description: z2.optional(z2.string()),
9933
+ description: z2.string().optional(),
9525
9934
  /**
9526
- * A JSON Schema object defining the expected parameters for the tool.
9935
+ * A JSON Schema 2020-12 object defining the expected parameters for the tool.
9936
+ * Must have type: 'object' at the root level per MCP spec.
9527
9937
  */
9528
9938
  inputSchema: z2.object({
9529
9939
  type: z2.literal("object"),
9530
- properties: z2.optional(z2.object({}).passthrough()),
9531
- required: z2.optional(z2.array(z2.string()))
9532
- }).passthrough(),
9940
+ properties: z2.record(z2.string(), AssertObjectSchema).optional(),
9941
+ required: z2.array(z2.string()).optional()
9942
+ }).catchall(z2.unknown()),
9533
9943
  /**
9534
- * An optional JSON Schema object defining the structure of the tool's output returned in
9535
- * the structuredContent field of a CallToolResult.
9944
+ * An optional JSON Schema 2020-12 object defining the structure of the tool's output
9945
+ * returned in the structuredContent field of a CallToolResult.
9946
+ * Must have type: 'object' at the root level per MCP spec.
9536
9947
  */
9537
- outputSchema: z2.optional(z2.object({
9948
+ outputSchema: z2.object({
9538
9949
  type: z2.literal("object"),
9539
- properties: z2.optional(z2.object({}).passthrough()),
9540
- required: z2.optional(z2.array(z2.string()))
9541
- }).passthrough()),
9950
+ properties: z2.record(z2.string(), AssertObjectSchema).optional(),
9951
+ required: z2.array(z2.string()).optional()
9952
+ }).catchall(z2.unknown()).optional(),
9542
9953
  /**
9543
9954
  * Optional additional tool information.
9544
9955
  */
9545
- annotations: z2.optional(ToolAnnotationsSchema),
9956
+ annotations: ToolAnnotationsSchema.optional(),
9957
+ /**
9958
+ * Execution-related properties for this tool.
9959
+ */
9960
+ execution: ToolExecutionSchema.optional(),
9546
9961
  /**
9547
9962
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9548
9963
  * for notes on _meta usage.
9549
9964
  */
9550
- _meta: z2.optional(z2.object({}).passthrough())
9551
- }).merge(IconsSchema);
9965
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
9966
+ });
9552
9967
  var ListToolsRequestSchema = PaginatedRequestSchema.extend({
9553
9968
  method: z2.literal("tools/list")
9554
9969
  });
@@ -9568,7 +9983,7 @@ var CallToolResultSchema = ResultSchema.extend({
9568
9983
  *
9569
9984
  * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
9570
9985
  */
9571
- structuredContent: z2.object({}).passthrough().optional(),
9986
+ structuredContent: z2.record(z2.string(), z2.unknown()).optional(),
9572
9987
  /**
9573
9988
  * Whether the tool call ended in an error.
9574
9989
  *
@@ -9583,103 +9998,185 @@ var CallToolResultSchema = ResultSchema.extend({
9583
9998
  * server does not support tool calls, or any other exceptional conditions,
9584
9999
  * should be reported as an MCP error response.
9585
10000
  */
9586
- isError: z2.optional(z2.boolean())
10001
+ isError: z2.boolean().optional()
9587
10002
  });
9588
10003
  var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
9589
10004
  toolResult: z2.unknown()
9590
10005
  }));
10006
+ var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
10007
+ /**
10008
+ * The name of the tool to call.
10009
+ */
10010
+ name: z2.string(),
10011
+ /**
10012
+ * Arguments to pass to the tool.
10013
+ */
10014
+ arguments: z2.record(z2.string(), z2.unknown()).optional()
10015
+ });
9591
10016
  var CallToolRequestSchema = RequestSchema.extend({
9592
10017
  method: z2.literal("tools/call"),
9593
- params: BaseRequestParamsSchema.extend({
9594
- name: z2.string(),
9595
- arguments: z2.optional(z2.record(z2.unknown()))
9596
- })
10018
+ params: CallToolRequestParamsSchema
9597
10019
  });
9598
10020
  var ToolListChangedNotificationSchema = NotificationSchema.extend({
9599
- method: z2.literal("notifications/tools/list_changed")
10021
+ method: z2.literal("notifications/tools/list_changed"),
10022
+ params: NotificationsParamsSchema.optional()
10023
+ });
10024
+ var ListChangedOptionsBaseSchema = z2.object({
10025
+ /**
10026
+ * If true, the list will be refreshed automatically when a list changed notification is received.
10027
+ * The callback will be called with the updated list.
10028
+ *
10029
+ * If false, the callback will be called with null items, allowing manual refresh.
10030
+ *
10031
+ * @default true
10032
+ */
10033
+ autoRefresh: z2.boolean().default(true),
10034
+ /**
10035
+ * Debounce time in milliseconds for list changed notification processing.
10036
+ *
10037
+ * Multiple notifications received within this timeframe will only trigger one refresh.
10038
+ * Set to 0 to disable debouncing.
10039
+ *
10040
+ * @default 300
10041
+ */
10042
+ debounceMs: z2.number().int().nonnegative().default(300)
9600
10043
  });
9601
10044
  var LoggingLevelSchema = z2.enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
10045
+ var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
10046
+ /**
10047
+ * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
10048
+ */
10049
+ level: LoggingLevelSchema
10050
+ });
9602
10051
  var SetLevelRequestSchema = RequestSchema.extend({
9603
10052
  method: z2.literal("logging/setLevel"),
9604
- params: BaseRequestParamsSchema.extend({
9605
- /**
9606
- * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
9607
- */
9608
- level: LoggingLevelSchema
9609
- })
10053
+ params: SetLevelRequestParamsSchema
10054
+ });
10055
+ var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
10056
+ /**
10057
+ * The severity of this log message.
10058
+ */
10059
+ level: LoggingLevelSchema,
10060
+ /**
10061
+ * An optional name of the logger issuing this message.
10062
+ */
10063
+ logger: z2.string().optional(),
10064
+ /**
10065
+ * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
10066
+ */
10067
+ data: z2.unknown()
9610
10068
  });
9611
10069
  var LoggingMessageNotificationSchema = NotificationSchema.extend({
9612
10070
  method: z2.literal("notifications/message"),
9613
- params: BaseNotificationParamsSchema.extend({
9614
- /**
9615
- * The severity of this log message.
9616
- */
9617
- level: LoggingLevelSchema,
9618
- /**
9619
- * An optional name of the logger issuing this message.
9620
- */
9621
- logger: z2.optional(z2.string()),
9622
- /**
9623
- * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
9624
- */
9625
- data: z2.unknown()
9626
- })
10071
+ params: LoggingMessageNotificationParamsSchema
9627
10072
  });
9628
10073
  var ModelHintSchema = z2.object({
9629
10074
  /**
9630
10075
  * A hint for a model name.
9631
10076
  */
9632
10077
  name: z2.string().optional()
9633
- }).passthrough();
10078
+ });
9634
10079
  var ModelPreferencesSchema = z2.object({
9635
10080
  /**
9636
10081
  * Optional hints to use for model selection.
9637
10082
  */
9638
- hints: z2.optional(z2.array(ModelHintSchema)),
10083
+ hints: z2.array(ModelHintSchema).optional(),
9639
10084
  /**
9640
10085
  * How much to prioritize cost when selecting a model.
9641
10086
  */
9642
- costPriority: z2.optional(z2.number().min(0).max(1)),
10087
+ costPriority: z2.number().min(0).max(1).optional(),
9643
10088
  /**
9644
10089
  * How much to prioritize sampling speed (latency) when selecting a model.
9645
10090
  */
9646
- speedPriority: z2.optional(z2.number().min(0).max(1)),
10091
+ speedPriority: z2.number().min(0).max(1).optional(),
9647
10092
  /**
9648
10093
  * How much to prioritize intelligence and capabilities when selecting a model.
9649
10094
  */
9650
- intelligencePriority: z2.optional(z2.number().min(0).max(1))
9651
- }).passthrough();
10095
+ intelligencePriority: z2.number().min(0).max(1).optional()
10096
+ });
10097
+ var ToolChoiceSchema = z2.object({
10098
+ /**
10099
+ * Controls when tools are used:
10100
+ * - "auto": Model decides whether to use tools (default)
10101
+ * - "required": Model MUST use at least one tool before completing
10102
+ * - "none": Model MUST NOT use any tools
10103
+ */
10104
+ mode: z2.enum(["auto", "required", "none"]).optional()
10105
+ });
10106
+ var ToolResultContentSchema = z2.object({
10107
+ type: z2.literal("tool_result"),
10108
+ toolUseId: z2.string().describe("The unique identifier for the corresponding tool call."),
10109
+ content: z2.array(ContentBlockSchema).default([]),
10110
+ structuredContent: z2.object({}).loose().optional(),
10111
+ isError: z2.boolean().optional(),
10112
+ /**
10113
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
10114
+ * for notes on _meta usage.
10115
+ */
10116
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
10117
+ });
10118
+ var SamplingContentSchema = z2.discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
10119
+ var SamplingMessageContentBlockSchema = z2.discriminatedUnion("type", [
10120
+ TextContentSchema,
10121
+ ImageContentSchema,
10122
+ AudioContentSchema,
10123
+ ToolUseContentSchema,
10124
+ ToolResultContentSchema
10125
+ ]);
9652
10126
  var SamplingMessageSchema = z2.object({
9653
- role: z2.enum(["user", "assistant"]),
9654
- content: z2.union([TextContentSchema, ImageContentSchema, AudioContentSchema])
9655
- }).passthrough();
10127
+ role: RoleSchema,
10128
+ content: z2.union([SamplingMessageContentBlockSchema, z2.array(SamplingMessageContentBlockSchema)]),
10129
+ /**
10130
+ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
10131
+ * for notes on _meta usage.
10132
+ */
10133
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
10134
+ });
10135
+ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
10136
+ messages: z2.array(SamplingMessageSchema),
10137
+ /**
10138
+ * The server's preferences for which model to select. The client MAY modify or omit this request.
10139
+ */
10140
+ modelPreferences: ModelPreferencesSchema.optional(),
10141
+ /**
10142
+ * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
10143
+ */
10144
+ systemPrompt: z2.string().optional(),
10145
+ /**
10146
+ * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
10147
+ * The client MAY ignore this request.
10148
+ *
10149
+ * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
10150
+ * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
10151
+ */
10152
+ includeContext: z2.enum(["none", "thisServer", "allServers"]).optional(),
10153
+ temperature: z2.number().optional(),
10154
+ /**
10155
+ * The requested maximum number of tokens to sample (to prevent runaway completions).
10156
+ *
10157
+ * The client MAY choose to sample fewer tokens than the requested maximum.
10158
+ */
10159
+ maxTokens: z2.number().int(),
10160
+ stopSequences: z2.array(z2.string()).optional(),
10161
+ /**
10162
+ * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
10163
+ */
10164
+ metadata: AssertObjectSchema.optional(),
10165
+ /**
10166
+ * Tools that the model may use during generation.
10167
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
10168
+ */
10169
+ tools: z2.array(ToolSchema).optional(),
10170
+ /**
10171
+ * Controls how the model uses tools.
10172
+ * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
10173
+ * Default is `{ mode: "auto" }`.
10174
+ */
10175
+ toolChoice: ToolChoiceSchema.optional()
10176
+ });
9656
10177
  var CreateMessageRequestSchema = RequestSchema.extend({
9657
10178
  method: z2.literal("sampling/createMessage"),
9658
- params: BaseRequestParamsSchema.extend({
9659
- messages: z2.array(SamplingMessageSchema),
9660
- /**
9661
- * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
9662
- */
9663
- systemPrompt: z2.optional(z2.string()),
9664
- /**
9665
- * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request.
9666
- */
9667
- includeContext: z2.optional(z2.enum(["none", "thisServer", "allServers"])),
9668
- temperature: z2.optional(z2.number()),
9669
- /**
9670
- * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested.
9671
- */
9672
- maxTokens: z2.number().int(),
9673
- stopSequences: z2.optional(z2.array(z2.string())),
9674
- /**
9675
- * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
9676
- */
9677
- metadata: z2.optional(z2.object({}).passthrough()),
9678
- /**
9679
- * The server's preferences for which model to select.
9680
- */
9681
- modelPreferences: z2.optional(ModelPreferencesSchema)
9682
- })
10179
+ params: CreateMessageRequestParamsSchema
9683
10180
  });
9684
10181
  var CreateMessageResultSchema = ResultSchema.extend({
9685
10182
  /**
@@ -9687,67 +10184,193 @@ var CreateMessageResultSchema = ResultSchema.extend({
9687
10184
  */
9688
10185
  model: z2.string(),
9689
10186
  /**
9690
- * The reason why sampling stopped.
10187
+ * The reason why sampling stopped, if known.
10188
+ *
10189
+ * Standard values:
10190
+ * - "endTurn": Natural end of the assistant's turn
10191
+ * - "stopSequence": A stop sequence was encountered
10192
+ * - "maxTokens": Maximum token limit was reached
10193
+ *
10194
+ * This field is an open string to allow for provider-specific stop reasons.
9691
10195
  */
9692
10196
  stopReason: z2.optional(z2.enum(["endTurn", "stopSequence", "maxTokens"]).or(z2.string())),
9693
- role: z2.enum(["user", "assistant"]),
9694
- content: z2.discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema])
10197
+ role: RoleSchema,
10198
+ /**
10199
+ * Response content. Single content block (text, image, or audio).
10200
+ */
10201
+ content: SamplingContentSchema
10202
+ });
10203
+ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
10204
+ /**
10205
+ * The name of the model that generated the message.
10206
+ */
10207
+ model: z2.string(),
10208
+ /**
10209
+ * The reason why sampling stopped, if known.
10210
+ *
10211
+ * Standard values:
10212
+ * - "endTurn": Natural end of the assistant's turn
10213
+ * - "stopSequence": A stop sequence was encountered
10214
+ * - "maxTokens": Maximum token limit was reached
10215
+ * - "toolUse": The model wants to use one or more tools
10216
+ *
10217
+ * This field is an open string to allow for provider-specific stop reasons.
10218
+ */
10219
+ stopReason: z2.optional(z2.enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(z2.string())),
10220
+ role: RoleSchema,
10221
+ /**
10222
+ * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
10223
+ */
10224
+ content: z2.union([SamplingMessageContentBlockSchema, z2.array(SamplingMessageContentBlockSchema)])
9695
10225
  });
9696
10226
  var BooleanSchemaSchema = z2.object({
9697
10227
  type: z2.literal("boolean"),
9698
- title: z2.optional(z2.string()),
9699
- description: z2.optional(z2.string()),
9700
- default: z2.optional(z2.boolean())
9701
- }).passthrough();
10228
+ title: z2.string().optional(),
10229
+ description: z2.string().optional(),
10230
+ default: z2.boolean().optional()
10231
+ });
9702
10232
  var StringSchemaSchema = z2.object({
9703
10233
  type: z2.literal("string"),
9704
- title: z2.optional(z2.string()),
9705
- description: z2.optional(z2.string()),
9706
- minLength: z2.optional(z2.number()),
9707
- maxLength: z2.optional(z2.number()),
9708
- format: z2.optional(z2.enum(["email", "uri", "date", "date-time"]))
9709
- }).passthrough();
10234
+ title: z2.string().optional(),
10235
+ description: z2.string().optional(),
10236
+ minLength: z2.number().optional(),
10237
+ maxLength: z2.number().optional(),
10238
+ format: z2.enum(["email", "uri", "date", "date-time"]).optional(),
10239
+ default: z2.string().optional()
10240
+ });
9710
10241
  var NumberSchemaSchema = z2.object({
9711
10242
  type: z2.enum(["number", "integer"]),
9712
- title: z2.optional(z2.string()),
9713
- description: z2.optional(z2.string()),
9714
- minimum: z2.optional(z2.number()),
9715
- maximum: z2.optional(z2.number())
9716
- }).passthrough();
9717
- var EnumSchemaSchema = z2.object({
10243
+ title: z2.string().optional(),
10244
+ description: z2.string().optional(),
10245
+ minimum: z2.number().optional(),
10246
+ maximum: z2.number().optional(),
10247
+ default: z2.number().optional()
10248
+ });
10249
+ var UntitledSingleSelectEnumSchemaSchema = z2.object({
9718
10250
  type: z2.literal("string"),
9719
- title: z2.optional(z2.string()),
9720
- description: z2.optional(z2.string()),
10251
+ title: z2.string().optional(),
10252
+ description: z2.string().optional(),
10253
+ enum: z2.array(z2.string()),
10254
+ default: z2.string().optional()
10255
+ });
10256
+ var TitledSingleSelectEnumSchemaSchema = z2.object({
10257
+ type: z2.literal("string"),
10258
+ title: z2.string().optional(),
10259
+ description: z2.string().optional(),
10260
+ oneOf: z2.array(z2.object({
10261
+ const: z2.string(),
10262
+ title: z2.string()
10263
+ })),
10264
+ default: z2.string().optional()
10265
+ });
10266
+ var LegacyTitledEnumSchemaSchema = z2.object({
10267
+ type: z2.literal("string"),
10268
+ title: z2.string().optional(),
10269
+ description: z2.string().optional(),
9721
10270
  enum: z2.array(z2.string()),
9722
- enumNames: z2.optional(z2.array(z2.string()))
9723
- }).passthrough();
9724
- var PrimitiveSchemaDefinitionSchema = z2.union([BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, EnumSchemaSchema]);
10271
+ enumNames: z2.array(z2.string()).optional(),
10272
+ default: z2.string().optional()
10273
+ });
10274
+ var SingleSelectEnumSchemaSchema = z2.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
10275
+ var UntitledMultiSelectEnumSchemaSchema = z2.object({
10276
+ type: z2.literal("array"),
10277
+ title: z2.string().optional(),
10278
+ description: z2.string().optional(),
10279
+ minItems: z2.number().optional(),
10280
+ maxItems: z2.number().optional(),
10281
+ items: z2.object({
10282
+ type: z2.literal("string"),
10283
+ enum: z2.array(z2.string())
10284
+ }),
10285
+ default: z2.array(z2.string()).optional()
10286
+ });
10287
+ var TitledMultiSelectEnumSchemaSchema = z2.object({
10288
+ type: z2.literal("array"),
10289
+ title: z2.string().optional(),
10290
+ description: z2.string().optional(),
10291
+ minItems: z2.number().optional(),
10292
+ maxItems: z2.number().optional(),
10293
+ items: z2.object({
10294
+ anyOf: z2.array(z2.object({
10295
+ const: z2.string(),
10296
+ title: z2.string()
10297
+ }))
10298
+ }),
10299
+ default: z2.array(z2.string()).optional()
10300
+ });
10301
+ var MultiSelectEnumSchemaSchema = z2.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
10302
+ var EnumSchemaSchema = z2.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
10303
+ var PrimitiveSchemaDefinitionSchema = z2.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
10304
+ var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
10305
+ /**
10306
+ * The elicitation mode.
10307
+ *
10308
+ * Optional for backward compatibility. Clients MUST treat missing mode as "form".
10309
+ */
10310
+ mode: z2.literal("form").optional(),
10311
+ /**
10312
+ * The message to present to the user describing what information is being requested.
10313
+ */
10314
+ message: z2.string(),
10315
+ /**
10316
+ * A restricted subset of JSON Schema.
10317
+ * Only top-level properties are allowed, without nesting.
10318
+ */
10319
+ requestedSchema: z2.object({
10320
+ type: z2.literal("object"),
10321
+ properties: z2.record(z2.string(), PrimitiveSchemaDefinitionSchema),
10322
+ required: z2.array(z2.string()).optional()
10323
+ })
10324
+ });
10325
+ var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
10326
+ /**
10327
+ * The elicitation mode.
10328
+ */
10329
+ mode: z2.literal("url"),
10330
+ /**
10331
+ * The message to present to the user explaining why the interaction is needed.
10332
+ */
10333
+ message: z2.string(),
10334
+ /**
10335
+ * The ID of the elicitation, which must be unique within the context of the server.
10336
+ * The client MUST treat this ID as an opaque value.
10337
+ */
10338
+ elicitationId: z2.string(),
10339
+ /**
10340
+ * The URL that the user should navigate to.
10341
+ */
10342
+ url: z2.string().url()
10343
+ });
10344
+ var ElicitRequestParamsSchema = z2.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
9725
10345
  var ElicitRequestSchema = RequestSchema.extend({
9726
10346
  method: z2.literal("elicitation/create"),
9727
- params: BaseRequestParamsSchema.extend({
9728
- /**
9729
- * The message to present to the user.
9730
- */
9731
- message: z2.string(),
9732
- /**
9733
- * The schema for the requested user input.
9734
- */
9735
- requestedSchema: z2.object({
9736
- type: z2.literal("object"),
9737
- properties: z2.record(z2.string(), PrimitiveSchemaDefinitionSchema),
9738
- required: z2.optional(z2.array(z2.string()))
9739
- }).passthrough()
9740
- })
10347
+ params: ElicitRequestParamsSchema
10348
+ });
10349
+ var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
10350
+ /**
10351
+ * The ID of the elicitation that completed.
10352
+ */
10353
+ elicitationId: z2.string()
10354
+ });
10355
+ var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
10356
+ method: z2.literal("notifications/elicitation/complete"),
10357
+ params: ElicitationCompleteNotificationParamsSchema
9741
10358
  });
9742
10359
  var ElicitResultSchema = ResultSchema.extend({
9743
10360
  /**
9744
- * The user's response action.
10361
+ * The user action in response to the elicitation.
10362
+ * - "accept": User submitted the form/confirmed the action
10363
+ * - "decline": User explicitly decline the action
10364
+ * - "cancel": User dismissed without making an explicit choice
9745
10365
  */
9746
10366
  action: z2.enum(["accept", "decline", "cancel"]),
9747
10367
  /**
9748
- * The collected user input content (only present if action is "accept").
10368
+ * The submitted form data, only present when action is "accept".
10369
+ * Contains values matching the requested schema.
10370
+ * Per MCP spec, content is "typically omitted" for decline/cancel actions.
10371
+ * We normalize null to undefined for leniency while maintaining type compatibility.
9749
10372
  */
9750
- content: z2.optional(z2.record(z2.string(), z2.unknown()))
10373
+ content: z2.preprocess((val) => val === null ? void 0 : val, z2.record(z2.string(), z2.union([z2.string(), z2.number(), z2.boolean(), z2.array(z2.string())])).optional())
9751
10374
  });
9752
10375
  var ResourceTemplateReferenceSchema = z2.object({
9753
10376
  type: z2.literal("ref/resource"),
@@ -9755,41 +10378,42 @@ var ResourceTemplateReferenceSchema = z2.object({
9755
10378
  * The URI or URI template of the resource.
9756
10379
  */
9757
10380
  uri: z2.string()
9758
- }).passthrough();
10381
+ });
9759
10382
  var PromptReferenceSchema = z2.object({
9760
10383
  type: z2.literal("ref/prompt"),
9761
10384
  /**
9762
10385
  * The name of the prompt or prompt template
9763
10386
  */
9764
10387
  name: z2.string()
9765
- }).passthrough();
9766
- var CompleteRequestSchema = RequestSchema.extend({
9767
- method: z2.literal("completion/complete"),
9768
- params: BaseRequestParamsSchema.extend({
9769
- ref: z2.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
10388
+ });
10389
+ var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
10390
+ ref: z2.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
10391
+ /**
10392
+ * The argument's information
10393
+ */
10394
+ argument: z2.object({
9770
10395
  /**
9771
- * The argument's information
10396
+ * The name of the argument
9772
10397
  */
9773
- argument: z2.object({
9774
- /**
9775
- * The name of the argument
9776
- */
9777
- name: z2.string(),
9778
- /**
9779
- * The value of the argument to use for completion matching.
9780
- */
9781
- value: z2.string()
9782
- }).passthrough(),
9783
- context: z2.optional(z2.object({
9784
- /**
9785
- * Previously-resolved variables in a URI template or prompt.
9786
- */
9787
- arguments: z2.optional(z2.record(z2.string(), z2.string()))
9788
- }))
9789
- })
10398
+ name: z2.string(),
10399
+ /**
10400
+ * The value of the argument to use for completion matching.
10401
+ */
10402
+ value: z2.string()
10403
+ }),
10404
+ context: z2.object({
10405
+ /**
10406
+ * Previously-resolved variables in a URI template or prompt.
10407
+ */
10408
+ arguments: z2.record(z2.string(), z2.string()).optional()
10409
+ }).optional()
10410
+ });
10411
+ var CompleteRequestSchema = RequestSchema.extend({
10412
+ method: z2.literal("completion/complete"),
10413
+ params: CompleteRequestParamsSchema
9790
10414
  });
9791
10415
  var CompleteResultSchema = ResultSchema.extend({
9792
- completion: z2.object({
10416
+ completion: z2.looseObject({
9793
10417
  /**
9794
10418
  * An array of completion values. Must not exceed 100 items.
9795
10419
  */
@@ -9802,7 +10426,7 @@ var CompleteResultSchema = ResultSchema.extend({
9802
10426
  * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
9803
10427
  */
9804
10428
  hasMore: z2.optional(z2.boolean())
9805
- }).passthrough()
10429
+ })
9806
10430
  });
9807
10431
  var RootSchema = z2.object({
9808
10432
  /**
@@ -9812,21 +10436,23 @@ var RootSchema = z2.object({
9812
10436
  /**
9813
10437
  * An optional name for the root.
9814
10438
  */
9815
- name: z2.optional(z2.string()),
10439
+ name: z2.string().optional(),
9816
10440
  /**
9817
10441
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
9818
10442
  * for notes on _meta usage.
9819
10443
  */
9820
- _meta: z2.optional(z2.object({}).passthrough())
9821
- }).passthrough();
10444
+ _meta: z2.record(z2.string(), z2.unknown()).optional()
10445
+ });
9822
10446
  var ListRootsRequestSchema = RequestSchema.extend({
9823
- method: z2.literal("roots/list")
10447
+ method: z2.literal("roots/list"),
10448
+ params: BaseRequestParamsSchema.optional()
9824
10449
  });
9825
10450
  var ListRootsResultSchema = ResultSchema.extend({
9826
10451
  roots: z2.array(RootSchema)
9827
10452
  });
9828
10453
  var RootsListChangedNotificationSchema = NotificationSchema.extend({
9829
- method: z2.literal("notifications/roots/list_changed")
10454
+ method: z2.literal("notifications/roots/list_changed"),
10455
+ params: NotificationsParamsSchema.optional()
9830
10456
  });
9831
10457
  var ClientRequestSchema = z2.union([
9832
10458
  PingRequestSchema,
@@ -9841,16 +10467,39 @@ var ClientRequestSchema = z2.union([
9841
10467
  SubscribeRequestSchema,
9842
10468
  UnsubscribeRequestSchema,
9843
10469
  CallToolRequestSchema,
9844
- ListToolsRequestSchema
10470
+ ListToolsRequestSchema,
10471
+ GetTaskRequestSchema,
10472
+ GetTaskPayloadRequestSchema,
10473
+ ListTasksRequestSchema,
10474
+ CancelTaskRequestSchema
9845
10475
  ]);
9846
10476
  var ClientNotificationSchema = z2.union([
9847
10477
  CancelledNotificationSchema,
9848
10478
  ProgressNotificationSchema,
9849
10479
  InitializedNotificationSchema,
9850
- RootsListChangedNotificationSchema
10480
+ RootsListChangedNotificationSchema,
10481
+ TaskStatusNotificationSchema
10482
+ ]);
10483
+ var ClientResultSchema = z2.union([
10484
+ EmptyResultSchema,
10485
+ CreateMessageResultSchema,
10486
+ CreateMessageResultWithToolsSchema,
10487
+ ElicitResultSchema,
10488
+ ListRootsResultSchema,
10489
+ GetTaskResultSchema,
10490
+ ListTasksResultSchema,
10491
+ CreateTaskResultSchema
10492
+ ]);
10493
+ var ServerRequestSchema = z2.union([
10494
+ PingRequestSchema,
10495
+ CreateMessageRequestSchema,
10496
+ ElicitRequestSchema,
10497
+ ListRootsRequestSchema,
10498
+ GetTaskRequestSchema,
10499
+ GetTaskPayloadRequestSchema,
10500
+ ListTasksRequestSchema,
10501
+ CancelTaskRequestSchema
9851
10502
  ]);
9852
- var ClientResultSchema = z2.union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]);
9853
- var ServerRequestSchema = z2.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]);
9854
10503
  var ServerNotificationSchema = z2.union([
9855
10504
  CancelledNotificationSchema,
9856
10505
  ProgressNotificationSchema,
@@ -9858,7 +10507,9 @@ var ServerNotificationSchema = z2.union([
9858
10507
  ResourceUpdatedNotificationSchema,
9859
10508
  ResourceListChangedNotificationSchema,
9860
10509
  ToolListChangedNotificationSchema,
9861
- PromptListChangedNotificationSchema
10510
+ PromptListChangedNotificationSchema,
10511
+ TaskStatusNotificationSchema,
10512
+ ElicitationCompleteNotificationSchema
9862
10513
  ]);
9863
10514
  var ServerResultSchema = z2.union([
9864
10515
  EmptyResultSchema,
@@ -9870,18 +10521,195 @@ var ServerResultSchema = z2.union([
9870
10521
  ListResourceTemplatesResultSchema,
9871
10522
  ReadResourceResultSchema,
9872
10523
  CallToolResultSchema,
9873
- ListToolsResultSchema
10524
+ ListToolsResultSchema,
10525
+ GetTaskResultSchema,
10526
+ ListTasksResultSchema,
10527
+ CreateTaskResultSchema
9874
10528
  ]);
9875
- var McpError = class extends Error {
10529
+ var McpError = class _McpError extends Error {
9876
10530
  constructor(code, message, data) {
9877
10531
  super(`MCP error ${code}: ${message}`);
9878
10532
  this.code = code;
9879
10533
  this.data = data;
9880
10534
  this.name = "McpError";
9881
10535
  }
10536
+ /**
10537
+ * Factory method to create the appropriate error type based on the error code and data
10538
+ */
10539
+ static fromError(code, message, data) {
10540
+ if (code === ErrorCode.UrlElicitationRequired && data) {
10541
+ const errorData = data;
10542
+ if (errorData.elicitations) {
10543
+ return new UrlElicitationRequiredError(errorData.elicitations, message);
10544
+ }
10545
+ }
10546
+ return new _McpError(code, message, data);
10547
+ }
10548
+ };
10549
+ var UrlElicitationRequiredError = class extends McpError {
10550
+ constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
10551
+ super(ErrorCode.UrlElicitationRequired, message, {
10552
+ elicitations
10553
+ });
10554
+ }
10555
+ get elicitations() {
10556
+ return this.data?.elicitations ?? [];
10557
+ }
9882
10558
  };
9883
10559
 
9884
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
10560
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
10561
+ init_esm_shims();
10562
+ function isTerminal(status) {
10563
+ return status === "completed" || status === "failed" || status === "cancelled";
10564
+ }
10565
+
10566
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
10567
+ init_esm_shims();
10568
+ import * as z4mini2 from "zod/v4-mini";
10569
+
10570
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/index.js
10571
+ init_esm_shims();
10572
+
10573
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js
10574
+ init_esm_shims();
10575
+
10576
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js
10577
+ init_esm_shims();
10578
+
10579
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/errorMessages.js
10580
+ init_esm_shims();
10581
+
10582
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
10583
+ init_esm_shims();
10584
+
10585
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parseDef.js
10586
+ init_esm_shims();
10587
+
10588
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js
10589
+ init_esm_shims();
10590
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod/v3";
10591
+
10592
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
10593
+ init_esm_shims();
10594
+
10595
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js
10596
+ init_esm_shims();
10597
+ import { ZodFirstPartyTypeKind } from "zod/v3";
10598
+
10599
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
10600
+ init_esm_shims();
10601
+
10602
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
10603
+ init_esm_shims();
10604
+
10605
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
10606
+ init_esm_shims();
10607
+
10608
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
10609
+ init_esm_shims();
10610
+
10611
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/date.js
10612
+ init_esm_shims();
10613
+
10614
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/default.js
10615
+ init_esm_shims();
10616
+
10617
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
10618
+ init_esm_shims();
10619
+
10620
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
10621
+ init_esm_shims();
10622
+
10623
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
10624
+ init_esm_shims();
10625
+
10626
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
10627
+ init_esm_shims();
10628
+
10629
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/map.js
10630
+ init_esm_shims();
10631
+
10632
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js
10633
+ init_esm_shims();
10634
+ import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod/v3";
10635
+
10636
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
10637
+ init_esm_shims();
10638
+ var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
10639
+
10640
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
10641
+ init_esm_shims();
10642
+
10643
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
10644
+ init_esm_shims();
10645
+
10646
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/null.js
10647
+ init_esm_shims();
10648
+
10649
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
10650
+ init_esm_shims();
10651
+
10652
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/union.js
10653
+ init_esm_shims();
10654
+
10655
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/number.js
10656
+ init_esm_shims();
10657
+
10658
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/object.js
10659
+ init_esm_shims();
10660
+
10661
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
10662
+ init_esm_shims();
10663
+
10664
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
10665
+ init_esm_shims();
10666
+
10667
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
10668
+ init_esm_shims();
10669
+
10670
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/set.js
10671
+ init_esm_shims();
10672
+
10673
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
10674
+ init_esm_shims();
10675
+
10676
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
10677
+ init_esm_shims();
10678
+
10679
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
10680
+ init_esm_shims();
10681
+
10682
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
10683
+ init_esm_shims();
10684
+
10685
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parseTypes.js
10686
+ init_esm_shims();
10687
+
10688
+ // ../../node_modules/.pnpm/zod-to-json-schema@3.25.0_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
10689
+ init_esm_shims();
10690
+
10691
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
10692
+ function getMethodLiteral(schema) {
10693
+ const shape = getObjectShape(schema);
10694
+ const methodSchema = shape?.method;
10695
+ if (!methodSchema) {
10696
+ throw new Error("Schema is missing a method literal");
10697
+ }
10698
+ const value = getLiteralValue(methodSchema);
10699
+ if (typeof value !== "string") {
10700
+ throw new Error("Schema method literal must be a string");
10701
+ }
10702
+ return value;
10703
+ }
10704
+ function parseWithCompat(schema, data) {
10705
+ const result = safeParse2(schema, data);
10706
+ if (!result.success) {
10707
+ throw result.error;
10708
+ }
10709
+ return result.data;
10710
+ }
10711
+
10712
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
9885
10713
  var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
9886
10714
  var Protocol = class {
9887
10715
  constructor(_options) {
@@ -9894,9 +10722,10 @@ var Protocol = class {
9894
10722
  this._progressHandlers = /* @__PURE__ */ new Map();
9895
10723
  this._timeoutInfo = /* @__PURE__ */ new Map();
9896
10724
  this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
10725
+ this._taskProgressTokens = /* @__PURE__ */ new Map();
10726
+ this._requestResolvers = /* @__PURE__ */ new Map();
9897
10727
  this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
9898
- const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
9899
- controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
10728
+ this._oncancel(notification);
9900
10729
  });
9901
10730
  this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
9902
10731
  this._onprogress(notification);
@@ -9906,6 +10735,117 @@ var Protocol = class {
9906
10735
  // Automatic pong by default.
9907
10736
  (_request) => ({})
9908
10737
  );
10738
+ this._taskStore = _options?.taskStore;
10739
+ this._taskMessageQueue = _options?.taskMessageQueue;
10740
+ if (this._taskStore) {
10741
+ this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
10742
+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
10743
+ if (!task) {
10744
+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
10745
+ }
10746
+ return {
10747
+ ...task
10748
+ };
10749
+ });
10750
+ this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
10751
+ const handleTaskResult = async () => {
10752
+ const taskId = request.params.taskId;
10753
+ if (this._taskMessageQueue) {
10754
+ let queuedMessage;
10755
+ while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
10756
+ if (queuedMessage.type === "response" || queuedMessage.type === "error") {
10757
+ const message = queuedMessage.message;
10758
+ const requestId = message.id;
10759
+ const resolver = this._requestResolvers.get(requestId);
10760
+ if (resolver) {
10761
+ this._requestResolvers.delete(requestId);
10762
+ if (queuedMessage.type === "response") {
10763
+ resolver(message);
10764
+ } else {
10765
+ const errorMessage = message;
10766
+ const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
10767
+ resolver(error2);
10768
+ }
10769
+ } else {
10770
+ const messageType = queuedMessage.type === "response" ? "Response" : "Error";
10771
+ this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
10772
+ }
10773
+ continue;
10774
+ }
10775
+ await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });
10776
+ }
10777
+ }
10778
+ const task = await this._taskStore.getTask(taskId, extra.sessionId);
10779
+ if (!task) {
10780
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
10781
+ }
10782
+ if (!isTerminal(task.status)) {
10783
+ await this._waitForTaskUpdate(taskId, extra.signal);
10784
+ return await handleTaskResult();
10785
+ }
10786
+ if (isTerminal(task.status)) {
10787
+ const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
10788
+ this._clearTaskQueue(taskId);
10789
+ return {
10790
+ ...result,
10791
+ _meta: {
10792
+ ...result._meta,
10793
+ [RELATED_TASK_META_KEY]: {
10794
+ taskId
10795
+ }
10796
+ }
10797
+ };
10798
+ }
10799
+ return await handleTaskResult();
10800
+ };
10801
+ return await handleTaskResult();
10802
+ });
10803
+ this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
10804
+ try {
10805
+ const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);
10806
+ return {
10807
+ tasks,
10808
+ nextCursor,
10809
+ _meta: {}
10810
+ };
10811
+ } catch (error2) {
10812
+ throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);
10813
+ }
10814
+ });
10815
+ this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
10816
+ try {
10817
+ const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
10818
+ if (!task) {
10819
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
10820
+ }
10821
+ if (isTerminal(task.status)) {
10822
+ throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
10823
+ }
10824
+ await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
10825
+ this._clearTaskQueue(request.params.taskId);
10826
+ const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
10827
+ if (!cancelledTask) {
10828
+ throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
10829
+ }
10830
+ return {
10831
+ _meta: {},
10832
+ ...cancelledTask
10833
+ };
10834
+ } catch (error2) {
10835
+ if (error2 instanceof McpError) {
10836
+ throw error2;
10837
+ }
10838
+ throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);
10839
+ }
10840
+ });
10841
+ }
10842
+ }
10843
+ async _oncancel(notification) {
10844
+ if (!notification.params.requestId) {
10845
+ return;
10846
+ }
10847
+ const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
10848
+ controller?.abort(notification.params.reason);
9909
10849
  }
9910
10850
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
9911
10851
  this._timeoutInfo.set(messageId, {
@@ -9924,7 +10864,7 @@ var Protocol = class {
9924
10864
  const totalElapsed = Date.now() - info2.startTime;
9925
10865
  if (info2.maxTotalTimeout && totalElapsed >= info2.maxTotalTimeout) {
9926
10866
  this._timeoutInfo.delete(messageId);
9927
- throw new McpError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
10867
+ throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
9928
10868
  maxTotalTimeout: info2.maxTotalTimeout,
9929
10869
  totalElapsed
9930
10870
  });
@@ -9946,22 +10886,21 @@ var Protocol = class {
9946
10886
  * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
9947
10887
  */
9948
10888
  async connect(transport) {
9949
- var _a, _b, _c;
9950
10889
  this._transport = transport;
9951
- const _onclose = (_a = this.transport) === null || _a === void 0 ? void 0 : _a.onclose;
10890
+ const _onclose = this.transport?.onclose;
9952
10891
  this._transport.onclose = () => {
9953
- _onclose === null || _onclose === void 0 ? void 0 : _onclose();
10892
+ _onclose?.();
9954
10893
  this._onclose();
9955
10894
  };
9956
- const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror;
10895
+ const _onerror = this.transport?.onerror;
9957
10896
  this._transport.onerror = (error2) => {
9958
- _onerror === null || _onerror === void 0 ? void 0 : _onerror(error2);
10897
+ _onerror?.(error2);
9959
10898
  this._onerror(error2);
9960
10899
  };
9961
- const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage;
10900
+ const _onmessage = this._transport?.onmessage;
9962
10901
  this._transport.onmessage = (message, extra) => {
9963
- _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra);
9964
- if (isJSONRPCResponse(message) || isJSONRPCError(message)) {
10902
+ _onmessage?.(message, extra);
10903
+ if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
9965
10904
  this._onresponse(message);
9966
10905
  } else if (isJSONRPCRequest(message)) {
9967
10906
  this._onrequest(message, extra);
@@ -9974,79 +10913,131 @@ var Protocol = class {
9974
10913
  await this._transport.start();
9975
10914
  }
9976
10915
  _onclose() {
9977
- var _a;
9978
10916
  const responseHandlers = this._responseHandlers;
9979
10917
  this._responseHandlers = /* @__PURE__ */ new Map();
9980
10918
  this._progressHandlers.clear();
10919
+ this._taskProgressTokens.clear();
9981
10920
  this._pendingDebouncedNotifications.clear();
10921
+ const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
9982
10922
  this._transport = void 0;
9983
- (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
9984
- const error2 = new McpError(ErrorCode.ConnectionClosed, "Connection closed");
10923
+ this.onclose?.();
9985
10924
  for (const handler of responseHandlers.values()) {
9986
10925
  handler(error2);
9987
10926
  }
9988
10927
  }
9989
10928
  _onerror(error2) {
9990
- var _a;
9991
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error2);
10929
+ this.onerror?.(error2);
9992
10930
  }
9993
10931
  _onnotification(notification) {
9994
- var _a;
9995
- const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler;
10932
+ const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
9996
10933
  if (handler === void 0) {
9997
10934
  return;
9998
10935
  }
9999
10936
  Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
10000
10937
  }
10001
10938
  _onrequest(request, extra) {
10002
- var _a, _b;
10003
- const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler;
10939
+ const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
10004
10940
  const capturedTransport = this._transport;
10941
+ const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
10005
10942
  if (handler === void 0) {
10006
- capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
10943
+ const errorResponse = {
10007
10944
  jsonrpc: "2.0",
10008
10945
  id: request.id,
10009
10946
  error: {
10010
10947
  code: ErrorCode.MethodNotFound,
10011
10948
  message: "Method not found"
10012
10949
  }
10013
- }).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
10950
+ };
10951
+ if (relatedTaskId && this._taskMessageQueue) {
10952
+ this._enqueueTaskMessage(relatedTaskId, {
10953
+ type: "error",
10954
+ message: errorResponse,
10955
+ timestamp: Date.now()
10956
+ }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
10957
+ } else {
10958
+ capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
10959
+ }
10014
10960
  return;
10015
10961
  }
10016
10962
  const abortController = new AbortController();
10017
10963
  this._requestHandlerAbortControllers.set(request.id, abortController);
10964
+ const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
10965
+ const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0;
10018
10966
  const fullExtra = {
10019
10967
  signal: abortController.signal,
10020
- sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId,
10021
- _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta,
10022
- sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
10023
- sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }),
10024
- authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
10968
+ sessionId: capturedTransport?.sessionId,
10969
+ _meta: request.params?._meta,
10970
+ sendNotification: async (notification) => {
10971
+ const notificationOptions = { relatedRequestId: request.id };
10972
+ if (relatedTaskId) {
10973
+ notificationOptions.relatedTask = { taskId: relatedTaskId };
10974
+ }
10975
+ await this.notification(notification, notificationOptions);
10976
+ },
10977
+ sendRequest: async (r, resultSchema, options) => {
10978
+ const requestOptions = { ...options, relatedRequestId: request.id };
10979
+ if (relatedTaskId && !requestOptions.relatedTask) {
10980
+ requestOptions.relatedTask = { taskId: relatedTaskId };
10981
+ }
10982
+ const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;
10983
+ if (effectiveTaskId && taskStore) {
10984
+ await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
10985
+ }
10986
+ return await this.request(r, resultSchema, requestOptions);
10987
+ },
10988
+ authInfo: extra?.authInfo,
10025
10989
  requestId: request.id,
10026
- requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
10027
- };
10028
- Promise.resolve().then(() => handler(request, fullExtra)).then((result) => {
10990
+ requestInfo: extra?.requestInfo,
10991
+ taskId: relatedTaskId,
10992
+ taskStore,
10993
+ taskRequestedTtl: taskCreationParams?.ttl,
10994
+ closeSSEStream: extra?.closeSSEStream,
10995
+ closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
10996
+ };
10997
+ Promise.resolve().then(() => {
10998
+ if (taskCreationParams) {
10999
+ this.assertTaskHandlerCapability(request.method);
11000
+ }
11001
+ }).then(() => handler(request, fullExtra)).then(async (result) => {
10029
11002
  if (abortController.signal.aborted) {
10030
11003
  return;
10031
11004
  }
10032
- return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
11005
+ const response = {
10033
11006
  result,
10034
11007
  jsonrpc: "2.0",
10035
11008
  id: request.id
10036
- });
10037
- }, (error2) => {
10038
- var _a2;
11009
+ };
11010
+ if (relatedTaskId && this._taskMessageQueue) {
11011
+ await this._enqueueTaskMessage(relatedTaskId, {
11012
+ type: "response",
11013
+ message: response,
11014
+ timestamp: Date.now()
11015
+ }, capturedTransport?.sessionId);
11016
+ } else {
11017
+ await capturedTransport?.send(response);
11018
+ }
11019
+ }, async (error2) => {
10039
11020
  if (abortController.signal.aborted) {
10040
11021
  return;
10041
11022
  }
10042
- return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
11023
+ const errorResponse = {
10043
11024
  jsonrpc: "2.0",
10044
11025
  id: request.id,
10045
11026
  error: {
10046
11027
  code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,
10047
- message: (_a2 = error2.message) !== null && _a2 !== void 0 ? _a2 : "Internal error"
11028
+ message: error2.message ?? "Internal error",
11029
+ ...error2["data"] !== void 0 && { data: error2["data"] }
10048
11030
  }
10049
- });
11031
+ };
11032
+ if (relatedTaskId && this._taskMessageQueue) {
11033
+ await this._enqueueTaskMessage(relatedTaskId, {
11034
+ type: "error",
11035
+ message: errorResponse,
11036
+ timestamp: Date.now()
11037
+ }, capturedTransport?.sessionId);
11038
+ } else {
11039
+ await capturedTransport?.send(errorResponse);
11040
+ }
10050
11041
  }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {
10051
11042
  this._requestHandlerAbortControllers.delete(request.id);
10052
11043
  });
@@ -10065,6 +11056,9 @@ var Protocol = class {
10065
11056
  try {
10066
11057
  this._resetTimeout(messageId);
10067
11058
  } catch (error2) {
11059
+ this._responseHandlers.delete(messageId);
11060
+ this._progressHandlers.delete(messageId);
11061
+ this._cleanupTimeout(messageId);
10068
11062
  responseHandler(error2);
10069
11063
  return;
10070
11064
  }
@@ -10073,18 +11067,42 @@ var Protocol = class {
10073
11067
  }
10074
11068
  _onresponse(response) {
10075
11069
  const messageId = Number(response.id);
11070
+ const resolver = this._requestResolvers.get(messageId);
11071
+ if (resolver) {
11072
+ this._requestResolvers.delete(messageId);
11073
+ if (isJSONRPCResultResponse(response)) {
11074
+ resolver(response);
11075
+ } else {
11076
+ const error2 = new McpError(response.error.code, response.error.message, response.error.data);
11077
+ resolver(error2);
11078
+ }
11079
+ return;
11080
+ }
10076
11081
  const handler = this._responseHandlers.get(messageId);
10077
11082
  if (handler === void 0) {
10078
11083
  this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
10079
11084
  return;
10080
11085
  }
10081
11086
  this._responseHandlers.delete(messageId);
10082
- this._progressHandlers.delete(messageId);
10083
11087
  this._cleanupTimeout(messageId);
10084
- if (isJSONRPCResponse(response)) {
11088
+ let isTaskResponse = false;
11089
+ if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
11090
+ const result = response.result;
11091
+ if (result.task && typeof result.task === "object") {
11092
+ const task = result.task;
11093
+ if (typeof task.taskId === "string") {
11094
+ isTaskResponse = true;
11095
+ this._taskProgressTokens.set(task.taskId, messageId);
11096
+ }
11097
+ }
11098
+ }
11099
+ if (!isTaskResponse) {
11100
+ this._progressHandlers.delete(messageId);
11101
+ }
11102
+ if (isJSONRPCResultResponse(response)) {
10085
11103
  handler(response);
10086
11104
  } else {
10087
- const error2 = new McpError(response.error.code, response.error.message, response.error.data);
11105
+ const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);
10088
11106
  handler(error2);
10089
11107
  }
10090
11108
  }
@@ -10095,119 +11113,326 @@ var Protocol = class {
10095
11113
  * Closes the connection.
10096
11114
  */
10097
11115
  async close() {
10098
- var _a;
10099
- await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close());
11116
+ await this._transport?.close();
11117
+ }
11118
+ /**
11119
+ * Sends a request and returns an AsyncGenerator that yields response messages.
11120
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
11121
+ *
11122
+ * @example
11123
+ * ```typescript
11124
+ * const stream = protocol.requestStream(request, resultSchema, options);
11125
+ * for await (const message of stream) {
11126
+ * switch (message.type) {
11127
+ * case 'taskCreated':
11128
+ * console.log('Task created:', message.task.taskId);
11129
+ * break;
11130
+ * case 'taskStatus':
11131
+ * console.log('Task status:', message.task.status);
11132
+ * break;
11133
+ * case 'result':
11134
+ * console.log('Final result:', message.result);
11135
+ * break;
11136
+ * case 'error':
11137
+ * console.error('Error:', message.error);
11138
+ * break;
11139
+ * }
11140
+ * }
11141
+ * ```
11142
+ *
11143
+ * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
11144
+ */
11145
+ async *requestStream(request, resultSchema, options) {
11146
+ const { task } = options ?? {};
11147
+ if (!task) {
11148
+ try {
11149
+ const result = await this.request(request, resultSchema, options);
11150
+ yield { type: "result", result };
11151
+ } catch (error2) {
11152
+ yield {
11153
+ type: "error",
11154
+ error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
11155
+ };
11156
+ }
11157
+ return;
11158
+ }
11159
+ let taskId;
11160
+ try {
11161
+ const createResult = await this.request(request, CreateTaskResultSchema, options);
11162
+ if (createResult.task) {
11163
+ taskId = createResult.task.taskId;
11164
+ yield { type: "taskCreated", task: createResult.task };
11165
+ } else {
11166
+ throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
11167
+ }
11168
+ while (true) {
11169
+ const task2 = await this.getTask({ taskId }, options);
11170
+ yield { type: "taskStatus", task: task2 };
11171
+ if (isTerminal(task2.status)) {
11172
+ if (task2.status === "completed") {
11173
+ const result = await this.getTaskResult({ taskId }, resultSchema, options);
11174
+ yield { type: "result", result };
11175
+ } else if (task2.status === "failed") {
11176
+ yield {
11177
+ type: "error",
11178
+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
11179
+ };
11180
+ } else if (task2.status === "cancelled") {
11181
+ yield {
11182
+ type: "error",
11183
+ error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
11184
+ };
11185
+ }
11186
+ return;
11187
+ }
11188
+ if (task2.status === "input_required") {
11189
+ const result = await this.getTaskResult({ taskId }, resultSchema, options);
11190
+ yield { type: "result", result };
11191
+ return;
11192
+ }
11193
+ const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
11194
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
11195
+ options?.signal?.throwIfAborted();
11196
+ }
11197
+ } catch (error2) {
11198
+ yield {
11199
+ type: "error",
11200
+ error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
11201
+ };
11202
+ }
10100
11203
  }
10101
11204
  /**
10102
- * Sends a request and wait for a response.
11205
+ * Sends a request and waits for a response.
10103
11206
  *
10104
11207
  * Do not use this method to emit notifications! Use notification() instead.
10105
11208
  */
10106
11209
  request(request, resultSchema, options) {
10107
- const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {};
11210
+ const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
10108
11211
  return new Promise((resolve, reject) => {
10109
- var _a, _b, _c, _d, _e, _f;
11212
+ const earlyReject = (error2) => {
11213
+ reject(error2);
11214
+ };
10110
11215
  if (!this._transport) {
10111
- reject(new Error("Not connected"));
11216
+ earlyReject(new Error("Not connected"));
10112
11217
  return;
10113
11218
  }
10114
- if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) {
10115
- this.assertCapabilityForMethod(request.method);
11219
+ if (this._options?.enforceStrictCapabilities === true) {
11220
+ try {
11221
+ this.assertCapabilityForMethod(request.method);
11222
+ if (task) {
11223
+ this.assertTaskCapability(request.method);
11224
+ }
11225
+ } catch (e) {
11226
+ earlyReject(e);
11227
+ return;
11228
+ }
10116
11229
  }
10117
- (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted();
11230
+ options?.signal?.throwIfAborted();
10118
11231
  const messageId = this._requestMessageId++;
10119
11232
  const jsonrpcRequest = {
10120
11233
  ...request,
10121
11234
  jsonrpc: "2.0",
10122
11235
  id: messageId
10123
11236
  };
10124
- if (options === null || options === void 0 ? void 0 : options.onprogress) {
11237
+ if (options?.onprogress) {
10125
11238
  this._progressHandlers.set(messageId, options.onprogress);
10126
11239
  jsonrpcRequest.params = {
10127
11240
  ...request.params,
10128
11241
  _meta: {
10129
- ...((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {},
11242
+ ...request.params?._meta || {},
10130
11243
  progressToken: messageId
10131
11244
  }
10132
11245
  };
10133
11246
  }
11247
+ if (task) {
11248
+ jsonrpcRequest.params = {
11249
+ ...jsonrpcRequest.params,
11250
+ task
11251
+ };
11252
+ }
11253
+ if (relatedTask) {
11254
+ jsonrpcRequest.params = {
11255
+ ...jsonrpcRequest.params,
11256
+ _meta: {
11257
+ ...jsonrpcRequest.params?._meta || {},
11258
+ [RELATED_TASK_META_KEY]: relatedTask
11259
+ }
11260
+ };
11261
+ }
10134
11262
  const cancel = (reason) => {
10135
- var _a2;
10136
11263
  this._responseHandlers.delete(messageId);
10137
11264
  this._progressHandlers.delete(messageId);
10138
11265
  this._cleanupTimeout(messageId);
10139
- (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send({
11266
+ this._transport?.send({
10140
11267
  jsonrpc: "2.0",
10141
11268
  method: "notifications/cancelled",
10142
11269
  params: {
10143
11270
  requestId: messageId,
10144
11271
  reason: String(reason)
10145
11272
  }
10146
- }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => this._onerror(new Error(`Failed to send cancellation: ${error2}`)));
10147
- reject(reason);
11273
+ }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));
11274
+ const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
11275
+ reject(error2);
10148
11276
  };
10149
11277
  this._responseHandlers.set(messageId, (response) => {
10150
- var _a2;
10151
- if ((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.aborted) {
11278
+ if (options?.signal?.aborted) {
10152
11279
  return;
10153
11280
  }
10154
11281
  if (response instanceof Error) {
10155
11282
  return reject(response);
10156
11283
  }
10157
11284
  try {
10158
- const result = resultSchema.parse(response.result);
10159
- resolve(result);
11285
+ const parseResult = safeParse2(resultSchema, response.result);
11286
+ if (!parseResult.success) {
11287
+ reject(parseResult.error);
11288
+ } else {
11289
+ resolve(parseResult.data);
11290
+ }
10160
11291
  } catch (error2) {
10161
11292
  reject(error2);
10162
11293
  }
10163
11294
  });
10164
- (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener("abort", () => {
10165
- var _a2;
10166
- cancel((_a2 = options === null || options === void 0 ? void 0 : options.signal) === null || _a2 === void 0 ? void 0 : _a2.reason);
10167
- });
10168
- const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
10169
- const timeoutHandler = () => cancel(new McpError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
10170
- this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false);
10171
- this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
10172
- this._cleanupTimeout(messageId);
10173
- reject(error2);
11295
+ options?.signal?.addEventListener("abort", () => {
11296
+ cancel(options?.signal?.reason);
10174
11297
  });
11298
+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
11299
+ const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
11300
+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
11301
+ const relatedTaskId = relatedTask?.taskId;
11302
+ if (relatedTaskId) {
11303
+ const responseResolver = (response) => {
11304
+ const handler = this._responseHandlers.get(messageId);
11305
+ if (handler) {
11306
+ handler(response);
11307
+ } else {
11308
+ this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
11309
+ }
11310
+ };
11311
+ this._requestResolvers.set(messageId, responseResolver);
11312
+ this._enqueueTaskMessage(relatedTaskId, {
11313
+ type: "request",
11314
+ message: jsonrpcRequest,
11315
+ timestamp: Date.now()
11316
+ }).catch((error2) => {
11317
+ this._cleanupTimeout(messageId);
11318
+ reject(error2);
11319
+ });
11320
+ } else {
11321
+ this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
11322
+ this._cleanupTimeout(messageId);
11323
+ reject(error2);
11324
+ });
11325
+ }
10175
11326
  });
10176
11327
  }
11328
+ /**
11329
+ * Gets the current status of a task.
11330
+ *
11331
+ * @experimental Use `client.experimental.tasks.getTask()` to access this method.
11332
+ */
11333
+ async getTask(params, options) {
11334
+ return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
11335
+ }
11336
+ /**
11337
+ * Retrieves the result of a completed task.
11338
+ *
11339
+ * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
11340
+ */
11341
+ async getTaskResult(params, resultSchema, options) {
11342
+ return this.request({ method: "tasks/result", params }, resultSchema, options);
11343
+ }
11344
+ /**
11345
+ * Lists tasks, optionally starting from a pagination cursor.
11346
+ *
11347
+ * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
11348
+ */
11349
+ async listTasks(params, options) {
11350
+ return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
11351
+ }
11352
+ /**
11353
+ * Cancels a specific task.
11354
+ *
11355
+ * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
11356
+ */
11357
+ async cancelTask(params, options) {
11358
+ return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
11359
+ }
10177
11360
  /**
10178
11361
  * Emits a notification, which is a one-way message that does not expect a response.
10179
11362
  */
10180
11363
  async notification(notification, options) {
10181
- var _a, _b;
10182
11364
  if (!this._transport) {
10183
11365
  throw new Error("Not connected");
10184
11366
  }
10185
11367
  this.assertNotificationCapability(notification.method);
10186
- const debouncedMethods = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : [];
10187
- const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId);
11368
+ const relatedTaskId = options?.relatedTask?.taskId;
11369
+ if (relatedTaskId) {
11370
+ const jsonrpcNotification2 = {
11371
+ ...notification,
11372
+ jsonrpc: "2.0",
11373
+ params: {
11374
+ ...notification.params,
11375
+ _meta: {
11376
+ ...notification.params?._meta || {},
11377
+ [RELATED_TASK_META_KEY]: options.relatedTask
11378
+ }
11379
+ }
11380
+ };
11381
+ await this._enqueueTaskMessage(relatedTaskId, {
11382
+ type: "notification",
11383
+ message: jsonrpcNotification2,
11384
+ timestamp: Date.now()
11385
+ });
11386
+ return;
11387
+ }
11388
+ const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
11389
+ const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;
10188
11390
  if (canDebounce) {
10189
11391
  if (this._pendingDebouncedNotifications.has(notification.method)) {
10190
11392
  return;
10191
11393
  }
10192
11394
  this._pendingDebouncedNotifications.add(notification.method);
10193
11395
  Promise.resolve().then(() => {
10194
- var _a2;
10195
11396
  this._pendingDebouncedNotifications.delete(notification.method);
10196
11397
  if (!this._transport) {
10197
11398
  return;
10198
11399
  }
10199
- const jsonrpcNotification2 = {
11400
+ let jsonrpcNotification2 = {
10200
11401
  ...notification,
10201
11402
  jsonrpc: "2.0"
10202
11403
  };
10203
- (_a2 = this._transport) === null || _a2 === void 0 ? void 0 : _a2.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
11404
+ if (options?.relatedTask) {
11405
+ jsonrpcNotification2 = {
11406
+ ...jsonrpcNotification2,
11407
+ params: {
11408
+ ...jsonrpcNotification2.params,
11409
+ _meta: {
11410
+ ...jsonrpcNotification2.params?._meta || {},
11411
+ [RELATED_TASK_META_KEY]: options.relatedTask
11412
+ }
11413
+ }
11414
+ };
11415
+ }
11416
+ this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
10204
11417
  });
10205
11418
  return;
10206
11419
  }
10207
- const jsonrpcNotification = {
11420
+ let jsonrpcNotification = {
10208
11421
  ...notification,
10209
11422
  jsonrpc: "2.0"
10210
11423
  };
11424
+ if (options?.relatedTask) {
11425
+ jsonrpcNotification = {
11426
+ ...jsonrpcNotification,
11427
+ params: {
11428
+ ...jsonrpcNotification.params,
11429
+ _meta: {
11430
+ ...jsonrpcNotification.params?._meta || {},
11431
+ [RELATED_TASK_META_KEY]: options.relatedTask
11432
+ }
11433
+ }
11434
+ };
11435
+ }
10211
11436
  await this._transport.send(jsonrpcNotification, options);
10212
11437
  }
10213
11438
  /**
@@ -10216,10 +11441,11 @@ var Protocol = class {
10216
11441
  * Note that this will replace any previous request handler for the same method.
10217
11442
  */
10218
11443
  setRequestHandler(requestSchema, handler) {
10219
- const method = requestSchema.shape.method.value;
11444
+ const method = getMethodLiteral(requestSchema);
10220
11445
  this.assertRequestHandlerCapability(method);
10221
11446
  this._requestHandlers.set(method, (request, extra) => {
10222
- return Promise.resolve(handler(requestSchema.parse(request), extra));
11447
+ const parsed = parseWithCompat(requestSchema, request);
11448
+ return Promise.resolve(handler(parsed, extra));
10223
11449
  });
10224
11450
  }
10225
11451
  /**
@@ -10242,7 +11468,11 @@ var Protocol = class {
10242
11468
  * Note that this will replace any previous notification handler for the same method.
10243
11469
  */
10244
11470
  setNotificationHandler(notificationSchema, handler) {
10245
- this._notificationHandlers.set(notificationSchema.shape.method.value, (notification) => Promise.resolve(handler(notificationSchema.parse(notification))));
11471
+ const method = getMethodLiteral(notificationSchema);
11472
+ this._notificationHandlers.set(method, (notification) => {
11473
+ const parsed = parseWithCompat(notificationSchema, notification);
11474
+ return Promise.resolve(handler(parsed));
11475
+ });
10246
11476
  }
10247
11477
  /**
10248
11478
  * Removes the notification handler for the given method.
@@ -10250,24 +11480,177 @@ var Protocol = class {
10250
11480
  removeNotificationHandler(method) {
10251
11481
  this._notificationHandlers.delete(method);
10252
11482
  }
11483
+ /**
11484
+ * Cleans up the progress handler associated with a task.
11485
+ * This should be called when a task reaches a terminal status.
11486
+ */
11487
+ _cleanupTaskProgressHandler(taskId) {
11488
+ const progressToken = this._taskProgressTokens.get(taskId);
11489
+ if (progressToken !== void 0) {
11490
+ this._progressHandlers.delete(progressToken);
11491
+ this._taskProgressTokens.delete(taskId);
11492
+ }
11493
+ }
11494
+ /**
11495
+ * Enqueues a task-related message for side-channel delivery via tasks/result.
11496
+ * @param taskId The task ID to associate the message with
11497
+ * @param message The message to enqueue
11498
+ * @param sessionId Optional session ID for binding the operation to a specific session
11499
+ * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
11500
+ *
11501
+ * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
11502
+ * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
11503
+ * simply propagates the error.
11504
+ */
11505
+ async _enqueueTaskMessage(taskId, message, sessionId) {
11506
+ if (!this._taskStore || !this._taskMessageQueue) {
11507
+ throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
11508
+ }
11509
+ const maxQueueSize = this._options?.maxTaskQueueSize;
11510
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
11511
+ }
11512
+ /**
11513
+ * Clears the message queue for a task and rejects any pending request resolvers.
11514
+ * @param taskId The task ID whose queue should be cleared
11515
+ * @param sessionId Optional session ID for binding the operation to a specific session
11516
+ */
11517
+ async _clearTaskQueue(taskId, sessionId) {
11518
+ if (this._taskMessageQueue) {
11519
+ const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
11520
+ for (const message of messages) {
11521
+ if (message.type === "request" && isJSONRPCRequest(message.message)) {
11522
+ const requestId = message.message.id;
11523
+ const resolver = this._requestResolvers.get(requestId);
11524
+ if (resolver) {
11525
+ resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
11526
+ this._requestResolvers.delete(requestId);
11527
+ } else {
11528
+ this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
11529
+ }
11530
+ }
11531
+ }
11532
+ }
11533
+ }
11534
+ /**
11535
+ * Waits for a task update (new messages or status change) with abort signal support.
11536
+ * Uses polling to check for updates at the task's configured poll interval.
11537
+ * @param taskId The task ID to wait for
11538
+ * @param signal Abort signal to cancel the wait
11539
+ * @returns Promise that resolves when an update occurs or rejects if aborted
11540
+ */
11541
+ async _waitForTaskUpdate(taskId, signal) {
11542
+ let interval = this._options?.defaultTaskPollInterval ?? 1e3;
11543
+ try {
11544
+ const task = await this._taskStore?.getTask(taskId);
11545
+ if (task?.pollInterval) {
11546
+ interval = task.pollInterval;
11547
+ }
11548
+ } catch {
11549
+ }
11550
+ return new Promise((resolve, reject) => {
11551
+ if (signal.aborted) {
11552
+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
11553
+ return;
11554
+ }
11555
+ const timeoutId = setTimeout(resolve, interval);
11556
+ signal.addEventListener("abort", () => {
11557
+ clearTimeout(timeoutId);
11558
+ reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
11559
+ }, { once: true });
11560
+ });
11561
+ }
11562
+ requestTaskStore(request, sessionId) {
11563
+ const taskStore = this._taskStore;
11564
+ if (!taskStore) {
11565
+ throw new Error("No task store configured");
11566
+ }
11567
+ return {
11568
+ createTask: async (taskParams) => {
11569
+ if (!request) {
11570
+ throw new Error("No request provided");
11571
+ }
11572
+ return await taskStore.createTask(taskParams, request.id, {
11573
+ method: request.method,
11574
+ params: request.params
11575
+ }, sessionId);
11576
+ },
11577
+ getTask: async (taskId) => {
11578
+ const task = await taskStore.getTask(taskId, sessionId);
11579
+ if (!task) {
11580
+ throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
11581
+ }
11582
+ return task;
11583
+ },
11584
+ storeTaskResult: async (taskId, status, result) => {
11585
+ await taskStore.storeTaskResult(taskId, status, result, sessionId);
11586
+ const task = await taskStore.getTask(taskId, sessionId);
11587
+ if (task) {
11588
+ const notification = TaskStatusNotificationSchema.parse({
11589
+ method: "notifications/tasks/status",
11590
+ params: task
11591
+ });
11592
+ await this.notification(notification);
11593
+ if (isTerminal(task.status)) {
11594
+ this._cleanupTaskProgressHandler(taskId);
11595
+ }
11596
+ }
11597
+ },
11598
+ getTaskResult: (taskId) => {
11599
+ return taskStore.getTaskResult(taskId, sessionId);
11600
+ },
11601
+ updateTaskStatus: async (taskId, status, statusMessage) => {
11602
+ const task = await taskStore.getTask(taskId, sessionId);
11603
+ if (!task) {
11604
+ throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
11605
+ }
11606
+ if (isTerminal(task.status)) {
11607
+ throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
11608
+ }
11609
+ await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
11610
+ const updatedTask = await taskStore.getTask(taskId, sessionId);
11611
+ if (updatedTask) {
11612
+ const notification = TaskStatusNotificationSchema.parse({
11613
+ method: "notifications/tasks/status",
11614
+ params: updatedTask
11615
+ });
11616
+ await this.notification(notification);
11617
+ if (isTerminal(updatedTask.status)) {
11618
+ this._cleanupTaskProgressHandler(taskId);
11619
+ }
11620
+ }
11621
+ },
11622
+ listTasks: (cursor) => {
11623
+ return taskStore.listTasks(cursor, sessionId);
11624
+ }
11625
+ };
11626
+ }
10253
11627
  };
11628
+ function isPlainObject(value) {
11629
+ return value !== null && typeof value === "object" && !Array.isArray(value);
11630
+ }
10254
11631
  function mergeCapabilities(base, additional) {
10255
- return Object.entries(additional).reduce((acc, [key, value]) => {
10256
- if (value && typeof value === "object") {
10257
- acc[key] = acc[key] ? { ...acc[key], ...value } : value;
11632
+ const result = { ...base };
11633
+ for (const key in additional) {
11634
+ const k = key;
11635
+ const addValue = additional[k];
11636
+ if (addValue === void 0)
11637
+ continue;
11638
+ const baseValue = result[k];
11639
+ if (isPlainObject(baseValue) && isPlainObject(addValue)) {
11640
+ result[k] = { ...baseValue, ...addValue };
10258
11641
  } else {
10259
- acc[key] = value;
11642
+ result[k] = addValue;
10260
11643
  }
10261
- return acc;
10262
- }, { ...base });
11644
+ }
11645
+ return result;
10263
11646
  }
10264
11647
 
10265
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
11648
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
10266
11649
  init_esm_shims();
10267
11650
  var import_ajv = __toESM(require_ajv(), 1);
10268
11651
  var import_ajv_formats = __toESM(require_dist(), 1);
10269
11652
  function createDefaultAjvInstance() {
10270
- const ajv = new import_ajv.Ajv({
11653
+ const ajv = new import_ajv.default({
10271
11654
  strict: false,
10272
11655
  validateFormats: true,
10273
11656
  validateSchema: false,
@@ -10299,7 +11682,7 @@ var AjvJsonSchemaValidator = class {
10299
11682
  * ```
10300
11683
  */
10301
11684
  constructor(ajv) {
10302
- this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance();
11685
+ this._ajv = ajv ?? createDefaultAjvInstance();
10303
11686
  }
10304
11687
  /**
10305
11688
  * Create a validator for the given JSON Schema
@@ -10311,8 +11694,7 @@ var AjvJsonSchemaValidator = class {
10311
11694
  * @returns A validator function that validates input data
10312
11695
  */
10313
11696
  getValidator(schema) {
10314
- var _a;
10315
- const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a = this._ajv.getSchema(schema.$id)) !== null && _a !== void 0 ? _a : this._ajv.compile(schema) : this._ajv.compile(schema);
11697
+ const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
10316
11698
  return (input) => {
10317
11699
  const valid = ajvValidator(input);
10318
11700
  if (valid) {
@@ -10332,13 +11714,121 @@ var AjvJsonSchemaValidator = class {
10332
11714
  }
10333
11715
  };
10334
11716
 
10335
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
11717
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
11718
+ init_esm_shims();
11719
+ var ExperimentalServerTasks = class {
11720
+ constructor(_server) {
11721
+ this._server = _server;
11722
+ }
11723
+ /**
11724
+ * Sends a request and returns an AsyncGenerator that yields response messages.
11725
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
11726
+ *
11727
+ * This method provides streaming access to request processing, allowing you to
11728
+ * observe intermediate task status updates for task-augmented requests.
11729
+ *
11730
+ * @param request - The request to send
11731
+ * @param resultSchema - Zod schema for validating the result
11732
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
11733
+ * @returns AsyncGenerator that yields ResponseMessage objects
11734
+ *
11735
+ * @experimental
11736
+ */
11737
+ requestStream(request, resultSchema, options) {
11738
+ return this._server.requestStream(request, resultSchema, options);
11739
+ }
11740
+ /**
11741
+ * Gets the current status of a task.
11742
+ *
11743
+ * @param taskId - The task identifier
11744
+ * @param options - Optional request options
11745
+ * @returns The task status
11746
+ *
11747
+ * @experimental
11748
+ */
11749
+ async getTask(taskId, options) {
11750
+ return this._server.getTask({ taskId }, options);
11751
+ }
11752
+ /**
11753
+ * Retrieves the result of a completed task.
11754
+ *
11755
+ * @param taskId - The task identifier
11756
+ * @param resultSchema - Zod schema for validating the result
11757
+ * @param options - Optional request options
11758
+ * @returns The task result
11759
+ *
11760
+ * @experimental
11761
+ */
11762
+ async getTaskResult(taskId, resultSchema, options) {
11763
+ return this._server.getTaskResult({ taskId }, resultSchema, options);
11764
+ }
11765
+ /**
11766
+ * Lists tasks with optional pagination.
11767
+ *
11768
+ * @param cursor - Optional pagination cursor
11769
+ * @param options - Optional request options
11770
+ * @returns List of tasks with optional next cursor
11771
+ *
11772
+ * @experimental
11773
+ */
11774
+ async listTasks(cursor, options) {
11775
+ return this._server.listTasks(cursor ? { cursor } : void 0, options);
11776
+ }
11777
+ /**
11778
+ * Cancels a running task.
11779
+ *
11780
+ * @param taskId - The task identifier
11781
+ * @param options - Optional request options
11782
+ *
11783
+ * @experimental
11784
+ */
11785
+ async cancelTask(taskId, options) {
11786
+ return this._server.cancelTask({ taskId }, options);
11787
+ }
11788
+ };
11789
+
11790
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
11791
+ init_esm_shims();
11792
+ function assertToolsCallTaskCapability(requests, method, entityName) {
11793
+ if (!requests) {
11794
+ throw new Error(`${entityName} does not support task creation (required for ${method})`);
11795
+ }
11796
+ switch (method) {
11797
+ case "tools/call":
11798
+ if (!requests.tools?.call) {
11799
+ throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
11800
+ }
11801
+ break;
11802
+ default:
11803
+ break;
11804
+ }
11805
+ }
11806
+ function assertClientRequestTaskCapability(requests, method, entityName) {
11807
+ if (!requests) {
11808
+ throw new Error(`${entityName} does not support task creation (required for ${method})`);
11809
+ }
11810
+ switch (method) {
11811
+ case "sampling/createMessage":
11812
+ if (!requests.sampling?.createMessage) {
11813
+ throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
11814
+ }
11815
+ break;
11816
+ case "elicitation/create":
11817
+ if (!requests.elicitation?.create) {
11818
+ throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
11819
+ }
11820
+ break;
11821
+ default:
11822
+ break;
11823
+ }
11824
+ }
11825
+
11826
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
10336
11827
  var Server = class extends Protocol {
10337
11828
  /**
10338
11829
  * Initializes this server with the given name and version information.
10339
11830
  */
10340
11831
  constructor(_serverInfo, options) {
10341
- var _a, _b;
10342
11832
  super(options);
10343
11833
  this._serverInfo = _serverInfo;
10344
11834
  this._loggingLevels = /* @__PURE__ */ new Map();
@@ -10347,18 +11837,14 @@ var Server = class extends Protocol {
10347
11837
  const currentLevel = this._loggingLevels.get(sessionId);
10348
11838
  return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
10349
11839
  };
10350
- this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {};
10351
- this._instructions = options === null || options === void 0 ? void 0 : options.instructions;
10352
- this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator();
11840
+ this._capabilities = options?.capabilities ?? {};
11841
+ this._instructions = options?.instructions;
11842
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();
10353
11843
  this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
10354
- this.setNotificationHandler(InitializedNotificationSchema, () => {
10355
- var _a2;
10356
- return (_a2 = this.oninitialized) === null || _a2 === void 0 ? void 0 : _a2.call(this);
10357
- });
11844
+ this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());
10358
11845
  if (this._capabilities.logging) {
10359
11846
  this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
10360
- var _a2;
10361
- const transportSessionId = extra.sessionId || ((_a2 = extra.requestInfo) === null || _a2 === void 0 ? void 0 : _a2.headers["mcp-session-id"]) || void 0;
11847
+ const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0;
10362
11848
  const { level } = request.params;
10363
11849
  const parseResult = LoggingLevelSchema.safeParse(level);
10364
11850
  if (parseResult.success) {
@@ -10368,6 +11854,21 @@ var Server = class extends Protocol {
10368
11854
  });
10369
11855
  }
10370
11856
  }
11857
+ /**
11858
+ * Access experimental features.
11859
+ *
11860
+ * WARNING: These APIs are experimental and may change without notice.
11861
+ *
11862
+ * @experimental
11863
+ */
11864
+ get experimental() {
11865
+ if (!this._experimental) {
11866
+ this._experimental = {
11867
+ tasks: new ExperimentalServerTasks(this)
11868
+ };
11869
+ }
11870
+ return this._experimental;
11871
+ }
10371
11872
  /**
10372
11873
  * Registers new capabilities. This can only be called before connecting to a transport.
10373
11874
  *
@@ -10379,21 +11880,71 @@ var Server = class extends Protocol {
10379
11880
  }
10380
11881
  this._capabilities = mergeCapabilities(this._capabilities, capabilities);
10381
11882
  }
11883
+ /**
11884
+ * Override request handler registration to enforce server-side validation for tools/call.
11885
+ */
11886
+ setRequestHandler(requestSchema, handler) {
11887
+ const shape = getObjectShape(requestSchema);
11888
+ const methodSchema = shape?.method;
11889
+ if (!methodSchema) {
11890
+ throw new Error("Schema is missing a method literal");
11891
+ }
11892
+ let methodValue;
11893
+ if (isZ4Schema(methodSchema)) {
11894
+ const v4Schema = methodSchema;
11895
+ const v4Def = v4Schema._zod?.def;
11896
+ methodValue = v4Def?.value ?? v4Schema.value;
11897
+ } else {
11898
+ const v3Schema = methodSchema;
11899
+ const legacyDef = v3Schema._def;
11900
+ methodValue = legacyDef?.value ?? v3Schema.value;
11901
+ }
11902
+ if (typeof methodValue !== "string") {
11903
+ throw new Error("Schema method literal must be a string");
11904
+ }
11905
+ const method = methodValue;
11906
+ if (method === "tools/call") {
11907
+ const wrappedHandler = async (request, extra) => {
11908
+ const validatedRequest = safeParse2(CallToolRequestSchema, request);
11909
+ if (!validatedRequest.success) {
11910
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
11911
+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
11912
+ }
11913
+ const { params } = validatedRequest.data;
11914
+ const result = await Promise.resolve(handler(request, extra));
11915
+ if (params.task) {
11916
+ const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
11917
+ if (!taskValidationResult.success) {
11918
+ const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
11919
+ throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
11920
+ }
11921
+ return taskValidationResult.data;
11922
+ }
11923
+ const validationResult = safeParse2(CallToolResultSchema, result);
11924
+ if (!validationResult.success) {
11925
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
11926
+ throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
11927
+ }
11928
+ return validationResult.data;
11929
+ };
11930
+ return super.setRequestHandler(requestSchema, wrappedHandler);
11931
+ }
11932
+ return super.setRequestHandler(requestSchema, handler);
11933
+ }
10382
11934
  assertCapabilityForMethod(method) {
10383
- var _a, _b, _c;
10384
11935
  switch (method) {
10385
11936
  case "sampling/createMessage":
10386
- if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) {
11937
+ if (!this._clientCapabilities?.sampling) {
10387
11938
  throw new Error(`Client does not support sampling (required for ${method})`);
10388
11939
  }
10389
11940
  break;
10390
11941
  case "elicitation/create":
10391
- if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.elicitation)) {
11942
+ if (!this._clientCapabilities?.elicitation) {
10392
11943
  throw new Error(`Client does not support elicitation (required for ${method})`);
10393
11944
  }
10394
11945
  break;
10395
11946
  case "roots/list":
10396
- if (!((_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.roots)) {
11947
+ if (!this._clientCapabilities?.roots) {
10397
11948
  throw new Error(`Client does not support listing roots (required for ${method})`);
10398
11949
  }
10399
11950
  break;
@@ -10424,6 +11975,11 @@ var Server = class extends Protocol {
10424
11975
  throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
10425
11976
  }
10426
11977
  break;
11978
+ case "notifications/elicitation/complete":
11979
+ if (!this._clientCapabilities?.elicitation?.url) {
11980
+ throw new Error(`Client does not support URL elicitation (required for ${method})`);
11981
+ }
11982
+ break;
10427
11983
  case "notifications/cancelled":
10428
11984
  break;
10429
11985
  case "notifications/progress":
@@ -10431,10 +11987,13 @@ var Server = class extends Protocol {
10431
11987
  }
10432
11988
  }
10433
11989
  assertRequestHandlerCapability(method) {
11990
+ if (!this._capabilities) {
11991
+ return;
11992
+ }
10434
11993
  switch (method) {
10435
- case "sampling/createMessage":
10436
- if (!this._capabilities.sampling) {
10437
- throw new Error(`Server does not support sampling (required for ${method})`);
11994
+ case "completion/complete":
11995
+ if (!this._capabilities.completions) {
11996
+ throw new Error(`Server does not support completions (required for ${method})`);
10438
11997
  }
10439
11998
  break;
10440
11999
  case "logging/setLevel":
@@ -10461,11 +12020,28 @@ var Server = class extends Protocol {
10461
12020
  throw new Error(`Server does not support tools (required for ${method})`);
10462
12021
  }
10463
12022
  break;
12023
+ case "tasks/get":
12024
+ case "tasks/list":
12025
+ case "tasks/result":
12026
+ case "tasks/cancel":
12027
+ if (!this._capabilities.tasks) {
12028
+ throw new Error(`Server does not support tasks capability (required for ${method})`);
12029
+ }
12030
+ break;
10464
12031
  case "ping":
10465
12032
  case "initialize":
10466
12033
  break;
10467
12034
  }
10468
12035
  }
12036
+ assertTaskCapability(method) {
12037
+ assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client");
12038
+ }
12039
+ assertTaskHandlerCapability(method) {
12040
+ if (!this._capabilities) {
12041
+ return;
12042
+ }
12043
+ assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server");
12044
+ }
10469
12045
  async _oninitialize(request) {
10470
12046
  const requestedVersion = request.params.protocolVersion;
10471
12047
  this._clientCapabilities = request.params.capabilities;
@@ -10496,26 +12072,100 @@ var Server = class extends Protocol {
10496
12072
  async ping() {
10497
12073
  return this.request({ method: "ping" }, EmptyResultSchema);
10498
12074
  }
12075
+ // Implementation
10499
12076
  async createMessage(params, options) {
12077
+ if (params.tools || params.toolChoice) {
12078
+ if (!this._clientCapabilities?.sampling?.tools) {
12079
+ throw new Error("Client does not support sampling tools capability.");
12080
+ }
12081
+ }
12082
+ if (params.messages.length > 0) {
12083
+ const lastMessage = params.messages[params.messages.length - 1];
12084
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
12085
+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");
12086
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
12087
+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
12088
+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
12089
+ if (hasToolResults) {
12090
+ if (lastContent.some((c) => c.type !== "tool_result")) {
12091
+ throw new Error("The last message must contain only tool_result content if any is present");
12092
+ }
12093
+ if (!hasPreviousToolUse) {
12094
+ throw new Error("tool_result blocks are not matching any tool_use from the previous message");
12095
+ }
12096
+ }
12097
+ if (hasPreviousToolUse) {
12098
+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
12099
+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
12100
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
12101
+ throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
12102
+ }
12103
+ }
12104
+ }
12105
+ if (params.tools) {
12106
+ return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);
12107
+ }
10500
12108
  return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
10501
12109
  }
12110
+ /**
12111
+ * Creates an elicitation request for the given parameters.
12112
+ * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
12113
+ * @param params The parameters for the elicitation request.
12114
+ * @param options Optional request options.
12115
+ * @returns The result of the elicitation request.
12116
+ */
10502
12117
  async elicitInput(params, options) {
10503
- const result = await this.request({ method: "elicitation/create", params }, ElicitResultSchema, options);
10504
- if (result.action === "accept" && result.content && params.requestedSchema) {
10505
- try {
10506
- const validator = this._jsonSchemaValidator.getValidator(params.requestedSchema);
10507
- const validationResult = validator(result.content);
10508
- if (!validationResult.valid) {
10509
- throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
10510
- }
10511
- } catch (error2) {
10512
- if (error2 instanceof McpError) {
10513
- throw error2;
12118
+ const mode = params.mode ?? "form";
12119
+ switch (mode) {
12120
+ case "url": {
12121
+ if (!this._clientCapabilities?.elicitation?.url) {
12122
+ throw new Error("Client does not support url elicitation.");
12123
+ }
12124
+ const urlParams = params;
12125
+ return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);
12126
+ }
12127
+ case "form": {
12128
+ if (!this._clientCapabilities?.elicitation?.form) {
12129
+ throw new Error("Client does not support form elicitation.");
12130
+ }
12131
+ const formParams = params.mode === "form" ? params : { ...params, mode: "form" };
12132
+ const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options);
12133
+ if (result.action === "accept" && result.content && formParams.requestedSchema) {
12134
+ try {
12135
+ const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);
12136
+ const validationResult = validator(result.content);
12137
+ if (!validationResult.valid) {
12138
+ throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
12139
+ }
12140
+ } catch (error2) {
12141
+ if (error2 instanceof McpError) {
12142
+ throw error2;
12143
+ }
12144
+ throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`);
12145
+ }
10514
12146
  }
10515
- throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`);
12147
+ return result;
10516
12148
  }
10517
12149
  }
10518
- return result;
12150
+ }
12151
+ /**
12152
+ * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
12153
+ * notification for the specified elicitation ID.
12154
+ *
12155
+ * @param elicitationId The ID of the elicitation to mark as complete.
12156
+ * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
12157
+ * @returns A function that emits the completion notification when awaited.
12158
+ */
12159
+ createElicitationCompletionNotifier(elicitationId, options) {
12160
+ if (!this._clientCapabilities?.elicitation?.url) {
12161
+ throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
12162
+ }
12163
+ return () => this.notification({
12164
+ method: "notifications/elicitation/complete",
12165
+ params: {
12166
+ elicitationId
12167
+ }
12168
+ }, options);
10519
12169
  }
10520
12170
  async listRoots(params, options) {
10521
12171
  return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);
@@ -10553,11 +12203,11 @@ var Server = class extends Protocol {
10553
12203
  }
10554
12204
  };
10555
12205
 
10556
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
12206
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
10557
12207
  init_esm_shims();
10558
12208
  import process2 from "process";
10559
12209
 
10560
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
12210
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
10561
12211
  init_esm_shims();
10562
12212
  var ReadBuffer = class {
10563
12213
  append(chunk) {
@@ -10586,7 +12236,7 @@ function serializeMessage(message) {
10586
12236
  return JSON.stringify(message) + "\n";
10587
12237
  }
10588
12238
 
10589
- // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.21.1/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
12239
+ // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.25.1_hono@4.11.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
10590
12240
  var StdioServerTransport = class {
10591
12241
  constructor(_stdin = process2.stdin, _stdout = process2.stdout) {
10592
12242
  this._stdin = _stdin;
@@ -10598,8 +12248,7 @@ var StdioServerTransport = class {
10598
12248
  this.processReadBuffer();
10599
12249
  };
10600
12250
  this._onerror = (error2) => {
10601
- var _a;
10602
- (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error2);
12251
+ this.onerror?.(error2);
10603
12252
  };
10604
12253
  }
10605
12254
  /**
@@ -10614,21 +12263,19 @@ var StdioServerTransport = class {
10614
12263
  this._stdin.on("error", this._onerror);
10615
12264
  }
10616
12265
  processReadBuffer() {
10617
- var _a, _b;
10618
12266
  while (true) {
10619
12267
  try {
10620
12268
  const message = this._readBuffer.readMessage();
10621
12269
  if (message === null) {
10622
12270
  break;
10623
12271
  }
10624
- (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message);
12272
+ this.onmessage?.(message);
10625
12273
  } catch (error2) {
10626
- (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error2);
12274
+ this.onerror?.(error2);
10627
12275
  }
10628
12276
  }
10629
12277
  }
10630
12278
  async close() {
10631
- var _a;
10632
12279
  this._stdin.off("data", this._ondata);
10633
12280
  this._stdin.off("error", this._onerror);
10634
12281
  const remainingDataListeners = this._stdin.listenerCount("data");
@@ -10636,7 +12283,7 @@ var StdioServerTransport = class {
10636
12283
  this._stdin.pause();
10637
12284
  }
10638
12285
  this._readBuffer.clear();
10639
- (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this);
12286
+ this.onclose?.();
10640
12287
  }
10641
12288
  send(message) {
10642
12289
  return new Promise((resolve) => {
@@ -11593,7 +13240,7 @@ function showCustomHelp() {
11593
13240
 
11594
13241
  // src/version.ts
11595
13242
  init_esm_shims();
11596
- import { readFileSync } from "fs";
13243
+ import { readFileSync as readFileSync2 } from "fs";
11597
13244
  import { dirname, join as join3 } from "path";
11598
13245
  import { fileURLToPath as fileURLToPath3 } from "url";
11599
13246
  var __filename3 = fileURLToPath3(import.meta.url);
@@ -11601,7 +13248,7 @@ var __dirname3 = dirname(__filename3);
11601
13248
  function getVersion() {
11602
13249
  try {
11603
13250
  const packageJsonPath = join3(__dirname3, "../package.json");
11604
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
13251
+ const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
11605
13252
  return packageJson.version;
11606
13253
  } catch {
11607
13254
  return "0.0.0";