clanka 0.8.3 → 0.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/AgentExecutor.d.ts.map +1 -1
  2. package/dist/AgentExecutor.js +1 -1
  3. package/dist/AgentExecutor.js.map +1 -1
  4. package/dist/AgentExecutor.test.d.ts +2 -0
  5. package/dist/AgentExecutor.test.d.ts.map +1 -0
  6. package/dist/AgentExecutor.test.js +87 -0
  7. package/dist/AgentExecutor.test.js.map +1 -0
  8. package/dist/AgentSkills.test.js +1 -0
  9. package/dist/AgentSkills.test.js.map +1 -1
  10. package/dist/AgentTools.d.ts.map +1 -1
  11. package/dist/AgentTools.js +2 -1
  12. package/dist/AgentTools.js.map +1 -1
  13. package/dist/Compaction.test.js +1 -0
  14. package/dist/Compaction.test.js.map +1 -1
  15. package/dist/bin/{Effect-BCeySOy1.mjs → Effect-BEUn4I5E.mjs} +339 -288
  16. package/dist/bin/Effect-BEUn4I5E.mjs.map +1 -0
  17. package/dist/bin/{McpClient-DP4jlaD1.mjs → McpClient-C0FVuDj2.mjs} +218 -62
  18. package/dist/bin/McpClient-C0FVuDj2.mjs.map +1 -0
  19. package/dist/bin/{OutputFormatter-Ch8yFytV.mjs → OutputFormatter-DffD5oxX.mjs} +8 -8
  20. package/dist/bin/OutputFormatter-DffD5oxX.mjs.map +1 -0
  21. package/dist/bin/{Schema-C9JQ5hI0.mjs → Schema-CjUGw2Xh.mjs} +480 -384
  22. package/dist/bin/Schema-CjUGw2Xh.mjs.map +1 -0
  23. package/dist/bin/{SemanticSearch-BJGnYhFt.mjs → SemanticSearch-CFB73IPb.mjs} +321 -268
  24. package/dist/bin/SemanticSearch-CFB73IPb.mjs.map +1 -0
  25. package/dist/bin/{Stream-CgH3SuLu.mjs → Stream-Cu6P7ZHo.mjs} +180 -172
  26. package/dist/bin/Stream-Cu6P7ZHo.mjs.map +1 -0
  27. package/dist/bin/cli.mjs +306 -259
  28. package/dist/bin/cli.mjs.map +1 -1
  29. package/package.json +20 -20
  30. package/src/AgentExecutor.test.ts +133 -0
  31. package/src/AgentExecutor.ts +1 -2
  32. package/src/AgentSkills.test.ts +1 -0
  33. package/src/AgentTools.ts +2 -1
  34. package/src/Compaction.test.ts +1 -0
  35. package/dist/bin/Effect-BCeySOy1.mjs.map +0 -1
  36. package/dist/bin/McpClient-DP4jlaD1.mjs.map +0 -1
  37. package/dist/bin/OutputFormatter-Ch8yFytV.mjs.map +0 -1
  38. package/dist/bin/Schema-C9JQ5hI0.mjs.map +0 -1
  39. package/dist/bin/SemanticSearch-BJGnYhFt.mjs.map +0 -1
  40. package/dist/bin/Stream-CgH3SuLu.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
- import { Ct as promise, Ta as Service, Wt as sync, Y as gen, Yt as tryPromise, er as effect, t as acquireRelease, z as fn } from "./Effect-BCeySOy1.mjs";
2
- import { d as Defect, z as TaggedError } from "./Schema-C9JQ5hI0.mjs";
1
+ import { B as fn, Ea as Service, Gt as sync, X as gen, Xt as tryPromise, t as acquireRelease, tr as effect, wt as promise } from "./Effect-BEUn4I5E.mjs";
2
+ import { d as Defect, z as TaggedError } from "./Schema-CjUGw2Xh.mjs";
3
3
  import { O as __commonJSMin, k as __toESM } from "./cli.mjs";
4
4
  //#region node_modules/.pnpm/zod@4.4.2/node_modules/zod/v4/core/core.js
5
5
  var _a$1;
@@ -3383,7 +3383,7 @@ const optionalProcessor = (schema, ctx, _json, params) => {
3383
3383
  seen.ref = def.innerType;
3384
3384
  };
3385
3385
  //#endregion
3386
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
3386
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
3387
3387
  function isZ4Schema(s) {
3388
3388
  return !!s._zod;
3389
3389
  }
@@ -4349,7 +4349,7 @@ function number(params) {
4349
4349
  return _coercedNumber(ZodNumber, params);
4350
4350
  }
4351
4351
  //#endregion
4352
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
4352
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
4353
4353
  const LATEST_PROTOCOL_VERSION = "2025-11-25";
4354
4354
  const SUPPORTED_PROTOCOL_VERSIONS = [
4355
4355
  LATEST_PROTOCOL_VERSION,
@@ -5150,12 +5150,12 @@ var UrlElicitationRequiredError = class extends McpError {
5150
5150
  }
5151
5151
  };
5152
5152
  //#endregion
5153
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
5153
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
5154
5154
  function isTerminal(status) {
5155
5155
  return status === "completed" || status === "failed" || status === "cancelled";
5156
5156
  }
5157
5157
  //#endregion
5158
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
5158
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
5159
5159
  function getMethodLiteral(schema) {
5160
5160
  const methodSchema = getObjectShape(schema)?.method;
5161
5161
  if (!methodSchema) throw new Error("Schema is missing a method literal");
@@ -5169,7 +5169,7 @@ function parseWithCompat(schema, data) {
5169
5169
  return result.data;
5170
5170
  }
5171
5171
  //#endregion
5172
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
5172
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
5173
5173
  const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
5174
5174
  var Protocol = class {
5175
5175
  constructor(_options) {
@@ -5202,6 +5202,7 @@ var Protocol = class {
5202
5202
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
5203
5203
  const handleTaskResult = async () => {
5204
5204
  const taskId = request.params.taskId;
5205
+ if (!await this._taskStore.getTask(taskId, extra.sessionId)) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
5205
5206
  if (this._taskMessageQueue) {
5206
5207
  let queuedMessage;
5207
5208
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -5228,12 +5229,12 @@ var Protocol = class {
5228
5229
  const task = await this._taskStore.getTask(taskId, extra.sessionId);
5229
5230
  if (!task) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
5230
5231
  if (!isTerminal(task.status)) {
5231
- await this._waitForTaskUpdate(taskId, extra.signal);
5232
+ await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
5232
5233
  return await handleTaskResult();
5233
5234
  }
5234
5235
  if (isTerminal(task.status)) {
5235
5236
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
5236
- this._clearTaskQueue(taskId);
5237
+ this._clearTaskQueue(taskId, extra.sessionId);
5237
5238
  return {
5238
5239
  ...result,
5239
5240
  _meta: {
@@ -5264,7 +5265,7 @@ var Protocol = class {
5264
5265
  if (!task) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
5265
5266
  if (isTerminal(task.status)) throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
5266
5267
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
5267
- this._clearTaskQueue(request.params.taskId);
5268
+ this._clearTaskQueue(request.params.taskId, extra.sessionId);
5268
5269
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
5269
5270
  if (!cancelledTask) throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
5270
5271
  return {
@@ -5364,6 +5365,17 @@ var Protocol = class {
5364
5365
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
5365
5366
  const capturedTransport = this._transport;
5366
5367
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
5368
+ const sessionId = capturedTransport?.sessionId;
5369
+ const store = this._taskStore;
5370
+ let relatedTaskFound = true;
5371
+ let relatedTaskLookup;
5372
+ if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
5373
+ relatedTaskFound = false;
5374
+ relatedTaskLookup = (async () => {
5375
+ if (!await store.getTask(relatedTaskId, sessionId)) throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
5376
+ relatedTaskFound = true;
5377
+ })();
5378
+ }
5367
5379
  if (handler === void 0) {
5368
5380
  const errorResponse = {
5369
5381
  jsonrpc: "2.0",
@@ -5373,7 +5385,14 @@ var Protocol = class {
5373
5385
  message: "Method not found"
5374
5386
  }
5375
5387
  };
5376
- if (relatedTaskId && this._taskMessageQueue) this._enqueueTaskMessage(relatedTaskId, {
5388
+ if (relatedTaskId && relatedTaskLookup) {
5389
+ const queuedError = {
5390
+ type: "error",
5391
+ message: errorResponse,
5392
+ timestamp: Date.now()
5393
+ };
5394
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
5395
+ } else if (relatedTaskId && this._taskMessageQueue) this._enqueueTaskMessage(relatedTaskId, {
5377
5396
  type: "error",
5378
5397
  message: errorResponse,
5379
5398
  timestamp: Date.now()
@@ -5415,7 +5434,8 @@ var Protocol = class {
5415
5434
  closeSSEStream: extra?.closeSSEStream,
5416
5435
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
5417
5436
  };
5418
- Promise.resolve().then(() => {
5437
+ (relatedTaskLookup ?? Promise.resolve()).then(() => {
5438
+ if (relatedTaskLookup && abortController.signal.aborted) throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
5419
5439
  if (taskCreationParams) this.assertTaskHandlerCapability(request.method);
5420
5440
  }).then(() => handler(request, fullExtra)).then(async (result) => {
5421
5441
  if (abortController.signal.aborted) return;
@@ -5441,7 +5461,7 @@ var Protocol = class {
5441
5461
  ...error["data"] !== void 0 && { data: error["data"] }
5442
5462
  }
5443
5463
  };
5444
- if (relatedTaskId && this._taskMessageQueue) await this._enqueueTaskMessage(relatedTaskId, {
5464
+ if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) await this._enqueueTaskMessage(relatedTaskId, {
5445
5465
  type: "error",
5446
5466
  message: errorResponse,
5447
5467
  timestamp: Date.now()
@@ -5801,7 +5821,7 @@ var Protocol = class {
5801
5821
  async _enqueueTaskMessage(taskId, message, sessionId) {
5802
5822
  if (!this._taskStore || !this._taskMessageQueue) throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
5803
5823
  const maxQueueSize = this._options?.maxTaskQueueSize;
5804
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
5824
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
5805
5825
  }
5806
5826
  async _clearTaskQueue(taskId, sessionId) {
5807
5827
  if (this._taskMessageQueue) {
@@ -5816,10 +5836,10 @@ var Protocol = class {
5816
5836
  }
5817
5837
  }
5818
5838
  }
5819
- async _waitForTaskUpdate(taskId, signal) {
5839
+ async _waitForTaskUpdate(taskId, signal, sessionId) {
5820
5840
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
5821
5841
  try {
5822
- const task = await this._taskStore?.getTask(taskId);
5842
+ const task = await this._taskStore?.getTask(taskId, sessionId);
5823
5843
  if (task?.pollInterval) interval = task.pollInterval;
5824
5844
  } catch {}
5825
5845
  return new Promise((resolve, reject) => {
@@ -12227,7 +12247,7 @@ var require_dist = __commonJSMin(((exports, module) => {
12227
12247
  exports.default = formatsPlugin;
12228
12248
  }));
12229
12249
  //#endregion
12230
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
12250
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
12231
12251
  var import_ajv = __toESM(require_ajv(), 1);
12232
12252
  var import_dist = __toESM(require_dist(), 1);
12233
12253
  function createDefaultAjvInstance() {
@@ -12261,7 +12281,7 @@ var AjvJsonSchemaValidator = class {
12261
12281
  }
12262
12282
  };
12263
12283
  //#endregion
12264
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
12284
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
12265
12285
  var ExperimentalClientTasks = class {
12266
12286
  constructor(_client) {
12267
12287
  this._client = _client;
@@ -12331,7 +12351,7 @@ var ExperimentalClientTasks = class {
12331
12351
  }
12332
12352
  };
12333
12353
  //#endregion
12334
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
12354
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
12335
12355
  function assertToolsCallTaskCapability(requests, method, entityName) {
12336
12356
  if (!requests) throw new Error(`${entityName} does not support task creation (required for ${method})`);
12337
12357
  switch (method) {
@@ -12348,7 +12368,7 @@ function assertClientRequestTaskCapability(requests, method, entityName) {
12348
12368
  }
12349
12369
  }
12350
12370
  //#endregion
12351
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
12371
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
12352
12372
  function applyElicitationDefaults(schema, data) {
12353
12373
  if (!schema || data === null || typeof data !== "object") return;
12354
12374
  if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
@@ -12770,7 +12790,7 @@ var require_content_type = __commonJSMin(((exports) => {
12770
12790
  }
12771
12791
  }));
12772
12792
  //#endregion
12773
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
12793
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js
12774
12794
  var import_content_type = __toESM(require_content_type(), 1);
12775
12795
  function mediaTypeEssence(header) {
12776
12796
  if (!header) return;
@@ -12783,7 +12803,7 @@ function mediaTypeEssence(header) {
12783
12803
  }
12784
12804
  }
12785
12805
  //#endregion
12786
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
12806
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
12787
12807
  function normalizeHeaders(headers) {
12788
12808
  if (!headers) return {};
12789
12809
  if (headers instanceof Headers) return Object.fromEntries(headers.entries());
@@ -12803,6 +12823,65 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
12803
12823
  });
12804
12824
  };
12805
12825
  }
12826
+ const MAX_REDIRECTS = 5;
12827
+ const REDIRECT_STATUSES = [
12828
+ 301,
12829
+ 302,
12830
+ 303,
12831
+ 307,
12832
+ 308
12833
+ ];
12834
+ function isWithinOrigin(from, to) {
12835
+ if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) return true;
12836
+ return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
12837
+ }
12838
+ function redirectTarget(response, requestUrl) {
12839
+ const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
12840
+ try {
12841
+ return location ? new URL(location, requestUrl) : void 0;
12842
+ } catch {
12843
+ return;
12844
+ }
12845
+ }
12846
+ function followWithinOrigin(baseFetch, url, init, response, followed = 0) {
12847
+ const target = redirectTarget(response, url);
12848
+ const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
12849
+ if (!target || followed === MAX_REDIRECTS || !keepsMethod) return;
12850
+ const from = new URL(url);
12851
+ if ((target.username || target.password) && (target.username !== from.username || target.password !== from.password) || !isWithinOrigin(from, target)) return;
12852
+ return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, {
12853
+ ...init,
12854
+ redirect: "manual"
12855
+ })).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
12856
+ }
12857
+ const followingFetches = new WeakSet();
12858
+ function fetchLeavingRedirects(baseFetch) {
12859
+ const following = (url, init) => (baseFetch ?? fetch)(url, init);
12860
+ followingFetches.add(following);
12861
+ return following;
12862
+ }
12863
+ function fetchWithinOrigin(baseFetch = fetch) {
12864
+ if (followingFetches.has(baseFetch)) return baseFetch;
12865
+ return (url, init) => {
12866
+ if (init?.redirect === "error" || init?.redirect === "manual") return baseFetch(url, init);
12867
+ return Promise.resolve(baseFetch(url, {
12868
+ ...init,
12869
+ redirect: "manual"
12870
+ })).then((response) => followWithinOrigin(baseFetch, url, init, response) ?? response);
12871
+ };
12872
+ }
12873
+ function unfollowedRedirect(response, requestUrl) {
12874
+ if (response.type === "opaqueredirect") return "Redirect not followed: this runtime does not expose the redirect target";
12875
+ const from = response.url || requestUrl;
12876
+ const target = redirectTarget(response, from);
12877
+ if (!target) return;
12878
+ target.username = target.password = target.search = target.hash = "";
12879
+ if (target.protocol === "http:" && new URL(from).protocol === "https:") {
12880
+ target.protocol = "https:";
12881
+ return `Redirect to plain http not followed; try ${target.href} instead`;
12882
+ }
12883
+ return `Redirect to ${target.href} not followed`;
12884
+ }
12806
12885
  //#endregion
12807
12886
  //#region node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
12808
12887
  let crypto;
@@ -12837,7 +12916,7 @@ async function pkceChallenge(length) {
12837
12916
  };
12838
12917
  }
12839
12918
  //#endregion
12840
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
12919
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
12841
12920
  const SafeUrlSchema = url().superRefine((val, ctx) => {
12842
12921
  if (!URL.canParse(val)) {
12843
12922
  ctx.addIssue({
@@ -12936,7 +13015,8 @@ const OAuthTokensSchema = object({
12936
13015
  token_type: string(),
12937
13016
  expires_in: number().optional(),
12938
13017
  scope: string().optional(),
12939
- refresh_token: string().optional()
13018
+ refresh_token: string().optional(),
13019
+ issuer: string().optional().catch(void 0)
12940
13020
  }).strip();
12941
13021
  const OAuthErrorResponseSchema = object({
12942
13022
  error: string(),
@@ -12966,7 +13046,8 @@ const OAuthClientInformationSchema = object({
12966
13046
  client_id: string(),
12967
13047
  client_secret: string().optional(),
12968
13048
  client_id_issued_at: number$1().optional(),
12969
- client_secret_expires_at: number$1().optional()
13049
+ client_secret_expires_at: number$1().optional(),
13050
+ issuer: string().optional().catch(void 0)
12970
13051
  }).strip();
12971
13052
  const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
12972
13053
  const OAuthClientRegistrationErrorSchema = object({
@@ -12978,7 +13059,7 @@ const OAuthTokenRevocationRequestSchema = object({
12978
13059
  token_type_hint: string().optional()
12979
13060
  }).strip();
12980
13061
  //#endregion
12981
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
13062
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
12982
13063
  function resourceUrlFromServerUrl(url) {
12983
13064
  const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href);
12984
13065
  resourceURL.hash = "";
@@ -12994,7 +13075,7 @@ function checkResourceAllowed({ requestedResource, configuredResource }) {
12994
13075
  return requestedPath.startsWith(configuredPath);
12995
13076
  }
12996
13077
  //#endregion
12997
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
13078
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
12998
13079
  var OAuthError = class extends Error {
12999
13080
  constructor(message, errorUri) {
13000
13081
  super(message);
@@ -13067,7 +13148,7 @@ const OAUTH_ERRORS = {
13067
13148
  [InvalidTargetError.errorCode]: InvalidTargetError
13068
13149
  };
13069
13150
  //#endregion
13070
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
13151
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
13071
13152
  var UnauthorizedError = class extends Error {
13072
13153
  constructor(message) {
13073
13154
  super(message ?? "Unauthorized");
@@ -13125,10 +13206,31 @@ async function parseErrorResponse(input) {
13125
13206
  const { error, error_description, error_uri } = OAuthErrorResponseSchema.parse(JSON.parse(body));
13126
13207
  return new (OAUTH_ERRORS[error] || ServerError)(error_description || "", error_uri);
13127
13208
  } catch (error) {
13128
- const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error}. Raw body: ${body}`;
13209
+ const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
13210
+ const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error}. Raw body: ${body}`}`;
13129
13211
  return new ServerError(errorMessage);
13130
13212
  }
13131
13213
  }
13214
+ function issuersMatch(a, b) {
13215
+ let [x, y] = [a, b];
13216
+ try {
13217
+ [x, y] = [new URL(a).href, new URL(b).href];
13218
+ } catch {}
13219
+ return x === y || x.endsWith("/") && x.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x;
13220
+ }
13221
+ function discardIfIssuerMismatch(stored, issuer) {
13222
+ if (!stored) return void 0;
13223
+ if (typeof stored.issuer !== "string") return stored.issuer == null ? stored : {
13224
+ ...stored,
13225
+ issuer: void 0
13226
+ };
13227
+ return issuersMatch(stored.issuer, issuer) ? stored : void 0;
13228
+ }
13229
+ const TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
13230
+ const RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
13231
+ function boundElsewhereError(stored, issuer) {
13232
+ return new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`);
13233
+ }
13132
13234
  async function auth(provider, options) {
13133
13235
  try {
13134
13236
  return await authInternal(provider, options);
@@ -13178,27 +13280,46 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
13178
13280
  authorizationServerMetadata: metadata
13179
13281
  });
13180
13282
  }
13181
- const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
13283
+ const issuer = String(authorizationServerUrl);
13284
+ const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
13285
+ const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
13182
13286
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
13183
- let clientInformation = await Promise.resolve(provider.clientInformation());
13287
+ const storedClientInformation = await Promise.resolve(provider.clientInformation());
13288
+ let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
13289
+ const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
13290
+ if (storedClientInformation && !clientInformation && !canRegisterAgain) throw boundElsewhereError(storedClientInformation, issuer);
13291
+ const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
13292
+ const bindClientInformation = async () => {
13293
+ try {
13294
+ if (unstampedClientInformation) await provider.saveClientInformation?.({
13295
+ ...unstampedClientInformation,
13296
+ issuer
13297
+ });
13298
+ } catch {}
13299
+ };
13184
13300
  if (!clientInformation) {
13185
13301
  if (authorizationCode !== void 0) throw new Error("Existing OAuth client information is required when exchanging an authorization code");
13186
13302
  const supportsUrlBasedClientId = metadata?.client_id_metadata_document_supported === true;
13187
13303
  const clientMetadataUrl = provider.clientMetadataUrl;
13188
13304
  if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
13189
13305
  if (supportsUrlBasedClientId && clientMetadataUrl) {
13190
- clientInformation = { client_id: clientMetadataUrl };
13306
+ clientInformation = {
13307
+ client_id: clientMetadataUrl,
13308
+ issuer
13309
+ };
13191
13310
  await provider.saveClientInformation?.(clientInformation);
13192
13311
  } else {
13193
13312
  if (!provider.saveClientInformation) throw new Error("OAuth client information must be saveable for dynamic registration");
13194
- const fullInformation = await registerClient(authorizationServerUrl, {
13195
- metadata,
13196
- clientMetadata: provider.clientMetadata,
13197
- scope: resolvedScope,
13198
- fetchFn
13199
- });
13200
- await provider.saveClientInformation(fullInformation);
13201
- clientInformation = fullInformation;
13313
+ clientInformation = {
13314
+ ...await registerClient(authorizationServerUrl, {
13315
+ metadata,
13316
+ clientMetadata: provider.clientMetadata,
13317
+ scope: resolvedScope,
13318
+ fetchFn
13319
+ }),
13320
+ issuer
13321
+ };
13322
+ await provider.saveClientInformation(clientInformation);
13202
13323
  }
13203
13324
  }
13204
13325
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -13209,10 +13330,15 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
13209
13330
  authorizationCode,
13210
13331
  fetchFn
13211
13332
  });
13212
- await provider.saveTokens(tokens);
13333
+ await bindClientInformation();
13334
+ await provider.saveTokens({
13335
+ ...tokens,
13336
+ issuer
13337
+ });
13213
13338
  return "AUTHORIZED";
13214
13339
  }
13215
- const tokens = await provider.tokens();
13340
+ const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
13341
+ if (tokens?.refresh_token && tokens.issuer == null) console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged.");
13216
13342
  if (tokens?.refresh_token) try {
13217
13343
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
13218
13344
  metadata,
@@ -13222,7 +13348,11 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
13222
13348
  addClientAuthentication: provider.addClientAuthentication,
13223
13349
  fetchFn
13224
13350
  });
13225
- await provider.saveTokens(newTokens);
13351
+ await bindClientInformation();
13352
+ await provider.saveTokens({
13353
+ ...newTokens,
13354
+ issuer
13355
+ });
13226
13356
  return "AUTHORIZED";
13227
13357
  } catch (error) {
13228
13358
  if (!(error instanceof OAuthError) || error instanceof ServerError) {} else throw error;
@@ -13302,7 +13432,7 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
13302
13432
  }
13303
13433
  async function fetchWithCorsRetry(url, headers, fetchFn = fetch) {
13304
13434
  try {
13305
- return await fetchFn(url, { headers });
13435
+ return await fetchWithinOrigin(fetchFn)(url, { headers });
13306
13436
  } catch (error) {
13307
13437
  if (error instanceof TypeError) {
13308
13438
  if (headers) return fetchWithCorsRetry(url, void 0, fetchFn);
@@ -13319,7 +13449,7 @@ async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) {
13319
13449
  return await fetchWithCorsRetry(url, { "MCP-Protocol-Version": protocolVersion }, fetchFn);
13320
13450
  }
13321
13451
  function shouldAttemptFallback(response, pathname) {
13322
- return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
13452
+ return !response || !response.ok && response.status < 500 && pathname !== "/";
13323
13453
  }
13324
13454
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
13325
13455
  const issuer = new URL(serverUrl);
@@ -13377,7 +13507,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
13377
13507
  if (!response) continue;
13378
13508
  if (!response.ok) {
13379
13509
  await response.body?.cancel();
13380
- if (response.status >= 400 && response.status < 500) continue;
13510
+ if (response.status < 500) continue;
13381
13511
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
13382
13512
  }
13383
13513
  if (type === "oauth") return OAuthMetadataSchema.parse(await response.json());
@@ -13399,6 +13529,9 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
13399
13529
  resourceMetadata
13400
13530
  };
13401
13531
  }
13532
+ function resourceIndicatorToString(resource) {
13533
+ return typeof resource === "string" ? resource : resource.href;
13534
+ }
13402
13535
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
13403
13536
  let authorizationUrl;
13404
13537
  if (metadata) {
@@ -13417,7 +13550,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
13417
13550
  if (state) authorizationUrl.searchParams.set("state", state);
13418
13551
  if (scope) authorizationUrl.searchParams.set("scope", scope);
13419
13552
  if (scope?.includes("offline_access")) authorizationUrl.searchParams.append("prompt", "consent");
13420
- if (resource) authorizationUrl.searchParams.set("resource", resource.href);
13553
+ if (resource) authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
13421
13554
  return {
13422
13555
  authorizationUrl,
13423
13556
  codeVerifier
@@ -13437,16 +13570,16 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
13437
13570
  "Content-Type": "application/x-www-form-urlencoded",
13438
13571
  Accept: "application/json"
13439
13572
  });
13440
- if (resource) tokenRequestParams.set("resource", resource.href);
13573
+ if (resource) tokenRequestParams.set("resource", resourceIndicatorToString(resource));
13441
13574
  if (addClientAuthentication) await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
13442
13575
  else if (clientInformation) applyClientAuthentication(selectClientAuthMethod(clientInformation, metadata?.token_endpoint_auth_methods_supported ?? []), clientInformation, headers, tokenRequestParams);
13443
- const response = await (fetchFn ?? fetch)(tokenUrl, {
13576
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
13444
13577
  method: "POST",
13445
13578
  headers,
13446
13579
  body: tokenRequestParams
13447
13580
  });
13448
13581
  if (!response.ok) throw await parseErrorResponse(response);
13449
- return OAuthTokensSchema.parse(await response.json());
13582
+ return TokenResponseSchema.parse(await response.json());
13450
13583
  }
13451
13584
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
13452
13585
  return {
@@ -13465,6 +13598,13 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
13465
13598
  };
13466
13599
  }
13467
13600
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
13601
+ const readClientInformation = async () => {
13602
+ const storedClientInformation = await provider.clientInformation();
13603
+ const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
13604
+ if (storedClientInformation && !checked) throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
13605
+ return checked;
13606
+ };
13607
+ let clientInformation = await readClientInformation();
13468
13608
  const scope = provider.clientMetadata.scope;
13469
13609
  let tokenRequestParams;
13470
13610
  if (provider.prepareTokenRequest) tokenRequestParams = await provider.prepareTokenRequest(scope);
@@ -13473,11 +13613,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
13473
13613
  if (!provider.redirectUrl) throw new Error("redirectUrl is required for authorization_code flow");
13474
13614
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, await provider.codeVerifier(), provider.redirectUrl);
13475
13615
  }
13476
- const clientInformation = await provider.clientInformation();
13616
+ clientInformation ?? (clientInformation = await readClientInformation());
13477
13617
  return executeTokenRequest(authorizationServerUrl, {
13478
13618
  metadata,
13479
13619
  tokenRequestParams,
13480
- clientInformation: clientInformation ?? void 0,
13620
+ clientInformation,
13481
13621
  addClientAuthentication: provider.addClientAuthentication,
13482
13622
  resource,
13483
13623
  fetchFn
@@ -13489,7 +13629,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
13489
13629
  if (!metadata.registration_endpoint) throw new Error("Incompatible auth server: does not support dynamic client registration");
13490
13630
  registrationUrl = new URL(metadata.registration_endpoint);
13491
13631
  } else registrationUrl = new URL("/register", authorizationServerUrl);
13492
- const response = await (fetchFn ?? fetch)(registrationUrl, {
13632
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
13493
13633
  method: "POST",
13494
13634
  headers: { "Content-Type": "application/json" },
13495
13635
  body: JSON.stringify({
@@ -13498,7 +13638,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
13498
13638
  })
13499
13639
  });
13500
13640
  if (!response.ok) throw await parseErrorResponse(response);
13501
- return OAuthClientInformationFullSchema.parse(await response.json());
13641
+ return RegistrationResponseSchema.parse(await response.json());
13502
13642
  }
13503
13643
  //#endregion
13504
13644
  //#region node_modules/.pnpm/eventsource-parser@3.1.1/node_modules/eventsource-parser/dist/index.js
@@ -13694,7 +13834,7 @@ var EventSourceParserStream = class extends TransformStream {
13694
13834
  }
13695
13835
  };
13696
13836
  //#endregion
13697
- //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
13837
+ //#region node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_zod@4.4.2/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
13698
13838
  const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
13699
13839
  initialReconnectionDelay: 1e3,
13700
13840
  maxReconnectionDelay: 3e4,
@@ -13717,9 +13857,18 @@ var StreamableHTTPClientTransport = class {
13717
13857
  this._authProvider = opts?.authProvider;
13718
13858
  this._fetch = opts?.fetch;
13719
13859
  this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
13860
+ this._followRedirects = opts?.redirectPolicy === "follow";
13861
+ if (this._followRedirects) {
13862
+ this._fetch = fetchLeavingRedirects(this._fetch);
13863
+ this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
13864
+ }
13720
13865
  this._sessionId = opts?.sessionId;
13721
13866
  this._reconnectionOptions = opts?.reconnectionOptions ?? DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
13722
13867
  }
13868
+ _unfollowedRedirect(response, url) {
13869
+ const text = unfollowedRedirect(response, url);
13870
+ return text && !this._followRedirects ? `${text} (redirectPolicy: 'same-origin')` : text;
13871
+ }
13723
13872
  async _authThenStart() {
13724
13873
  if (!this._authProvider) throw new UnauthorizedError("No auth provider");
13725
13874
  let result;
@@ -13757,16 +13906,23 @@ var StreamableHTTPClientTransport = class {
13757
13906
  const headers = await this._commonHeaders();
13758
13907
  headers.set("Accept", "text/event-stream");
13759
13908
  if (resumptionToken) headers.set("last-event-id", resumptionToken);
13760
- const response = await (this._fetch ?? fetch)(this._url, {
13909
+ const fetchFn = this._fetch ?? fetch;
13910
+ const init = {
13761
13911
  method: "GET",
13762
13912
  headers,
13763
13913
  signal: this._abortController?.signal
13914
+ };
13915
+ let response = await fetchFn(this._url, this._followRedirects ? init : {
13916
+ ...init,
13917
+ redirect: "manual"
13764
13918
  });
13919
+ const followed = this._followRedirects ? void 0 : followWithinOrigin(fetchFn, this._url, init, response);
13920
+ if (followed) response = await followed;
13765
13921
  if (!response.ok) {
13766
13922
  await response.body?.cancel();
13767
13923
  if (response.status === 401 && this._authProvider) return await this._authThenStart();
13768
13924
  if (response.status === 405) return;
13769
- throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
13925
+ throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
13770
13926
  }
13771
13927
  this._handleSseStream(response.body, options, true);
13772
13928
  } catch (error) {
@@ -13888,7 +14044,7 @@ var StreamableHTTPClientTransport = class {
13888
14044
  body: JSON.stringify(message),
13889
14045
  signal: this._abortController?.signal
13890
14046
  };
13891
- const response = await (this._fetch ?? fetch)(this._url, init);
14047
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
13892
14048
  const sessionId = response.headers.get("mcp-session-id");
13893
14049
  if (sessionId) this._sessionId = sessionId;
13894
14050
  if (!response.ok) {
@@ -13924,7 +14080,7 @@ var StreamableHTTPClientTransport = class {
13924
14080
  return this.send(message);
13925
14081
  }
13926
14082
  }
13927
- throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
14083
+ throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${this._unfollowedRedirect(response, this._url) ?? text}`);
13928
14084
  }
13929
14085
  this._hasCompletedAuthFlow = false;
13930
14086
  this._lastUpscopingHeader = void 0;
@@ -13965,9 +14121,9 @@ var StreamableHTTPClientTransport = class {
13965
14121
  headers,
13966
14122
  signal: this._abortController?.signal
13967
14123
  };
13968
- const response = await (this._fetch ?? fetch)(this._url, init);
14124
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._url, init);
13969
14125
  await response.body?.cancel();
13970
- if (!response.ok && response.status !== 405) throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
14126
+ if (!response.ok && response.status !== 405) throw new StreamableHTTPError(response.status, `Failed to terminate session: ${this._unfollowedRedirect(response, this._url) ?? response.statusText}`);
13971
14127
  this._sessionId = void 0;
13972
14128
  } catch (error) {
13973
14129
  this.onerror?.(error);
@@ -14020,4 +14176,4 @@ const layer = effect(McpClient, gen(function* () {
14020
14176
  //#endregion
14021
14177
  export { McpClient, McpClientError, layer };
14022
14178
 
14023
- //# sourceMappingURL=McpClient-DP4jlaD1.mjs.map
14179
+ //# sourceMappingURL=McpClient-C0FVuDj2.mjs.map