linkque-cli-v2 1.3.5 → 1.3.7

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 (18) hide show
  1. package/linkquejs.js +14 -104
  2. package/package.json +1 -1
  3. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-NBYB7HSY.js → chunk-AACYYAZ6.js} +1 -1
  4. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-HM7KNEG3.js → chunk-DNTEEBEH.js} +5 -0
  5. package/vendor/linkque-agent-appwrite-integrate/dist/esm/chunk-EAODRPW4.js +518 -0
  6. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-LT6VSAY4.js → chunk-RHMVQTA7.js} +56 -144
  7. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{chunk-VVEDZWQ5.js → chunk-ZNU4GVF3.js} +15262 -378
  8. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-bsd-H2ZLZRGB.js → getMachineId-bsd-JGCLGHFY.js} +1 -1
  9. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-darwin-HUKYR46U.js → getMachineId-darwin-COHLFNXH.js} +1 -1
  10. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-linux-M5ZADHBA.js → getMachineId-linux-XV3Z5FQG.js} +1 -1
  11. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-unsupported-BM5RZZVM.js → getMachineId-unsupported-FCRKLIZL.js} +1 -1
  12. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{getMachineId-win-BQPUF5TW.js → getMachineId-win-A4WRNVV6.js} +1 -1
  13. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{mistral-conversations-TQA2MPJJ.js → mistral-conversations-5RZTVEO2.js} +1 -1
  14. package/vendor/linkque-agent-appwrite-integrate/dist/esm/{otel-RXJWJ2TU.js → otel-WGS5CC2J.js} +250 -267
  15. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/chat.js +413 -625
  16. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/handler/clientCapability.js +4 -3
  17. package/vendor/linkque-agent-appwrite-integrate/dist/esm/runtime/protocol.js +4 -3
  18. package/worker.js +430 -87
package/worker.js CHANGED
@@ -80,6 +80,7 @@ var init_agentProtocol = __esm({
80
80
  (function(EArgsMappingValueType2) {
81
81
  EArgsMappingValueType2["DEFAULT"] = "DEFAULT";
82
82
  EArgsMappingValueType2["CONST"] = "CONST";
83
+ EArgsMappingValueType2["SYSTEM_VARIABLE"] = "SYSTEM_VARIABLE";
83
84
  })(EArgsMappingValueType || (EArgsMappingValueType = {}));
84
85
  (function(EHookStage2) {
85
86
  EHookStage2["PREPARE_AGENT_LOOP"] = "PREPARE_AGENT_LOOP";
@@ -11513,7 +11514,7 @@ var init_cardSemanticSnapshot = __esm({
11513
11514
  function createCardPresentationToolName(resourceId) {
11514
11515
  return stableToolName("a2ui_card", resourceId);
11515
11516
  }
11516
- async function executeCardPresentation(resource, registry2, runtimeContext, args, signal) {
11517
+ async function executeCardPresentation(resource, registry2, runtimeContext, args, signal, context2) {
11517
11518
  const config2 = parseCardConfig(resource);
11518
11519
  if (config2.schemaVersion !== "2") {
11519
11520
  throw new Error(`Schema v${config2.schemaVersion} cards must be executed through the card data-source loop`);
@@ -11542,7 +11543,7 @@ async function executeCardPresentation(resource, registry2, runtimeContext, args
11542
11543
  inputSchema,
11543
11544
  outputSchema: isJsonObject(handle.outputSchema) ? handle.outputSchema : FALLBACK_OBJECT_SCHEMA,
11544
11545
  call: async (input, callSignal) => {
11545
- const result = await handle.execute(supplementMcpInput(input, invocation, config2.presentationInputSchema, inputSchema), callSignal);
11546
+ const result = await handle.execute(supplementMcpInput(input, invocation, config2.presentationInputSchema, inputSchema), callSignal, context2);
11546
11547
  return { structuredContent: readStructuredContent(result) };
11547
11548
  }
11548
11549
  };
@@ -11823,6 +11824,8 @@ function aggregateMcpServers(resources, protocolAgentId) {
11823
11824
  argsMappingRules: [],
11824
11825
  allowedTools: void 0,
11825
11826
  resourceIds: [],
11827
+ allToolResourceIds: [],
11828
+ resourceIdsByTool: /* @__PURE__ */ new Map(),
11826
11829
  description: ""
11827
11830
  };
11828
11831
  specs.set(serverName, spec);
@@ -11846,14 +11849,19 @@ function aggregateMcpServers(resources, protocolAgentId) {
11846
11849
  if (allowed && allowed.length > 0) {
11847
11850
  if (!spec.allowedTools)
11848
11851
  spec.allowedTools = /* @__PURE__ */ new Set();
11849
- for (const toolName of allowed)
11852
+ for (const toolName of allowed) {
11850
11853
  spec.allowedTools.add(toolName);
11854
+ addToolResourceId(spec.resourceIdsByTool, toolName, resource.resourceId);
11855
+ }
11856
+ } else {
11857
+ spec.allToolResourceIds.push(resource.resourceId);
11851
11858
  }
11852
11859
  continue;
11853
11860
  }
11854
11861
  if (!spec.allowedTools)
11855
11862
  spec.allowedTools = /* @__PURE__ */ new Set();
11856
11863
  spec.allowedTools.add(resource.config.toolName);
11864
+ addToolResourceId(spec.resourceIdsByTool, resource.config.toolName, resource.resourceId);
11857
11865
  for (const rule of resource.config.argsMappingRules ?? []) {
11858
11866
  const fullRule = {
11859
11867
  mcpToolName: resource.config.toolName,
@@ -11867,6 +11875,11 @@ function aggregateMcpServers(resources, protocolAgentId) {
11867
11875
  }
11868
11876
  return [...specs.values()];
11869
11877
  }
11878
+ function addToolResourceId(target, toolName, resourceId) {
11879
+ const current = target.get(toolName) ?? [];
11880
+ current.push(resourceId);
11881
+ target.set(toolName, current);
11882
+ }
11870
11883
  var init_mcpAggregator = __esm({
11871
11884
  "../linkque-agent-runtime/dist/esm/core/mcpAggregator.js"() {
11872
11885
  "use strict";
@@ -11875,6 +11888,14 @@ var init_mcpAggregator = __esm({
11875
11888
  });
11876
11889
 
11877
11890
  // ../linkque-agent-runtime/dist/esm/core/mcpProxyTool.js
11891
+ function resourceIdsForTool(spec, toolName) {
11892
+ if (!spec.allToolResourceIds && !spec.resourceIdsByTool)
11893
+ return spec.resourceIds;
11894
+ return [
11895
+ ...spec.allToolResourceIds ?? [],
11896
+ ...spec.resourceIdsByTool?.get(toolName) ?? []
11897
+ ];
11898
+ }
11878
11899
  function parseProxyArgs(args) {
11879
11900
  if (!isRecord(args))
11880
11901
  return {};
@@ -11949,6 +11970,7 @@ var init_mcpProxyTool = __esm({
11949
11970
  specByResourceId;
11950
11971
  specs;
11951
11972
  debugLog;
11973
+ authorizeCall;
11952
11974
  constructor(provider, specs, options = {}) {
11953
11975
  this.provider = provider;
11954
11976
  this.specs = specs;
@@ -11956,6 +11978,7 @@ var init_mcpProxyTool = __esm({
11956
11978
  this.specByResourceId = new Map(specs.flatMap((spec) => spec.resourceIds.map((id) => [id, spec])));
11957
11979
  this.debugLog = options.debugLog ?? (() => {
11958
11980
  });
11981
+ this.authorizeCall = options.authorizeCall;
11959
11982
  }
11960
11983
  /**
11961
11984
  * 产单个 `mcp` 代理工具描述符,注入 `agentReq.tools`。
@@ -11968,7 +11991,7 @@ var init_mcpProxyTool = __esm({
11968
11991
  label: "MCP",
11969
11992
  description: MCP_PROXY_DESCRIPTION,
11970
11993
  inputSchema: MCP_PROXY_INPUT_SCHEMA,
11971
- execute: (args, signal) => this.dispatch(args, signal)
11994
+ execute: (args, signal, context2) => this.dispatch(args, signal, context2)
11972
11995
  };
11973
11996
  }
11974
11997
  /** {@link IMcpToolRegistry.resolve}:按 (resourceId, toolName) 解析可调用句柄。 */
@@ -11985,7 +12008,18 @@ var init_mcpProxyTool = __esm({
11985
12008
  return {
11986
12009
  inputSchema: tool.inputSchema,
11987
12010
  outputSchema: tool.outputSchema,
11988
- execute: (args, sig) => entry.server.callTool(tool.name, args, sig)
12011
+ execute: async (args, sig, context2) => {
12012
+ const headers = await this.authorizeCall?.({
12013
+ resourceIds: [resourceId],
12014
+ toolName: tool.name,
12015
+ signal: sig,
12016
+ context: context2
12017
+ });
12018
+ return entry.server.callTool(tool.name, args, sig, {
12019
+ ...headers ? { headers } : {},
12020
+ ...context2 ? { context: context2 } : {}
12021
+ });
12022
+ }
11989
12023
  };
11990
12024
  }
11991
12025
  /** 关闭所有已连 server(忽略单 server 关闭错误)。 */
@@ -12072,7 +12106,7 @@ var init_mcpProxyTool = __esm({
12072
12106
  }
12073
12107
  // —— 派发 ——
12074
12108
  /** 按入参字段派发;返回 LLM 可读文本。 */
12075
- async dispatch(args, signal) {
12109
+ async dispatch(args, signal, context2) {
12076
12110
  const params = parseProxyArgs(args);
12077
12111
  if (params.connect !== void 0) {
12078
12112
  return this.executeConnect(params.connect, signal);
@@ -12087,7 +12121,7 @@ var init_mcpProxyTool = __esm({
12087
12121
  return this.executeSearch(params.search, params.server);
12088
12122
  }
12089
12123
  if (params.tool !== void 0) {
12090
- return this.executeCall(params.tool, params.args, params.server, signal);
12124
+ return this.executeCall(params.tool, params.args, params.server, signal, context2);
12091
12125
  }
12092
12126
  if (params.server !== void 0) {
12093
12127
  return this.executeList(params.server, signal);
@@ -12215,14 +12249,23 @@ ${formatSchema(tool.inputSchema)}`);
12215
12249
  return lines.join("\n").trim();
12216
12250
  }
12217
12251
  /** `mcp({ tool: "name", args: {...} })`:调用工具,返回序列化结果。 */
12218
- async executeCall(toolName, args, serverHint, signal) {
12252
+ async executeCall(toolName, args, serverHint, signal, context2) {
12219
12253
  const found = await this.findTool(toolName, serverHint, signal);
12220
12254
  if (!found) {
12221
12255
  return `Tool "${toolName}" not found. Use mcp({ search: "..." }) to search.`;
12222
12256
  }
12223
- const { entry, tool } = found;
12257
+ const { entry, tool, spec } = found;
12224
12258
  try {
12225
- const result = await entry.server.callTool(tool.name, args, signal);
12259
+ const headers = await this.authorizeCall?.({
12260
+ resourceIds: resourceIdsForTool(spec, tool.name),
12261
+ toolName: tool.name,
12262
+ signal,
12263
+ context: context2
12264
+ });
12265
+ const result = await entry.server.callTool(tool.name, args, signal, {
12266
+ ...headers ? { headers } : {},
12267
+ ...context2 ? { context: context2 } : {}
12268
+ });
12226
12269
  return serializeToolResult(result);
12227
12270
  } catch (error40) {
12228
12271
  const message = error40 instanceof Error ? error40.message : String(error40);
@@ -12239,7 +12282,7 @@ ${formatSchema(tool.inputSchema)}`);
12239
12282
  continue;
12240
12283
  const tool = entry.tools.find((t2) => t2.name === toolName);
12241
12284
  if (tool) {
12242
- return { entry, server: spec.serverName, tool };
12285
+ return { entry, server: spec.serverName, tool, spec };
12243
12286
  }
12244
12287
  }
12245
12288
  await Promise.all(specs.map((s2) => this.ensureEntry(s2.serverName, signal)));
@@ -12249,7 +12292,7 @@ ${formatSchema(tool.inputSchema)}`);
12249
12292
  continue;
12250
12293
  const tool = entry.tools.find((t2) => t2.name === toolName);
12251
12294
  if (tool) {
12252
- return { entry, server: spec.serverName, tool };
12295
+ return { entry, server: spec.serverName, tool, spec };
12253
12296
  }
12254
12297
  }
12255
12298
  return void 0;
@@ -13827,7 +13870,8 @@ var init_runtimeConfigProvider = __esm({
13827
13870
  LINKQUEGW_KNOWLEDGE_BASE_URL: LINKQUE_ENDPOINT_PROD,
13828
13871
  LINKQUEGW_WEB_SEARCH_BASE_URL: LINKQUE_ENDPOINT_PROD,
13829
13872
  LINKQUEGW_EVENT_BASE_URL: LINKQUE_ENDPOINT_PROD,
13830
- LINKQUEGW_MCP_SIGN_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/mcp/signature`
13873
+ LINKQUEGW_MCP_SIGN_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/mcp/signature`,
13874
+ LINKQUEGW_TOKEN_VERIFY_ENDPOINT: `${LINKQUE_ENDPOINT_PROD}/api/auth/verify`
13831
13875
  });
13832
13876
  RuntimeConfigProvider = class {
13833
13877
  defaults;
@@ -13978,6 +14022,7 @@ var init_httpLoggingFetch = __esm({
13978
14022
  "x-api-key",
13979
14023
  "x-signature-content",
13980
14024
  "x-alipay-sdk-version",
14025
+ "x-alipay-authcode",
13981
14026
  "anthropic-api-key"
13982
14027
  ]);
13983
14028
  REDACTED_VALUE = "ak***";
@@ -206595,7 +206640,7 @@ var init_cardRenderMcpServer = __esm({
206595
206640
  description: createPresentationDescription(config2),
206596
206641
  inputSchema: config2.presentationInputSchema,
206597
206642
  // execute 委托 callTool,返回 IAgentPresentationToolResult(execute 返回 unknown 兼容)。
206598
- execute: (args, signal) => this.callTool(name, args, signal)
206643
+ execute: (args, signal, context2) => this.callTool(name, args, signal, { context: context2 })
206599
206644
  });
206600
206645
  continue;
206601
206646
  }
@@ -206652,7 +206697,7 @@ var init_cardRenderMcpServer = __esm({
206652
206697
  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
206698
  inputSchema: normalizeMcpInputSchema(discoveredHandle?.inputSchema),
206654
206699
  outputSchema: CARD_SOURCE_RECEIPT_SCHEMA,
206655
- execute: async (args, signal) => {
206700
+ execute: async (args, signal, context2) => {
206656
206701
  if (!state2.selected || this.activeCardId !== resource.resourceId)
206657
206702
  throw new Error(`\u8C03\u7528\u6570\u636E\u6E90\u524D\uFF0C\u8BF7\u5148\u9009\u62E9\u5361\u7247 ${name}`);
206658
206703
  const missingDependencies = (source.dependsOn ?? []).filter((dependency) => !state2.results.has(dependency));
@@ -206662,7 +206707,7 @@ var init_cardRenderMcpServer = __esm({
206662
206707
  if (!handle)
206663
206708
  throw new Error(`MCP \u5DE5\u5177 ${source.mcpResourceId}/${source.toolName} \u5F53\u524D\u4E0D\u53EF\u7528`);
206664
206709
  const mcpStartedAt = Date.now();
206665
- const result = await handle.execute(args, signal);
206710
+ const result = await handle.execute(args, signal, context2);
206666
206711
  signal?.throwIfAborted();
206667
206712
  if (this.closed)
206668
206713
  throw new Error("\u5361\u7247\u8FD0\u884C\u5DF2\u7ED3\u675F");
@@ -206770,22 +206815,22 @@ ${AFTER_CARD_DESCRIPTION}`,
206770
206815
  this.toolByName = new Map(tools.map((tool) => [tool.name, tool]));
206771
206816
  return tools;
206772
206817
  }
206773
- async callTool(name, args, signal) {
206818
+ async callTool(name, args, signal, options) {
206774
206819
  const resource = this.resources.find((r2) => createCardPresentationToolName(r2.resourceId) === name);
206775
206820
  if (!resource) {
206776
206821
  const descriptor = this.toolByName.get(name);
206777
206822
  if (!descriptor)
206778
206823
  throw new Error(`\u672A\u77E5\u5361\u7247\u5DE5\u5177: ${name}`);
206779
- return descriptor.execute(args, signal);
206824
+ return descriptor.execute(args, signal, options?.context);
206780
206825
  }
206781
206826
  const config2 = parseCardConfig(resource);
206782
206827
  if (config2.schemaVersion === "3" || config2.schemaVersion === "4") {
206783
206828
  const descriptor = this.toolByName.get(name);
206784
206829
  if (!descriptor)
206785
206830
  throw new Error(`\u672A\u77E5\u5361\u7247\u5DE5\u5177: ${name}`);
206786
- return descriptor.execute(args, signal);
206831
+ return descriptor.execute(args, signal, options?.context);
206787
206832
  }
206788
- return executeCardPresentation(resource, this.registry, this.runtimeContext, args, signal);
206833
+ return executeCardPresentation(resource, this.registry, this.runtimeContext, args, signal, options?.context);
206789
206834
  }
206790
206835
  async close() {
206791
206836
  this.closed = true;
@@ -207453,7 +207498,8 @@ var init_agentRuntime = __esm({
207453
207498
  debugLog?.("[mcp] no mcp servers configured (no MCP tools will be available)", EDebugLogScope.MCP);
207454
207499
  }
207455
207500
  const mcpProxy = new McpProxyTool(this.mcpServerProvider, mcpServerSpecs, {
207456
- debugLog
207501
+ debugLog,
207502
+ ...options.mcpCallAuthorizer ? { authorizeCall: options.mcpCallAuthorizer } : {}
207457
207503
  });
207458
207504
  cleanup.push(() => mcpProxy.closeAll());
207459
207505
  const cardServer = new CardRenderMcpServer(this.cardResources, mcpProxy, { ...options.runtimeContext, threadId: request.threadId }, debugLog);
@@ -207669,6 +207715,8 @@ async function* runConversation(request, auth2, options = {}) {
207669
207715
  runOptions.requestSource = options.requestSource;
207670
207716
  if (options.debugLog)
207671
207717
  runOptions.debugLog = options.debugLog;
207718
+ if (options.mcpCallAuthorizer)
207719
+ runOptions.mcpCallAuthorizer = options.mcpCallAuthorizer;
207672
207720
  runOptions.runtimeContext = {
207673
207721
  ...options.runtimeContext,
207674
207722
  ...request.agentId ? { agentId: request.agentId } : {},
@@ -208379,6 +208427,49 @@ init_cardTools();
208379
208427
  init_mcpNaming();
208380
208428
  init_mcpAggregator();
208381
208429
 
208430
+ // ../linkque-agent-runtime/dist/esm/core/mcpPhoneAuthorization.js
208431
+ init_esm();
208432
+ var McpPhoneAuthorizationRequiredError = class extends Error {
208433
+ required;
208434
+ code = "MCP_PHONE_AUTHORIZATION_REQUIRED";
208435
+ constructor(required2) {
208436
+ super("\u8C03\u7528\u8BE5 MCP Tool \u524D\u9700\u8981\u83B7\u53D6\u624B\u673A\u53F7\u6388\u6743");
208437
+ this.required = required2;
208438
+ this.name = "McpPhoneAuthorizationRequiredError";
208439
+ }
208440
+ };
208441
+ var McpPhoneAuthorizationFailedError = class extends Error {
208442
+ code = "MCP_PHONE_AUTHORIZATION_FAILED";
208443
+ constructor() {
208444
+ super("\u672A\u53D6\u5F97\u624B\u673A\u53F7\u6388\u6743\uFF0C\u65E0\u6CD5\u8C03\u7528\u8BE5 MCP Tool");
208445
+ this.name = "McpPhoneAuthorizationFailedError";
208446
+ }
208447
+ };
208448
+ function createRequestMcpPhoneAuthorizer(protocol, attempt) {
208449
+ return async ({ resourceIds, toolName, signal }) => {
208450
+ if (signal?.aborted)
208451
+ throw Object.assign(new Error("\u64CD\u4F5C\u5DF2\u53D6\u6D88"), { name: "AbortError" });
208452
+ const policy = resolvePhoneAuthorizationDependency(protocol, resourceIds, toolName);
208453
+ if (!policy)
208454
+ return void 0;
208455
+ if (attempt?.kind === "authorized")
208456
+ return { "x-alipay-authcode": attempt.authCode };
208457
+ if (attempt?.kind === "unavailable") {
208458
+ if (policy.required)
208459
+ throw new McpPhoneAuthorizationFailedError();
208460
+ return void 0;
208461
+ }
208462
+ throw new McpPhoneAuthorizationRequiredError(policy.required);
208463
+ };
208464
+ }
208465
+ function isMcpPhoneAuthorizationError(error40) {
208466
+ return error40 instanceof McpPhoneAuthorizationRequiredError || error40 instanceof McpPhoneAuthorizationFailedError;
208467
+ }
208468
+ function resolvePhoneAuthorizationDependency(protocol, resourceIds, toolName) {
208469
+ 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") : []);
208470
+ return dependencies.length ? { required: dependencies.some((dependency) => dependency.required) } : void 0;
208471
+ }
208472
+
208382
208473
  // ../linkque-agent-runtime/dist/esm/core/homeData.js
208383
208474
  init_esm2();
208384
208475
  init_esm();
@@ -208406,7 +208497,9 @@ async function executeHomeData(input) {
208406
208497
  if (spec.allowedTools && !spec.allowedTools.has(request.binding.toolName)) {
208407
208498
  return failure("TOOL_NOT_ALLOWED", "\u5F53\u524D Agent \u672A\u5141\u8BB8\u8C03\u7528\u8BE5 MCP \u5DE5\u5177", false);
208408
208499
  }
208409
- const registry2 = new McpProxyTool(input.mcpServerProvider, specs);
208500
+ const registry2 = new McpProxyTool(input.mcpServerProvider, specs, {
208501
+ authorizeCall: createRequestMcpPhoneAuthorizer(input.protocol, input.phoneAuthorization)
208502
+ });
208410
208503
  try {
208411
208504
  const handle = await registry2.resolve(spec.resourceIds[0], request.binding.toolName, input.signal);
208412
208505
  if (!handle) {
@@ -208434,6 +208527,8 @@ async function executeHomeData(input) {
208434
208527
  try {
208435
208528
  result = await handle.execute(toolInput, input.signal);
208436
208529
  } catch (error40) {
208530
+ if (isMcpPhoneAuthorizationError(error40))
208531
+ throw error40;
208437
208532
  return failure("EXECUTION_FAILED", error40 instanceof Error ? error40.message : "MCP \u5DE5\u5177\u8C03\u7528\u5931\u8D25", true);
208438
208533
  }
208439
208534
  const structured = readStructuredContent2(result);
@@ -208685,7 +208780,7 @@ async function executeCardActionInternal(input, diagnostics) {
208685
208780
  });
208686
208781
  diagnostics.write("binding_resolved", { output: createTrade });
208687
208782
  diagnostics.stage = "tool_resolve";
208688
- const registry2 = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog);
208783
+ const registry2 = createRegistry(input.protocol, input.mcpServerProvider, diagnostics.debugLog, input.phoneAuthorization);
208689
208784
  try {
208690
208785
  diagnostics.write("tool_resolve_started", { input: createTrade });
208691
208786
  const tool = await registry2.resolve(createTrade.mcpResourceId, createTrade.toolName, input.signal);
@@ -208713,6 +208808,8 @@ async function executeCardActionInternal(input, diagnostics) {
208713
208808
  diagnostics.write("tool_completed", { output: result });
208714
208809
  } catch (error40) {
208715
208810
  diagnostics.error("tool_failed", error40);
208811
+ if (isMcpPhoneAuthorizationError(error40))
208812
+ throw error40;
208716
208813
  return failure2("EXECUTION_FAILED", "\u521B\u5EFA\u4EA4\u6613\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5", true);
208717
208814
  }
208718
208815
  diagnostics.stage = "tool_output";
@@ -208852,9 +208949,12 @@ function materializeValue(definition, supplied) {
208852
208949
  }
208853
208950
  return definition;
208854
208951
  }
208855
- function createRegistry(protocol, provider, debugLog) {
208952
+ function createRegistry(protocol, provider, debugLog, phoneAuthorization) {
208856
208953
  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 });
208954
+ return new McpProxyTool(provider, aggregateMcpServers(resources, protocol.agentId), {
208955
+ debugLog,
208956
+ authorizeCall: createRequestMcpPhoneAuthorizer(protocol, phoneAuthorization)
208957
+ });
208858
208958
  }
208859
208959
  function readStructuredContent3(result) {
208860
208960
  const object3 = cloneJsonObject(result);
@@ -208894,7 +208994,9 @@ async function executeAuthorizedMcp(input) {
208894
208994
  if (!input.userId.trim())
208895
208995
  return failure3("AUTH_REQUIRED", "\u7F3A\u5C11\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD", false);
208896
208996
  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));
208997
+ const registry2 = new McpProxyTool(input.mcpServerProvider, aggregateMcpServers(resources, input.protocol.agentId), {
208998
+ authorizeCall: createRequestMcpPhoneAuthorizer(input.protocol, input.phoneAuthorization)
208999
+ });
208898
209000
  try {
208899
209001
  const tool = await registry2.resolve(input.tool.mcpResourceId, input.tool.toolName, input.signal);
208900
209002
  if (!tool)
@@ -208906,7 +209008,9 @@ async function executeAuthorizedMcp(input) {
208906
209008
  let result;
208907
209009
  try {
208908
209010
  result = await tool.execute(input.tool.input, input.signal);
208909
- } catch {
209011
+ } catch (error40) {
209012
+ if (isMcpPhoneAuthorizationError(error40))
209013
+ throw error40;
208910
209014
  return failure3("EXECUTION_UNCERTAIN", "MCP \u6267\u884C\u7ED3\u679C\u4E0D\u786E\u5B9A\uFF0C\u8BF7\u52FF\u81EA\u52A8\u91CD\u8BD5", false);
208911
209015
  }
208912
209016
  const structured = readStructuredContent4(result);
@@ -208970,7 +209074,8 @@ async function executeFunctionActionMcp(input) {
208970
209074
  callId: request.callId,
208971
209075
  tool: request.tool,
208972
209076
  mcpServerProvider: input.mcpServerProvider,
208973
- signal: input.signal
209077
+ signal: input.signal,
209078
+ phoneAuthorization: input.phoneAuthorization
208974
209079
  });
208975
209080
  }
208976
209081
  function failure4(code, message, retryable) {
@@ -212389,6 +212494,53 @@ function sleep(ms) {
212389
212494
  });
212390
212495
  }
212391
212496
 
212497
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationContext.js
212498
+ var import_node_async_hooks = require("node:async_hooks");
212499
+ async function waitForMcpOperation(operation, signal) {
212500
+ signal.throwIfAborted();
212501
+ let onAbort = () => {
212502
+ };
212503
+ try {
212504
+ return await Promise.race([
212505
+ new Promise((_, reject) => {
212506
+ onAbort = () => reject(signal.reason);
212507
+ signal.addEventListener("abort", onAbort, { once: true });
212508
+ }),
212509
+ Promise.resolve().then(() => {
212510
+ signal.throwIfAborted();
212511
+ return operation();
212512
+ })
212513
+ ]);
212514
+ } finally {
212515
+ signal.removeEventListener("abort", onAbort);
212516
+ }
212517
+ }
212518
+ var McpInvocationContext = class {
212519
+ storage = new import_node_async_hooks.AsyncLocalStorage();
212520
+ current() {
212521
+ return this.storage.getStore();
212522
+ }
212523
+ async run(timeoutMs, signal, operation) {
212524
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
212525
+ throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
212526
+ signal?.throwIfAborted();
212527
+ const controller = new AbortController();
212528
+ const context2 = {
212529
+ signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
212530
+ deadline: performance.now() + timeoutMs
212531
+ };
212532
+ const timer = setTimeout(() => controller.abort(new DOMException("MCP \u8C03\u7528\u603B\u9884\u7B97\u5DF2\u8017\u5C3D", "TimeoutError")), Math.min(timeoutMs, 2147483647));
212533
+ try {
212534
+ return await this.storage.run(context2, () => waitForMcpOperation(() => operation(context2), context2.signal));
212535
+ } catch (error40) {
212536
+ context2.signal.throwIfAborted();
212537
+ throw error40;
212538
+ } finally {
212539
+ clearTimeout(timer);
212540
+ }
212541
+ }
212542
+ };
212543
+
212392
212544
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteSignatureSigner.js
212393
212545
  init_config();
212394
212546
  init_httpLoggingFetch();
@@ -212397,11 +212549,13 @@ var RemoteSignatureSigner = class {
212397
212549
  agentId;
212398
212550
  signEndpoint;
212399
212551
  fetchImpl;
212552
+ rawFetch;
212400
212553
  getAuthorizationHeader;
212401
212554
  constructor(options) {
212402
212555
  this.agentId = options.agentId;
212403
212556
  this.signEndpoint = options.signEndpoint ?? DEFAULT_SIGN_ENDPOINT;
212404
212557
  const baseFetch = options.fetchImpl ?? globalThis.fetch;
212558
+ this.rawFetch = baseFetch;
212405
212559
  this.fetchImpl = options.debugLog ? createHttpLoggingFetch(options.debugLog, "mcp-sign", baseFetch) : baseFetch;
212406
212560
  this.getAuthorizationHeader = options.getAuthorizationHeader;
212407
212561
  }
@@ -212412,7 +212566,8 @@ var RemoteSignatureSigner = class {
212412
212566
  * @returns `{authorization, signatureContent, userId?}`
212413
212567
  * @throws 签名服务非 2xx / 鉴权头获取失败 / 响应缺字段时抛错(由 signingFetch 转 transport-error)。
212414
212568
  */
212415
- async sign(req) {
212569
+ async sign(req, options = {}) {
212570
+ options.signal?.throwIfAborted();
212416
212571
  const body = JSON.stringify({
212417
212572
  agentId: this.agentId,
212418
212573
  httpMethod: req.httpMethod,
@@ -212423,16 +212578,16 @@ var RemoteSignatureSigner = class {
212423
212578
  "content-type": "application/json",
212424
212579
  "x-linkque-agent-id": this.agentId
212425
212580
  };
212426
- if (this.getAuthorizationHeader) {
212427
- headers.authorization = await this.getAuthorizationHeader();
212581
+ if (options.authorizationHeader !== void 0) {
212582
+ headers.authorization = options.authorizationHeader;
212583
+ } else if (this.getAuthorizationHeader) {
212584
+ headers.authorization = options.signal ? await waitForMcpOperation(() => this.getAuthorizationHeader(), options.signal) : await this.getAuthorizationHeader();
212428
212585
  }
212429
- const resp = await this.fetchImpl(this.signEndpoint, {
212430
- method: "POST",
212431
- headers,
212432
- body
212433
- });
212586
+ options.signal?.throwIfAborted();
212587
+ const resp = await (options.sensitive ? this.rawFetch : this.fetchImpl)(this.signEndpoint, { method: "POST", headers, body, signal: options.signal });
212588
+ options.signal?.throwIfAborted();
212434
212589
  if (!resp.ok) {
212435
- const text2 = await safeText(resp);
212590
+ const text2 = options.sensitive ? "" : await safeText(resp);
212436
212591
  throw new Error(`linkquegw \u7B7E\u540D\u670D\u52A1\u5931\u8D25: status=${resp.status}${text2 ? ` body=${text2}` : ""}`);
212437
212592
  }
212438
212593
  const parsed = await resp.json().catch(() => ({}));
@@ -212473,7 +212628,7 @@ function extractFromWrapped(wrapped) {
212473
212628
  };
212474
212629
  }
212475
212630
  function optionalUserId(value) {
212476
- return typeof value === "string" && value.trim() ? { userId: value.trim() } : {};
212631
+ return typeof value === "string" && value.trim() ? { userId: value } : {};
212477
212632
  }
212478
212633
  async function safeText(resp) {
212479
212634
  try {
@@ -214018,20 +214173,42 @@ var SSEClientTransport = class {
214018
214173
  }
214019
214174
  };
214020
214175
 
214176
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/mcpInvocationError.js
214177
+ var McpInvocationError = class extends Error {
214178
+ code;
214179
+ constructor(code, message) {
214180
+ super(`${code}: ${message}`);
214181
+ this.code = code;
214182
+ this.name = "McpInvocationError";
214183
+ }
214184
+ };
214185
+
214021
214186
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/signingFetch.js
214022
214187
  init_httpLoggingFetch();
214023
214188
  var ALIPAY_SDK_VERSION = "@alipay/open-mcp-server-2.0.4";
214024
214189
  var OAGW_ALIPAY_UID_HEADER = "x-oagw-alipay-uid";
214025
- function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, debugLog) {
214190
+ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, debugLog, getCallHeaders, invocationContext) {
214026
214191
  const loggedFetch = debugLog ? createHttpLoggingFetch(debugLog, "mcp-call", baseFetch) : baseFetch;
214027
214192
  return async (url2, init) => {
214193
+ const invocation = invocationContext?.current();
214194
+ const signals = [init?.signal, invocation?.signal].filter((signal2) => !!signal2);
214195
+ const signal = signals.length ? AbortSignal.any(signals) : void 0;
214196
+ signal?.throwIfAborted();
214028
214197
  const targetUrl = url2 instanceof URL ? url2 : new URL(typeof url2 === "string" ? url2 : url2.url);
214029
214198
  const req = {
214030
214199
  httpMethod: init?.method ?? "GET",
214031
214200
  httpRequestUrl: targetUrl.pathname + targetUrl.search,
214032
214201
  httpRequestBody: typeof init?.body === "string" ? init.body : ""
214033
214202
  };
214034
- const { authorization, signatureContent, userId } = await signer.sign(req);
214203
+ const { authorization, signatureContent, userId } = await signer.sign(req, {
214204
+ authorizationHeader: invocation?.auth?.authorization,
214205
+ signal,
214206
+ sensitive: !!invocation?.auth
214207
+ });
214208
+ signal?.throwIfAborted();
214209
+ if (invocation?.auth && userId !== invocation.auth.userId) {
214210
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u7B7E\u540D\u8EAB\u4EFD\u4E0E\u6821\u9A8C\u8EAB\u4EFD\u4E0D\u4E00\u81F4");
214211
+ }
214035
214212
  const headers = new Headers(init?.headers);
214036
214213
  headers.set("Authorization", authorization);
214037
214214
  headers.set("X-Signature-Content", Buffer.from(signatureContent).toString("base64"));
@@ -214041,7 +214218,18 @@ function createSigningFetch(signer, baseFetch = globalThis.fetch, onTraceId, deb
214041
214218
  } else {
214042
214219
  headers.delete(OAGW_ALIPAY_UID_HEADER);
214043
214220
  }
214044
- const resp = await loggedFetch(url2, { ...init, headers });
214221
+ if ((init?.method ?? "GET").toUpperCase() === "POST") {
214222
+ const authCode = getCallHeaders?.()?.["x-alipay-authcode"];
214223
+ if (authCode)
214224
+ headers.set("x-alipay-authcode", authCode);
214225
+ else
214226
+ headers.delete("x-alipay-authcode");
214227
+ }
214228
+ const resp = await (invocation?.auth ? baseFetch : loggedFetch)(url2, {
214229
+ ...init,
214230
+ headers,
214231
+ ...signal ? { signal } : {}
214232
+ });
214045
214233
  if (onTraceId) {
214046
214234
  try {
214047
214235
  const traceId = resp.headers.get("alipay-trace-id");
@@ -214069,10 +214257,10 @@ function withTimeout(fetch3, timeoutMs) {
214069
214257
  return fetch3(url2, { ...init, signal });
214070
214258
  };
214071
214259
  }
214072
- function createSseTransport(config2, signer, onTraceId, debugLog) {
214260
+ function createSseTransport(config2, signer, onTraceId, debugLog, getCallHeaders, invocationContext) {
214073
214261
  const url2 = new URL(config2.sseEndpoint, config2.remoteBaseUrl);
214074
214262
  const timeoutMs = config2.requestTimeoutMs ?? 18e4;
214075
- const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog), timeoutMs);
214263
+ const signingFetch = withTimeout(createSigningFetch(signer, void 0, onTraceId, debugLog, getCallHeaders, invocationContext), timeoutMs);
214076
214264
  return new SSEClientTransport(url2, {
214077
214265
  // SSE 建连(EventSource)的 GET fetch:SDK 先包默认头再调这里。
214078
214266
  eventSourceInit: { fetch: signingFetch },
@@ -214083,6 +214271,17 @@ function createSseTransport(config2, signer, onTraceId, debugLog) {
214083
214271
 
214084
214272
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/argsMapper.js
214085
214273
  init_esm();
214274
+ var USER_ID = Symbol("\u7CFB\u7EDF\u53D8\u91CF\u7528\u6237\u6807\u8BC6");
214275
+ function assertSafePath(segments) {
214276
+ if (segments.some((s2) => ["__proto__", "constructor", "prototype"].includes(String(s2)))) {
214277
+ throw new McpInvocationError("MCP_SYSTEM_VARIABLE_INVALID", "\u6620\u5C04\u8DEF\u5F84\u7981\u6B62\u8BBF\u95EE\u539F\u578B");
214278
+ }
214279
+ }
214280
+ function assertContainer(value) {
214281
+ if (value === null || typeof value !== "object") {
214282
+ throw new McpInvocationError("MCP_SYSTEM_VARIABLE_INVALID", "\u6620\u5C04\u8DEF\u5F84\u4E0D\u53EF\u5199");
214283
+ }
214284
+ }
214086
214285
  function parsePath(path9) {
214087
214286
  if (path9 === "")
214088
214287
  return [];
@@ -214107,50 +214306,60 @@ function parsePath(path9) {
214107
214306
  return segments;
214108
214307
  }
214109
214308
  function getByPath(obj, segments) {
214309
+ assertSafePath(segments);
214110
214310
  let cur = obj;
214111
214311
  for (const seg of segments) {
214112
214312
  if (cur === null || cur === void 0)
214113
214313
  return void 0;
214114
- cur = cur[seg];
214314
+ cur = Object.hasOwn(Object(cur), seg) ? cur[seg] : void 0;
214115
214315
  }
214116
214316
  return cur;
214117
214317
  }
214118
214318
  function setByPath(obj, segments, value) {
214319
+ assertSafePath(segments);
214119
214320
  if (segments.length === 0)
214120
214321
  return;
214121
214322
  let cur = obj;
214122
214323
  for (let i2 = 0; i2 < segments.length - 1; i2 += 1) {
214123
214324
  const seg = segments[i2];
214124
214325
  const next = segments[i2 + 1];
214125
- const existing = cur[seg];
214326
+ assertContainer(cur);
214327
+ const existing = Object.hasOwn(cur, seg) ? cur[seg] : void 0;
214126
214328
  if (existing === null || existing === void 0) {
214127
214329
  cur[seg] = typeof next === "number" ? [] : {};
214128
214330
  }
214129
214331
  cur = cur[seg];
214130
214332
  }
214131
214333
  const last = segments[segments.length - 1];
214132
- cur[last] = value;
214334
+ assertContainer(cur);
214335
+ Object.defineProperty(cur, last, {
214336
+ value,
214337
+ enumerable: true,
214338
+ writable: true,
214339
+ configurable: true
214340
+ });
214133
214341
  }
214134
214342
  function unsetByPath(obj, segments) {
214343
+ assertSafePath(segments);
214135
214344
  if (segments.length === 0)
214136
214345
  return;
214137
214346
  let cur = obj;
214138
214347
  for (let i2 = 0; i2 < segments.length - 1; i2 += 1) {
214139
214348
  const seg = segments[i2];
214140
- cur = cur[seg];
214349
+ assertContainer(cur);
214350
+ cur = Object.hasOwn(cur, seg) ? cur[seg] : void 0;
214141
214351
  if (cur === null || cur === void 0)
214142
214352
  return;
214143
214353
  }
214144
214354
  const last = segments[segments.length - 1];
214145
214355
  if (cur !== void 0) {
214356
+ assertContainer(cur);
214146
214357
  delete cur[last];
214147
214358
  }
214148
214359
  }
214149
- function applyArgsMappingRules(toolName, args, rules) {
214360
+ function createArgsMappingPlan(toolName, args, rules) {
214150
214361
  const out = args ? JSON.parse(JSON.stringify(args)) : {};
214151
- if (!rules || rules.length === 0)
214152
- return out;
214153
- for (const rule of rules) {
214362
+ for (const rule of rules ?? []) {
214154
214363
  if (rule.mcpToolName !== toolName)
214155
214364
  continue;
214156
214365
  const segments = parsePath(rule.argJsonPath);
@@ -214158,6 +214367,13 @@ function applyArgsMappingRules(toolName, args, rules) {
214158
214367
  unsetByPath(out, segments);
214159
214368
  continue;
214160
214369
  }
214370
+ if (rule.valueType === EArgsMappingValueType.SYSTEM_VARIABLE) {
214371
+ if (rule.value !== "${userId}" || segments.length === 0) {
214372
+ throw new McpInvocationError("MCP_SYSTEM_VARIABLE_INVALID", "\u7CFB\u7EDF\u53D8\u91CF\u914D\u7F6E\u65E0\u6548");
214373
+ }
214374
+ setByPath(out, segments, USER_ID);
214375
+ continue;
214376
+ }
214161
214377
  if (rule.valueType === EArgsMappingValueType.CONST) {
214162
214378
  setByPath(out, segments, rule.value);
214163
214379
  continue;
@@ -214169,12 +214385,82 @@ function applyArgsMappingRules(toolName, args, rules) {
214169
214385
  continue;
214170
214386
  }
214171
214387
  }
214172
- return out;
214388
+ const contains = (value) => value === USER_ID || value !== null && typeof value === "object" && Object.values(value).some(contains);
214389
+ const requiresUserId = contains(out);
214390
+ return {
214391
+ requiresUserId,
214392
+ resolve(identity) {
214393
+ if (requiresUserId && !identity?.userId?.trim()) {
214394
+ throw new McpInvocationError("MCP_USER_AUTH_REQUIRED", "\u7CFB\u7EDF\u53D8\u91CF\u9700\u8981\u53EF\u4FE1\u7528\u6237\u8EAB\u4EFD");
214395
+ }
214396
+ const visit = (value) => {
214397
+ if (value === USER_ID)
214398
+ return identity.userId;
214399
+ if (Array.isArray(value))
214400
+ return value.map(visit);
214401
+ if (value !== null && typeof value === "object") {
214402
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item)]));
214403
+ }
214404
+ return value;
214405
+ };
214406
+ return visit(out);
214407
+ }
214408
+ };
214409
+ }
214410
+ function resolveArgsMappingPlan(plan, identity) {
214411
+ return plan.resolve(identity);
214173
214412
  }
214174
214413
 
214175
214414
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/index.js
214176
214415
  init_esm();
214177
214416
 
214417
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteGatewayMcpServer.js
214418
+ var import_node_async_hooks2 = require("node:async_hooks");
214419
+
214420
+ // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/linkquegwTokenVerifier.js
214421
+ init_config();
214422
+ function assertMcpUserAuthorization(authorization) {
214423
+ if (!/^Bearer\s+\S+$/i.test(authorization.trim())) {
214424
+ throw new McpInvocationError("MCP_USER_AUTH_REQUIRED", "\u7CFB\u7EDF\u53D8\u91CF\u9700\u8981\u7528\u6237 Bearer \u51ED\u636E");
214425
+ }
214426
+ }
214427
+ var LinkquegwTokenVerifier = class {
214428
+ options;
214429
+ constructor(options = {}) {
214430
+ this.options = options;
214431
+ }
214432
+ async verify(input) {
214433
+ input.signal?.throwIfAborted();
214434
+ assertMcpUserAuthorization(input.authorization);
214435
+ try {
214436
+ const response = await (this.options.fetchImpl ?? globalThis.fetch)(this.options.endpoint ?? RUNTIME_CONFIG_DEFAULTS.LINKQUEGW_TOKEN_VERIFY_ENDPOINT, {
214437
+ method: "POST",
214438
+ headers: {
214439
+ authorization: input.authorization,
214440
+ "content-type": "application/json"
214441
+ },
214442
+ body: JSON.stringify({ agentId: input.agentId }),
214443
+ signal: input.signal
214444
+ });
214445
+ if (!response.ok)
214446
+ throw new Error("\u6821\u9A8C\u8BF7\u6C42\u5931\u8D25");
214447
+ const result = await response.json();
214448
+ input.signal?.throwIfAborted();
214449
+ if (result?.success !== true || typeof result.data?.userId !== "string" || !result.data.userId.trim() || typeof result.data.agentId !== "string" || !result.data.agentId.trim()) {
214450
+ throw new Error("\u8EAB\u4EFD\u54CD\u5E94\u65E0\u6548");
214451
+ }
214452
+ if (result.data.agentId !== input.agentId)
214453
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u7528\u6237\u51ED\u636E\u4E0D\u5C5E\u4E8E\u76EE\u6807 Agent");
214454
+ return { userId: result.data.userId, agentId: result.data.agentId };
214455
+ } catch (error40) {
214456
+ input.signal?.throwIfAborted();
214457
+ if (error40 instanceof McpInvocationError)
214458
+ throw error40;
214459
+ throw new McpInvocationError("MCP_TOKEN_VERIFY_FAILED", "\u7528\u6237\u51ED\u636E\u6821\u9A8C\u5931\u8D25");
214460
+ }
214461
+ }
214462
+ };
214463
+
214178
214464
  // ../linkque-agent-runtime/dist/esm/impl/mcp/alipay/remoteGatewayMcpServer.js
214179
214465
  init_types();
214180
214466
  init_logFailure();
@@ -214187,6 +214473,8 @@ var defaultCreateSigner = (config2, getAuthorizationHeader, debugLog) => new Rem
214187
214473
  });
214188
214474
  var defaultCreateClient = () => new Client({ name: "linkque-agent-runtime-mcp-client", version: "1.0.0" });
214189
214475
  var RemoteGatewayMcpServerProvider = class {
214476
+ invocationContext = new McpInvocationContext();
214477
+ createTokenVerifier;
214190
214478
  resolveConfig;
214191
214479
  getAuthorizationHeader;
214192
214480
  createSigner;
@@ -214195,6 +214483,7 @@ var RemoteGatewayMcpServerProvider = class {
214195
214483
  debugLog;
214196
214484
  constructor(options) {
214197
214485
  this.resolveConfig = options.resolveConfig;
214486
+ this.createTokenVerifier = options.createTokenVerifier ?? ((config2) => new LinkquegwTokenVerifier({ endpoint: config2.verifyTokenEndpoint }));
214198
214487
  this.getAuthorizationHeader = options.getAuthorizationHeader;
214199
214488
  this.createSigner = options.createSigner ?? ((config2, getAuthorizationHeader) => defaultCreateSigner(config2, getAuthorizationHeader, this.debugLog));
214200
214489
  this.createClient = options.createClient ?? defaultCreateClient;
@@ -214207,8 +214496,13 @@ var RemoteGatewayMcpServerProvider = class {
214207
214496
  /** 连单个远端 server 并包装成 IMcpServer。建连失败有限重试 + 失败清理由 helper 负责。 */
214208
214497
  async connectOne(resource) {
214209
214498
  const config2 = await this.resolveConfig(resource);
214499
+ const timeoutMs = config2.requestTimeoutMs ?? 18e4;
214500
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
214501
+ throw new Error("MCP \u8D85\u65F6\u5FC5\u987B\u4E3A\u6709\u9650\u6B63\u6570");
214502
+ const verifier = this.createTokenVerifier(config2);
214503
+ const callHeaders = new import_node_async_hooks2.AsyncLocalStorage();
214210
214504
  const { client } = await connectMcpClientWithRetry(config2, {
214211
- createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog),
214505
+ createTransport: () => createSseTransport(config2, this.createSigner(config2, this.getAuthorizationHeader), this.onTraceId, this.debugLog, () => callHeaders.getStore(), this.invocationContext),
214212
214506
  createClient: () => this.createClient()
214213
214507
  });
214214
214508
  const serverName = resource.config.serverName ?? resource.resourceId;
@@ -214220,7 +214514,7 @@ var RemoteGatewayMcpServerProvider = class {
214220
214514
  if (!this.debugLog)
214221
214515
  return;
214222
214516
  try {
214223
- this.debugLog(`[mcp-client] ${JSON.stringify({ serverName, resourceId: resource.resourceId, requestId, method, phase, payload })}`, EDebugLogScope.MCP);
214517
+ this.debugLog(`[mcp-client] ${JSON.stringify({ serverName, resourceId: resource.resourceId, requestId, method, phase, payload: this.invocationContext.current()?.auth ? { redacted: true } : payload })}`, EDebugLogScope.MCP);
214224
214518
  } catch (error40) {
214225
214519
  warnLogFailure("remoteGatewayMcpServer.log", error40);
214226
214520
  }
@@ -214237,19 +214531,52 @@ var RemoteGatewayMcpServerProvider = class {
214237
214531
  };
214238
214532
  const loggedClient = {
214239
214533
  listTools: () => request("tools/list", {}, () => client.listTools()),
214240
- callTool: (params) => request("tools/call", params, () => client.callTool(params))
214241
- };
214534
+ callTool: (params, resultSchema, requestOptions) => request("tools/call", params, () => client.callTool(params, resultSchema, requestOptions))
214535
+ };
214536
+ const callTool = (name, args, signal, options) => callHeaders.run(options?.headers ?? {}, () => this.invocationContext.run(timeoutMs, signal, async (invocation) => {
214537
+ const plan = createArgsMappingPlan(name, args, argsMappingRules);
214538
+ if (plan.requiresUserId) {
214539
+ if (config2.signEndpoint !== void 0 && config2.signEndpoint !== DEFAULT_SIGN_ENDPOINT && !config2.verifyTokenEndpoint?.trim())
214540
+ throw new McpInvocationError("MCP_CONFIG_INVALID", "\u81EA\u5B9A\u4E49\u7B7E\u540D\u7AEF\u70B9\u5FC5\u987B\u540C\u65F6\u914D\u7F6E\u7528\u6237\u51ED\u636E\u6821\u9A8C\u7AEF\u70B9");
214541
+ if (!this.getAuthorizationHeader)
214542
+ throw new McpInvocationError("MCP_USER_AUTH_REQUIRED", "\u7CFB\u7EDF\u53D8\u91CF\u9700\u8981\u7528\u6237\u51ED\u636E");
214543
+ const authorization = await waitForMcpOperation(() => this.getAuthorizationHeader(), invocation.signal);
214544
+ assertMcpUserAuthorization(authorization);
214545
+ const identity = await waitForMcpOperation(() => verifier.verify({
214546
+ authorization,
214547
+ agentId: config2.agentId,
214548
+ signal: invocation.signal
214549
+ }), invocation.signal);
214550
+ if (!identity.userId?.trim() || identity.agentId !== config2.agentId)
214551
+ throw new McpInvocationError("MCP_IDENTITY_MISMATCH", "\u6821\u9A8C\u8EAB\u4EFD\u65E0\u6548");
214552
+ invocation.auth = {
214553
+ authorization,
214554
+ userId: identity.userId,
214555
+ agentId: identity.agentId
214556
+ };
214557
+ }
214558
+ const mapped = resolveArgsMappingPlan(plan, invocation.auth);
214559
+ invocation.signal.throwIfAborted();
214560
+ const remaining = Math.max(1, invocation.deadline - performance.now());
214561
+ try {
214562
+ return await loggedClient.callTool({ name, arguments: mapped }, void 0, {
214563
+ signal: invocation.signal,
214564
+ timeout: remaining,
214565
+ maxTotalTimeout: remaining,
214566
+ resetTimeoutOnProgress: false
214567
+ });
214568
+ } catch (error40) {
214569
+ invocation.signal.throwIfAborted();
214570
+ if (invocation.auth && !(error40 instanceof McpInvocationError))
214571
+ throw new Error("MCP \u7528\u6237\u5DE5\u5177\u8C03\u7528\u5931\u8D25");
214572
+ throw error40;
214573
+ }
214574
+ }));
214242
214575
  return {
214243
214576
  resourceId: resource.resourceId,
214244
214577
  serverName,
214245
- listTools: () => listToolsFromClient(loggedClient, resource.resourceId),
214246
- callTool: (name, args) => {
214247
- const mapped = applyArgsMappingRules(name, args, argsMappingRules);
214248
- return loggedClient.callTool({
214249
- name,
214250
- arguments: mapped ?? {}
214251
- });
214252
- },
214578
+ listTools: () => listToolsFromClient(loggedClient, resource.resourceId, callTool),
214579
+ callTool,
214253
214580
  close: async () => {
214254
214581
  try {
214255
214582
  await client.close();
@@ -214259,14 +214586,14 @@ var RemoteGatewayMcpServerProvider = class {
214259
214586
  };
214260
214587
  }
214261
214588
  };
214262
- async function listToolsFromClient(client, resourceId) {
214589
+ async function listToolsFromClient(client, resourceId, callTool) {
214263
214590
  const result = await client.listTools();
214264
214591
  const tools = result.tools ?? [];
214265
214592
  return tools.map((tool) => {
214266
214593
  const descriptor = {
214267
214594
  name: tool.name,
214268
214595
  resourceId,
214269
- execute: (args) => client.callTool({ name: tool.name, arguments: args })
214596
+ execute: (args, signal) => callTool(tool.name, args, signal)
214270
214597
  };
214271
214598
  if (tool.description !== void 0)
214272
214599
  descriptor.description = tool.description;
@@ -215502,7 +215829,7 @@ init_noopRuntimeTelemetry();
215502
215829
  // ../linkque-agent-runtime/dist/esm/impl/telemetry/identityQueue.js
215503
215830
  init_telemetry();
215504
215831
  init_telemetryEnums2();
215505
- var import_node_async_hooks = require("node:async_hooks");
215832
+ var import_node_async_hooks3 = require("node:async_hooks");
215506
215833
  init_esm6();
215507
215834
  var import_core11 = __toESM(require_src(), 1);
215508
215835
  function authorizationKey(auth2) {
@@ -215516,7 +215843,7 @@ function authorizationKey(auth2) {
215516
215843
  }
215517
215844
  var IdentityQueue = class {
215518
215845
  options;
215519
- exportContext = new import_node_async_hooks.AsyncLocalStorage();
215846
+ exportContext = new import_node_async_hooks3.AsyncLocalStorage();
215520
215847
  get isExporting() {
215521
215848
  return this.exportContext.getStore() === true;
215522
215849
  }
@@ -216360,21 +216687,22 @@ function createSandboxMcpHandler() {
216360
216687
  if (payload.agentId !== void 0 && payload.agentId !== protocol.agentId) {
216361
216688
  return failure5(403, "AGENT_MISMATCH", "Agent \u4E0D\u5339\u914D");
216362
216689
  }
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
216690
  try {
216691
+ if (value.operation === "homeData.request") {
216692
+ const result2 = await executeHomeData({
216693
+ request: { ...payload, agentId: protocol.agentId },
216694
+ protocol,
216695
+ userId,
216696
+ mcpServerProvider: provider,
216697
+ phoneAuthorization: { kind: "unavailable" }
216698
+ });
216699
+ return { status: result2.ok ? 200 : 400, body: result2 };
216700
+ }
216701
+ 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(
216702
+ (key) => !["mcpResourceId", "toolName", "input"].includes(key)
216703
+ )) {
216704
+ return failure5(400, "INVALID_INPUT", "MCP \u8C03\u7528\u53C2\u6570\u65E0\u6548");
216705
+ }
216378
216706
  const result = await executeAuthorizedMcp({
216379
216707
  protocol,
216380
216708
  agentId: protocol.agentId,
@@ -216385,13 +216713,17 @@ function createSandboxMcpHandler() {
216385
216713
  toolName: payload.tool.toolName,
216386
216714
  input: payload.tool.input
216387
216715
  },
216388
- mcpServerProvider: provider
216716
+ mcpServerProvider: provider,
216717
+ phoneAuthorization: { kind: "unavailable" }
216389
216718
  });
216390
216719
  return {
216391
216720
  status: result.ok ? 200 : result.error.code === "EXECUTION_UNCERTAIN" ? 409 : 400,
216392
216721
  body: result
216393
216722
  };
216394
- } catch {
216723
+ } catch (error40) {
216724
+ if (error40 instanceof McpPhoneAuthorizationFailedError) {
216725
+ return failure5(403, error40.code, "\u6C99\u7BB1\u4E0D\u652F\u6301\u624B\u673A\u53F7\u6388\u6743\uFF0C\u8BF7\u4F7F\u7528\u771F\u673A\u9884\u89C8");
216726
+ }
216395
216727
  return failure5(
216396
216728
  409,
216397
216729
  "EXECUTION_UNCERTAIN",
@@ -216821,6 +217153,7 @@ var handleSandboxChat = async (req, res, deps, activeRuns2, cancelActiveRun2) =>
216821
217153
  cwd: deps.cwd,
216822
217154
  signal: abort.signal,
216823
217155
  telemetryContext: deps.createTelemetryContext(request.runId),
217156
+ mcpCallAuthorizer: deps.createMcpCallAuthorizer(protocol),
216824
217157
  debugLog: deps.debugLog,
216825
217158
  ...inboundUserId && { runtimeContext: { userId: inboundUserId } }
216826
217159
  });
@@ -216887,6 +217220,7 @@ function createMcpConfigResolver(options) {
216887
217220
  sseEndpoint: `api/v1/open/mcps/${resolveServerName(resource.config)}/sse`,
216888
217221
  agentId: options.agentId,
216889
217222
  ...options.signEndpoint ? { signEndpoint: options.signEndpoint } : {},
217223
+ ...options.verifyTokenEndpoint ? { verifyTokenEndpoint: options.verifyTokenEndpoint } : {},
216890
217224
  ...options.requestTimeoutMs ? { requestTimeoutMs: options.requestTimeoutMs } : {}
216891
217225
  });
216892
217226
  }
@@ -216982,6 +217316,7 @@ var AGENT_ENV_SNAPSHOT = [
216982
217316
  ["LINKQUE_BASE_URL", false],
216983
217317
  ["LINKQUE_OPEN_MCP_BASE_URL", false],
216984
217318
  ["LINKQUE_MCP_SIGN_ENDPOINT", false],
217319
+ ["LINKQUEGW_TOKEN_VERIFY_ENDPOINT", false],
216985
217320
  ["LINKQUE_AGENT_MCP_FIXTURE_URL", false]
216986
217321
  ];
216987
217322
  var formatEnvSnapshot = (env2) => {
@@ -217032,6 +217367,9 @@ var handleRun = async (req, res, input, debugLog) => {
217032
217367
  agentId: input.agentId,
217033
217368
  bodyMaxBytes: 1024 * 1024,
217034
217369
  createRuntime,
217370
+ createMcpCallAuthorizer: (protocol) => createRequestMcpPhoneAuthorizer(protocol, {
217371
+ kind: "unavailable"
217372
+ }),
217035
217373
  debugLog,
217036
217374
  createTelemetryContext: agentDevTelemetry.createContext
217037
217375
  },
@@ -217070,7 +217408,8 @@ var handleHomeData = async (req, res, input) => {
217070
217408
  request: homeDataInput.request,
217071
217409
  protocol,
217072
217410
  userId: homeDataInput.userId,
217073
- mcpServerProvider: createMcpServerProvider(protocol)
217411
+ mcpServerProvider: createMcpServerProvider(protocol),
217412
+ phoneAuthorization: { kind: "unavailable" }
217074
217413
  });
217075
217414
  res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
217076
217415
  res.end(JSON.stringify(result));
@@ -217108,6 +217447,7 @@ var handleA2UIAction = async (req, res, input, debugLog) => {
217108
217447
  ...proxyInput.tenantId ? { tenantId: proxyInput.tenantId } : {}
217109
217448
  },
217110
217449
  mcpServerProvider: createMcpServerProvider(protocol),
217450
+ phoneAuthorization: { kind: "unavailable" },
217111
217451
  debugLog
217112
217452
  });
217113
217453
  res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
@@ -217139,7 +217479,8 @@ var handleFunctionActionMcp = async (req, res, input) => {
217139
217479
  request: proxyInput.request,
217140
217480
  protocol,
217141
217481
  runtimeContext: { threadId: request.threadId, userId: proxyInput.userId },
217142
- mcpServerProvider: createMcpServerProvider(protocol)
217482
+ mcpServerProvider: createMcpServerProvider(protocol),
217483
+ phoneAuthorization: { kind: "unavailable" }
217143
217484
  });
217144
217485
  writeJson(
217145
217486
  res,
@@ -217285,7 +217626,9 @@ var main = async () => {
217285
217626
  const resolveConfig = createMcpConfigResolver({
217286
217627
  agentId: protocol.agentId,
217287
217628
  remoteBaseUrl: config2.get("LINKQUE_OPEN_MCP_BASE_URL"),
217288
- signEndpoint: config2.get("LINKQUE_MCP_SIGN_ENDPOINT")
217629
+ signEndpoint: config2.get("LINKQUE_MCP_SIGN_ENDPOINT"),
217630
+ // 保留未显式配置的状态,由运行时检查自定义环境配置是否完整。
217631
+ verifyTokenEndpoint: config2.getRaw("LINKQUEGW_TOKEN_VERIFY_ENDPOINT")?.trim() || void 0
217289
217632
  });
217290
217633
  return new RemoteGatewayMcpServerProvider({
217291
217634
  resolveConfig,