linkque-cli-v2 1.6.3 → 1.6.4

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 (25) hide show
  1. package/dev/worker.js +16 -3
  2. package/linkquejs.js +1015 -631
  3. package/package.json +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/anthropic-messages-GSYNBLMR.js +17 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{azure-openai-responses-HVAVRLTK.js → azure-openai-responses-NPKMM3LF.js} +7 -9
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-ZRFVXCIT.js → chunk-CO4I3RJE.js} +15 -2
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Q2Y6LMNC.js → chunk-J4JCPZDI.js} +5 -7
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-4XAZNSEQ.js → chunk-JMBJJF7P.js} +18 -5
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{anthropic-messages-5DOLTIGP.js → chunk-KDHBKVSL.js} +14 -15
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-MK4MI4S5.js → chunk-UZS5YLV2.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-4VLP3ODV.js → chunk-VBERH5QM.js} +404 -59
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-Y3G4J3TB.js → chunk-XOLFZ4XS.js} +316 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{dist-ZPLSQEAM.js → dist-TGBYXSBU.js} +27 -42
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-generative-ai-OLT56CSV.js → google-generative-ai-KD7MXONK.js} +8 -10
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{google-vertex-4DBBJ7SR.js → google-vertex-TREYA472.js} +9 -11
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-OEBGEDLQ.js → mistral-conversations-OEOTQWE5.js} +7 -9
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-codex-responses-3KOC6KHN.js → openai-codex-responses-GEFKSNVN.js} +10 -12
  18. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-completions-HG6OJRL5.js → openai-completions-TAACO6T5.js} +13 -15
  19. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{openai-responses-F6V2PG3Y.js → openai-responses-4DDTXIGI.js} +12 -14
  20. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +181 -60
  21. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +2 -2
  22. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +2 -2
  23. package/worker.js +348 -89
  24. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-RYONFGPP.js +0 -317
  25. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{pi-messages-DC4DVRAJ.js → pi-messages-7JN3W3BC.js} +4 -4
package/worker.js CHANGED
@@ -15367,7 +15367,9 @@ var init_httpLoggingFetch = __esm({
15367
15367
  "x-signature-content",
15368
15368
  "x-alipay-sdk-version",
15369
15369
  "x-alipay-authcode",
15370
- "anthropic-api-key"
15370
+ "anthropic-api-key",
15371
+ "x-linkque-runtime-mac",
15372
+ "x-linkque-run-proof"
15371
15373
  ]);
15372
15374
  REDACTED_VALUE = "ak***";
15373
15375
  RESPONSE_CORRELATION_HEADER_NAMES = [
@@ -69831,64 +69833,50 @@ var require_common2 = __commonJS({
69831
69833
  createDebug.namespaces = namespaces;
69832
69834
  createDebug.names = [];
69833
69835
  createDebug.skips = [];
69834
- const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
69835
- for (const ns of split) {
69836
- if (ns[0] === "-") {
69837
- createDebug.skips.push(ns.slice(1));
69838
- } else {
69839
- createDebug.names.push(ns);
69836
+ let i2;
69837
+ const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
69838
+ const len = split.length;
69839
+ for (i2 = 0; i2 < len; i2++) {
69840
+ if (!split[i2]) {
69841
+ continue;
69840
69842
  }
69841
- }
69842
- }
69843
- function matchesTemplate(search3, template) {
69844
- let searchIndex = 0;
69845
- let templateIndex = 0;
69846
- let starIndex = -1;
69847
- let matchIndex = 0;
69848
- while (searchIndex < search3.length) {
69849
- if (templateIndex < template.length && (template[templateIndex] === search3[searchIndex] || template[templateIndex] === "*")) {
69850
- if (template[templateIndex] === "*") {
69851
- starIndex = templateIndex;
69852
- matchIndex = searchIndex;
69853
- templateIndex++;
69854
- } else {
69855
- searchIndex++;
69856
- templateIndex++;
69857
- }
69858
- } else if (starIndex !== -1) {
69859
- templateIndex = starIndex + 1;
69860
- matchIndex++;
69861
- searchIndex = matchIndex;
69843
+ namespaces = split[i2].replace(/\*/g, ".*?");
69844
+ if (namespaces[0] === "-") {
69845
+ createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
69862
69846
  } else {
69863
- return false;
69847
+ createDebug.names.push(new RegExp("^" + namespaces + "$"));
69864
69848
  }
69865
69849
  }
69866
- while (templateIndex < template.length && template[templateIndex] === "*") {
69867
- templateIndex++;
69868
- }
69869
- return templateIndex === template.length;
69870
69850
  }
69871
69851
  function disable() {
69872
69852
  const namespaces = [
69873
- ...createDebug.names,
69874
- ...createDebug.skips.map((namespace) => "-" + namespace)
69853
+ ...createDebug.names.map(toNamespace),
69854
+ ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
69875
69855
  ].join(",");
69876
69856
  createDebug.enable("");
69877
69857
  return namespaces;
69878
69858
  }
69879
69859
  function enabled(name) {
69880
- for (const skip of createDebug.skips) {
69881
- if (matchesTemplate(name, skip)) {
69860
+ if (name[name.length - 1] === "*") {
69861
+ return true;
69862
+ }
69863
+ let i2;
69864
+ let len;
69865
+ for (i2 = 0, len = createDebug.skips.length; i2 < len; i2++) {
69866
+ if (createDebug.skips[i2].test(name)) {
69882
69867
  return false;
69883
69868
  }
69884
69869
  }
69885
- for (const ns of createDebug.names) {
69886
- if (matchesTemplate(name, ns)) {
69870
+ for (i2 = 0, len = createDebug.names.length; i2 < len; i2++) {
69871
+ if (createDebug.names[i2].test(name)) {
69887
69872
  return true;
69888
69873
  }
69889
69874
  }
69890
69875
  return false;
69891
69876
  }
69877
+ function toNamespace(regexp) {
69878
+ return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
69879
+ }
69892
69880
  function coerce2(val) {
69893
69881
  if (val instanceof Error) {
69894
69882
  return val.stack || val.message;
@@ -70007,11 +69995,10 @@ var require_browser = __commonJS({
70007
69995
  if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
70008
69996
  return false;
70009
69997
  }
70010
- let m2;
70011
69998
  return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
70012
69999
  typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
70013
70000
  // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
70014
- typeof navigator !== "undefined" && navigator.userAgent && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
70001
+ typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
70015
70002
  typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
70016
70003
  }
70017
70004
  function formatArgs(args) {
@@ -70049,7 +70036,7 @@ var require_browser = __commonJS({
70049
70036
  function load() {
70050
70037
  let r2;
70051
70038
  try {
70052
- r2 = exports2.storage.getItem("debug") || exports2.storage.getItem("DEBUG");
70039
+ r2 = exports2.storage.getItem("debug");
70053
70040
  } catch (error40) {
70054
70041
  }
70055
70042
  if (!r2 && typeof process !== "undefined" && "env" in process) {
@@ -70332,7 +70319,7 @@ var require_node5 = __commonJS({
70332
70319
  return (/* @__PURE__ */ new Date()).toISOString() + " ";
70333
70320
  }
70334
70321
  function log(...args) {
70335
- return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
70322
+ return process.stderr.write(util2.format(...args) + "\n");
70336
70323
  }
70337
70324
  function save(namespaces) {
70338
70325
  if (namespaces) {
@@ -89817,11 +89804,23 @@ var require_websocket = __commonJS({
89817
89804
  this._isServer = false;
89818
89805
  this._redirects = 0;
89819
89806
  if (protocols === void 0) {
89820
- protocols = [];
89807
+ if (!options || options.protocols === void 0) {
89808
+ protocols = [];
89809
+ } else if (Array.isArray(options.protocols)) {
89810
+ protocols = options.protocols;
89811
+ } else {
89812
+ protocols = [options.protocols];
89813
+ }
89821
89814
  } else if (!Array.isArray(protocols)) {
89822
89815
  if (typeof protocols === "object" && protocols !== null) {
89823
89816
  options = protocols;
89824
- protocols = [];
89817
+ if (options.protocols === void 0) {
89818
+ protocols = [];
89819
+ } else if (Array.isArray(options.protocols)) {
89820
+ protocols = options.protocols;
89821
+ } else {
89822
+ protocols = [options.protocols];
89823
+ }
89825
89824
  } else {
89826
89825
  protocols = [protocols];
89827
89826
  }
@@ -90018,7 +90017,6 @@ var require_websocket = __commonJS({
90018
90017
  }
90019
90018
  return;
90020
90019
  }
90021
- this._readyState = _WebSocket.CLOSING;
90022
90020
  this._sender.close(code, data, !this._isServer, (err3) => {
90023
90021
  if (err3) return;
90024
90022
  this._closeFrameSent = true;
@@ -90026,6 +90024,7 @@ var require_websocket = __commonJS({
90026
90024
  this._socket.end();
90027
90025
  }
90028
90026
  });
90027
+ this._readyState = _WebSocket.CLOSING;
90029
90028
  setCloseTimer(this);
90030
90029
  }
90031
90030
  /**
@@ -90250,6 +90249,7 @@ var require_websocket = __commonJS({
90250
90249
  socketPath: void 0,
90251
90250
  hostname: void 0,
90252
90251
  protocol: void 0,
90252
+ protocols: void 0,
90253
90253
  timeout: void 0,
90254
90254
  method: "GET",
90255
90255
  host: void 0,
@@ -206800,6 +206800,55 @@ var init_testProvider = __esm({
206800
206800
  }
206801
206801
  });
206802
206802
 
206803
+ // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/transportAnthropicApi.js
206804
+ function createTransportAnthropicApi(modelFetch) {
206805
+ const call = (model, context2, options = {}) => {
206806
+ const client = new Anthropic({
206807
+ baseURL: model.baseUrl,
206808
+ apiKey: options.apiKey ?? null,
206809
+ authToken: null,
206810
+ defaultHeaders: { ...model.headers, ...options.headers },
206811
+ fetch: modelFetch,
206812
+ maxRetries: 0
206813
+ });
206814
+ return stream(model, context2, {
206815
+ ...options,
206816
+ client,
206817
+ maxRetries: 0
206818
+ });
206819
+ };
206820
+ const simple = (model, context2, options) => {
206821
+ const base = buildBaseOptions(model, context2, options, options?.apiKey);
206822
+ if (!options?.reasoning)
206823
+ return call(model, context2, { ...base, thinkingEnabled: false });
206824
+ if (model.compat?.forceAdaptiveThinking === true) {
206825
+ const mapped = model.thinkingLevelMap?.[options.reasoning];
206826
+ const effort = typeof mapped === "string" ? mapped : options.reasoning === "minimal" || options.reasoning === "low" ? "low" : options.reasoning === "medium" ? "medium" : "high";
206827
+ return call(model, context2, { ...base, thinkingEnabled: true, effort });
206828
+ }
206829
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
206830
+ const maxTokens = clampMaxTokensToContext(model, context2, adjusted.maxTokens);
206831
+ return call(model, context2, {
206832
+ ...base,
206833
+ thinkingEnabled: true,
206834
+ maxTokens,
206835
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
206836
+ });
206837
+ };
206838
+ return {
206839
+ stream: (m2, c, o) => call(m2, c, o),
206840
+ streamSimple: (m2, c, o) => simple(m2, c, o)
206841
+ };
206842
+ }
206843
+ var init_transportAnthropicApi = __esm({
206844
+ "../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/transportAnthropicApi.js"() {
206845
+ "use strict";
206846
+ init_sdk();
206847
+ init_anthropic_messages();
206848
+ init_simple_options();
206849
+ }
206850
+ });
206851
+
206803
206852
  // ../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js
206804
206853
  function createApiKeyAuth(authName, fixedApiKey) {
206805
206854
  return {
@@ -206822,7 +206871,7 @@ function createAnthropicProvider(options) {
206822
206871
  auth: { apiKey: createApiKeyAuth(authName, fixedApiKey) },
206823
206872
  models,
206824
206873
  // 复用 pi-ai 内置的 Anthropic Messages 协议实现(含 stream/SSE 逻辑)
206825
- api: anthropicMessagesApi()
206874
+ api: options.modelFetch ? createTransportAnthropicApi(options.modelFetch) : anthropicMessagesApi()
206826
206875
  });
206827
206876
  }
206828
206877
  function buildAnthropicModel(providerId, baseUrl, descriptor) {
@@ -206846,6 +206895,7 @@ var init_anthropicProvider = __esm({
206846
206895
  "../linkque-agent-runtime/dist/esm/impl/agent/pi/provider/base/anthropicProvider.js"() {
206847
206896
  "use strict";
206848
206897
  init_compat2();
206898
+ init_transportAnthropicApi();
206849
206899
  }
206850
206900
  });
206851
206901
 
@@ -206856,13 +206906,14 @@ function createLinkqueModel(modelId, baseUrl = LINKQUE_DEFAULT_BASE_URL) {
206856
206906
  id: modelId
206857
206907
  });
206858
206908
  }
206859
- function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL) {
206909
+ function createLinkqueProvider(baseUrl = LINKQUE_DEFAULT_BASE_URL, modelFetch) {
206860
206910
  return createAnthropicProvider({
206861
206911
  providerId: LINKQUE_PROVIDER_ID,
206862
206912
  providerName: "Linkque",
206863
206913
  baseUrl,
206864
206914
  models: LINKQUE_MODELS,
206865
- authName: "Linkque API key"
206915
+ authName: "Linkque API key",
206916
+ modelFetch
206866
206917
  });
206867
206918
  }
206868
206919
  var LINKQUE_PROVIDER_ID, LINKQUE_AGENT_ID_HEADER, LINKQUE_RUN_ID_HEADER, LINKQUE_CHAT_ID_HEADER, LINKQUE_USER_ID_HEADER, LINKQUE_REQUEST_SOURCE_HEADER, LINKQUE_DEFAULT_BASE_URL, SANDBOX_AGENT_ACCESS_KEY_PLACEHOLDER, LINKQUE_MODELS, LINKQUE_PASSTHROUGH_DEFAULTS;
@@ -207179,7 +207230,7 @@ var init_agentService = __esm({
207179
207230
  async startSession() {
207180
207231
  const models = createModels();
207181
207232
  const providerId = providerIdFor(this.auth.provider);
207182
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
207233
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, this.auth.modelFetch));
207183
207234
  models.setProvider(createTestProvider().provider);
207184
207235
  let model;
207185
207236
  if (this.options.model !== void 0) {
@@ -207393,7 +207444,7 @@ var init_followUpQuestionGenerator = __esm({
207393
207444
  }
207394
207445
  async generate(input) {
207395
207446
  const models = this.modelsFactory();
207396
- models.setProvider(createLinkqueProvider(this.linkqueBaseUrl));
207447
+ models.setProvider(createLinkqueProvider(this.linkqueBaseUrl, input.auth.modelFetch));
207397
207448
  let model = models.getModel(LINKQUE_PROVIDER_ID, FOLLOW_UP_QUESTION_MODEL_ID);
207398
207449
  model ??= createLinkqueModel(FOLLOW_UP_QUESTION_MODEL_ID, this.linkqueBaseUrl);
207399
207450
  model = {
@@ -207940,6 +207991,29 @@ var init_types12 = __esm({
207940
207991
  }
207941
207992
  });
207942
207993
 
207994
+ // ../linkque-agent-runtime/dist/esm/core/scenarioRunAuthorization.js
207995
+ async function authorizeAgentRun(runId, identity, port) {
207996
+ if (typeof runId !== "string" || !/^[\x21-\x7e]{1,64}$/u.test(runId) || typeof identity?.userId !== "string" || !/^[\x21-\x7e]{1,128}$/u.test(identity.userId) || typeof identity.agentId !== "string" || !/^[A-Za-z0-9_-]{1,128}$/u.test(identity.agentId)) {
207997
+ throw new Error("SCENARIO_RUNTIME_AUTH_INVALID");
207998
+ }
207999
+ const result = await port.authorizeRun({
208000
+ runId,
208001
+ agentId: identity.agentId,
208002
+ appbaseUserId: identity.userId
208003
+ });
208004
+ if (result?.quotaMode === "NORMAL")
208005
+ return { quotaMode: "NORMAL" };
208006
+ if (result?.quotaMode !== "LIMITED" && result?.quotaMode !== "AUTH_ONLY" || typeof result.modelFetch !== "function") {
208007
+ throw new Error("SCENARIO_RUN_UNAVAILABLE");
208008
+ }
208009
+ return result;
208010
+ }
208011
+ var init_scenarioRunAuthorization = __esm({
208012
+ "../linkque-agent-runtime/dist/esm/core/scenarioRunAuthorization.js"() {
208013
+ "use strict";
208014
+ }
208015
+ });
208016
+
207943
208017
  // ../linkque-agent-runtime/dist/esm/core/agentRuntimePlugin.js
207944
208018
  function assertAgentConfigRoot(value, pluginName) {
207945
208019
  if (typeof value !== "object" || value === null || !("agent" in value)) {
@@ -209209,6 +209283,7 @@ var init_agentRuntime = __esm({
209209
209283
  init_runtimeErrorBoundary();
209210
209284
  init_toolObservation();
209211
209285
  init_types12();
209286
+ init_scenarioRunAuthorization();
209212
209287
  init_esm();
209213
209288
  init_types();
209214
209289
  init_followUpQuestionGenerator();
@@ -209388,6 +209463,28 @@ var init_agentRuntime = __esm({
209388
209463
  }
209389
209464
  /** 产出 AgentStreamEvent 流;内核编排「解析上行资源 → 组请求 → agent loop」。 */
209390
209465
  async *runAgentLoop(request, auth2, options = {}) {
209466
+ if (options.runAuthorization) {
209467
+ try {
209468
+ const grant = await authorizeAgentRun(request.runId, options.runtimeContext, options.runAuthorization);
209469
+ if (grant.quotaMode !== "NORMAL")
209470
+ auth2 = { ...auth2, modelFetch: grant.modelFetch };
209471
+ } catch (error40) {
209472
+ const reason = error40 instanceof Error ? error40.message : "";
209473
+ const code = [
209474
+ "SCENARIO_TURN_LIMIT",
209475
+ "SCENARIO_RUNTIME_AUTH_INVALID",
209476
+ "SCENARIO_RUNTIME_REPLAY"
209477
+ ].includes(reason) ? reason : "SCENARIO_RUN_UNAVAILABLE";
209478
+ yield {
209479
+ type: "error",
209480
+ error: {
209481
+ code,
209482
+ message: code === "SCENARIO_TURN_LIMIT" ? "\u4F53\u9A8C\u5BF9\u8BDD\u6B21\u6570\u5DF2\u7528\u5B8C" : "\u672C\u8F6E\u5BF9\u8BDD\u672A\u83B7\u51C6\u6267\u884C"
209483
+ }
209484
+ };
209485
+ return;
209486
+ }
209487
+ }
209391
209488
  const input = {
209392
209489
  runId: request.runId,
209393
209490
  agentId: options.runtimeContext?.agentId ?? this.agentId,
@@ -209973,6 +210070,8 @@ async function* runConversation(request, auth2, options = {}) {
209973
210070
  const ports = options.agentLoop ? { agentLoop: options.agentLoop } : void 0;
209974
210071
  const runtime = options.runtime ?? (options.protocol ? AgentRuntime.create(options.protocol, ports) : new AgentRuntime(ports));
209975
210072
  const runOptions = {};
210073
+ if (options.runAuthorization)
210074
+ runOptions.runAuthorization = options.runAuthorization;
209976
210075
  if (options.sessionId !== void 0)
209977
210076
  runOptions.sessionId = options.sessionId;
209978
210077
  if (options.cwd !== void 0)
@@ -210287,6 +210386,7 @@ async function waitForObservation(promise2, signal) {
210287
210386
  function createImageTool(image, input, options, rules) {
210288
210387
  const fetchImpl = options.fetchImpl ?? globalThis.fetch;
210289
210388
  const auth2 = { ...input.auth };
210389
+ const modelFetch = auth2.modelFetch ?? fetchImpl;
210290
210390
  const cache = /* @__PURE__ */ new Map();
210291
210391
  let calls = 0;
210292
210392
  return {
@@ -210326,7 +210426,7 @@ function createImageTool(image, input, options, rules) {
210326
210426
  const pending = (async () => {
210327
210427
  try {
210328
210428
  const resolved = await resolveImage(image, fetchImpl, rules, signal);
210329
- const response = await fetchImpl(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
210429
+ const response = await modelFetch(`${(options.baseUrl ?? RUNTIME_CONFIG_DEFAULTS.LINKQUE_BASE_URL).replace(/\/+$/, "")}/v1/messages`, {
210330
210430
  method: "POST",
210331
210431
  signal,
210332
210432
  redirect: "error",
@@ -212895,6 +212995,9 @@ var Protocol = class {
212895
212995
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
212896
212996
  const handleTaskResult = async () => {
212897
212997
  const taskId = request.params.taskId;
212998
+ if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
212999
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
213000
+ }
212898
213001
  if (this._taskMessageQueue) {
212899
213002
  let queuedMessage;
212900
213003
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -212925,12 +213028,12 @@ var Protocol = class {
212925
213028
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
212926
213029
  }
212927
213030
  if (!isTerminal(task.status)) {
212928
- await this._waitForTaskUpdate(taskId, extra.signal);
213031
+ await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
212929
213032
  return await handleTaskResult();
212930
213033
  }
212931
213034
  if (isTerminal(task.status)) {
212932
213035
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
212933
- this._clearTaskQueue(taskId);
213036
+ this._clearTaskQueue(taskId, extra.sessionId);
212934
213037
  return {
212935
213038
  ...result,
212936
213039
  _meta: {
@@ -212967,7 +213070,7 @@ var Protocol = class {
212967
213070
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
212968
213071
  }
212969
213072
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
212970
- this._clearTaskQueue(request.params.taskId);
213073
+ this._clearTaskQueue(request.params.taskId, extra.sessionId);
212971
213074
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
212972
213075
  if (!cancelledTask) {
212973
213076
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -213095,6 +213198,19 @@ var Protocol = class {
213095
213198
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
213096
213199
  const capturedTransport = this._transport;
213097
213200
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
213201
+ const sessionId = capturedTransport?.sessionId;
213202
+ const store = this._taskStore;
213203
+ let relatedTaskFound = true;
213204
+ let relatedTaskLookup;
213205
+ if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
213206
+ relatedTaskFound = false;
213207
+ relatedTaskLookup = (async () => {
213208
+ if (!await store.getTask(relatedTaskId, sessionId)) {
213209
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
213210
+ }
213211
+ relatedTaskFound = true;
213212
+ })();
213213
+ }
213098
213214
  if (handler === void 0) {
213099
213215
  const errorResponse = {
213100
213216
  jsonrpc: "2.0",
@@ -213104,7 +213220,10 @@ var Protocol = class {
213104
213220
  message: "Method not found"
213105
213221
  }
213106
213222
  };
213107
- if (relatedTaskId && this._taskMessageQueue) {
213223
+ if (relatedTaskId && relatedTaskLookup) {
213224
+ const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
213225
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error40) => this._onerror(new Error(`Failed to send an error response: ${error40}`)));
213226
+ } else if (relatedTaskId && this._taskMessageQueue) {
213108
213227
  this._enqueueTaskMessage(relatedTaskId, {
213109
213228
  type: "error",
213110
213229
  message: errorResponse,
@@ -213155,7 +213274,10 @@ var Protocol = class {
213155
213274
  closeSSEStream: extra?.closeSSEStream,
213156
213275
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
213157
213276
  };
213158
- Promise.resolve().then(() => {
213277
+ (relatedTaskLookup ?? Promise.resolve()).then(() => {
213278
+ if (relatedTaskLookup && abortController.signal.aborted) {
213279
+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
213280
+ }
213159
213281
  if (taskCreationParams) {
213160
213282
  this.assertTaskHandlerCapability(request.method);
213161
213283
  }
@@ -213190,7 +213312,7 @@ var Protocol = class {
213190
213312
  ...error40["data"] !== void 0 && { data: error40["data"] }
213191
213313
  }
213192
213314
  };
213193
- if (relatedTaskId && this._taskMessageQueue) {
213315
+ if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
213194
213316
  await this._enqueueTaskMessage(relatedTaskId, {
213195
213317
  type: "error",
213196
213318
  message: errorResponse,
@@ -213670,7 +213792,7 @@ var Protocol = class {
213670
213792
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
213671
213793
  }
213672
213794
  const maxQueueSize = this._options?.maxTaskQueueSize;
213673
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
213795
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
213674
213796
  }
213675
213797
  /**
213676
213798
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -213699,12 +213821,13 @@ var Protocol = class {
213699
213821
  * Uses polling to check for updates at the task's configured poll interval.
213700
213822
  * @param taskId The task ID to wait for
213701
213823
  * @param signal Abort signal to cancel the wait
213824
+ * @param sessionId Session of the request that waits, passed to the task store
213702
213825
  * @returns Promise that resolves when an update occurs or rejects if aborted
213703
213826
  */
213704
- async _waitForTaskUpdate(taskId, signal) {
213827
+ async _waitForTaskUpdate(taskId, signal, sessionId) {
213705
213828
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
213706
213829
  try {
213707
- const task = await this._taskStore?.getTask(taskId);
213830
+ const task = await this._taskStore?.getTask(taskId, sessionId);
213708
213831
  if (task?.pollInterval) {
213709
213832
  interval = task.pollInterval;
213710
213833
  }
@@ -215344,6 +215467,68 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
215344
215467
  return baseFetch(url2, mergedInit);
215345
215468
  };
215346
215469
  }
215470
+ var MAX_REDIRECTS = 5;
215471
+ var REDIRECT_STATUSES = [301, 302, 303, 307, 308];
215472
+ function isWithinOrigin(from, to) {
215473
+ if (from.protocol === to.protocol && from.hostname === to.hostname && from.port === to.port) {
215474
+ return true;
215475
+ }
215476
+ return from.hostname === to.hostname && from.protocol === "http:" && from.port === "" && to.protocol === "https:" && to.port === "";
215477
+ }
215478
+ function redirectTarget(response, requestUrl) {
215479
+ const location = REDIRECT_STATUSES.includes(response.status) ? response.headers.get("location") : null;
215480
+ try {
215481
+ return location ? new URL(location, requestUrl) : void 0;
215482
+ } catch {
215483
+ return void 0;
215484
+ }
215485
+ }
215486
+ function followWithinOrigin(baseFetch, url2, init, response, followed = 0) {
215487
+ const target = redirectTarget(response, url2);
215488
+ const keepsMethod = response.status === 307 || response.status === 308 || (init?.method ?? "GET").toUpperCase() === "GET";
215489
+ if (!target || followed === MAX_REDIRECTS || !keepsMethod) {
215490
+ return void 0;
215491
+ }
215492
+ const from = new URL(url2);
215493
+ const addsUserinfo = (target.username || target.password) && (target.username !== from.username || target.password !== from.password);
215494
+ if (addsUserinfo || !isWithinOrigin(from, target)) {
215495
+ return void 0;
215496
+ }
215497
+ return Promise.resolve(response.body?.cancel()).then(() => baseFetch(target, { ...init, redirect: "manual" })).then((next) => followWithinOrigin(baseFetch, target, init, next, followed + 1) ?? next);
215498
+ }
215499
+ var followingFetches = /* @__PURE__ */ new WeakSet();
215500
+ function fetchLeavingRedirects(baseFetch) {
215501
+ const following = (url2, init) => (baseFetch ?? fetch)(url2, init);
215502
+ followingFetches.add(following);
215503
+ return following;
215504
+ }
215505
+ function fetchWithinOrigin(baseFetch = fetch) {
215506
+ if (followingFetches.has(baseFetch)) {
215507
+ return baseFetch;
215508
+ }
215509
+ return (url2, init) => {
215510
+ if (init?.redirect === "error" || init?.redirect === "manual") {
215511
+ return baseFetch(url2, init);
215512
+ }
215513
+ return Promise.resolve(baseFetch(url2, { ...init, redirect: "manual" })).then((response) => followWithinOrigin(baseFetch, url2, init, response) ?? response);
215514
+ };
215515
+ }
215516
+ function unfollowedRedirect(response, requestUrl) {
215517
+ if (response.type === "opaqueredirect") {
215518
+ return "Redirect not followed: this runtime does not expose the redirect target";
215519
+ }
215520
+ const from = response.url || requestUrl;
215521
+ const target = redirectTarget(response, from);
215522
+ if (!target) {
215523
+ return void 0;
215524
+ }
215525
+ target.username = target.password = target.search = target.hash = "";
215526
+ if (target.protocol === "http:" && new URL(from).protocol === "https:") {
215527
+ target.protocol = "https:";
215528
+ return `Redirect to plain http not followed; try ${target.href} instead`;
215529
+ }
215530
+ return `Redirect to ${target.href} not followed`;
215531
+ }
215347
215532
 
215348
215533
  // ../../node_modules/pkce-challenge/dist/index.node.js
215349
215534
  var crypto2;
@@ -215491,7 +215676,12 @@ var OAuthTokensSchema = object2({
215491
215676
  token_type: string2(),
215492
215677
  expires_in: coerce_exports.number().optional(),
215493
215678
  scope: string2().optional(),
215494
- refresh_token: string2().optional()
215679
+ refresh_token: string2().optional(),
215680
+ /**
215681
+ * Not part of the wire format: the authorization server this value was obtained from, added by
215682
+ * the client's `auth()` before it is stored and compared when it is read back.
215683
+ */
215684
+ issuer: string2().optional().catch(void 0)
215495
215685
  }).strip();
215496
215686
  var OAuthErrorResponseSchema = object2({
215497
215687
  error: string2(),
@@ -215521,7 +215711,12 @@ var OAuthClientInformationSchema = object2({
215521
215711
  client_id: string2(),
215522
215712
  client_secret: string2().optional(),
215523
215713
  client_id_issued_at: number2().optional(),
215524
- client_secret_expires_at: number2().optional()
215714
+ client_secret_expires_at: number2().optional(),
215715
+ /**
215716
+ * Not part of the wire format: the authorization server this value was obtained from, added by
215717
+ * the client's `auth()` before it is stored and compared when it is read back.
215718
+ */
215719
+ issuer: string2().optional().catch(void 0)
215525
215720
  }).strip();
215526
215721
  var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
215527
215722
  var OAuthClientRegistrationErrorSchema = object2({
@@ -215719,10 +215914,31 @@ async function parseErrorResponse(input) {
215719
215914
  const errorClass = OAUTH_ERRORS[error40] || ServerError;
215720
215915
  return new errorClass(error_description || "", error_uri);
215721
215916
  } catch (error40) {
215722
- const errorMessage4 = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error40}. Raw body: ${body}`;
215917
+ const redirect = input instanceof Response ? unfollowedRedirect(input, input.url) : void 0;
215918
+ const errorMessage4 = `${statusCode ? `HTTP ${statusCode}: ` : ""}${redirect ?? `Invalid OAuth error response: ${error40}. Raw body: ${body}`}`;
215723
215919
  return new ServerError(errorMessage4);
215724
215920
  }
215725
215921
  }
215922
+ function issuersMatch(a, b) {
215923
+ let [x2, y] = [a, b];
215924
+ try {
215925
+ [x2, y] = [new URL(a).href, new URL(b).href];
215926
+ } catch {
215927
+ }
215928
+ return x2 === y || x2.endsWith("/") && x2.slice(0, -1) === y || y.endsWith("/") && y.slice(0, -1) === x2;
215929
+ }
215930
+ function discardIfIssuerMismatch(stored, issuer) {
215931
+ if (!stored)
215932
+ return void 0;
215933
+ if (typeof stored.issuer !== "string")
215934
+ return stored.issuer == null ? stored : { ...stored, issuer: void 0 };
215935
+ return issuersMatch(stored.issuer, issuer) ? stored : void 0;
215936
+ }
215937
+ var TokenResponseSchema = OAuthTokensSchema.omit({ issuer: true });
215938
+ var RegistrationResponseSchema = OAuthClientInformationFullSchema.omit({ issuer: true });
215939
+ function boundElsewhereError(stored, issuer) {
215940
+ 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.`);
215941
+ }
215726
215942
  async function auth(provider, options) {
215727
215943
  try {
215728
215944
  return await authInternal(provider, options);
@@ -215776,9 +215992,24 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215776
215992
  authorizationServerMetadata: metadata
215777
215993
  });
215778
215994
  }
215779
- const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
215995
+ const issuer = String(authorizationServerUrl);
215996
+ const selectedResource = await selectResourceURL(serverUrl, provider, resourceMetadata);
215997
+ const resource = selectedResource && resourceMetadata && !provider.validateResourceURL ? resourceMetadata.resource : selectedResource;
215780
215998
  const resolvedScope = scope || resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
215781
- let clientInformation = await Promise.resolve(provider.clientInformation());
215999
+ const storedClientInformation = await Promise.resolve(provider.clientInformation());
216000
+ let clientInformation = discardIfIssuerMismatch(storedClientInformation, issuer);
216001
+ const canRegisterAgain = provider.saveClientInformation !== void 0 && !!provider.redirectUrl;
216002
+ if (storedClientInformation && !clientInformation && !canRegisterAgain) {
216003
+ throw boundElsewhereError(storedClientInformation, issuer);
216004
+ }
216005
+ const unstampedClientInformation = clientInformation?.issuer == null ? clientInformation : void 0;
216006
+ const bindClientInformation = async () => {
216007
+ try {
216008
+ if (unstampedClientInformation)
216009
+ await provider.saveClientInformation?.({ ...unstampedClientInformation, issuer });
216010
+ } catch {
216011
+ }
216012
+ };
215782
216013
  if (!clientInformation) {
215783
216014
  if (authorizationCode !== void 0) {
215784
216015
  throw new Error("Existing OAuth client information is required when exchanging an authorization code");
@@ -215790,9 +216021,7 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215790
216021
  }
215791
216022
  const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
215792
216023
  if (shouldUseUrlBasedClientId) {
215793
- clientInformation = {
215794
- client_id: clientMetadataUrl
215795
- };
216024
+ clientInformation = { client_id: clientMetadataUrl, issuer };
215796
216025
  await provider.saveClientInformation?.(clientInformation);
215797
216026
  } else {
215798
216027
  if (!provider.saveClientInformation) {
@@ -215804,8 +216033,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215804
216033
  scope: resolvedScope,
215805
216034
  fetchFn
215806
216035
  });
215807
- await provider.saveClientInformation(fullInformation);
215808
- clientInformation = fullInformation;
216036
+ clientInformation = { ...fullInformation, issuer };
216037
+ await provider.saveClientInformation(clientInformation);
215809
216038
  }
215810
216039
  }
215811
216040
  const nonInteractiveFlow = !provider.redirectUrl;
@@ -215816,10 +216045,14 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215816
216045
  authorizationCode,
215817
216046
  fetchFn
215818
216047
  });
215819
- await provider.saveTokens(tokens2);
216048
+ await bindClientInformation();
216049
+ await provider.saveTokens({ ...tokens2, issuer });
215820
216050
  return "AUTHORIZED";
215821
216051
  }
215822
- const tokens = await provider.tokens();
216052
+ const tokens = discardIfIssuerMismatch(await provider.tokens(), issuer);
216053
+ if (tokens?.refresh_token && tokens.issuer == null) {
216054
+ 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.");
216055
+ }
215823
216056
  if (tokens?.refresh_token) {
215824
216057
  try {
215825
216058
  const newTokens = await refreshAuthorization(authorizationServerUrl, {
@@ -215830,7 +216063,8 @@ async function authInternal(provider, { serverUrl, authorizationCode, scope, res
215830
216063
  addClientAuthentication: provider.addClientAuthentication,
215831
216064
  fetchFn
215832
216065
  });
215833
- await provider.saveTokens(newTokens);
216066
+ await bindClientInformation();
216067
+ await provider.saveTokens({ ...newTokens, issuer });
215834
216068
  return "AUTHORIZED";
215835
216069
  } catch (error40) {
215836
216070
  if (!(error40 instanceof OAuthError) || error40 instanceof ServerError) {
@@ -215929,7 +216163,7 @@ async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn =
215929
216163
  }
215930
216164
  async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
215931
216165
  try {
215932
- return await fetchFn(url2, { headers });
216166
+ return await fetchWithinOrigin(fetchFn)(url2, { headers });
215933
216167
  } catch (error40) {
215934
216168
  if (error40 instanceof TypeError) {
215935
216169
  if (headers) {
@@ -215954,7 +216188,7 @@ async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
215954
216188
  return await fetchWithCorsRetry(url2, headers, fetchFn);
215955
216189
  }
215956
216190
  function shouldAttemptFallback(response, pathname) {
215957
- return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
216191
+ return !response || !response.ok && response.status < 500 && pathname !== "/";
215958
216192
  }
215959
216193
  async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
215960
216194
  const issuer = new URL(serverUrl);
@@ -216020,7 +216254,7 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
216020
216254
  }
216021
216255
  if (!response.ok) {
216022
216256
  await response.body?.cancel();
216023
- if (response.status >= 400 && response.status < 500) {
216257
+ if (response.status < 500) {
216024
216258
  continue;
216025
216259
  }
216026
216260
  throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
@@ -216053,6 +216287,9 @@ async function discoverOAuthServerInfo(serverUrl, opts) {
216053
216287
  resourceMetadata
216054
216288
  };
216055
216289
  }
216290
+ function resourceIndicatorToString(resource) {
216291
+ return typeof resource === "string" ? resource : resource.href;
216292
+ }
216056
216293
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state: state2, resource }) {
216057
216294
  let authorizationUrl;
216058
216295
  if (metadata) {
@@ -216084,7 +216321,7 @@ async function startAuthorization(authorizationServerUrl, { metadata, clientInfo
216084
216321
  authorizationUrl.searchParams.append("prompt", "consent");
216085
216322
  }
216086
216323
  if (resource) {
216087
- authorizationUrl.searchParams.set("resource", resource.href);
216324
+ authorizationUrl.searchParams.set("resource", resourceIndicatorToString(resource));
216088
216325
  }
216089
216326
  return { authorizationUrl, codeVerifier };
216090
216327
  }
@@ -216103,7 +216340,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216103
216340
  Accept: "application/json"
216104
216341
  });
216105
216342
  if (resource) {
216106
- tokenRequestParams.set("resource", resource.href);
216343
+ tokenRequestParams.set("resource", resourceIndicatorToString(resource));
216107
216344
  }
216108
216345
  if (addClientAuthentication) {
216109
216346
  await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
@@ -216112,7 +216349,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216112
216349
  const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
216113
216350
  applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
216114
216351
  }
216115
- const response = await (fetchFn ?? fetch)(tokenUrl, {
216352
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(tokenUrl, {
216116
216353
  method: "POST",
216117
216354
  headers,
216118
216355
  body: tokenRequestParams
@@ -216120,7 +216357,7 @@ async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequ
216120
216357
  if (!response.ok) {
216121
216358
  throw await parseErrorResponse(response);
216122
216359
  }
216123
- return OAuthTokensSchema.parse(await response.json());
216360
+ return TokenResponseSchema.parse(await response.json());
216124
216361
  }
216125
216362
  async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
216126
216363
  const tokenRequestParams = new URLSearchParams({
@@ -216138,6 +216375,15 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
216138
216375
  return { refresh_token: refreshToken, ...tokens };
216139
216376
  }
216140
216377
  async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
216378
+ const readClientInformation = async () => {
216379
+ const storedClientInformation = await provider.clientInformation();
216380
+ const checked = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
216381
+ if (storedClientInformation && !checked) {
216382
+ throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
216383
+ }
216384
+ return checked;
216385
+ };
216386
+ let clientInformation = await readClientInformation();
216141
216387
  const scope = provider.clientMetadata.scope;
216142
216388
  let tokenRequestParams;
216143
216389
  if (provider.prepareTokenRequest) {
@@ -216153,11 +216399,11 @@ async function fetchToken(provider, authorizationServerUrl, { metadata, resource
216153
216399
  const codeVerifier = await provider.codeVerifier();
216154
216400
  tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
216155
216401
  }
216156
- const clientInformation = await provider.clientInformation();
216402
+ clientInformation ?? (clientInformation = await readClientInformation());
216157
216403
  return executeTokenRequest(authorizationServerUrl, {
216158
216404
  metadata,
216159
216405
  tokenRequestParams,
216160
- clientInformation: clientInformation ?? void 0,
216406
+ clientInformation,
216161
216407
  addClientAuthentication: provider.addClientAuthentication,
216162
216408
  resource,
216163
216409
  fetchFn
@@ -216173,7 +216419,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216173
216419
  } else {
216174
216420
  registrationUrl = new URL("/register", authorizationServerUrl);
216175
216421
  }
216176
- const response = await (fetchFn ?? fetch)(registrationUrl, {
216422
+ const response = await fetchWithinOrigin(fetchFn ?? fetch)(registrationUrl, {
216177
216423
  method: "POST",
216178
216424
  headers: {
216179
216425
  "Content-Type": "application/json"
@@ -216186,7 +216432,7 @@ async function registerClient(authorizationServerUrl, { metadata, clientMetadata
216186
216432
  if (!response.ok) {
216187
216433
  throw await parseErrorResponse(response);
216188
216434
  }
216189
- return OAuthClientInformationFullSchema.parse(await response.json());
216435
+ return RegistrationResponseSchema.parse(await response.json());
216190
216436
  }
216191
216437
 
216192
216438
  // ../../node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
@@ -216207,6 +216453,16 @@ var SSEClientTransport = class {
216207
216453
  this._authProvider = opts?.authProvider;
216208
216454
  this._fetch = opts?.fetch;
216209
216455
  this._fetchWithInit = createFetchWithInit(opts?.fetch, opts?.requestInit);
216456
+ this._followRedirects = opts?.redirectPolicy === "follow";
216457
+ if (this._followRedirects) {
216458
+ this._fetch = fetchLeavingRedirects(this._fetch);
216459
+ this._fetchWithInit = fetchLeavingRedirects(this._fetchWithInit);
216460
+ }
216461
+ }
216462
+ /** Error text for a redirect `response` that was not followed, or `undefined` for any other response. */
216463
+ _unfollowedRedirect(response, url2) {
216464
+ const text2 = unfollowedRedirect(response, url2);
216465
+ return text2 && !this._followRedirects ? `${text2} (redirectPolicy: 'same-origin')` : text2;
216210
216466
  }
216211
216467
  async _authThenStart() {
216212
216468
  if (!this._authProvider) {
@@ -216247,7 +216503,9 @@ var SSEClientTransport = class {
216247
216503
  });
216248
216504
  }
216249
216505
  _startOrAuth() {
216250
- const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216506
+ const baseFetch = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
216507
+ const fetchImpl = this._followRedirects ? baseFetch : fetchWithinOrigin(baseFetch);
216508
+ let redirect;
216251
216509
  return new Promise((resolve, reject) => {
216252
216510
  this._eventSource = new EventSource(this._url.href, {
216253
216511
  ...this._eventSourceInit,
@@ -216258,6 +216516,7 @@ var SSEClientTransport = class {
216258
216516
  ...init,
216259
216517
  headers
216260
216518
  });
216519
+ redirect = this._unfollowedRedirect(response, url2);
216261
216520
  if (response.status === 401 && response.headers.has("www-authenticate")) {
216262
216521
  const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
216263
216522
  this._resourceMetadataUrl = resourceMetadataUrl;
@@ -216272,7 +216531,7 @@ var SSEClientTransport = class {
216272
216531
  this._authThenStart().then(resolve, reject);
216273
216532
  return;
216274
216533
  }
216275
- const error40 = new SseError(event.code, event.message, event);
216534
+ const error40 = new SseError(event.code, redirect ?? event.message, event);
216276
216535
  reject(error40);
216277
216536
  this.onerror?.(error40);
216278
216537
  };
@@ -216349,7 +216608,7 @@ var SSEClientTransport = class {
216349
216608
  body: JSON.stringify(message),
216350
216609
  signal: this._abortController?.signal
216351
216610
  };
216352
- const response = await (this._fetch ?? fetch)(this._endpoint, init);
216611
+ const response = await fetchWithinOrigin(this._fetch ?? fetch)(this._endpoint, init);
216353
216612
  if (!response.ok) {
216354
216613
  const text2 = await response.text().catch(() => null);
216355
216614
  if (response.status === 401 && this._authProvider) {
@@ -216367,7 +216626,7 @@ var SSEClientTransport = class {
216367
216626
  }
216368
216627
  return this.send(message);
216369
216628
  }
216370
- throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text2}`);
216629
+ throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${this._unfollowedRedirect(response, this._endpoint) ?? text2}`);
216371
216630
  }
216372
216631
  await response.body?.cancel();
216373
216632
  } catch (error40) {