linkque-cli-v2 1.3.5 → 1.3.6

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.
@@ -3,11 +3,11 @@ import {
3
3
  runClientCapability,
4
4
  runClientCapabilityCleanup,
5
5
  runClientCapabilityResult
6
- } from "../../chunk-LT6VSAY4.js";
6
+ } from "../../chunk-7SF3H2GM.js";
7
7
  import "../../chunk-IWOFD643.js";
8
8
  import "../../chunk-PXCGFBV5.js";
9
9
  import "../../chunk-ETG6PNHQ.js";
10
- import "../../chunk-VVEDZWQ5.js";
10
+ import "../../chunk-RHFHCJYP.js";
11
11
  import "../../chunk-XUFLSZM4.js";
12
12
  import "../../chunk-GAYNLDWK.js";
13
13
  import "../../chunk-HM7KNEG3.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  getBakedProtocol,
3
3
  setBakedProtocol
4
- } from "../chunk-NBYB7HSY.js";
5
- import "../chunk-VVEDZWQ5.js";
4
+ } from "../chunk-NHRW2KQW.js";
5
+ import "../chunk-RHFHCJYP.js";
6
6
  import "../chunk-XUFLSZM4.js";
7
7
  import "../chunk-GAYNLDWK.js";
8
8
  import "../chunk-HM7KNEG3.js";
package/worker.js CHANGED
@@ -4360,14 +4360,13 @@ var require_fast_uri = __commonJS({
4360
4360
  if (!malformedIPLiteral) {
4361
4361
  malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP2);
4362
4362
  }
4363
- if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) {
4364
- let host = isIP2 ? parsed.host : normalizePercentEncoding(parsed.host, true);
4365
- if (!isIP2) {
4366
- host = normalizePercentEncoding(host.toLowerCase());
4367
- }
4368
- parsed.host = reescapeHostDelimiters(host, isIP2);
4369
- }
4370
4363
  if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
4364
+ if (uri.indexOf("%") !== -1) {
4365
+ if (parsed.host !== void 0 && !malformedIPLiteral) {
4366
+ const host = isIP2 ? parsed.host : normalizePercentEncoding(parsed.host, true);
4367
+ parsed.host = reescapeHostDelimiters(host, isIP2);
4368
+ }
4369
+ }
4371
4370
  if (parsed.path) {
4372
4371
  parsed.path = normalizePathEncoding(parsed.path);
4373
4372
  }
@@ -11513,7 +11512,7 @@ var init_cardSemanticSnapshot = __esm({
11513
11512
  function createCardPresentationToolName(resourceId) {
11514
11513
  return stableToolName("a2ui_card", resourceId);
11515
11514
  }
11516
- async function executeCardPresentation(resource, registry2, runtimeContext, args, signal) {
11515
+ async function executeCardPresentation(resource, registry2, runtimeContext, args, signal, context2) {
11517
11516
  const config2 = parseCardConfig(resource);
11518
11517
  if (config2.schemaVersion !== "2") {
11519
11518
  throw new Error(`Schema v${config2.schemaVersion} cards must be executed through the card data-source loop`);
@@ -11542,7 +11541,7 @@ async function executeCardPresentation(resource, registry2, runtimeContext, args
11542
11541
  inputSchema,
11543
11542
  outputSchema: isJsonObject(handle.outputSchema) ? handle.outputSchema : FALLBACK_OBJECT_SCHEMA,
11544
11543
  call: async (input, callSignal) => {
11545
- const result = await handle.execute(supplementMcpInput(input, invocation, config2.presentationInputSchema, inputSchema), callSignal);
11544
+ const result = await handle.execute(supplementMcpInput(input, invocation, config2.presentationInputSchema, inputSchema), callSignal, context2);
11546
11545
  return { structuredContent: readStructuredContent(result) };
11547
11546
  }
11548
11547
  };
@@ -11823,6 +11822,8 @@ function aggregateMcpServers(resources, protocolAgentId) {
11823
11822
  argsMappingRules: [],
11824
11823
  allowedTools: void 0,
11825
11824
  resourceIds: [],
11825
+ allToolResourceIds: [],
11826
+ resourceIdsByTool: /* @__PURE__ */ new Map(),
11826
11827
  description: ""
11827
11828
  };
11828
11829
  specs.set(serverName, spec);
@@ -11846,14 +11847,19 @@ function aggregateMcpServers(resources, protocolAgentId) {
11846
11847
  if (allowed && allowed.length > 0) {
11847
11848
  if (!spec.allowedTools)
11848
11849
  spec.allowedTools = /* @__PURE__ */ new Set();
11849
- for (const toolName of allowed)
11850
+ for (const toolName of allowed) {
11850
11851
  spec.allowedTools.add(toolName);
11852
+ addToolResourceId(spec.resourceIdsByTool, toolName, resource.resourceId);
11853
+ }
11854
+ } else {
11855
+ spec.allToolResourceIds.push(resource.resourceId);
11851
11856
  }
11852
11857
  continue;
11853
11858
  }
11854
11859
  if (!spec.allowedTools)
11855
11860
  spec.allowedTools = /* @__PURE__ */ new Set();
11856
11861
  spec.allowedTools.add(resource.config.toolName);
11862
+ addToolResourceId(spec.resourceIdsByTool, resource.config.toolName, resource.resourceId);
11857
11863
  for (const rule of resource.config.argsMappingRules ?? []) {
11858
11864
  const fullRule = {
11859
11865
  mcpToolName: resource.config.toolName,
@@ -11867,6 +11873,11 @@ function aggregateMcpServers(resources, protocolAgentId) {
11867
11873
  }
11868
11874
  return [...specs.values()];
11869
11875
  }
11876
+ function addToolResourceId(target, toolName, resourceId) {
11877
+ const current = target.get(toolName) ?? [];
11878
+ current.push(resourceId);
11879
+ target.set(toolName, current);
11880
+ }
11870
11881
  var init_mcpAggregator = __esm({
11871
11882
  "../linkque-agent-runtime/dist/esm/core/mcpAggregator.js"() {
11872
11883
  "use strict";
@@ -11875,6 +11886,14 @@ var init_mcpAggregator = __esm({
11875
11886
  });
11876
11887
 
11877
11888
  // ../linkque-agent-runtime/dist/esm/core/mcpProxyTool.js
11889
+ function resourceIdsForTool(spec, toolName) {
11890
+ if (!spec.allToolResourceIds && !spec.resourceIdsByTool)
11891
+ return spec.resourceIds;
11892
+ return [
11893
+ ...spec.allToolResourceIds ?? [],
11894
+ ...spec.resourceIdsByTool?.get(toolName) ?? []
11895
+ ];
11896
+ }
11878
11897
  function parseProxyArgs(args) {
11879
11898
  if (!isRecord(args))
11880
11899
  return {};
@@ -11949,6 +11968,7 @@ var init_mcpProxyTool = __esm({
11949
11968
  specByResourceId;
11950
11969
  specs;
11951
11970
  debugLog;
11971
+ authorizeCall;
11952
11972
  constructor(provider, specs, options = {}) {
11953
11973
  this.provider = provider;
11954
11974
  this.specs = specs;
@@ -11956,6 +11976,7 @@ var init_mcpProxyTool = __esm({
11956
11976
  this.specByResourceId = new Map(specs.flatMap((spec) => spec.resourceIds.map((id) => [id, spec])));
11957
11977
  this.debugLog = options.debugLog ?? (() => {
11958
11978
  });
11979
+ this.authorizeCall = options.authorizeCall;
11959
11980
  }
11960
11981
  /**
11961
11982
  * 产单个 `mcp` 代理工具描述符,注入 `agentReq.tools`。
@@ -11968,7 +11989,7 @@ var init_mcpProxyTool = __esm({
11968
11989
  label: "MCP",
11969
11990
  description: MCP_PROXY_DESCRIPTION,
11970
11991
  inputSchema: MCP_PROXY_INPUT_SCHEMA,
11971
- execute: (args, signal) => this.dispatch(args, signal)
11992
+ execute: (args, signal, context2) => this.dispatch(args, signal, context2)
11972
11993
  };
11973
11994
  }
11974
11995
  /** {@link IMcpToolRegistry.resolve}:按 (resourceId, toolName) 解析可调用句柄。 */
@@ -11985,7 +12006,18 @@ var init_mcpProxyTool = __esm({
11985
12006
  return {
11986
12007
  inputSchema: tool.inputSchema,
11987
12008
  outputSchema: tool.outputSchema,
11988
- execute: (args, sig) => entry.server.callTool(tool.name, args, sig)
12009
+ execute: async (args, sig, context2) => {
12010
+ const headers = await this.authorizeCall?.({
12011
+ resourceIds: [resourceId],
12012
+ toolName: tool.name,
12013
+ signal: sig,
12014
+ context: context2
12015
+ });
12016
+ return entry.server.callTool(tool.name, args, sig, {
12017
+ ...headers ? { headers } : {},
12018
+ ...context2 ? { context: context2 } : {}
12019
+ });
12020
+ }
11989
12021
  };
11990
12022
  }
11991
12023
  /** 关闭所有已连 server(忽略单 server 关闭错误)。 */
@@ -12072,7 +12104,7 @@ var init_mcpProxyTool = __esm({
12072
12104
  }
12073
12105
  // —— 派发 ——
12074
12106
  /** 按入参字段派发;返回 LLM 可读文本。 */
12075
- async dispatch(args, signal) {
12107
+ async dispatch(args, signal, context2) {
12076
12108
  const params = parseProxyArgs(args);
12077
12109
  if (params.connect !== void 0) {
12078
12110
  return this.executeConnect(params.connect, signal);
@@ -12087,7 +12119,7 @@ var init_mcpProxyTool = __esm({
12087
12119
  return this.executeSearch(params.search, params.server);
12088
12120
  }
12089
12121
  if (params.tool !== void 0) {
12090
- return this.executeCall(params.tool, params.args, params.server, signal);
12122
+ return this.executeCall(params.tool, params.args, params.server, signal, context2);
12091
12123
  }
12092
12124
  if (params.server !== void 0) {
12093
12125
  return this.executeList(params.server, signal);
@@ -12215,14 +12247,23 @@ ${formatSchema(tool.inputSchema)}`);
12215
12247
  return lines.join("\n").trim();
12216
12248
  }
12217
12249
  /** `mcp({ tool: "name", args: {...} })`:调用工具,返回序列化结果。 */
12218
- async executeCall(toolName, args, serverHint, signal) {
12250
+ async executeCall(toolName, args, serverHint, signal, context2) {
12219
12251
  const found = await this.findTool(toolName, serverHint, signal);
12220
12252
  if (!found) {
12221
12253
  return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
12222
12254
  }
12223
- const { entry, tool } = found;
12255
+ const { entry, tool, spec } = found;
12224
12256
  try {
12225
- const result = await entry.server.callTool(tool.name, args, signal);
12257
+ const headers = await this.authorizeCall?.({
12258
+ resourceIds: resourceIdsForTool(spec, tool.name),
12259
+ toolName: tool.name,
12260
+ signal,
12261
+ context: context2
12262
+ });
12263
+ const result = await entry.server.callTool(tool.name, args, signal, {
12264
+ ...headers ? { headers } : {},
12265
+ ...context2 ? { context: context2 } : {}
12266
+ });
12226
12267
  return serializeToolResult(result);
12227
12268
  } catch (error40) {
12228
12269
  const message = error40 instanceof Error ? error40.message : String(error40);
@@ -12239,7 +12280,7 @@ ${formatSchema(tool.inputSchema)}`);
12239
12280
  continue;
12240
12281
  const tool = entry.tools.find((t2) => t2.name === toolName);
12241
12282
  if (tool) {
12242
- return { entry, server: spec.serverName, tool };
12283
+ return { entry, server: spec.serverName, tool, spec };
12243
12284
  }
12244
12285
  }
12245
12286
  await Promise.all(specs.map((s2) => this.ensureEntry(s2.serverName, signal)));
@@ -12249,7 +12290,7 @@ ${formatSchema(tool.inputSchema)}`);
12249
12290
  continue;
12250
12291
  const tool = entry.tools.find((t2) => t2.name === toolName);
12251
12292
  if (tool) {
12252
- return { entry, server: spec.serverName, tool };
12293
+ return { entry, server: spec.serverName, tool, spec };
12253
12294
  }
12254
12295
  }
12255
12296
  return void 0;
@@ -13978,6 +14019,7 @@ var init_httpLoggingFetch = __esm({
13978
14019
  "x-api-key",
13979
14020
  "x-signature-content",
13980
14021
  "x-alipay-sdk-version",
14022
+ "x-alipay-authcode",
13981
14023
  "anthropic-api-key"
13982
14024
  ]);
13983
14025
  REDACTED_VALUE = "ak***";
@@ -206595,7 +206637,7 @@ var init_cardRenderMcpServer = __esm({
206595
206637
  description: createPresentationDescription(config2),
206596
206638
  inputSchema: config2.presentationInputSchema,
206597
206639
  // execute 委托 callTool,返回 IAgentPresentationToolResult(execute 返回 unknown 兼容)。
206598
- execute: (args, signal) => this.callTool(name, args, signal)
206640
+ execute: (args, signal, context2) => this.callTool(name, args, signal, { context: context2 })
206599
206641
  });
206600
206642
  continue;
206601
206643
  }
@@ -206652,7 +206694,7 @@ var init_cardRenderMcpServer = __esm({
206652
206694
  description: `\u9009\u62E9 ${name} \u540E\u4F7F\u7528\u3002${source.purpose}\u3002\u6839\u636E\u5BF9\u8BDD\u548C\u5DF2\u6709\u6570\u636E\u6E90\u7ED3\u679C\u786E\u5B9A\u6240\u6709 MCP \u53C2\u6570\u3002${CARD_SEQUENCE}`,
206653
206695
  inputSchema: normalizeMcpInputSchema(discoveredHandle?.inputSchema),
206654
206696
  outputSchema: CARD_SOURCE_RECEIPT_SCHEMA,
206655
- execute: async (args, signal) => {
206697
+ execute: async (args, signal, context2) => {
206656
206698
  if (!state2.selected || this.activeCardId !== resource.resourceId)
206657
206699
  throw new Error(`\u8C03\u7528\u6570\u636E\u6E90\u524D\uFF0C\u8BF7\u5148\u9009\u62E9\u5361\u7247 ${name}`);
206658
206700
  const missingDependencies = (source.dependsOn ?? []).filter((dependency) => !state2.results.has(dependency));
@@ -206662,7 +206704,7 @@ var init_cardRenderMcpServer = __esm({
206662
206704
  if (!handle)
206663
206705
  throw new Error(`MCP \u5DE5\u5177 ${source.mcpResourceId}/${source.toolName} \u5F53\u524D\u4E0D\u53EF\u7528`);
206664
206706
  const mcpStartedAt = Date.now();
206665
- const result = await handle.execute(args, signal);
206707
+ const result = await handle.execute(args, signal, context2);
206666
206708
  signal?.throwIfAborted();
206667
206709
  if (this.closed)
206668
206710
  throw new Error("\u5361\u7247\u8FD0\u884C\u5DF2\u7ED3\u675F");
@@ -206770,22 +206812,22 @@ ${AFTER_CARD_DESCRIPTION}`,
206770
206812
  this.toolByName = new Map(tools.map((tool) => [tool.name, tool]));
206771
206813
  return tools;
206772
206814
  }
206773
- async callTool(name, args, signal) {
206815
+ async callTool(name, args, signal, options) {
206774
206816
  const resource = this.resources.find((r2) => createCardPresentationToolName(r2.resourceId) === name);
206775
206817
  if (!resource) {
206776
206818
  const descriptor = this.toolByName.get(name);
206777
206819
  if (!descriptor)
206778
206820
  throw new Error(`\u672A\u77E5\u5361\u7247\u5DE5\u5177: ${name}`);
206779
- return descriptor.execute(args, signal);
206821
+ return descriptor.execute(args, signal, options?.context);
206780
206822
  }
206781
206823
  const config2 = parseCardConfig(resource);
206782
206824
  if (config2.schemaVersion === "3" || config2.schemaVersion === "4") {
206783
206825
  const descriptor = this.toolByName.get(name);
206784
206826
  if (!descriptor)
206785
206827
  throw new Error(`\u672A\u77E5\u5361\u7247\u5DE5\u5177: ${name}`);
206786
- return descriptor.execute(args, signal);
206828
+ return descriptor.execute(args, signal, options?.context);
206787
206829
  }
206788
- return executeCardPresentation(resource, this.registry, this.runtimeContext, args, signal);
206830
+ return executeCardPresentation(resource, this.registry, this.runtimeContext, args, signal, options?.context);
206789
206831
  }
206790
206832
  async close() {
206791
206833
  this.closed = true;
@@ -207453,7 +207495,8 @@ var init_agentRuntime = __esm({
207453
207495
  debugLog?.("[mcp] no mcp servers configured (no MCP tools will be available)", EDebugLogScope.MCP);
207454
207496
  }
207455
207497
  const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
207456
- debugLog
207498
+ debugLog,
207499
+ ...options.mcpCallAuthorizer ? { authorizeCall: options.mcpCallAuthorizer } : {}
207457
207500
  });
207458
207501
  cleanup.push(() => mcpProxy.closeAll());
207459
207502
  const cardServer = new CardRenderMcpServer(this.cardResources, mcpProxy, { ...options.runtimeContext, threadId: request.threadId }, debugLog);
@@ -207669,6 +207712,8 @@ async function* runConversation(request, auth2, options = {}) {
207669
207712
  runOptions.requestSource = options.requestSource;
207670
207713
  if (options.debugLog)
207671
207714
  runOptions.debugLog = options.debugLog;
207715
+ if (options.mcpCallAuthorizer)
207716
+ runOptions.mcpCallAuthorizer = options.mcpCallAuthorizer;
207672
207717
  runOptions.runtimeContext = {
207673
207718
  ...options.runtimeContext,
207674
207719
  ...request.agentId ? { agentId: request.agentId } : {},
@@ -208379,6 +208424,49 @@ init_cardTools();
208379
208424
  init_mcpNaming();
208380
208425
  init_mcpAggregator();
208381
208426
 
208427
+ // ../linkque-agent-runtime/dist/esm/core/mcpPhoneAuthorization.js
208428
+ init_esm();
208429
+ var McpPhoneAuthorizationRequiredError = class extends Error {
208430
+ required;
208431
+ code = "MCP_PHONE_AUTHORIZATION_REQUIRED";
208432
+ constructor(required2) {
208433
+ super("\u8C03\u7528\u8BE5 MCP Tool \u524D\u9700\u8981\u83B7\u53D6\u624B\u673A\u53F7\u6388\u6743");
208434
+ this.required = required2;
208435
+ this.name = "McpPhoneAuthorizationRequiredError";
208436
+ }
208437
+ };
208438
+ var McpPhoneAuthorizationFailedError = class extends Error {
208439
+ code = "MCP_PHONE_AUTHORIZATION_FAILED";
208440
+ constructor() {
208441
+ super("\u672A\u53D6\u5F97\u624B\u673A\u53F7\u6388\u6743\uFF0C\u65E0\u6CD5\u8C03\u7528\u8BE5 MCP Tool");
208442
+ this.name = "McpPhoneAuthorizationFailedError";
208443
+ }
208444
+ };
208445
+ function createRequestMcpPhoneAuthorizer(protocol, attempt) {
208446
+ return async ({ resourceIds, toolName, signal }) => {
208447
+ if (signal?.aborted)
208448
+ throw Object.assign(new Error("\u64CD\u4F5C\u5DF2\u53D6\u6D88"), { name: "AbortError" });
208449
+ const policy = resolvePhoneAuthorizationDependency(protocol, resourceIds, toolName);
208450
+ if (!policy)
208451
+ return void 0;
208452
+ if (attempt?.kind === "authorized")
208453
+ return { "x-alipay-authcode": attempt.authCode };
208454
+ if (attempt?.kind === "unavailable") {
208455
+ if (policy.required)
208456
+ throw new McpPhoneAuthorizationFailedError();
208457
+ return void 0;
208458
+ }
208459
+ throw new McpPhoneAuthorizationRequiredError(policy.required);
208460
+ };
208461
+ }
208462
+ function isMcpPhoneAuthorizationError(error40) {
208463
+ return error40 instanceof McpPhoneAuthorizationRequiredError || error40 instanceof McpPhoneAuthorizationFailedError;
208464
+ }
208465
+ function resolvePhoneAuthorizationDependency(protocol, resourceIds, toolName) {
208466
+ const dependencies = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP_TOOL).flatMap((resource) => resourceIds.includes(resource.resourceId) && resource.config.toolName === toolName ? (resource.config.dependencies ?? []).filter((dependency) => dependency.name === "phoneAuthorization") : []);
208467
+ return dependencies.length ? { required: dependencies.some((dependency) => dependency.required) } : void 0;
208468
+ }
208469
+
208382
208470
  // ../linkque-agent-runtime/dist/esm/core/homeData.js
208383
208471
  init_esm2();
208384
208472
  init_esm();
@@ -208406,7 +208494,9 @@ async function executeHomeData(input) {
208406
208494
  if (spec.allowedTools && !spec.allowedTools.has(request.binding.toolName)) {
208407
208495
  return failure("TOOL_NOT_ALLOWED", "\u5F53\u524D Agent \u672A\u5141\u8BB8\u8C03\u7528\u8BE5 MCP \u5DE5\u5177", false);
208408
208496
  }
208409
- const registry2 = new McpProxyTool(input.mcpServerProvider, specs);
208497
+ const registry2 = new McpProxyTool(input.mcpServerProvider, specs, {
208498
+ authorizeCall: createRequestMcpPhoneAuthorizer(input.protocol, input.phoneAuthorization)
208499
+ });
208410
208500
  try {
208411
208501
  const handle = await registry2.resolve(spec.resourceIds[0], request.binding.toolName, input.signal);
208412
208502
  if (!handle) {
@@ -208434,6 +208524,8 @@ async function executeHomeData(input) {
208434
208524
  try {
208435
208525
  result = await handle.execute(toolInput, input.signal);
208436
208526
  } catch (error40) {
208527
+ if (isMcpPhoneAuthorizationError(error40))
208528
+ throw error40;
208437
208529
  return failure("EXECUTION_FAILED", error40 instanceof Error ? error40.message : "MCP \u5DE5\u5177\u8C03\u7528\u5931\u8D25", true);
208438
208530
  }
208439
208531
  const structured = readStructuredContent2(result);
@@ -208685,7 +208777,7 @@ async function executeCardActionInternal(input, diagnostics) {
208685
208777
  });
208686
208778
  diagnostics.write("binding_resolved", { output: createTrade });
208687
208779
  diagnostics.stage = "tool_resolve";
208688
- const registry2 = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog);
208780
+ const registry2 = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog, input.phoneAuthorization);
208689
208781
  try {
208690
208782
  diagnostics.write("tool_resolve_started", { input: createTrade });
208691
208783
  const tool = await registry2.resolve(createTrade.mcpResourceId, createTrade.toolName, input.signal);
@@ -208713,6 +208805,8 @@ async function executeCardActionInternal(input, diagnostics) {
208713
208805
  diagnostics.write("tool_completed", { output: result });
208714
208806
  } catch (error40) {
208715
208807
  diagnostics.error("tool_failed", error40);
208808
+ if (isMcpPhoneAuthorizationError(error40))
208809
+ throw error40;
208716
208810
  return failure2("EXECUTION_FAILED", "\u521B\u5EFA\u4EA4\u6613\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5", true);
208717
208811
  }
208718
208812
  diagnostics.stage = "tool_output";
@@ -208852,9 +208946,12 @@ function materializeValue(definition, supplied) {
208852
208946
  }
208853
208947
  return definition;
208854
208948
  }
208855
- function createRegistry(protocol, provider, debugLog) {
208949
+ function createRegistry(protocol, provider, debugLog, phoneAuthorization) {
208856
208950
  const resources = protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
208857
- return new McpProxyTool(provider, aggregateMcpServers(resources, protocol.agentId), { debugLog });
208951
+ return new McpProxyTool(provider, aggregateMcpServers(resources, protocol.agentId), {
208952
+ debugLog,
208953
+ authorizeCall: createRequestMcpPhoneAuthorizer(protocol, phoneAuthorization)
208954
+ });
208858
208955
  }
208859
208956
  function readStructuredContent3(result) {
208860
208957
  const object3 = cloneJsonObject(result);
@@ -208894,7 +208991,9 @@ async function executeAuthorizedMcp(input) {
208894
208991
  if (!input.userId.trim())
208895
208992
  return failure3("AUTH_REQUIRED", "\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
208896
208993
  const resources = input.protocol.agent.resources.filter((resource) => resource.resourceType === EResourceType.MCP || resource.resourceType === EResourceType.MCP_TOOL);
208897
- const registry2 = new McpProxyTool(input.mcpServerProvider, aggregateMcpServers(resources, input.protocol.agentId));
208994
+ const registry2 = new McpProxyTool(input.mcpServerProvider, aggregateMcpServers(resources, input.protocol.agentId), {
208995
+ authorizeCall: createRequestMcpPhoneAuthorizer(input.protocol, input.phoneAuthorization)
208996
+ });
208898
208997
  try {
208899
208998
  const tool = await registry2.resolve(input.tool.mcpResourceId, input.tool.toolName, input.signal);
208900
208999
  if (!tool)
@@ -208906,7 +209005,9 @@ async function executeAuthorizedMcp(input) {
208906
209005
  let result;
208907
209006
  try {
208908
209007
  result = await tool.execute(input.tool.input, input.signal);
208909
- } catch {
209008
+ } catch (error40) {
209009
+ if (isMcpPhoneAuthorizationError(error40))
209010
+ throw error40;
208910
209011
  return failure3("EXECUTION_UNCERTAIN", "MCP \u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u52FF\u81EA\u52A8\u91CD\u8BD5", false);
208911
209012
  }
208912
209013
  const structured = readStructuredContent4(result);
@@ -208970,7 +209071,8 @@ async function executeFunctionActionMcp(input) {
208970
209071
  callId: request.callId,
208971
209072
  tool: request.tool,
208972
209073
  mcpServerProvider: input.mcpServerProvider,
208973
- signal: input.signal
209074
+ signal: input.signal,
209075
+ phoneAuthorization: input.phoneAuthorization
208974
209076
  });
208975
209077
  }
208976
209078
  function failure4(code, message, retryable) {
@@ -214022,7 +214124,7 @@ var SSEClientTransport = class {
214022
214124
  init_httpLoggingFetch();
214023
214125
  var ALIPAY_SDK_VERSION = "@alipay/open-mcp-server-2.0.4";
214024
214126
  var OAGW_ALIPAY_UID_HEADER = "x-oagw-alipay-uid";
214025
- function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, debugLog) {
214127
+ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, debugLog, getCallHeaders) {
214026
214128
  const loggedFetch = debugLog ? createHttpLoggingFetch(debugLog, "mcp-call", baseFetch) : baseFetch;
214027
214129
  return async (url2, init) => {
214028
214130
  const targetUrl = url2 instanceof URL ? url2 : new URL(typeof url2 === "string" ? url2 : url2.url);
@@ -214041,6 +214143,13 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
214041
214143
  } else {
214042
214144
  headers.delete(OAGW_ALIPAY_UID_HEADER);
214043
214145
  }
214146
+ if ((init?.method ?? "GET").toUpperCase() === "POST") {
214147
+ const authCode = getCallHeaders?.()?.["x-alipay-authcode"];
214148
+ if (authCode)
214149
+ headers.set("x-alipay-authcode", authCode);
214150
+ else
214151
+ headers.delete("x-alipay-authcode");
214152
+ }
214044
214153
  const resp = await loggedFetch(url2, { ...init, headers });
214045
214154
  if (onTraceId) {
214046
214155
  try {
@@ -214069,10 +214178,10 @@ function withTimeout(fetch3, timeoutMs) {
214069
214178
  return fetch3(url2, { ...init, signal });
214070
214179
  };
214071
214180
  }
214072
- function createSseTransport(config2, signer, onTraceId, debugLog) {
214181
+ function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders) {
214073
214182
  const url2 = new URL(config2.sseEndpoint, config2.remoteBaseUrl);
214074
214183
  const timeoutMs = config2.requestTimeoutMs ?? 18e4;
214075
- const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog), timeoutMs);
214184
+ const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders), timeoutMs);
214076
214185
  return new SSEClientTransport(url2, {
214077
214186
  // SSE 建连(EventSource)的 GET fetch:SDK 先包默认头再调这里。
214078
214187
  eventSourceInit: { fetch: signingFetch },
@@ -214176,6 +214285,7 @@ function applyArgsMappingRules(toolName, args, rules) {
214176
214285
  init_esm();
214177
214286
 
214178
214287
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteGatewayMcpServer.js
214288
+ var import_node_async_hooks = require("node:async_hooks");
214179
214289
  init_types();
214180
214290
  init_logFailure();
214181
214291
  var defaultCreateSigner = (config2, getAuthorizationHeader, debugLog) => new RemoteSignatureSigner({
@@ -214207,8 +214317,9 @@ var RemoteGatewayMcpServerProvider = class {
214207
214317
  /** 连单个远端 server 并包装成 IMcpServer。建连失败有限重试 + 失败清理由 helper 负责。 */
214208
214318
  async connectOne(resource) {
214209
214319
  const config2 = await this.resolveConfig(resource);
214320
+ const callHeaders = new import_node_async_hooks.AsyncLocalStorage();
214210
214321
  const { client } = await connectMcpClientWithRetry(config2, {
214211
- createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog),
214322
+ createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore()),
214212
214323
  createClient: () => this.createClient()
214213
214324
  });
214214
214325
  const serverName = resource.config.serverName ?? resource.resourceId;
@@ -214243,12 +214354,9 @@ var RemoteGatewayMcpServerProvider = class {
214243
214354
  resourceId: resource.resourceId,
214244
214355
  serverName,
214245
214356
  listTools: () => listToolsFromClient(loggedClient, resource.resourceId),
214246
- callTool: (name, args) => {
214357
+ callTool: (name, args, _signal, options) => {
214247
214358
  const mapped = applyArgsMappingRules(name, args, argsMappingRules);
214248
- return loggedClient.callTool({
214249
- name,
214250
- arguments: mapped ?? {}
214251
- });
214359
+ return callHeaders.run(options?.headers ?? {}, () => loggedClient.callTool({ name, arguments: mapped ?? {} }));
214252
214360
  },
214253
214361
  close: async () => {
214254
214362
  try {
@@ -215502,7 +215610,7 @@ init_noopRuntimeTelemetry();
215502
215610
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/identityQueue.js
215503
215611
  init_telemetry();
215504
215612
  init_telemetryEnums2();
215505
- var import_node_async_hooks = require("node:async_hooks");
215613
+ var import_node_async_hooks2 = require("node:async_hooks");
215506
215614
  init_esm6();
215507
215615
  var import_core11 = __toESM(require_src(), 1);
215508
215616
  function authorizationKey(auth2) {
@@ -215516,7 +215624,7 @@ function authorizationKey(auth2) {
215516
215624
  }
215517
215625
  var IdentityQueue = class {
215518
215626
  options;
215519
- exportContext = new import_node_async_hooks.AsyncLocalStorage();
215627
+ exportContext = new import_node_async_hooks2.AsyncLocalStorage();
215520
215628
  get isExporting() {
215521
215629
  return this.exportContext.getStore() === true;
215522
215630
  }
@@ -216360,21 +216468,22 @@ function createSandboxMcpHandler() {
216360
216468
  if (payload.agentId !== void 0 && payload.agentId !== protocol.agentId) {
216361
216469
  return failure5(403, "AGENT_MISMATCH", "Agent \u4E0D\u5339\u914D");
216362
216470
  }
216363
- if (value.operation === "homeData.request") {
216364
- const result = await executeHomeData({
216365
- request: { ...payload, agentId: protocol.agentId },
216366
- protocol,
216367
- userId,
216368
- mcpServerProvider: provider
216369
- });
216370
- return { status: result.ok ? 200 : 400, body: result };
216371
- }
216372
- if (value.operation !== "mcp.call" || typeof payload.callId !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/u.test(payload.callId) || !record2(payload.tool) || typeof payload.tool.mcpResourceId !== "string" || !payload.tool.mcpResourceId.trim() || typeof payload.tool.toolName !== "string" || !payload.tool.toolName.trim() || !record2(payload.tool.input) || Object.keys(payload.tool).some(
216373
- (key) => !["mcpResourceId", "toolName", "input"].includes(key)
216374
- )) {
216375
- return failure5(400, "INVALID_INPUT", "MCP \u8C03\u7528\u53C2\u6570\u65E0\u6548");
216376
- }
216377
216471
  try {
216472
+ if (value.operation === "homeData.request") {
216473
+ const result2 = await executeHomeData({
216474
+ request: { ...payload, agentId: protocol.agentId },
216475
+ protocol,
216476
+ userId,
216477
+ mcpServerProvider: provider,
216478
+ phoneAuthorization: { kind: "unavailable" }
216479
+ });
216480
+ return { status: result2.ok ? 200 : 400, body: result2 };
216481
+ }
216482
+ if (value.operation !== "mcp.call" || typeof payload.callId !== "string" || !/^[A-Za-z0-9._:-]{1,128}$/u.test(payload.callId) || !record2(payload.tool) || typeof payload.tool.mcpResourceId !== "string" || !payload.tool.mcpResourceId.trim() || typeof payload.tool.toolName !== "string" || !payload.tool.toolName.trim() || !record2(payload.tool.input) || Object.keys(payload.tool).some(
216483
+ (key) => !["mcpResourceId", "toolName", "input"].includes(key)
216484
+ )) {
216485
+ return failure5(400, "INVALID_INPUT", "MCP \u8C03\u7528\u53C2\u6570\u65E0\u6548");
216486
+ }
216378
216487
  const result = await executeAuthorizedMcp({
216379
216488
  protocol,
216380
216489
  agentId: protocol.agentId,
@@ -216385,13 +216494,17 @@ function createSandboxMcpHandler() {
216385
216494
  toolName: payload.tool.toolName,
216386
216495
  input: payload.tool.input
216387
216496
  },
216388
- mcpServerProvider: provider
216497
+ mcpServerProvider: provider,
216498
+ phoneAuthorization: { kind: "unavailable" }
216389
216499
  });
216390
216500
  return {
216391
216501
  status: result.ok ? 200 : result.error.code === "EXECUTION_UNCERTAIN" ? 409 : 400,
216392
216502
  body: result
216393
216503
  };
216394
- } catch {
216504
+ } catch (error40) {
216505
+ if (error40 instanceof McpPhoneAuthorizationFailedError) {
216506
+ return failure5(403, error40.code, "\u6C99\u7BB1\u4E0D\u652F\u6301\u624B\u673A\u53F7\u6388\u6743\uFF0C\u8BF7\u4F7F\u7528\u771F\u673A\u9884\u89C8");
216507
+ }
216395
216508
  return failure5(
216396
216509
  409,
216397
216510
  "EXECUTION_UNCERTAIN",
@@ -216821,6 +216934,7 @@ var handleSandboxChat = async (req, res, deps, activeRuns2, cancelActiveRun2) =>
216821
216934
  cwd: deps.cwd,
216822
216935
  signal: abort.signal,
216823
216936
  telemetryContext: deps.createTelemetryContext(request.runId),
216937
+ mcpCallAuthorizer: deps.createMcpCallAuthorizer(protocol),
216824
216938
  debugLog: deps.debugLog,
216825
216939
  ...inboundUserId && { runtimeContext: { userId: inboundUserId } }
216826
216940
  });
@@ -217032,6 +217146,9 @@ var handleRun = async (req, res, input, debugLog) => {
217032
217146
  agentId: input.agentId,
217033
217147
  bodyMaxBytes: 1024 * 1024,
217034
217148
  createRuntime,
217149
+ createMcpCallAuthorizer: (protocol) => createRequestMcpPhoneAuthorizer(protocol, {
217150
+ kind: "unavailable"
217151
+ }),
217035
217152
  debugLog,
217036
217153
  createTelemetryContext: agentDevTelemetry.createContext
217037
217154
  },
@@ -217070,7 +217187,8 @@ var handleHomeData = async (req, res, input) => {
217070
217187
  request: homeDataInput.request,
217071
217188
  protocol,
217072
217189
  userId: homeDataInput.userId,
217073
- mcpServerProvider: createMcpServerProvider(protocol)
217190
+ mcpServerProvider: createMcpServerProvider(protocol),
217191
+ phoneAuthorization: { kind: "unavailable" }
217074
217192
  });
217075
217193
  res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
217076
217194
  res.end(JSON.stringify(result));
@@ -217108,6 +217226,7 @@ var handleA2UIAction = async (req, res, input, debugLog) => {
217108
217226
  ...proxyInput.tenantId ? { tenantId: proxyInput.tenantId } : {}
217109
217227
  },
217110
217228
  mcpServerProvider: createMcpServerProvider(protocol),
217229
+ phoneAuthorization: { kind: "unavailable" },
217111
217230
  debugLog
217112
217231
  });
217113
217232
  res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
@@ -217139,7 +217258,8 @@ var handleFunctionActionMcp = async (req, res, input) => {
217139
217258
  request: proxyInput.request,
217140
217259
  protocol,
217141
217260
  runtimeContext: { threadId: request.threadId, userId: proxyInput.userId },
217142
- mcpServerProvider: createMcpServerProvider(protocol)
217261
+ mcpServerProvider: createMcpServerProvider(protocol),
217262
+ phoneAuthorization: { kind: "unavailable" }
217143
217263
  });
217144
217264
  writeJson(
217145
217265
  res,