index.ts 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  1. import {
  2. Client,
  3. ClientCredentialsProvider,
  4. computeScopeUnion,
  5. ProtocolError,
  6. SdkError,
  7. SdkErrorCode,
  8. SSEClientTransport,
  9. StreamableHTTPClientTransport,
  10. UnsupportedProtocolVersionError,
  11. type AuthProvider,
  12. type OAuthClientProvider,
  13. type VersionNegotiationMode,
  14. type VersionNegotiationOptions,
  15. } from "@modelcontextprotocol/client";
  16. import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
  17. import type {
  18. Logger,
  19. McpCallToolOptions,
  20. McpCallToolRequest,
  21. McpConnectionSnapshot,
  22. McpConnectOptions,
  23. McpContentBlock,
  24. McpElicitationPort,
  25. McpElicitationTrace,
  26. McpListResourcesRequest,
  27. McpListResourcesResult,
  28. McpListResourceTemplatesResult,
  29. McpNotificationPort,
  30. McpOAuthConfig,
  31. McpPort,
  32. McpReadResourceRequest,
  33. McpReadResourceResult,
  34. McpResourceSubscriptionRequest,
  35. McpServerConfig,
  36. McpServerStatus,
  37. McpToolCallResult,
  38. McpToolDescriptor,
  39. OfficialMcpAuthFailureReason,
  40. OfficialMcpAuthHeadersPort,
  41. OfficialMcpTrustedOriginRegistry,
  42. } from "@zcode/contracts";
  43. import {
  44. McpResourceSubscribeUnsupportedError,
  45. ZCODE_MCP_SERVER_REQUEST_ID_META_KEY,
  46. } from "@zcode/contracts";
  47. import {
  48. OFFICIAL_MCP_AUTH_META_KEY,
  49. ZCODE_OFFICIAL_MCP_AUTH_TYPE,
  50. type McpServerFailureKind,
  51. type OfficialMcpAuthFailureKind,
  52. } from "@zcode/shared";
  53. import { buildMcpAppsClientCapabilities } from "@zcode/shared/mcp-apps";
  54. import { createHash, randomUUID } from "node:crypto";
  55. import { resolve } from "node:path";
  56. import { isDeepStrictEqual, stripVTControlCharacters } from "node:util";
  57. import {
  58. createSharedZCodeCredentialStore,
  59. type SharedZCodeCredentialStore,
  60. } from "../auth/shared-credentials.js";
  61. import { normalizeMcpToolDescriptor } from "./descriptor.js";
  62. import {
  63. buildMcpStdioEnv,
  64. createMcpTransportFetch,
  65. type NetworkEgressEnvPolicy,
  66. } from "./network.js";
  67. import {
  68. applyMcpNodeFallbackEnv,
  69. type McpNodeFallback,
  70. type McpNodeFallbackProvider,
  71. } from "./node-fallback.js";
  72. import { loadCredentialPair } from "./oauth-credentials.js";
  73. import {
  74. classifyInteractiveAuthorizationTrigger,
  75. type InteractiveAuthorizationTrigger,
  76. } from "./oauth-errors.js";
  77. import {
  78. MCP_OAUTH_AUTHORIZATION_TRANSACTION_TTL_MS,
  79. runMcpInteractiveAuthorization,
  80. type McpInteractiveAuthorizationOutcome,
  81. } from "./oauth-interactive.js";
  82. import { createMcpOAuthTokenProvider } from "./oauth-provider.js";
  83. import {
  84. createCredentialKeyPrefix,
  85. type McpOAuthAuthorizationContext,
  86. type McpOAuthRuntimeOptions,
  87. } from "./oauth.js";
  88. import {
  89. createOfficialMcpAuthFetch,
  90. OfficialMcpAuthError,
  91. type OfficialMcpServerResponseInfo,
  92. } from "./official-auth.js";
  93. import {
  94. createMcpConnectionPool,
  95. type McpConnectionContext,
  96. type McpConnectionPool,
  97. } from "./pool.js";
  98. import { terminateMcpStdioProcessTree } from "./process-tree.js";
  99. import { McpResourceSubscriptionRegistry } from "./resource-subscriptions.js";
  100. import { ProcessTreeStdioClientTransport } from "./stdio-transport.js";
  101. import type { McpTelemetryTracker } from "./telemetry.js";
  102. import {
  103. createMcpDeadline,
  104. McpTimeoutError,
  105. remainingMcpDeadlineMs,
  106. waitWithinMcpDeadline,
  107. withTimeout,
  108. type McpDeadline,
  109. } from "./timeout.js";
  110. const DEFAULT_MCP_TIMEOUT_MS = 30_000;
  111. // 存活探测只允许占用很短的时间:它挂在设置页刷新的同步路径上,超时即判死并触发重连。
  112. const MCP_PING_TIMEOUT_MS = 5_000;
  113. const MAX_MCP_VERSION_PROBE_TIMEOUT_MS = 5_000;
  114. const MCP_STDIO_STDERR_LOG_MAX_CHARS = 4_000;
  115. const MCP_STDIO_ERROR_MESSAGE_MAX_CHARS = 512;
  116. /**
  117. * span → request id 的暂存条数上限。正常情况下每条都会在同一次 tool call 结束时被取走,
  118. * 留下的只有无人认领的(如连接期请求),几十条足够,纯为防止长会话下无界增长。
  119. */
  120. const MAX_TRACKED_SERVER_REQUEST_IDS = 64;
  121. export interface CreateMcpAdapterOptions {
  122. clientName?: string;
  123. clientVersion?: string;
  124. connectionContext?: McpConnectionContext;
  125. env?: NodeJS.ProcessEnv;
  126. logger?: Logger;
  127. telemetry?: McpTelemetryTracker;
  128. mcpOAuth?: McpOAuthRuntimeOptions;
  129. network?: NetworkEgressEnvPolicy;
  130. /**
  131. * 桌面 Electron Node 回退:宿主注入时,stdio MCP 的 node/npm/npx 在用户 PATH 缺失时
  132. * 回退到 Electron 与随包 npm(docs/design/v2/mcp-node-fallback.md)。缺省时 env 不变。
  133. */
  134. nodeFallback?: McpNodeFallbackProvider;
  135. /**
  136. * 官方 Server MCP 鉴权依赖。trustedOrigins 缺失时仍 fail closed;authHeadersPort
  137. * 可缺省,此时各请求匿名降级并交给服务端做权威判定。
  138. */
  139. officialMcpAuth?: {
  140. authHeadersPort?: OfficialMcpAuthHeadersPort;
  141. trustedOrigins: OfficialMcpTrustedOriginRegistry;
  142. /**
  143. * 当前 ZCode API origin。stdio 形态没有 `url` 可供校验,targetOrigin 只能由宿主给出
  144. * ——插件因此无法把身份头导向别的 origin。
  145. * 与 trustedOrigins 的 `resolveZCodeApiOrigin` 必须同源,否则两侧判定会分叉。
  146. */
  147. resolveZCodeApiOrigin?: () => string;
  148. workspaceIdentity?: string;
  149. };
  150. workingDirectory?: string;
  151. /** 有此端口才向 server 宣告 elicitation 能力;缺省时 server 的 elicitation/create 收到 method not found。 */
  152. elicitation?: McpElicitationPort;
  153. /** server → client 通知(资源更新 / 列表变化 / 工具列表变化 / 日志)的出口;缺省只记 debug。 */
  154. notifications?: McpNotificationPort;
  155. }
  156. type McpClient = Client;
  157. type McpTransport = StdioClientTransport | StreamableHTTPClientTransport | SSEClientTransport;
  158. type AuthorizationCodeOAuthConfig = Extract<McpOAuthConfig, { type: "authorization_code" }>;
  159. /**
  160. * stdio 官方 MCP 的身份头载荷,随每条出站协议消息的 `_meta` 下发。
  161. *
  162. * 失败也下发(`ok: false` + 枚举 reason);stdio 插件拿不到头时不会去打官方端点。HTTP 路径则
  163. * 由 adapter 发起无身份的 tools/call,让 ZCode server 返回权威结构化错误。把 reason 交给 stdio
  164. * 插件才能让它把"未登录"与"无 Coding Plan
  165. * 套餐"如实呈现给用户,而不是静默降级成一句莫名其妙的失败。
  166. */
  167. type OfficialMcpAuthMetaPayload =
  168. | { ok: true; headers: Record<string, string> }
  169. | { ok: false; reason: OfficialMcpAuthFailureReason };
  170. /** 订阅的 server → client 通知方法名(MCP 规范)。 */
  171. export const MCP_NOTIFICATION_TOOLS_LIST_CHANGED = "notifications/tools/list_changed";
  172. export const MCP_NOTIFICATION_RESOURCES_UPDATED = "notifications/resources/updated";
  173. export const MCP_NOTIFICATION_RESOURCES_LIST_CHANGED = "notifications/resources/list_changed";
  174. export const MCP_NOTIFICATION_MESSAGE = "notifications/message";
  175. interface McpServerRecord {
  176. client?: McpClient;
  177. abortController?: AbortController;
  178. connecting?: Promise<McpServerStatus>;
  179. config: McpServerConfig;
  180. status: McpServerStatus;
  181. tools: McpToolDescriptor[];
  182. /** 收到 tools/list_changed 后置位,下一次 listTools 重拉。 */
  183. toolsStale?: boolean;
  184. transport?: McpTransport;
  185. }
  186. /** resources/list 项:只透传标准字段(含 _meta),丢掉 SDK 附加的运行时字段。 */
  187. function pickResourceDescriptor(
  188. resource: unknown,
  189. includeUri = true,
  190. ): {
  191. uri?: string;
  192. name?: string;
  193. title?: string;
  194. description?: string;
  195. mimeType?: string;
  196. _meta?: Record<string, unknown>;
  197. } {
  198. const item = isRecord(resource) ? resource : {};
  199. return {
  200. ...(includeUri ? { uri: typeof item.uri === "string" ? item.uri : "" } : {}),
  201. ...(typeof item.name === "string" ? { name: item.name } : {}),
  202. ...(typeof item.title === "string" ? { title: item.title } : {}),
  203. ...(typeof item.description === "string" ? { description: item.description } : {}),
  204. ...(typeof item.mimeType === "string" ? { mimeType: item.mimeType } : {}),
  205. ...(isRecord(item._meta) ? { _meta: item._meta } : {}),
  206. };
  207. }
  208. export function createMcpAdapter(options: CreateMcpAdapterOptions = {}): McpPort {
  209. return new NodeMcpAdapter(options);
  210. }
  211. export function createMcpAdapterConnectionPool(
  212. options: CreateMcpAdapterOptions = {},
  213. ): McpConnectionPool {
  214. return createMcpConnectionPool({
  215. logger: options.logger,
  216. telemetry: options.telemetry,
  217. createAdapter: ({ connectionContext, workingDirectory }) =>
  218. createMcpAdapter({
  219. ...options,
  220. connectionContext,
  221. workingDirectory: workingDirectory ?? options.workingDirectory,
  222. }),
  223. });
  224. }
  225. export {
  226. createMcpConnectionPool,
  227. type McpConnectionPool,
  228. type McpConnectionPoolOptions,
  229. } from "./pool.js";
  230. export {
  231. createMcpNodeFallbackProvider,
  232. type CreateMcpNodeFallbackProviderOptions,
  233. type McpNodeFallback,
  234. type McpNodeFallbackProvider,
  235. } from "./node-fallback.js";
  236. export {
  237. createMcpTelemetryTracker,
  238. resolvePluginName,
  239. type McpTelemetryTracker,
  240. type McpTrackedProcess,
  241. } from "./telemetry.js";
  242. /** elicitation 模式白名单(MCP form 与 兼容别名)。 */
  243. const SUPPORTED_ELICITATION_MODES = new Set(["form", "openai/form", "openaiForm"]);
  244. function isSupportedElicitationMode(mode: unknown): boolean {
  245. return mode === undefined || (typeof mode === "string" && SUPPORTED_ELICITATION_MODES.has(mode));
  246. }
  247. class NodeMcpAdapter implements McpPort {
  248. private readonly adapterInstanceId = randomUUID();
  249. private readonly clientName: string;
  250. private readonly clientVersion: string;
  251. private readonly connectionContext?: McpConnectionContext;
  252. private readonly env?: NodeJS.ProcessEnv;
  253. private readonly logger?: Logger;
  254. private readonly mcpOAuth?: McpOAuthRuntimeOptions;
  255. private readonly network?: NetworkEgressEnvPolicy;
  256. private readonly nodeFallback?: McpNodeFallbackProvider;
  257. private readonly officialMcpAuth?: CreateMcpAdapterOptions["officialMcpAuth"];
  258. private readonly telemetry?: McpTelemetryTracker;
  259. private readonly connectionGenerations = new Map<string, number>();
  260. private credentialStore?: SharedZCodeCredentialStore;
  261. /**
  262. * 官方鉴权失败分类的暂存槽。不能从 error 对象读——SDK 的 version
  263. * negotiation 会把 OfficialMcpAuthError 重新包装成普通 Error,instanceof 失效;
  264. * 也不允许按错误文本反解。因此在抛出点写入,failConnection 取用后立即清除。
  265. */
  266. private readonly lastOfficialAuthKind = new Map<string, OfficialMcpAuthFailureKind>();
  267. /**
  268. * span → 服务端 request id。只有官方 MCP 会写入(唯一能看到响应头的地方是 auth fetch
  269. * wrapper),供 in-band 失败(HTTP 200 + `isError`)把 id 带回 tool result。
  270. *
  271. * 用 span 而不是 traceId 作键:traceId 覆盖整个顶层 session,同一 session 的多次调用
  272. * 共用它,关联会串号;span 是一次 tool call 的粒度。
  273. *
  274. * 有界并即取即删:拿不到匹配的 span(如 initialize / tools/list,它们没有 `_meta`)
  275. * 就让条目自然被挤出,绝不"取最近一次"兜底——那会把上一次调用的 id 贴到这一次的失败上。
  276. */
  277. private readonly serverRequestIdBySpan = new Map<string, string>();
  278. private readonly connectionDiagnosticByServer = new Map<
  279. string,
  280. Pick<McpServerStatus, "failureKind" | "serverRequestId">
  281. >();
  282. private readonly records = new Map<string, McpServerRecord>();
  283. private readonly workingDirectory?: string;
  284. private readonly elicitation?: McpElicitationPort;
  285. private readonly notifications?: McpNotificationPort;
  286. /** 资源订阅登记表 serverName → uri → subscriberKey;唯一 owner,连接层计数。 */
  287. private readonly resourceSubscriptions = new McpResourceSubscriptionRegistry();
  288. /** tools/list_changed 累计次数,runtime 按此判断是否需要重注册。 */
  289. private toolListRevisionCounter = 0;
  290. /** 每个 server 当前正在执行的工具调用 trace;elicitation 借此归属到会话 / 工具行。 */
  291. private readonly activeCallTraces = new Map<string, McpElicitationTrace>();
  292. constructor(options: CreateMcpAdapterOptions) {
  293. this.clientName = options.clientName ?? "zcode";
  294. this.clientVersion = options.clientVersion ?? "0.0.0";
  295. this.connectionContext = options.connectionContext;
  296. this.env = options.env;
  297. this.logger = options.logger?.child({
  298. ...this.connectionContext,
  299. module: "adapters.mcp",
  300. });
  301. this.mcpOAuth = options.mcpOAuth;
  302. this.network = options.network;
  303. this.nodeFallback = options.nodeFallback;
  304. this.officialMcpAuth = options.officialMcpAuth;
  305. this.telemetry = options.telemetry;
  306. this.workingDirectory = options.workingDirectory;
  307. this.elicitation = options.elicitation;
  308. this.notifications = options.notifications;
  309. }
  310. async connectConfiguredServers(
  311. servers: Record<string, McpServerConfig>,
  312. options: McpConnectOptions = {},
  313. ): Promise<McpConnectionSnapshot> {
  314. const startedAt = Date.now();
  315. const serverNames = Object.keys(servers);
  316. this.logger?.info("MCP configured servers connection started", {
  317. event: "mcp.configured_servers.connect.started",
  318. serverCount: serverNames.length,
  319. serverNames,
  320. status: "started",
  321. });
  322. const configuredNames = new Set(Object.keys(servers));
  323. await Promise.all(
  324. Array.from(this.records.keys())
  325. .filter((name) => !configuredNames.has(name))
  326. .map((name) => this.disconnectServer(name)),
  327. );
  328. await Promise.all(
  329. Object.entries(servers).map(([name, config]) => {
  330. const record = this.records.get(name);
  331. if (
  332. record?.connecting &&
  333. record.status.status === "connecting" &&
  334. record.status.authorization &&
  335. isDeepStrictEqual(record.config, config)
  336. ) {
  337. // 相同配置的全量收敛可能与 OAuth callback 等待重叠;重新 connect
  338. // 会关闭原 session,使浏览器中已打开的授权 URL、PKCE/state 和 callback 一并失效。
  339. // 连接生命周期可以共享,但 Session 的 15 秒等待预算和 AbortSignal 不能继承设置页的 5 分钟预算。
  340. return this.waitForSharedConnection(name, record, options);
  341. }
  342. return this.connectServer(name, config, options);
  343. }),
  344. );
  345. const statuses = await this.status();
  346. const tools = await this.listTools();
  347. const statusCounts = Object.values(statuses).reduce<Record<string, number>>(
  348. (counts, status) => {
  349. counts[status.status] = (counts[status.status] ?? 0) + 1;
  350. return counts;
  351. },
  352. {},
  353. );
  354. this.logger?.info("MCP configured servers connection completed", {
  355. durationMs: Date.now() - startedAt,
  356. event: "mcp.configured_servers.connect.completed",
  357. serverCount: serverNames.length,
  358. status: "completed",
  359. statusCounts,
  360. toolCount: tools.length,
  361. });
  362. return {
  363. statuses,
  364. tools,
  365. };
  366. }
  367. async connectServer(
  368. name: string,
  369. config: McpServerConfig,
  370. options: McpConnectOptions = {},
  371. ): Promise<McpServerStatus> {
  372. const startedAt = Date.now();
  373. const timeoutMs = config.timeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;
  374. const generation = this.nextConnectionGeneration(name);
  375. this.lastOfficialAuthKind.delete(name);
  376. this.connectionDiagnosticByServer.delete(name);
  377. this.logger?.info("MCP server connection started", {
  378. event: "mcp.server.connect.started",
  379. mcpServerName: name,
  380. status: "started",
  381. timeoutMs,
  382. transport: config.type,
  383. });
  384. await this.closeRecord(name);
  385. if (config.enabled === false) {
  386. const status = this.createStatus(config, "disabled");
  387. this.records.set(name, { config, status, tools: [] });
  388. this.logger?.info("MCP server connection skipped", {
  389. durationMs: Date.now() - startedAt,
  390. event: "mcp.server.connect.skipped",
  391. mcpServerName: name,
  392. status: "completed",
  393. transport: config.type,
  394. });
  395. return status;
  396. }
  397. const abortController = new AbortController();
  398. const abortExternal = () => {
  399. abortController.abort(
  400. options.signal?.reason instanceof Error ? options.signal.reason : undefined,
  401. );
  402. };
  403. if (options.signal?.aborted) {
  404. abortExternal();
  405. } else {
  406. options.signal?.addEventListener("abort", abortExternal, { once: true });
  407. }
  408. const connectingStatus = this.createStatus(config, "connecting");
  409. const record: McpServerRecord = {
  410. abortController,
  411. config,
  412. status: connectingStatus,
  413. tools: [],
  414. };
  415. this.records.set(name, record);
  416. const connecting = this.openServerConnection({
  417. config,
  418. generation,
  419. name,
  420. oauthAuthorizationTimeoutMs: options.oauthAuthorizationTimeoutMs,
  421. signal: abortController.signal,
  422. timeoutMs,
  423. workingDirectory: options.workingDirectory,
  424. }).finally(() => {
  425. options.signal?.removeEventListener("abort", abortExternal);
  426. });
  427. record.connecting = connecting;
  428. // 过去 `oauthAuthorizationTimeoutMs`(session 的 15 秒)被当成 OAuth 事务寿命,
  429. // 15 秒后连同 callback listener 一起关掉,真人根本来不及在浏览器里完成授权(现场证据:
  430. // 一次成功授权耗时约 74 秒)。现在它只作为**本 caller 的等待预算**:到点返回当时的
  431. // snapshot(含授权 URL),后台连接与 300 秒授权事务继续存活。
  432. return await this.waitForSharedConnection(name, record, options);
  433. }
  434. async disconnectServer(name: string): Promise<McpServerStatus | undefined> {
  435. const record = this.records.get(name);
  436. if (!record) return undefined;
  437. this.nextConnectionGeneration(name);
  438. await this.closeRecord(name);
  439. const status = this.createStatus(record.config, "disconnected");
  440. this.records.set(name, {
  441. config: record.config,
  442. status,
  443. tools: [],
  444. });
  445. return status;
  446. }
  447. async status(): Promise<Record<string, McpServerStatus>> {
  448. return Object.fromEntries(
  449. Array.from(this.records.entries()).map(([name, record]) => [name, record.status]),
  450. );
  451. }
  452. // HTTP/SSE MCP 服务被停掉时不会派发 onclose(没有常驻流可断),record 会长期停在
  453. // connected;设置页刷新读到的就是这份"无声死亡"的旧快照,看起来像刷新按钮没生效。
  454. // ping 是 MCP 基础协议方法,用它把 transport 存活性显式化。
  455. async pingServer(name: string, options: { timeoutMs?: number } = {}): Promise<boolean> {
  456. const record = this.records.get(name);
  457. if (!record?.client || record.status.status !== "connected") {
  458. return false;
  459. }
  460. const timeoutMs = Math.min(
  461. options.timeoutMs ?? MCP_PING_TIMEOUT_MS,
  462. record.config.timeoutMs ?? DEFAULT_MCP_TIMEOUT_MS,
  463. );
  464. const generation = this.connectionGenerations.get(name) ?? 0;
  465. try {
  466. await record.client.ping({ timeout: timeoutMs });
  467. return true;
  468. } catch (error) {
  469. // server 回了 JSON-RPC 错误(例如未实现 ping)说明连接本身是活的,不能据此拆连接。
  470. if (isPeerAnsweredError(error)) {
  471. return true;
  472. }
  473. if (!this.isCurrentConnection(name, generation)) return false;
  474. const current = this.records.get(name);
  475. if (current && current.client === record.client) {
  476. current.status = this.createStatus(current.config, "disconnected", {
  477. error: "MCP server did not answer ping",
  478. failureKind: "unexpected_disconnect",
  479. });
  480. }
  481. this.logger?.warn("MCP server ping failed", {
  482. ...this.connectionContext,
  483. error: error instanceof Error ? error.message : String(error),
  484. event: "mcp.server.ping.failed",
  485. mcpServerName: name,
  486. status: "failed",
  487. transport: record.config.type,
  488. });
  489. return false;
  490. }
  491. }
  492. toolListRevision(): number {
  493. return this.toolListRevisionCounter;
  494. }
  495. async listTools(): Promise<McpToolDescriptor[]> {
  496. // 收到 notifications/tools/list_changed 的 server 在下一次 listTools 时重新拉取
  497. // (runtime 只在回合开始前调用,回合内工具表不变)。
  498. for (const [name, record] of this.records) {
  499. if (!record.toolsStale || !record.client || record.status.status !== "connected") continue;
  500. try {
  501. const listed = await record.client.listTools();
  502. record.tools = listed.tools.map((tool) =>
  503. normalizeMcpToolDescriptor(
  504. name,
  505. tool,
  506. record.config.timeoutMs,
  507. record.config.type === "http" &&
  508. record.config.auth?.type === ZCODE_OFFICIAL_MCP_AUTH_TYPE,
  509. ),
  510. );
  511. record.status = { ...record.status, toolCount: record.tools.length };
  512. record.toolsStale = false;
  513. this.logger?.info("MCP tool list refreshed after list_changed", {
  514. event: "mcp.tools.refreshed",
  515. mcpServerName: name,
  516. toolCount: record.tools.length,
  517. });
  518. } catch (error) {
  519. this.logger?.warn("MCP tool list refresh failed", {
  520. event: "mcp.tools.refresh_failed",
  521. mcpServerName: name,
  522. error: error instanceof Error ? error.message : String(error),
  523. });
  524. }
  525. }
  526. return Array.from(this.records.values()).flatMap((record) => record.tools);
  527. }
  528. /** `resources/list`,分页游标透传。 */
  529. async listResources(
  530. request: McpListResourcesRequest,
  531. options: McpCallToolOptions = {},
  532. ): Promise<McpListResourcesResult> {
  533. const { record, deadline, timeoutMessage } = await this.resolveForResourceRequest(
  534. request.serverName,
  535. "resources/list",
  536. options,
  537. );
  538. const result = await record.client.listResources(
  539. request.cursor ? { cursor: request.cursor } : {},
  540. { signal: options.signal, timeout: remainingMcpDeadlineMs(deadline, timeoutMessage) },
  541. );
  542. return {
  543. resources: (result.resources ?? []).map((resource) => {
  544. const { uri, ...rest } = pickResourceDescriptor(resource);
  545. return { uri: uri ?? "", ...rest };
  546. }),
  547. ...(typeof result.nextCursor === "string" ? { nextCursor: result.nextCursor } : {}),
  548. };
  549. }
  550. async listResourceTemplates(
  551. request: McpListResourcesRequest,
  552. options: McpCallToolOptions = {},
  553. ): Promise<McpListResourceTemplatesResult> {
  554. const { record, deadline, timeoutMessage } = await this.resolveForResourceRequest(
  555. request.serverName,
  556. "resources/templates/list",
  557. options,
  558. );
  559. const result = await record.client.listResourceTemplates(
  560. request.cursor ? { cursor: request.cursor } : {},
  561. { signal: options.signal, timeout: remainingMcpDeadlineMs(deadline, timeoutMessage) },
  562. );
  563. return {
  564. resourceTemplates: (result.resourceTemplates ?? []).map((template) => {
  565. const item = template as Record<string, unknown>;
  566. return {
  567. uriTemplate: typeof item.uriTemplate === "string" ? item.uriTemplate : "",
  568. ...pickResourceDescriptor(item, false),
  569. };
  570. }),
  571. ...(typeof result.nextCursor === "string" ? { nextCursor: result.nextCursor } : {}),
  572. };
  573. }
  574. /**
  575. * 按 (serverName, uri) 计数的订阅。同一连接被多个 session 共享时只向 server 订阅一次;
  576. * server 没声明 resources.subscribe 能力 → McpResourceSubscribeUnsupportedError。
  577. */
  578. async subscribeResource(
  579. request: McpResourceSubscriptionRequest,
  580. options: McpCallToolOptions = {},
  581. ): Promise<void> {
  582. const { record, deadline, timeoutMessage } = await this.resolveForResourceRequest(
  583. request.serverName,
  584. "resources/subscribe",
  585. options,
  586. );
  587. if (!record.client.getServerCapabilities()?.resources?.subscribe) {
  588. throw new McpResourceSubscribeUnsupportedError(request.serverName);
  589. }
  590. const { first } = this.resourceSubscriptions.add(
  591. request.serverName,
  592. request.uri,
  593. request.subscriberKey,
  594. );
  595. if (!first) return;
  596. try {
  597. await record.client.subscribeResource(
  598. { uri: request.uri },
  599. { signal: options.signal, timeout: remainingMcpDeadlineMs(deadline, timeoutMessage) },
  600. );
  601. } catch (error) {
  602. this.resourceSubscriptions.remove(request.serverName, request.uri, request.subscriberKey);
  603. throw error;
  604. }
  605. this.logger?.info("MCP resource subscribed", {
  606. event: "mcp.resource.subscribe",
  607. mcpServerName: request.serverName,
  608. uri: request.uri,
  609. status: "completed",
  610. });
  611. }
  612. async unsubscribeResource(
  613. request: McpResourceSubscriptionRequest,
  614. options: McpCallToolOptions = {},
  615. ): Promise<void> {
  616. const removed = this.resourceSubscriptions.remove(
  617. request.serverName,
  618. request.uri,
  619. request.subscriberKey,
  620. );
  621. if (!removed?.last) return;
  622. await this.unsubscribeOnServer(request.serverName, request.uri, options);
  623. }
  624. async unsubscribeResourcesBySubscriber(subscriberKeyPrefix: string): Promise<number> {
  625. const released = this.resourceSubscriptions.removeByPrefix(subscriberKeyPrefix);
  626. for (const { serverName, uri } of released) {
  627. await this.unsubscribeOnServer(serverName, uri, {});
  628. }
  629. return released.length;
  630. }
  631. /** 登记表快照(测试 / 诊断):serverName → uri → 订阅者数。 */
  632. resourceSubscriptionCounts(): Record<string, Record<string, number>> {
  633. return this.resourceSubscriptions.counts();
  634. }
  635. private async unsubscribeOnServer(
  636. serverName: string,
  637. uri: string,
  638. options: McpCallToolOptions,
  639. ): Promise<void> {
  640. const record = this.records.get(serverName);
  641. if (!record?.client || record.status.status !== "connected") return;
  642. try {
  643. await record.client.unsubscribeResource({ uri }, { signal: options.signal });
  644. this.logger?.info("MCP resource unsubscribed", {
  645. event: "mcp.resource.unsubscribe",
  646. mcpServerName: serverName,
  647. uri,
  648. status: "completed",
  649. });
  650. } catch (error) {
  651. // 退订失败只记日志:登记表已清,server 多发的通知因没有订阅者会被丢弃。
  652. this.logger?.warn("MCP resource unsubscribe failed", {
  653. event: "mcp.resource.unsubscribe",
  654. mcpServerName: serverName,
  655. uri,
  656. error: error instanceof Error ? error.message : String(error),
  657. status: "failed",
  658. });
  659. }
  660. }
  661. /** 断连重连后按登记表重放 subscribe(A3);单条失败不影响其它。 */
  662. private async replayResourceSubscriptions(serverName: string, client: McpClient): Promise<void> {
  663. const uris = this.resourceSubscriptions.uris(serverName);
  664. if (uris.length === 0) return;
  665. if (!client.getServerCapabilities()?.resources?.subscribe) return;
  666. for (const uri of uris) {
  667. try {
  668. await client.subscribeResource({ uri });
  669. } catch (error) {
  670. this.logger?.warn("MCP resource subscription replay failed", {
  671. event: "mcp.resource.subscribe",
  672. mcpServerName: serverName,
  673. uri,
  674. error: error instanceof Error ? error.message : String(error),
  675. status: "failed",
  676. });
  677. }
  678. }
  679. this.logger?.info("MCP resource subscriptions replayed after reconnect", {
  680. event: "mcp.resource.subscribe.replayed",
  681. mcpServerName: serverName,
  682. uriCount: uris.length,
  683. });
  684. }
  685. private async resolveForResourceRequest(
  686. serverName: string,
  687. operation: string,
  688. options: McpCallToolOptions,
  689. ): Promise<{
  690. record: McpServerRecord & { client: McpClient };
  691. deadline: McpDeadline;
  692. timeoutMessage: string;
  693. }> {
  694. const timeoutMs =
  695. options.timeoutMs ?? this.records.get(serverName)?.config.timeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;
  696. const deadline = createMcpDeadline(timeoutMs);
  697. const timeoutMessage = `MCP ${operation} ${serverName} timed out after ${timeoutMs}ms`;
  698. const record = await this.resolveConnectedRecord(
  699. serverName,
  700. deadline,
  701. timeoutMessage,
  702. options.signal,
  703. );
  704. return { record, deadline, timeoutMessage };
  705. }
  706. /**
  707. * server 主动通知。订阅类通知附上当前登记的 subscriberKey(宿主据此按会话拆分);
  708. * tools/list_changed 只标记 stale,下一次 listTools 再拉;没有端口时 SDK 默认丢弃。
  709. */
  710. private installNotificationHandlers(client: McpClient, serverName: string): void {
  711. const setNotificationHandler = (client as unknown as { setNotificationHandler?: unknown })
  712. .setNotificationHandler;
  713. if (typeof setNotificationHandler !== "function") return;
  714. // SDK 2.x:第一个参数是通知方法名(spec 方法直接用字符串),schema 是可选的第二个参数。
  715. const typed = client as unknown as {
  716. setNotificationHandler(method: string, handler: (notification: unknown) => void): void;
  717. };
  718. typed.setNotificationHandler(MCP_NOTIFICATION_TOOLS_LIST_CHANGED, () => {
  719. const record = this.records.get(serverName);
  720. if (record) record.toolsStale = true;
  721. this.toolListRevisionCounter += 1;
  722. this.notifications?.onNotification({ kind: "toolListChanged", serverName });
  723. });
  724. typed.setNotificationHandler(MCP_NOTIFICATION_RESOURCES_UPDATED, (notification) => {
  725. const uri = (notification as { params?: { uri?: unknown } }).params?.uri;
  726. if (typeof uri !== "string") return;
  727. this.notifications?.onNotification({
  728. kind: "resourceUpdated",
  729. serverName,
  730. uri,
  731. subscribers: this.resourceSubscriptions.subscribers(serverName, uri),
  732. });
  733. });
  734. typed.setNotificationHandler(MCP_NOTIFICATION_RESOURCES_LIST_CHANGED, () => {
  735. this.notifications?.onNotification({
  736. kind: "resourceListChanged",
  737. serverName,
  738. subscribers: this.resourceSubscriptions.allSubscribers(serverName),
  739. });
  740. });
  741. typed.setNotificationHandler(MCP_NOTIFICATION_MESSAGE, (notification) => {
  742. const params = (notification as { params?: Record<string, unknown> }).params ?? {};
  743. this.notifications?.onNotification({
  744. kind: "loggingMessage",
  745. serverName,
  746. level: typeof params.level === "string" ? params.level : "info",
  747. ...(typeof params.logger === "string" ? { logger: params.logger } : {}),
  748. data: params.data,
  749. });
  750. });
  751. }
  752. async callTool(
  753. request: McpCallToolRequest,
  754. options: McpCallToolOptions = {},
  755. ): Promise<McpToolCallResult> {
  756. const timeoutMs =
  757. options.timeoutMs ??
  758. this.records.get(request.serverName)?.config.timeoutMs ??
  759. DEFAULT_MCP_TIMEOUT_MS;
  760. const deadline = createMcpDeadline(timeoutMs);
  761. const timeoutMessage = `MCP tool ${request.serverName}/${request.toolName} timed out after ${timeoutMs}ms`;
  762. let record: McpServerRecord & { client: McpClient };
  763. if (options.appConnection) {
  764. const snapshot = this.appConnectionSnapshot(request.serverName);
  765. const current = this.records.get(request.serverName);
  766. if (
  767. !snapshot ||
  768. snapshot.identity !== options.appConnection.identity ||
  769. snapshot.generation !== options.appConnection.generation ||
  770. !current?.client
  771. )
  772. throw new Error("MCP App connection changed");
  773. options.signal?.throwIfAborted();
  774. record = current as McpServerRecord & { client: McpClient };
  775. } else {
  776. record = await this.resolveConnectedRecord(
  777. request.serverName,
  778. deadline,
  779. timeoutMessage,
  780. options.signal,
  781. );
  782. }
  783. try {
  784. return await this.callToolOnClient(
  785. record.client,
  786. request,
  787. remainingMcpDeadlineMs(deadline, timeoutMessage),
  788. options.signal,
  789. options.onProgress,
  790. );
  791. } catch (error) {
  792. if (options.appConnection) throw error;
  793. // 连接建立后 token 过期、被撤销或 scope 不足时,
  794. // 过去这些认证错误原样冒泡,用户看到裸错误且永远不会自愈——OAuth 自愈只存在于
  795. // startup connect 路径。现在运行期与建连期共用同一套 Phase 2 → Phase 1 编排。
  796. const trigger = classifyInteractiveAuthorizationTrigger(error);
  797. if (trigger && record.config.type !== "stdio") {
  798. return await this.recoverToolCallAuthorization({
  799. error,
  800. record,
  801. request,
  802. deadline,
  803. timeoutMessage,
  804. trigger,
  805. ...(options.signal ? { signal: options.signal } : {}),
  806. ...(options.onProgress ? { onProgress: options.onProgress } : {}),
  807. });
  808. }
  809. // 防 onclose 尚未派发的竞态:SDK 在 transport 已断时抛裸 "Not connected"。
  810. // 只对这一种确定的断连错误重连重试一次,其余错误原样冒泡。
  811. if (!(error instanceof Error) || error.message !== "Not connected") throw error;
  812. try {
  813. await waitWithinMcpDeadline(
  814. this.reconnectForCall(request.serverName, record.config),
  815. deadline,
  816. timeoutMessage,
  817. options.signal,
  818. );
  819. } catch (reconnectError) {
  820. this.logger?.warn("MCP server reconnect failed", {
  821. error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),
  822. event: "mcp.server.reconnect.failed",
  823. mcpServerName: request.serverName,
  824. status: "failed",
  825. });
  826. throw error;
  827. }
  828. const revived = this.records.get(request.serverName);
  829. if (!revived?.client || revived.status.status !== "connected") throw error;
  830. return await this.callToolOnClient(
  831. revived.client,
  832. request,
  833. remainingMcpDeadlineMs(deadline, timeoutMessage),
  834. options.signal,
  835. options.onProgress,
  836. );
  837. }
  838. }
  839. /**
  840. * 插件 UI 的 `ui://` 资源读取。与 callTool 共用连接等待 / 断连重连骨架(resolveConnectedRecord),
  841. * 保证走同一条连接与 OAuth 恢复路径;不做 tool 级 OAuth 二次恢复——资源读取失败直接冒泡,
  842. * 由 UI 回退到普通卡片。
  843. */
  844. async readResource(
  845. request: McpReadResourceRequest,
  846. options: McpCallToolOptions = {},
  847. ): Promise<McpReadResourceResult> {
  848. const timeoutMs =
  849. options.timeoutMs ??
  850. this.records.get(request.serverName)?.config.timeoutMs ??
  851. DEFAULT_MCP_TIMEOUT_MS;
  852. const deadline = createMcpDeadline(timeoutMs);
  853. const timeoutMessage = `MCP resource ${request.serverName} ${request.uri} timed out after ${timeoutMs}ms`;
  854. const record = await this.resolveConnectedRecord(
  855. request.serverName,
  856. deadline,
  857. timeoutMessage,
  858. options.signal,
  859. );
  860. const result = await record.client.readResource(
  861. { uri: request.uri },
  862. { signal: options.signal, timeout: remainingMcpDeadlineMs(deadline, timeoutMessage) },
  863. );
  864. return {
  865. contents: (result.contents ?? []).map((content) => {
  866. const item = content as Record<string, unknown>;
  867. return {
  868. uri: typeof item.uri === "string" ? item.uri : request.uri,
  869. ...(typeof item.mimeType === "string" ? { mimeType: item.mimeType } : {}),
  870. ...(typeof item.text === "string" ? { text: item.text } : {}),
  871. ...(typeof item.blob === "string" ? { blob: item.blob } : {}),
  872. ...(isRecord(item._meta) ? { _meta: item._meta } : {}),
  873. };
  874. }),
  875. };
  876. }
  877. /**
  878. * callTool / readResource 共用:等待共享 connecting 任务、对已断连 record 重连一次、
  879. * 返回处于 connected 的 record。抽出来是为了让资源读取与工具调用走完全相同的恢复路径。
  880. */
  881. private async resolveConnectedRecord(
  882. serverName: string,
  883. deadline: McpDeadline,
  884. timeoutMessage: string,
  885. signal: AbortSignal | undefined,
  886. ): Promise<McpServerRecord & { client: McpClient }> {
  887. const pending = this.records.get(serverName)?.connecting;
  888. if (pending) {
  889. // 修复原因:connecting 是 adapter 持有的共享连接/OAuth 恢复任务。过去这里裸 await,
  890. // tool caller 的 timeout/abort 完全失效;但直接 abort 底层任务又会关闭其他 caller 共用的
  891. // callback listener。这里只限制当前 waiter,共享任务继续由 record 生命周期持有。
  892. await waitWithinMcpDeadline(pending, deadline, timeoutMessage, signal);
  893. }
  894. // Bugfix:stdio MCP 子进程死亡后(如 node_repl 被异步错误击穿),此前没有任何恢复路径:
  895. // 连接只在 session 创建时建立一次,session resume 也不重建,该会话的工具从此永远失败。
  896. // 这里在调用前对已断连的 record 重连一次;server 进程内状态(如 REPL 变量)不可恢复,
  897. // 但工具本身恢复可用。
  898. const disconnected = this.records.get(serverName);
  899. if (disconnected && disconnected.status.status === "disconnected") {
  900. await waitWithinMcpDeadline(
  901. this.reconnectForCall(serverName, disconnected.config),
  902. deadline,
  903. timeoutMessage,
  904. signal,
  905. );
  906. }
  907. const record = this.records.get(serverName);
  908. if (!record?.client || record.status.status !== "connected") {
  909. throw new Error(`MCP server is not connected: ${serverName}`);
  910. }
  911. return record as McpServerRecord & { client: McpClient };
  912. }
  913. /** 连接期诊断按 server 保存;tool call request id 继续按 span 隔离。 */
  914. private rememberServerResponse(
  915. serverName: string,
  916. response: OfficialMcpServerResponseInfo,
  917. ): void {
  918. if (
  919. !response.spanId &&
  920. response.rpcMethod !== "tools/call" &&
  921. this.records.get(serverName)?.status.status === "connecting"
  922. ) {
  923. if (response.failureKind) {
  924. this.connectionDiagnosticByServer.set(serverName, {
  925. failureKind: response.failureKind,
  926. ...(response.serverRequestId ? { serverRequestId: response.serverRequestId } : {}),
  927. });
  928. }
  929. return;
  930. }
  931. if (!response.spanId) return;
  932. if (!response.serverRequestId) return;
  933. // 401 重试会对同一 span 产生两条响应,后写覆盖——留下的是最终那次,正是要报的那个。
  934. this.serverRequestIdBySpan.set(response.spanId, response.serverRequestId);
  935. while (this.serverRequestIdBySpan.size > MAX_TRACKED_SERVER_REQUEST_IDS) {
  936. const oldest = this.serverRequestIdBySpan.keys().next();
  937. if (oldest.done) break;
  938. this.serverRequestIdBySpan.delete(oldest.value);
  939. }
  940. }
  941. /** 取出并清除该 span 的 request id。取不到返回 undefined,不做任何兜底猜测。 */
  942. private takeServerRequestId(spanId: string | undefined): string | undefined {
  943. if (!spanId) return undefined;
  944. const requestId = this.serverRequestIdBySpan.get(spanId);
  945. if (requestId !== undefined) this.serverRequestIdBySpan.delete(spanId);
  946. return requestId;
  947. }
  948. /**
  949. * 解析 stdio 官方 MCP 本次出站协议消息的身份头。
  950. * 返回 undefined 表示"不是官方 stdio server"——此时 `_meta` 里绝不能出现该键,否则等于把
  951. * 身份头广播给任意第三方插件。
  952. */
  953. private async resolveOfficialStdioAuthMeta(
  954. serverName: string,
  955. config: McpServerConfig,
  956. signal: AbortSignal | undefined,
  957. ): Promise<OfficialMcpAuthMetaPayload | undefined> {
  958. if (config.type !== "stdio" || !isOfficialAuthConfig(config) || !config.official) {
  959. return undefined;
  960. }
  961. const official = config.official;
  962. const authHeadersPort = this.officialMcpAuth?.authHeadersPort;
  963. const trustedOrigins = this.officialMcpAuth?.trustedOrigins;
  964. const resolveZCodeApiOrigin = this.officialMcpAuth?.resolveZCodeApiOrigin;
  965. const logBase = {
  966. event: "mcp.official_auth.stdio_meta",
  967. mcpKey: official.mcpKey,
  968. mcpServerName: serverName,
  969. module: "adapters.mcp",
  970. };
  971. const fail = (reason: OfficialMcpAuthFailureReason): OfficialMcpAuthMetaPayload => {
  972. // 刻意不写 lastOfficialAuthKind:那个 map 只被 failConnection 读取,用来给**连接失败**
  973. // 打分类标签。stdio 的身份头缺失不会让连接失败,写进去会一直留着,等到该 server 之后
  974. // 因为别的原因(子进程死掉等)真正断连时被当成断连原因记进日志,属误导。
  975. // 本路径的可观测性由下面这条自己的 event + 下发给插件的 reason 承担。
  976. this.logger?.warn("Official MCP stdio auth headers unavailable", {
  977. ...logBase,
  978. reason,
  979. status: "failed",
  980. });
  981. return { ok: false, reason };
  982. };
  983. // standalone CLI 没有 host auth port。不静默省略该键:插件区分不了"宿主不支持"与
  984. // "宿主支持但我没登录",只有显式 reason 才能给出正确的用户提示。
  985. if (!authHeadersPort || !trustedOrigins || !resolveZCodeApiOrigin) {
  986. return fail("official_auth_unavailable");
  987. }
  988. // stdio 没有 url,origin 由宿主给出而非插件声明。isTrusted 在此退化为恒真断言,但仍要调用:
  989. // 它同时校验 https、拒绝带 username/password 的 URL,并让 dev loopback 开关继续生效。
  990. //
  991. // 这两步原来裸调用。origin 解析依赖 settings / 运行时环境,isTrusted 是
  992. // 注入的实现,两者都可能抛。异常裸冒泡会绕过整个失败分类:插件收不到 `{ok:false, reason}`,
  993. // 而 reason 是跨 adapter / host / UI 的契约(决定提示文案与是否重试)。因此统一映射为
  994. // official_auth_unavailable——宿主侧解析不出可信 origin,对插件而言就是"官方鉴权不可用"。
  995. // 错误文本只进日志,绝不参与流程判断。
  996. let targetOrigin: string;
  997. let trust: Awaited<ReturnType<OfficialMcpTrustedOriginRegistry["isTrusted"]>>;
  998. try {
  999. targetOrigin = resolveZCodeApiOrigin();
  1000. trust = await trustedOrigins.isTrusted({
  1001. mcpKey: official.mcpKey,
  1002. origin: targetOrigin,
  1003. pluginId: official.pluginId,
  1004. });
  1005. } catch (error) {
  1006. this.logger?.warn("Official MCP stdio origin resolution failed", {
  1007. ...logBase,
  1008. error: error instanceof Error ? error.message : String(error),
  1009. errorName: error instanceof Error ? error.name : "unknown",
  1010. pluginId: official.pluginId,
  1011. });
  1012. return fail("official_auth_unavailable");
  1013. }
  1014. if (!trust.trusted) {
  1015. this.logger?.warn("Official MCP stdio origin is not trusted", {
  1016. ...logBase,
  1017. detail: trust.detail ?? "unknown",
  1018. pluginId: official.pluginId,
  1019. targetOrigin,
  1020. });
  1021. return fail("official_mcp_origin_untrusted");
  1022. }
  1023. const resolved = await authHeadersPort.resolveHeaders({
  1024. mcpKey: official.mcpKey,
  1025. pluginId: official.pluginId,
  1026. targetOrigin,
  1027. ...(this.officialMcpAuth?.workspaceIdentity
  1028. ? { workspaceIdentity: this.officialMcpAuth.workspaceIdentity }
  1029. : {}),
  1030. ...(this.workingDirectory ? { workspacePath: this.workingDirectory } : {}),
  1031. ...(signal ? { signal } : {}),
  1032. });
  1033. if (!resolved.ok) return fail(resolved.reason);
  1034. // 只记 header 名与套餐维度,绝不记 header 值——日志留存周期不受控。
  1035. this.logger?.debug("Official MCP stdio auth headers attached", {
  1036. ...logBase,
  1037. identityHeaderNames: Object.keys(resolved.headers)
  1038. .map((name) => name.toLowerCase())
  1039. .sort(),
  1040. ...(resolved.headers["Bigmodel-Target-Type"]
  1041. ? { identityTargetType: resolved.headers["Bigmodel-Target-Type"] }
  1042. : {}),
  1043. status: "completed",
  1044. });
  1045. return { ok: true, headers: resolved.headers };
  1046. }
  1047. /** server 主动 elicitation/create:归属到该 server 当前工具调用的会话,交给宿主提问端口。 */
  1048. private installElicitationHandler(client: McpClient, serverName: string): void {
  1049. const port = this.elicitation;
  1050. const setRequestHandler = (client as unknown as { setRequestHandler?: unknown })
  1051. .setRequestHandler;
  1052. if (!port || typeof setRequestHandler !== "function") return;
  1053. (
  1054. client as unknown as {
  1055. setRequestHandler(
  1056. method: "elicitation/create",
  1057. handler: (request: {
  1058. params: { message: string; requestedSchema?: unknown };
  1059. }) => Promise<unknown>,
  1060. ): void;
  1061. }
  1062. ).setRequestHandler("elicitation/create", async (request) => {
  1063. // 接受缺省 / "form" / 兼容接口的 "openai/form" / "openaiForm";url 等其它模式 decline。
  1064. const mode = (request.params as { mode?: unknown }).mode;
  1065. if (!isSupportedElicitationMode(mode)) {
  1066. this.logger?.warn("MCP elicitation mode not supported, declining", {
  1067. event: "mcp.elicitation.unsupported_mode",
  1068. mcpServerName: serverName,
  1069. mode: String(mode),
  1070. });
  1071. return { action: "decline" };
  1072. }
  1073. const trace = this.activeCallTraces.get(serverName);
  1074. const result = await port.requestElicitation({
  1075. serverName,
  1076. message: request.params.message,
  1077. requestedSchema: request.params.requestedSchema,
  1078. ...(trace ? { trace } : {}),
  1079. });
  1080. return result.action === "accept"
  1081. ? { action: "accept", content: result.content ?? {} }
  1082. : { action: result.action };
  1083. });
  1084. }
  1085. /** 调用期间登记 trace,server 在这段时间发起的 elicitation 才能归属到会话 / 工具行。 */
  1086. private async callToolOnClient(
  1087. client: McpClient,
  1088. request: McpCallToolRequest,
  1089. timeoutMs: number,
  1090. signal: AbortSignal | undefined,
  1091. onProgress?: McpCallToolOptions["onProgress"],
  1092. ): Promise<McpToolCallResult> {
  1093. this.activeCallTraces.set(request.serverName, {
  1094. ...(request.trace?.sessionId ? { sessionId: String(request.trace.sessionId) } : {}),
  1095. ...(request.trace?.turnId ? { turnId: String(request.trace.turnId) } : {}),
  1096. ...(request.trace?.traceId ? { traceId: String(request.trace.traceId) } : {}),
  1097. });
  1098. try {
  1099. return await this.callToolOnClientInner(client, request, timeoutMs, signal, onProgress);
  1100. } finally {
  1101. this.activeCallTraces.delete(request.serverName);
  1102. }
  1103. }
  1104. private async callToolOnClientInner(
  1105. client: McpClient,
  1106. request: McpCallToolRequest,
  1107. timeoutMs: number,
  1108. signal: AbortSignal | undefined,
  1109. onProgress?: McpCallToolOptions["onProgress"],
  1110. ): Promise<McpToolCallResult> {
  1111. // 工具调用此前完全无日志:超时时既看不到预算是多少,也无法区分"服务端慢"与
  1112. // "客户端预算太小"。这里记录预算与耗时,但只记参数的 key(值可能是用户输入)。
  1113. const logBase = {
  1114. event: "mcp.tool.call",
  1115. mcpServerName: request.serverName,
  1116. mcpToolName: request.toolName,
  1117. module: "adapters.mcp",
  1118. timeoutMs,
  1119. };
  1120. const argumentKeys = Object.keys(request.arguments ?? {}).sort();
  1121. this.logger?.debug("MCP tool call started", {
  1122. ...logBase,
  1123. argumentKeys,
  1124. status: "started",
  1125. });
  1126. const startedAt = Date.now();
  1127. try {
  1128. const result = await client.callTool(
  1129. {
  1130. name: request.toolName,
  1131. arguments: request.arguments ?? {},
  1132. ...(request.trace || request.runtimeScope || request.workspaceKey || request.workspacePath
  1133. ? { _meta: mcpRequestMeta(request) }
  1134. : {}),
  1135. },
  1136. {
  1137. signal,
  1138. timeout: timeoutMs,
  1139. // 进度通知重置超时(A8):长任务只要持续上报就不会被 timeoutMs 打断;总时长由工具级 _meta.timeoutMs 约束。
  1140. resetTimeoutOnProgress: true,
  1141. ...(onProgress
  1142. ? {
  1143. onprogress: (notification: {
  1144. progress: number;
  1145. total?: number;
  1146. message?: string;
  1147. }) =>
  1148. onProgress({
  1149. progress: notification.progress,
  1150. ...(notification.total !== undefined ? { total: notification.total } : {}),
  1151. ...(notification.message !== undefined
  1152. ? { message: notification.message }
  1153. : {}),
  1154. }),
  1155. }
  1156. : {}),
  1157. },
  1158. );
  1159. const durationMs = Date.now() - startedAt;
  1160. const isError = typeof result.isError === "boolean" ? result.isError : false;
  1161. // 官方 MCP 的 in-band 失败(配额耗尽、无套餐)是 HTTP 200 + isError,wrapper 那条
  1162. // 非 2xx warn 覆盖不到;request id 也只有 wrapper 能看到,所以在这里按 span 取回。
  1163. const serverRequestId = this.takeServerRequestId(request.trace?.spanId);
  1164. const outcome = {
  1165. ...logBase,
  1166. contentBlocks: Array.isArray(result.content) ? result.content.length : 0,
  1167. durationMs,
  1168. hasStructuredContent: result.structuredContent !== undefined,
  1169. // 业务级失败(isError)与传输级失败不同,必须能分开统计。
  1170. isError,
  1171. ...(serverRequestId ? { serverRequestId } : {}),
  1172. };
  1173. if (isError) {
  1174. // 之前 in-band 失败只有这条 debug,而生产 logger 最低级别是 Info——等于配额耗尽
  1175. // 这类失败在生产日志里完全不可见。
  1176. this.logger?.warn("MCP tool returned an error", { ...outcome, status: "failed" });
  1177. } else {
  1178. this.logger?.debug("MCP tool call completed", { ...outcome, status: "completed" });
  1179. }
  1180. const meta = isRecord(result._meta) ? result._meta : undefined;
  1181. return {
  1182. content: Array.isArray(result.content)
  1183. ? (result.content as McpContentBlock[])
  1184. : [{ type: "text", text: "" }],
  1185. structuredContent: result.structuredContent,
  1186. isError: typeof result.isError === "boolean" ? result.isError : undefined,
  1187. // 只在失败时附加:成功路径上它是纯噪声。服务端已给的键一律不覆盖。
  1188. _meta:
  1189. isError && serverRequestId
  1190. ? { ...meta, [ZCODE_MCP_SERVER_REQUEST_ID_META_KEY]: serverRequestId }
  1191. : meta,
  1192. };
  1193. } catch (error) {
  1194. const durationMs = Date.now() - startedAt;
  1195. const message = error instanceof Error ? error.message : String(error);
  1196. // 判定是否为超时:SDK 超时会抛 MCP error code -32001 (RequestTimeout),
  1197. // 底层 fetch abort 抛 AbortError。两者都要能一眼认出,否则只能看到裸 message。
  1198. const timedOut =
  1199. /timed?\s*out|timeout/i.test(message) ||
  1200. (error instanceof Error && error.name === "AbortError");
  1201. // 传输级失败也带上:4xx/5xx 时 SDK 抛出的 message 里没有 request id。
  1202. const serverRequestId = this.takeServerRequestId(request.trace?.spanId);
  1203. this.logger?.warn("MCP tool call failed", {
  1204. ...logBase,
  1205. argumentKeys,
  1206. durationMs,
  1207. error: message,
  1208. ...(serverRequestId ? { serverRequestId } : {}),
  1209. errorName: error instanceof Error ? error.name : "unknown",
  1210. status: "failed",
  1211. timedOut,
  1212. // 耗时贴着预算 ⇒ 是我们掐断的;远小于预算 ⇒ 是对端或网络断的。
  1213. ...(timedOut ? { budgetExhausted: durationMs >= timeoutMs * 0.9 } : {}),
  1214. });
  1215. throw error;
  1216. }
  1217. }
  1218. private async reconnectForCall(name: string, config: McpServerConfig): Promise<void> {
  1219. this.logger?.warn("MCP server reconnecting after lost connection", {
  1220. event: "mcp.server.reconnect.started",
  1221. mcpServerName: name,
  1222. status: "started",
  1223. transport: config.type,
  1224. });
  1225. await this.connectServer(name, config);
  1226. }
  1227. /**
  1228. * 运行期认证恢复:Phase 2 交互授权 → Phase 1 重连 → 原 tool call 最多安全重试一次。
  1229. *
  1230. * 与建连期共用 `runInteractiveOAuthAuthorization`,因此单飞、fencing、caller 预算语义完全一致。
  1231. */
  1232. private async recoverToolCallAuthorization(input: {
  1233. deadline: McpDeadline;
  1234. error: unknown;
  1235. record: McpServerRecord;
  1236. request: McpCallToolRequest;
  1237. signal?: AbortSignal;
  1238. onProgress?: McpCallToolOptions["onProgress"];
  1239. timeoutMessage: string;
  1240. trigger: InteractiveAuthorizationTrigger;
  1241. }): Promise<McpToolCallResult> {
  1242. const { record, request } = input;
  1243. const config = record.config;
  1244. if (config.type === "stdio") throw input.error;
  1245. const oauthConfig = resolveAuthorizationCodeOAuthConfig(config);
  1246. if (!oauthConfig) throw input.error;
  1247. this.logger?.warn("MCP tool call requires OAuth authorization", {
  1248. event: "mcp.oauth.tool_call.authorization_required",
  1249. mcpServerName: request.serverName,
  1250. oauthTriggerReason: input.trigger.reason,
  1251. status: "started",
  1252. toolName: request.toolName,
  1253. });
  1254. const recovery = this.ensureToolCallAuthorizationRecovery({
  1255. config,
  1256. name: request.serverName,
  1257. oauthConfig,
  1258. record,
  1259. trigger: input.trigger,
  1260. });
  1261. const recoveredStatus = await waitWithinMcpDeadline(
  1262. recovery,
  1263. input.deadline,
  1264. input.timeoutMessage,
  1265. input.signal,
  1266. );
  1267. if (recoveredStatus.status !== "connected") {
  1268. throw input.error;
  1269. }
  1270. const revived = this.records.get(request.serverName);
  1271. if (!revived?.client || revived.status.status !== "connected") throw input.error;
  1272. return await this.callToolOnClient(
  1273. revived.client,
  1274. request,
  1275. remainingMcpDeadlineMs(input.deadline, input.timeoutMessage),
  1276. input.signal,
  1277. input.onProgress,
  1278. );
  1279. }
  1280. /**
  1281. * 创建或复用运行期 OAuth 恢复。完整的 Phase 2 → Phase 1 由 adapter-owned record 持有;
  1282. * tool caller 只能等待,不能用自己的 AbortSignal 终止共享事务。
  1283. */
  1284. private ensureToolCallAuthorizationRecovery(input: {
  1285. config: Extract<McpServerConfig, { type: "http" | "sse" }>;
  1286. name: string;
  1287. oauthConfig: AuthorizationCodeOAuthConfig;
  1288. record: McpServerRecord;
  1289. trigger: InteractiveAuthorizationTrigger;
  1290. }): Promise<McpServerStatus> {
  1291. const current = this.records.get(input.name);
  1292. if (
  1293. current?.connecting &&
  1294. current.status.status === "connecting" &&
  1295. isDeepStrictEqual(current.config, input.config)
  1296. ) {
  1297. return current.connecting;
  1298. }
  1299. const generation = this.nextConnectionGeneration(input.name);
  1300. const abortController = new AbortController();
  1301. const recoveryRecord: McpServerRecord = {
  1302. abortController,
  1303. config: input.config,
  1304. status: this.createStatus(input.config, "connecting", {
  1305. toolCount: input.record.tools.length,
  1306. }),
  1307. // 运行期工具已经向 core 广告;恢复期间保留 descriptor,避免设置页/借用端口误判工具消失。
  1308. tools: input.record.tools,
  1309. };
  1310. this.records.set(input.name, recoveryRecord);
  1311. const connecting = this.runToolCallAuthorizationRecovery({
  1312. abortController,
  1313. config: input.config,
  1314. generation,
  1315. name: input.name,
  1316. oauthConfig: input.oauthConfig,
  1317. previousClient: input.record.client,
  1318. previousTransport: input.record.transport,
  1319. trigger: input.trigger,
  1320. });
  1321. recoveryRecord.connecting = connecting;
  1322. return connecting;
  1323. }
  1324. private async runToolCallAuthorizationRecovery(input: {
  1325. abortController: AbortController;
  1326. config: Extract<McpServerConfig, { type: "http" | "sse" }>;
  1327. generation: number;
  1328. name: string;
  1329. oauthConfig: AuthorizationCodeOAuthConfig;
  1330. previousClient?: McpClient;
  1331. previousTransport?: McpTransport;
  1332. trigger: InteractiveAuthorizationTrigger;
  1333. }): Promise<McpServerStatus> {
  1334. const startedAt = Date.now();
  1335. try {
  1336. // 原 transport 的握手与 token 已失效,必须由共享 owner 统一退休;不能调用 connectServer,
  1337. // 否则 closeRecord 会 abort recoveryRecord 自己的 controller,形成自取消。
  1338. await this.closeClientAndTransport(input.name, input.previousClient, input.previousTransport);
  1339. const outcome = await this.runInteractiveOAuthAuthorization({
  1340. config: input.config,
  1341. generation: input.generation,
  1342. name: input.name,
  1343. oauthConfig: input.oauthConfig,
  1344. serverUrl: input.config.url,
  1345. signal: input.abortController.signal,
  1346. trigger: input.trigger,
  1347. });
  1348. if (outcome.status === "authorized" || outcome.status === "already-authorized") {
  1349. return await this.openServerConnection({
  1350. config: input.config,
  1351. generation: input.generation,
  1352. name: input.name,
  1353. oauthAuthorizationAttempted: true,
  1354. signal: input.abortController.signal,
  1355. timeoutMs: input.config.timeoutMs ?? DEFAULT_MCP_TIMEOUT_MS,
  1356. });
  1357. }
  1358. return await this.failConnection({
  1359. config: input.config,
  1360. error:
  1361. outcome.status === "pending"
  1362. ? new Error(
  1363. `MCP server ${input.name} OAuth authorization is still in progress; complete it in the browser and reconnect`,
  1364. )
  1365. : outcome.error,
  1366. failureKind: "oauth_authorization_failed",
  1367. generation: input.generation,
  1368. name: input.name,
  1369. startedAt,
  1370. });
  1371. } catch (error) {
  1372. // 防御边界:共享 recovery promise 必须是 total operation。任何未来新增的编排异常也只能
  1373. // 收敛为 failed record,不能留下 rejected connecting promise 污染后续 snapshot。
  1374. return await this.failConnection({
  1375. config: input.config,
  1376. error,
  1377. failureKind: "oauth_authorization_failed",
  1378. generation: input.generation,
  1379. name: input.name,
  1380. startedAt,
  1381. });
  1382. }
  1383. }
  1384. async close(): Promise<void> {
  1385. const startedAt = Date.now();
  1386. const serverCount = this.records.size;
  1387. for (const name of this.records.keys()) {
  1388. this.nextConnectionGeneration(name);
  1389. }
  1390. await Promise.all(Array.from(this.records.keys()).map((name) => this.closeRecord(name)));
  1391. this.records.clear();
  1392. this.connectionDiagnosticByServer.clear();
  1393. this.logger?.info("MCP adapter closed", {
  1394. durationMs: Date.now() - startedAt,
  1395. event: "mcp.adapter.closed",
  1396. serverCount,
  1397. status: "completed",
  1398. });
  1399. }
  1400. private waitForSharedConnection(
  1401. name: string,
  1402. record: McpServerRecord,
  1403. options: McpConnectOptions,
  1404. ): Promise<McpServerStatus> {
  1405. const connecting = record.connecting;
  1406. if (!connecting) return Promise.resolve(record.status);
  1407. if (options.oauthAuthorizationTimeoutMs === undefined && !options.signal) {
  1408. return connecting;
  1409. }
  1410. let abortHandler: (() => void) | undefined;
  1411. let timeoutId: ReturnType<typeof setTimeout> | undefined;
  1412. const currentStatus = () => this.records.get(name)?.status ?? record.status;
  1413. const waiters: Promise<McpServerStatus>[] = [connecting];
  1414. const timeoutMs = options.oauthAuthorizationTimeoutMs;
  1415. if (timeoutMs !== undefined) {
  1416. waiters.push(
  1417. new Promise((resolvePromise) => {
  1418. timeoutId = setTimeout(() => resolvePromise(currentStatus()), timeoutMs);
  1419. }),
  1420. );
  1421. }
  1422. if (options.signal) {
  1423. waiters.push(
  1424. new Promise((resolvePromise) => {
  1425. if (options.signal?.aborted) {
  1426. resolvePromise(currentStatus());
  1427. return;
  1428. }
  1429. abortHandler = () => resolvePromise(currentStatus());
  1430. options.signal?.addEventListener("abort", abortHandler, {
  1431. once: true,
  1432. });
  1433. }),
  1434. );
  1435. }
  1436. return Promise.race(waiters).finally(() => {
  1437. if (timeoutId !== undefined) clearTimeout(timeoutId);
  1438. if (abortHandler) options.signal?.removeEventListener("abort", abortHandler);
  1439. });
  1440. }
  1441. private async openServerConnection(input: {
  1442. config: McpServerConfig;
  1443. generation: number;
  1444. name: string;
  1445. oauthAuthorizationTimeoutMs?: number;
  1446. signal: AbortSignal;
  1447. timeoutMs: number;
  1448. workingDirectory?: string;
  1449. oauthAuthorizationAttempted?: boolean;
  1450. }): Promise<McpServerStatus> {
  1451. const {
  1452. config,
  1453. generation,
  1454. name,
  1455. oauthAuthorizationAttempted = false,
  1456. oauthAuthorizationTimeoutMs,
  1457. signal,
  1458. timeoutMs,
  1459. workingDirectory,
  1460. } = input;
  1461. const startedAt = Date.now();
  1462. let client: McpClient | undefined;
  1463. let connectDurationMs: number | undefined;
  1464. let getRecentStderr: (() => string | undefined) | undefined;
  1465. let listToolsDurationMs: number | undefined;
  1466. let transport: McpTransport | undefined;
  1467. let failureKind: McpServerFailureKind =
  1468. config.type === "stdio" ? "process_start_failed" : "network_unreachable";
  1469. try {
  1470. // 根因(MR !3089 评审 CR-02):首次 stdio 连接要先准备 node fallback(文件 IO),原先在
  1471. // createTransport 里裸等,不受连接超时与取消约束;IO 卡住时连接会一直停在 connecting。
  1472. const nodeFallback =
  1473. config.type === "stdio" && this.nodeFallback
  1474. ? await withTimeout(
  1475. this.nodeFallback.resolve(),
  1476. timeoutMs,
  1477. `MCP server ${name} node fallback preparation timed out after ${timeoutMs}ms`,
  1478. signal,
  1479. )
  1480. : undefined;
  1481. const transportBundle = await this.createTransport(
  1482. config,
  1483. name,
  1484. generation,
  1485. oauthAuthorizationTimeoutMs,
  1486. workingDirectory,
  1487. signal,
  1488. nodeFallback,
  1489. );
  1490. transport = transportBundle.transport;
  1491. getRecentStderr = this.attachStdioLogging(name, transport);
  1492. client = new Client(
  1493. {
  1494. name: this.clientName,
  1495. version: this.clientVersion,
  1496. },
  1497. {
  1498. versionNegotiation: resolveVersionNegotiation(config, timeoutMs),
  1499. capabilities: {
  1500. // MCP Apps 规范:宿主经 `extensions["io.modelcontextprotocol/ui"]` 宣告能渲染的 UI mimeType,
  1501. // 官方 SDK 的 server 据此决定是否下发 ui 资源(getUiCapability)。
  1502. ...buildMcpAppsClientCapabilities(),
  1503. // 只宣告 form 模式(url 模式不做);server 据此选择 elicitation 形态。
  1504. ...(this.elicitation ? { elicitation: { form: {} } } : {}),
  1505. },
  1506. },
  1507. );
  1508. this.installElicitationHandler(client, name);
  1509. this.installNotificationHandlers(client, name);
  1510. this.updateCurrentRecord(name, generation, {
  1511. client,
  1512. transport,
  1513. });
  1514. const connectStartedAt = Date.now();
  1515. await withTimeout(
  1516. client.connect(transport),
  1517. timeoutMs,
  1518. `MCP server ${name} connection timed out after ${timeoutMs}ms`,
  1519. signal,
  1520. );
  1521. connectDurationMs = Date.now() - connectStartedAt;
  1522. failureKind = "tool_list_failed";
  1523. const listToolsStartedAt = Date.now();
  1524. const listed = await withTimeout(
  1525. client.listTools(),
  1526. timeoutMs,
  1527. `MCP server ${name} tool listing timed out after ${timeoutMs}ms`,
  1528. signal,
  1529. );
  1530. listToolsDurationMs = Date.now() - listToolsStartedAt;
  1531. const tools = listed.tools.map((tool) =>
  1532. normalizeMcpToolDescriptor(
  1533. name,
  1534. tool,
  1535. config.timeoutMs,
  1536. // 只有 http 形态置位。这个标记的用途是**信任结果里的结构化标识**
  1537. // (额度耗尽 / 无套餐),因此判据必须是"结果由谁产出":
  1538. // - http:结果来自 ZCode 后端。fetch wrapper 对每次请求校验 origin;登录态只在
  1539. // tools/call 解析,缺失时由同一可信后端返回结构化 coding_plan_required;
  1540. // - stdio:结果由插件进程自己产出,可以任意伪造 `{"error_code":"quota_exceeded"}`,
  1541. // 从而在用户输入框上方弹出"额度用完 / 请开通 Coding Plan"的误导提示。
  1542. // 原判据是 `type !== "sse"`,把 stdio 一起放了进来,等于这道门槛在 stdio 上为零。
  1543. // 注意这不是在挡凭证外泄(那由 origin 校验负责),而是在挡**结果伪造**。
  1544. config.type === "http" && config.auth?.type === ZCODE_OFFICIAL_MCP_AUTH_TYPE,
  1545. config.alwaysLoad,
  1546. ),
  1547. );
  1548. const negotiatedProtocolEra = client.getProtocolEra();
  1549. const negotiatedProtocolVersion = client.getNegotiatedProtocolVersion();
  1550. const status = this.createStatus(config, "connected", {
  1551. protocolEra: negotiatedProtocolEra,
  1552. toolCount: tools.length,
  1553. });
  1554. if (!this.isCurrentConnection(name, generation)) {
  1555. await this.closeClientAndTransport(name, client, transport);
  1556. return this.records.get(name)?.status ?? status;
  1557. }
  1558. this.connectionDiagnosticByServer.delete(name);
  1559. this.records.set(name, {
  1560. client,
  1561. config,
  1562. status,
  1563. tools,
  1564. transport,
  1565. });
  1566. // A3:重连(同一 adapter 实例)后按登记表重放订阅;首次连接登记表为空,直接跳过。
  1567. await this.replayResourceSubscriptions(name, client);
  1568. const mcpTransportPid = getStdioTransportPid(transport);
  1569. const mcpProcessIdentity =
  1570. mcpTransportPid != null && this.connectionContext
  1571. ? this.telemetry?.recordProcessStarted({
  1572. connectionId: this.connectionContext.mcpConnectionId,
  1573. pid: mcpTransportPid,
  1574. })
  1575. : undefined;
  1576. // stdio MCP 子进程死亡(如 node_repl 被 REPL cell 的异步错误击穿)不能完全
  1577. // 静默——不记日志、状态停留在 connected,后续调用只会抛裸的 "Not connected"。
  1578. // 挂 onclose 把意外断连显式化;主动关闭路径会先清掉 onclose(见 closeClientAndTransport)。
  1579. client.onclose = () => {
  1580. if (!this.isCurrentConnection(name, generation)) return;
  1581. const current = this.records.get(name);
  1582. if (!current || current.client !== client) return;
  1583. this.nextConnectionGeneration(name);
  1584. const recentStderr = getRecentStderr?.();
  1585. const processExit = getStdioTransportExitInfo(transport);
  1586. current.status = this.createStatus(current.config, "disconnected", {
  1587. error: "MCP server connection closed unexpectedly",
  1588. failureKind: "unexpected_disconnect",
  1589. });
  1590. this.logger?.warn("MCP server connection lost", {
  1591. ...this.connectionContext,
  1592. event: "mcp.server.connection_lost",
  1593. mcpServerName: name,
  1594. ...(mcpTransportPid != null ? { mcpTransportPid } : {}),
  1595. ...(mcpProcessIdentity ?? {}),
  1596. ...(processExit
  1597. ? { exitCode: processExit.exitCode, signal: processExit.signal ?? undefined }
  1598. : {}),
  1599. status: "failed",
  1600. transport: current.config.type,
  1601. ...(recentStderr ? { stderr: recentStderr } : {}),
  1602. });
  1603. if (
  1604. current.config.type === "stdio" &&
  1605. this.connectionContext &&
  1606. (processExit || !isStdioTransportProcessAlive(transport))
  1607. ) {
  1608. this.telemetry?.recordProcessCrashed({
  1609. connectionId: this.connectionContext.mcpConnectionId,
  1610. exitCode: processExit?.exitCode ?? null,
  1611. signal: processExit?.signal ?? null,
  1612. });
  1613. }
  1614. };
  1615. // 此前连接日志只记录 transport,auto 协商后无法判断实际走 modern 还是 legacy。
  1616. // 同时记录配置策略和 SDK 握手结果,避免把 `auto` 误当成最终协议版本。
  1617. // 连接池上下文和 stdio transport PID 过去未进入同一事件,无法关联 session、
  1618. // workspace、协议版本和真实子进程;stdio PID 只代表最终会话 transport,不代表 probe child。
  1619. this.logger?.info("MCP server connected", {
  1620. ...this.connectionContext,
  1621. connectDurationMs,
  1622. durationMs: Date.now() - startedAt,
  1623. event: "mcp.server.connected",
  1624. listToolsDurationMs,
  1625. mcpClientName: this.clientName,
  1626. mcpClientVersion: this.clientVersion,
  1627. mcpProtocolEra: negotiatedProtocolEra ?? "unknown",
  1628. mcpProtocolVersion: negotiatedProtocolVersion ?? "unknown",
  1629. mcpServerName: name,
  1630. ...(mcpProcessIdentity ?? {}),
  1631. ...(mcpTransportPid != null ? { mcpTransportPid } : {}),
  1632. mcpVersionNegotiationMode: formatVersionNegotiationMode(config),
  1633. status: "completed",
  1634. toolCount: tools.length,
  1635. transport: config.type,
  1636. });
  1637. return status;
  1638. } catch (error) {
  1639. // 过去这里等的是旧 provider 自己开的 listener,且用 session 的 15 秒预算做
  1640. // 硬关闭——15 秒是 caller 的等待预算,不是授权事务的寿命。现在按错误类型判定是否需要
  1641. // 交互授权,并把授权交给 Phase 2 独立事务(独立锁、fresh DCR、300 秒事务 TTL)。
  1642. const trigger = oauthAuthorizationAttempted
  1643. ? undefined
  1644. : classifyInteractiveAuthorizationTrigger(error);
  1645. const authorizationCodeOAuthConfig =
  1646. trigger && config.type !== "stdio"
  1647. ? resolveAuthorizationCodeOAuthConfig(config)
  1648. : undefined;
  1649. if (trigger && authorizationCodeOAuthConfig && config.type !== "stdio") {
  1650. // negotiation 失败时 SDK 已关闭 transport,不可复用;Phase 2 也不需要 transport。
  1651. await this.closeClientAndTransport(name, client, transport);
  1652. const outcome = await this.runInteractiveOAuthAuthorization({
  1653. config,
  1654. generation,
  1655. name,
  1656. oauthConfig: authorizationCodeOAuthConfig,
  1657. serverUrl: config.url,
  1658. signal,
  1659. trigger,
  1660. });
  1661. if (outcome.status === "authorized" || outcome.status === "already-authorized") {
  1662. return await this.openServerConnection({
  1663. ...input,
  1664. oauthAuthorizationAttempted: true,
  1665. });
  1666. }
  1667. // client/transport 已在进入 Phase 2 前关闭,这里不再传入;failureKind 沿用
  1668. // 诊断分类,让设置页把"授权没完成"与网络/进程类失败区分开。
  1669. return this.failConnection({
  1670. config,
  1671. connectDurationMs,
  1672. error:
  1673. outcome.status === "pending"
  1674. ? new Error(
  1675. `MCP server ${name} OAuth authorization is still in progress; complete it in the browser and reconnect`,
  1676. )
  1677. : outcome.error,
  1678. failureKind: "oauth_authorization_failed",
  1679. generation,
  1680. getRecentStderr,
  1681. listToolsDurationMs,
  1682. name,
  1683. startedAt,
  1684. });
  1685. }
  1686. // `protocol_negotiation_failed` 枚举与 UI 文案在 shared/i18n 里早已存在,但 adapter
  1687. // 侧一直没有产出方——auto/pin 模式下 SDK 的 server/discover probe 硬失败(典型:飞书项目
  1688. // MCP 对未知方法回 HTTP 200 + id:null 的非标 JSON-RPC error,body 过不了
  1689. // JSONRPCMessageSchema)会一路落到默认 failureKind "network_unreachable",设置页因此
  1690. // 显示误导性的"网络不可达"。这里按结构化错误类型(SdkErrorCode / isInstance)识别 SDK
  1691. // 协商失败并产出正确分类,不依赖错误文本;withTimeout 不包装错误(timeout.ts 只透传
  1692. // reject),cause 链仅作防御性兜底。
  1693. const negotiationFailureKind = isProtocolNegotiationFailure(error)
  1694. ? ("protocol_negotiation_failed" as const)
  1695. : undefined;
  1696. return this.failConnection({
  1697. client,
  1698. config,
  1699. connectDurationMs,
  1700. error,
  1701. generation,
  1702. getRecentStderr,
  1703. listToolsDurationMs,
  1704. name,
  1705. startedAt,
  1706. transport,
  1707. failureKind: negotiationFailureKind ?? failureKind,
  1708. });
  1709. }
  1710. }
  1711. /**
  1712. * Phase 2:交互授权。
  1713. *
  1714. * 授权事务的寿命是 300 秒,与 caller 的等待预算(session 15 秒)无关;caller 侧的收口发生在
  1715. * `connectServer` / `waitForSharedConnection`,本方法不感知 caller 预算。
  1716. */
  1717. private async runInteractiveOAuthAuthorization(input: {
  1718. config: Extract<McpServerConfig, { type: "http" | "sse" }>;
  1719. generation: number;
  1720. name: string;
  1721. oauthConfig: AuthorizationCodeOAuthConfig;
  1722. serverUrl: string;
  1723. signal: AbortSignal;
  1724. trigger: InteractiveAuthorizationTrigger;
  1725. }): Promise<McpInteractiveAuthorizationOutcome> {
  1726. try {
  1727. const oauthOptions = this.createAuthorizationCodeOAuthOptions(
  1728. input.config,
  1729. input.name,
  1730. input.generation,
  1731. );
  1732. const credentialStore = oauthOptions?.credentialStore ?? createSharedZCodeCredentialStore();
  1733. const keyPrefix = createCredentialKeyPrefix(input.name, input.serverUrl, input.oauthConfig);
  1734. // 403 step-up 的最终 scope 必须是 config ∪ token.scope ∪ challenge
  1735. // 的并集。只带 challenge scope 重新授权时,授权服务器可能按新请求收回先前授予的 scope,
  1736. // 下一个请求换个 challenge 又 403,形成重授权乒乓。token response 的 scope 允许缺失
  1737. // (RFC 6749 §3.3),所以配置里声明过的 scope 必须显式并入,不能只看 token 回显。
  1738. let requestedScope: string | undefined = input.oauthConfig.scope;
  1739. if (input.trigger.requiredScope) {
  1740. const currentPair = await loadCredentialPair(credentialStore, keyPrefix);
  1741. requestedScope = computeScopeUnion(
  1742. input.oauthConfig.scope,
  1743. currentPair?.tokens?.scope,
  1744. input.trigger.requiredScope,
  1745. );
  1746. }
  1747. return await runMcpInteractiveAuthorization({
  1748. adapterInstanceId: this.adapterInstanceId,
  1749. config: input.oauthConfig,
  1750. credentialStore,
  1751. fetchFn: createMcpTransportFetch({ env: this.env, network: this.network }),
  1752. // 403 step-up:requiredScope 是当前 token scope 的严格超集时 refresh 无法扩权
  1753. // (RFC 6749 §6),必须强制重新授权,否则新 scope 会被静默丢弃并再次 403。
  1754. ...(input.trigger.reason === "insufficient_scope" ? { forceReauthorization: true } : {}),
  1755. keyPrefix,
  1756. logger: this.logger,
  1757. ...(oauthOptions?.onAuthorizationRequired
  1758. ? { onAuthorizationRequired: oauthOptions.onAuthorizationRequired }
  1759. : {}),
  1760. ...(oauthOptions?.openAuthorizationUrl
  1761. ? { openAuthorizationUrl: oauthOptions.openAuthorizationUrl }
  1762. : {}),
  1763. ...(requestedScope ? { requestedScope } : {}),
  1764. ...(input.trigger.resourceMetadataUrl
  1765. ? { resourceMetadataUrl: new URL(input.trigger.resourceMetadataUrl) }
  1766. : {}),
  1767. serverName: input.name,
  1768. serverUrl: input.serverUrl,
  1769. signal: input.signal,
  1770. transactionTtlMs: MCP_OAUTH_AUTHORIZATION_TRANSACTION_TTL_MS,
  1771. });
  1772. } catch (error) {
  1773. // 本方法的返回类型已经把编排失败建模为 outcome。过去 credential load、
  1774. // authz lease 或 follower callback 的异常会裸 reject,绕过 failConnection,留下
  1775. // status=connecting + rejected record.connecting,并让 connectConfiguredServers 整批失败。
  1776. this.logger?.warn("MCP OAuth authorization orchestration failed", {
  1777. error: error instanceof Error ? error.message : String(error),
  1778. errorName: error instanceof Error ? error.name : "unknown",
  1779. event: "mcp.oauth.authorization.orchestration_failed",
  1780. mcpServerName: input.name,
  1781. status: "failed",
  1782. });
  1783. return { status: "failed", error };
  1784. }
  1785. }
  1786. private async failConnection(input: {
  1787. client?: McpClient;
  1788. config: McpServerConfig;
  1789. connectDurationMs?: number;
  1790. error: unknown;
  1791. failureKind?: McpServerFailureKind;
  1792. generation: number;
  1793. getRecentStderr?: () => string | undefined;
  1794. listToolsDurationMs?: number;
  1795. name: string;
  1796. startedAt: number;
  1797. transport?: McpTransport;
  1798. }): Promise<McpServerStatus> {
  1799. const {
  1800. client,
  1801. config,
  1802. connectDurationMs,
  1803. error,
  1804. failureKind: fallbackFailureKind,
  1805. generation,
  1806. getRecentStderr,
  1807. listToolsDurationMs,
  1808. name,
  1809. startedAt,
  1810. transport,
  1811. } = input;
  1812. const message = error instanceof Error ? error.message : String(error);
  1813. // 官方 MCP 鉴权失败的稳定分类必须落进日志:failConnection 原先只记
  1814. // error.message,而多数分类并不出现在 message 文本里(只有 auth-port 那条带上了),
  1815. // 导致 official_mcp_origin_untrusted / official_auth_rejected 等在生产日志里 grep 不到。
  1816. const officialAuthKind =
  1817. (error instanceof OfficialMcpAuthError ? error.kind : undefined) ??
  1818. this.lastOfficialAuthKind.get(name);
  1819. this.lastOfficialAuthKind.delete(name);
  1820. const responseDiagnostic = this.connectionDiagnosticByServer.get(name);
  1821. this.connectionDiagnosticByServer.delete(name);
  1822. const failureKind =
  1823. (officialAuthKind === "official_mcp_origin_untrusted"
  1824. ? "official_origin_untrusted"
  1825. : undefined) ??
  1826. responseDiagnostic?.failureKind ??
  1827. (error instanceof McpTimeoutError && fallbackFailureKind !== "tool_list_failed"
  1828. ? "connection_timeout"
  1829. : undefined) ??
  1830. fallbackFailureKind ??
  1831. "connection_failed";
  1832. const displayMessage = responseDiagnostic?.serverRequestId
  1833. ? `${message} - ${responseDiagnostic.serverRequestId}`
  1834. : message;
  1835. const recentStderr = getRecentStderr?.();
  1836. // 子进程缺依赖等错误只写 stderr,SDK 通常只返回 Connection closed。
  1837. // 把同一次连接的脱敏诊断带给设置页;只展示证据,不按错误文本改变失败分类或重试。
  1838. const statusMessage =
  1839. config.type === "stdio"
  1840. ? [
  1841. sanitizeMcpStdioStderr(displayMessage).slice(0, MCP_STDIO_ERROR_MESSAGE_MAX_CHARS),
  1842. recentStderr,
  1843. ]
  1844. .filter(Boolean)
  1845. .join("\n\n")
  1846. : displayMessage;
  1847. const status = this.createStatus(config, "failed", {
  1848. error: statusMessage,
  1849. failureKind,
  1850. ...(responseDiagnostic?.serverRequestId
  1851. ? { serverRequestId: responseDiagnostic.serverRequestId }
  1852. : {}),
  1853. });
  1854. const mcpTransportPid = getStdioTransportPid(transport);
  1855. await this.closeClientAndTransport(name, client, transport);
  1856. if (!this.isCurrentConnection(name, generation)) {
  1857. return this.records.get(name)?.status ?? status;
  1858. }
  1859. this.records.set(name, { config, status, tools: [] });
  1860. this.logger?.warn("MCP server connection failed", {
  1861. ...this.connectionContext,
  1862. connectDurationMs,
  1863. durationMs: Date.now() - startedAt,
  1864. error: displayMessage,
  1865. event: "mcp.server.failed",
  1866. listToolsDurationMs,
  1867. mcpServerName: name,
  1868. ...(officialAuthKind ? { officialAuthKind } : {}),
  1869. ...(mcpTransportPid != null ? { mcpTransportPid } : {}),
  1870. status: "failed",
  1871. ...(recentStderr ? { stderr: recentStderr } : {}),
  1872. transport: config.type,
  1873. });
  1874. return status;
  1875. }
  1876. private async createTransport(
  1877. config: McpServerConfig,
  1878. serverName: string,
  1879. generation: number,
  1880. _oauthAuthorizationTimeoutMs?: number,
  1881. workingDirectory?: string,
  1882. signal?: AbortSignal,
  1883. nodeFallback?: McpNodeFallback,
  1884. ): Promise<{ transport: McpTransport }> {
  1885. if (config.type === "stdio") {
  1886. return {
  1887. transport: new ProcessTreeStdioClientTransport({
  1888. command: config.command,
  1889. args: config.args ?? [],
  1890. cwd: config.cwd
  1891. ? resolve(workingDirectory ?? this.workingDirectory ?? process.cwd(), config.cwd)
  1892. : (workingDirectory ?? this.workingDirectory),
  1893. // fallback 在 server env 之后合并:插件自带 PATH 时 shim 目录仍追加在末尾。
  1894. env: applyMcpNodeFallbackEnv(
  1895. {
  1896. ...buildMcpStdioEnv({ env: this.env, network: this.network }),
  1897. ...config.env,
  1898. },
  1899. nodeFallback,
  1900. ),
  1901. stderr: "pipe",
  1902. ...(isOfficialAuthConfig(config) && config.official
  1903. ? {
  1904. requestMetaProvider: async () => {
  1905. const authMeta = await this.resolveOfficialStdioAuthMeta(
  1906. serverName,
  1907. config,
  1908. signal,
  1909. );
  1910. return authMeta ? { [OFFICIAL_MCP_AUTH_META_KEY]: authMeta } : undefined;
  1911. },
  1912. }
  1913. : {}),
  1914. }),
  1915. };
  1916. }
  1917. const fetch = createMcpTransportFetch({
  1918. env: this.env,
  1919. network: this.network,
  1920. });
  1921. if (config.type === "http") {
  1922. const officialAuthFetch = this.createOfficialAuthFetch(config, serverName, generation);
  1923. return {
  1924. transport: new StreamableHTTPClientTransport(new URL(config.url), {
  1925. // 官方鉴权路径下 authProvider 必为 undefined:不落 OAuth 凭据、
  1926. // 不起 localhost 回调 server、401/403 不转授权流程。
  1927. authProvider: this.createOAuthClientProvider(serverName, config),
  1928. fetch: officialAuthFetch ?? fetch,
  1929. requestInit: config.headers ? { headers: config.headers } : undefined,
  1930. }),
  1931. };
  1932. }
  1933. return {
  1934. transport: new SSEClientTransport(new URL(config.url), {
  1935. authProvider: this.createOAuthClientProvider(serverName, config),
  1936. fetch,
  1937. requestInit: config.headers ? { headers: config.headers } : undefined,
  1938. }),
  1939. };
  1940. }
  1941. /**
  1942. * 官方鉴权 MCP 的动态 fetch。返回 undefined 表示走普通 MCP 路径。
  1943. *
  1944. * trusted origin 依赖缺失时直接 fail closed。auth port 可以缺失:wrapper 仍校验 origin,
  1945. * 各请求匿名降级并由服务端做权威判定。
  1946. */
  1947. private createOfficialAuthFetch(
  1948. config: McpServerConfig,
  1949. serverName: string,
  1950. generation: number,
  1951. ): typeof globalThis.fetch | undefined {
  1952. if (!isOfficialAuthConfig(config) || config.type !== "http" || !config.official) {
  1953. return undefined;
  1954. }
  1955. const official = config.official;
  1956. const authHeadersPort = this.officialMcpAuth?.authHeadersPort;
  1957. const trustedOrigins = this.officialMcpAuth?.trustedOrigins;
  1958. if (!trustedOrigins) {
  1959. return (() => {
  1960. throw new OfficialMcpAuthError(
  1961. "official_auth_unavailable",
  1962. `official MCP trusted origin registry is not available in this runtime: ${serverName}`,
  1963. );
  1964. }) as unknown as typeof globalThis.fetch;
  1965. }
  1966. return createOfficialMcpAuthFetch({
  1967. baseFetch: createMcpTransportFetch({ env: this.env, network: this.network }),
  1968. official,
  1969. onAuthFailure: (kind) => this.lastOfficialAuthKind.set(serverName, kind),
  1970. onServerResponse: (response) => {
  1971. if (this.isCurrentConnection(serverName, generation)) {
  1972. this.rememberServerResponse(serverName, response);
  1973. }
  1974. },
  1975. serverName,
  1976. trustedOrigins,
  1977. url: config.url,
  1978. ...(authHeadersPort ? { authHeadersPort } : {}),
  1979. ...(this.logger ? { logger: this.logger } : {}),
  1980. ...(this.officialMcpAuth?.workspaceIdentity
  1981. ? { workspaceIdentity: this.officialMcpAuth.workspaceIdentity }
  1982. : {}),
  1983. ...(this.workingDirectory ? { workspacePath: this.workingDirectory } : {}),
  1984. });
  1985. }
  1986. /**
  1987. * 运行期 auth provider。
  1988. *
  1989. * 过去这里对任何没有 Authorization header 的 HTTP/SSE MCP
  1990. * 都创建一个完整 OAuth session——而 session 在返回前就 `listen(0)` 起了一个 callback server,
  1991. * 即使凭据完全有效、根本不需要授权。同时完整 `OAuthClientProvider` 会让 401 走 SDK 的
  1992. * `auth()`,绕过我们的 refresh 单飞锁。
  1993. *
  1994. * 现在 authorization_code 一律使用纯 AuthProvider:被动连接零 listener、零 discovery、零 DCR,
  1995. * 交互授权只在 Phase 2 事务里发生。
  1996. */
  1997. private createOAuthClientProvider(
  1998. serverName: string,
  1999. config: McpServerConfig,
  2000. ): AuthProvider | OAuthClientProvider | undefined {
  2001. if (config.type === "stdio") return undefined;
  2002. // 官方鉴权与 OAuth 互斥:官方 MCP 的失败只能由 ZCode 登录/套餐解决,
  2003. // 交出任何 authProvider 都会让 401 误转成 MCP 授权流程。
  2004. if (isOfficialAuthConfig(config)) return undefined;
  2005. const authorizationCodeOAuthConfig = resolveAuthorizationCodeOAuthConfig(config);
  2006. if (authorizationCodeOAuthConfig) {
  2007. return createMcpOAuthTokenProvider({
  2008. config: authorizationCodeOAuthConfig,
  2009. credentialStore: this.resolveCredentialStore(),
  2010. fetchFn: createMcpTransportFetch({ env: this.env, network: this.network }),
  2011. keyPrefix: createCredentialKeyPrefix(serverName, config.url, authorizationCodeOAuthConfig),
  2012. ...(this.logger ? { logger: this.logger } : {}),
  2013. serverName,
  2014. serverUrl: config.url,
  2015. });
  2016. }
  2017. if (config.oauth?.type === "client_credentials") {
  2018. return new ClientCredentialsProvider({
  2019. clientId: config.oauth.clientId,
  2020. clientName: config.oauth.clientName ?? `${this.clientName}-${serverName}`,
  2021. clientSecret: config.oauth.clientSecret,
  2022. scope: config.oauth.scope,
  2023. });
  2024. }
  2025. return undefined;
  2026. }
  2027. private resolveCredentialStore(): SharedZCodeCredentialStore {
  2028. this.credentialStore ??= this.mcpOAuth?.credentialStore ?? createSharedZCodeCredentialStore();
  2029. return this.credentialStore;
  2030. }
  2031. private createAuthorizationCodeOAuthOptions(
  2032. config: McpServerConfig,
  2033. serverName: string,
  2034. generation: number,
  2035. oauthAuthorizationTimeoutMs?: number,
  2036. ): McpOAuthRuntimeOptions | undefined {
  2037. if (config.type === "stdio") return this.mcpOAuth;
  2038. return {
  2039. ...this.mcpOAuth,
  2040. authorizationTimeoutMs: oauthAuthorizationTimeoutMs ?? this.mcpOAuth?.authorizationTimeoutMs,
  2041. onAuthorizationRequired: async (context) => {
  2042. this.updateCurrentRecordStatus(serverName, generation, {
  2043. authorization: createOAuthAuthorizationStatus(context),
  2044. status: "connecting",
  2045. });
  2046. await this.mcpOAuth?.onAuthorizationRequired?.(context);
  2047. },
  2048. };
  2049. }
  2050. private attachStdioLogging(name: string, transport: McpTransport): () => string | undefined {
  2051. const stderrBuffer = createBoundedTextBuffer(MCP_STDIO_STDERR_LOG_MAX_CHARS);
  2052. const stderr = (
  2053. transport as {
  2054. stderr?: { on(event: "data", handler: (chunk: Buffer) => void): void };
  2055. }
  2056. ).stderr;
  2057. stderr?.on("data", (chunk) => {
  2058. const text = chunk.toString("utf8");
  2059. stderrBuffer.append(text);
  2060. this.logger?.debug("MCP stdio stderr", {
  2061. event: "mcp.stdio.stderr",
  2062. mcpServerName: name,
  2063. stderr: sanitizeMcpStdioStderr(text).slice(0, MCP_STDIO_STDERR_LOG_MAX_CHARS),
  2064. });
  2065. });
  2066. return () => {
  2067. const text = stderrBuffer.read();
  2068. if (!text) return undefined;
  2069. // 生产日志里单独的 Connection closed 无法定位 stdio MCP 子进程退出原因。
  2070. // 只在失败事件附带尾部 stderr,并先脱敏,避免把凭据或高频输出写入生产日志。
  2071. return sanitizeMcpStdioStderr(text).slice(-MCP_STDIO_STDERR_LOG_MAX_CHARS);
  2072. };
  2073. }
  2074. private async closeRecord(name: string): Promise<void> {
  2075. const record = this.records.get(name);
  2076. if (!record) return;
  2077. record.abortController?.abort(new Error(`MCP server ${name} connection closed`));
  2078. if (!record.client && !record.transport) return;
  2079. await this.closeClientAndTransport(name, record.client, record.transport);
  2080. }
  2081. private async closeClientAndTransport(
  2082. name: string,
  2083. client?: McpClient,
  2084. transport?: McpTransport,
  2085. ): Promise<void> {
  2086. const startedAt = Date.now();
  2087. const mcpTransportPid = getStdioTransportPid(transport);
  2088. // 主动关闭前先摘掉 connection_lost 监听,避免正常回收被误报为意外断连。
  2089. if (client) client.onclose = undefined;
  2090. // MCP SDK close 只保证直接 stdio 子进程退出,npx/npm wrapper 拉起的 MCP server
  2091. // 或 chrome-devtools-mcp watchdog 可能残留;这里先按进程树显式回收,再走 SDK close 清理协议状态。
  2092. await this.terminateStdioProcessTree(name, transport);
  2093. try {
  2094. await client?.close();
  2095. } catch (error) {
  2096. this.logger?.debug("MCP client close failed", {
  2097. error: error instanceof Error ? error.message : String(error),
  2098. event: "mcp.client.close.failed",
  2099. mcpServerName: name,
  2100. });
  2101. }
  2102. try {
  2103. await transport?.close();
  2104. } catch (error) {
  2105. this.logger?.debug("MCP transport close failed", {
  2106. error: error instanceof Error ? error.message : String(error),
  2107. event: "mcp.transport.close.failed",
  2108. mcpServerName: name,
  2109. });
  2110. }
  2111. if (
  2112. this.connectionContext &&
  2113. transport instanceof ProcessTreeStdioClientTransport &&
  2114. !transport.processAlive
  2115. ) {
  2116. this.telemetry?.recordProcessClosed({
  2117. connectionId: this.connectionContext.mcpConnectionId,
  2118. });
  2119. }
  2120. this.logger?.info("MCP server closed", {
  2121. ...this.connectionContext,
  2122. durationMs: Date.now() - startedAt,
  2123. event: "mcp.server.closed",
  2124. mcpServerName: name,
  2125. ...(mcpTransportPid != null ? { mcpTransportPid } : {}),
  2126. status: "completed",
  2127. });
  2128. }
  2129. private async terminateStdioProcessTree(name: string, transport?: McpTransport): Promise<void> {
  2130. const pid = getStdioTransportPid(transport);
  2131. if (pid == null) return;
  2132. try {
  2133. await terminateMcpStdioProcessTree(pid);
  2134. } catch (error) {
  2135. this.logger?.warn("MCP stdio process tree cleanup failed", {
  2136. ...this.connectionContext,
  2137. error: error instanceof Error ? error.message : String(error),
  2138. event: "mcp.stdio.process_tree_cleanup.failed",
  2139. mcpServerName: name,
  2140. mcpTransportPid: pid,
  2141. pid,
  2142. status: "failed",
  2143. });
  2144. }
  2145. }
  2146. private readonly appConnectionListeners = new Map<string, Set<() => void>>();
  2147. onAppConnectionInvalidated(name: string, listener: () => void): () => void {
  2148. const listeners = this.appConnectionListeners.get(name) ?? new Set();
  2149. listeners.add(listener);
  2150. this.appConnectionListeners.set(name, listeners);
  2151. return () => {
  2152. listeners.delete(listener);
  2153. if (!listeners.size) this.appConnectionListeners.delete(name);
  2154. };
  2155. }
  2156. async waitForAppConnection(
  2157. name: string,
  2158. ): Promise<{ identity: string; generation: number } | null> {
  2159. const record = this.records.get(name);
  2160. if (!record) return null;
  2161. const generation = this.connectionGenerations.get(name) ?? 0;
  2162. // 会话恢复先于 MCP 握手完成;复用已有连接任务,避免首次打开把 connecting 误判为失败。
  2163. await record.connecting;
  2164. return this.isCurrentConnection(name, generation) ? this.appConnectionSnapshot(name) : null;
  2165. }
  2166. appConnectionSnapshot(name: string): { identity: string; generation: number } | null {
  2167. const record = this.records.get(name);
  2168. if (!record?.client || record.status.status !== "connected") return null;
  2169. // 只向宿主输出摘要;配置中的凭据不进入协议或日志。属性排序避免配置序列化次序造成换源。
  2170. const canonical = (value: unknown): unknown => {
  2171. if (Array.isArray(value)) return value.map(canonical);
  2172. if (value && typeof value === "object")
  2173. return Object.fromEntries(
  2174. Object.entries(value)
  2175. .sort(([a], [b]) => a.localeCompare(b))
  2176. .map(([k, v]) => [k, canonical(v)]),
  2177. );
  2178. return value;
  2179. };
  2180. return {
  2181. identity: createHash("sha256")
  2182. .update(
  2183. JSON.stringify([
  2184. process.platform,
  2185. process.execPath,
  2186. this.workingDirectory ?? "",
  2187. name,
  2188. canonical(record.config),
  2189. ]),
  2190. )
  2191. .digest("hex"),
  2192. generation: this.connectionGenerations.get(name) ?? 0,
  2193. };
  2194. }
  2195. private nextConnectionGeneration(name: string): number {
  2196. const generation = (this.connectionGenerations.get(name) ?? 0) + 1;
  2197. this.connectionGenerations.set(name, generation);
  2198. // eslint-disable-next-line unicorn/no-useless-spread -- 回调可能增删监听器,本次通知必须固定接收者。
  2199. for (const listener of [...(this.appConnectionListeners.get(name) ?? [])]) listener();
  2200. return generation;
  2201. }
  2202. private isCurrentConnection(name: string, generation: number): boolean {
  2203. return this.connectionGenerations.get(name) === generation;
  2204. }
  2205. private updateCurrentRecord(
  2206. name: string,
  2207. generation: number,
  2208. patch: Partial<Pick<McpServerRecord, "client" | "transport">>,
  2209. ): void {
  2210. if (!this.isCurrentConnection(name, generation)) return;
  2211. const record = this.records.get(name);
  2212. if (!record) return;
  2213. Object.assign(record, patch);
  2214. }
  2215. private updateCurrentRecordStatus(
  2216. name: string,
  2217. generation: number,
  2218. patch: Partial<McpServerStatus>,
  2219. ): void {
  2220. if (!this.isCurrentConnection(name, generation)) return;
  2221. const record = this.records.get(name);
  2222. if (!record) return;
  2223. record.status = {
  2224. ...record.status,
  2225. ...patch,
  2226. updatedAt: new Date().toISOString(),
  2227. };
  2228. }
  2229. private createStatus(
  2230. config: McpServerConfig,
  2231. status: McpServerStatus["status"],
  2232. extra: {
  2233. authorization?: McpServerStatus["authorization"];
  2234. error?: string;
  2235. failureKind?: McpServerStatus["failureKind"];
  2236. protocolEra?: McpServerStatus["protocolEra"];
  2237. serverRequestId?: string;
  2238. toolCount?: number;
  2239. } = {},
  2240. ): McpServerStatus {
  2241. return {
  2242. status,
  2243. transport: config.type,
  2244. toolCount: extra.toolCount ?? 0,
  2245. updatedAt: new Date().toISOString(),
  2246. authorization: extra.authorization,
  2247. error: extra.error,
  2248. failureKind: extra.failureKind,
  2249. protocolEra: extra.protocolEra,
  2250. serverRequestId: extra.serverRequestId,
  2251. };
  2252. }
  2253. }
  2254. function mcpRequestMeta(request: McpCallToolRequest): Record<string, unknown> {
  2255. // nodeRepl.requestMeta 暴露。ZCode 所有 MCP server 都可忽略这些扩展键;node_repl browser
  2256. // bridge 则以它们作为回到当前 BrowserControlPort session 的唯一关联依据。runtime_scope
  2257. // 不能从 child session id 猜测,必须由实际执行工具的 runtime 显式透传。
  2258. const requestContext = {
  2259. ...(request.trace ? { trace_id: request.trace.traceId } : {}),
  2260. ...(request.trace?.spanId ? { span_id: request.trace.spanId } : {}),
  2261. ...(request.trace?.parentSpanId ? { parent_span_id: request.trace.parentSpanId } : {}),
  2262. ...(request.trace?.sessionId ? { session_id: request.trace.sessionId } : {}),
  2263. // subagent / 工作流子代理的调用带上派生它的顶层 session,工作区共享的 server 据此
  2264. // 让子代理与父 session 共用状态(文档插件查看面板 spec §8.2)。
  2265. ...(request.trace?.rootSessionId ? { root_session_id: request.trace.rootSessionId } : {}),
  2266. ...(request.trace?.turnId ? { turn_id: request.trace.turnId } : {}),
  2267. ...(request.runtimeScope ? { runtime_scope: request.runtimeScope } : {}),
  2268. ...(request.workspacePath ? { workspace_path: request.workspacePath } : {}),
  2269. ...(request.workspaceIdentity ? { workspace_identity: request.workspaceIdentity } : {}),
  2270. ...(request.workspaceKey ? { workspace_key: request.workspaceKey } : {}),
  2271. ...(request.remoteSessionId ? { remote_session_id: request.remoteSessionId } : {}),
  2272. ...(request.clientMode ? { client_mode: request.clientMode } : {}),
  2273. ...(request.deliveryKind ? { delivery_kind: request.deliveryKind } : {}),
  2274. ...(request.turnId && !request.trace?.turnId ? { turn_id: request.turnId } : {}),
  2275. };
  2276. return {
  2277. ...requestContext,
  2278. "com.zcode/request-context": requestContext,
  2279. };
  2280. }
  2281. function resolveVersionNegotiationMode(config: McpServerConfig): VersionNegotiationMode {
  2282. if (config.protocolVersion === "2026-07-28") return { pin: "2026-07-28" };
  2283. // deprecated SSE transport 本身只承载 legacy era;显式 modern pin 仍应失败而不能静默降级。
  2284. if (config.type === "sse") return "legacy";
  2285. if (config.protocolVersion === "legacy") return "legacy";
  2286. return "auto";
  2287. }
  2288. /**
  2289. * SDK 版本协商(auto/pin 的 server/discover probe)失败的稳定识别。
  2290. *
  2291. * 结构化判定,禁止匹配错误文本:
  2292. * - `SdkError(SdkErrorCode.EraNegotiationFailed)`:probe 硬失败(含非标 legacy server 的
  2293. * malformed 200 响应,经 transport 层 Zod 校验失败 + normalizeReply 落入 network-error 分支);
  2294. * - `UnsupportedProtocolVersionError`:recognized modern error,pin 版本不被 server 接受。
  2295. */
  2296. function isProtocolNegotiationFailure(error: unknown): boolean {
  2297. if (SdkError.isInstance(error) && error.code === SdkErrorCode.EraNegotiationFailed) {
  2298. return true;
  2299. }
  2300. if (UnsupportedProtocolVersionError.isInstance(error)) return true;
  2301. const cause = (error as { cause?: unknown } | undefined)?.cause;
  2302. if (cause !== undefined && cause !== error) {
  2303. return isProtocolNegotiationFailure(cause);
  2304. }
  2305. return false;
  2306. }
  2307. function formatVersionNegotiationMode(config: McpServerConfig): string {
  2308. const mode = resolveVersionNegotiationMode(config);
  2309. return typeof mode === "object" ? mode.pin : mode;
  2310. }
  2311. function resolveVersionNegotiation(
  2312. config: McpServerConfig,
  2313. timeoutMs: number,
  2314. ): VersionNegotiationOptions {
  2315. const mode = resolveVersionNegotiationMode(config);
  2316. if (mode === "legacy") return { mode };
  2317. // pin 没有 legacy fallback,probe 就是唯一 initialize 路径;沿用 auto 的 5 秒
  2318. // 保护上限会无视 server 的长连接预算,把冷启动正常但超过 5 秒的 node_repl 静默移出工具池。
  2319. const probeTimeoutMs =
  2320. typeof mode === "object"
  2321. ? Math.max(1, Math.floor(timeoutMs))
  2322. : Math.min(MAX_MCP_VERSION_PROBE_TIMEOUT_MS, Math.max(1, Math.floor(timeoutMs / 2)));
  2323. return {
  2324. mode,
  2325. probe: {
  2326. // 原因:SDK 的 stdio auto/pin 会先启动 disposable sibling;若沿用 SDK 60s 默认值,
  2327. // ZCode 的总连接超时可能先结束并让 probe 残留,也不给 legacy initialize 留预算。
  2328. timeoutMs: probeTimeoutMs,
  2329. },
  2330. };
  2331. }
  2332. function createOAuthAuthorizationStatus(
  2333. context: McpOAuthAuthorizationContext,
  2334. ): NonNullable<McpServerStatus["authorization"]> {
  2335. return {
  2336. type: "oauth_authorization_code",
  2337. authorizationUrl: context.authorizationUrl,
  2338. startedAt: new Date().toISOString(),
  2339. };
  2340. }
  2341. function resolveAuthorizationCodeOAuthConfig(
  2342. config: McpServerConfig,
  2343. ): AuthorizationCodeOAuthConfig | undefined {
  2344. if (config.type === "stdio") return undefined;
  2345. // 官方鉴权与 MCP OAuth 互斥。必须位于所有既有分支之前:
  2346. // 官方 MCP 既不写 oauth 字段、又禁止静态 authorization 头,若不在此短路就会落进
  2347. // 下面的 authorization_code 兜底,导致 401 时弹出 MCP 授权 UI —— 而官方鉴权失败
  2348. // 只能由 ZCode 自身的登录/套餐解决,不可能由目标 MCP 的 OAuth 授权解决。
  2349. if (isOfficialAuthConfig(config)) return undefined;
  2350. if (config.oauth?.type === "authorization_code") return config.oauth;
  2351. if (config.oauth?.type === "client_credentials") return undefined;
  2352. if (hasAuthorizationHeader(config.headers)) return undefined;
  2353. // 新建 HTTP/SSE MCP 常只保存 URL;OAuth 支持应由服务端
  2354. // WWW-Authenticate / discovery 触发,不能要求配置里预先写 oauth 字段。
  2355. return {
  2356. type: "authorization_code",
  2357. };
  2358. }
  2359. /**
  2360. * auth.type/provider 精确命中且 provenance 存在时为真;provenance 缺失说明不是 Plugin loader
  2361. * 产出的配置。
  2362. *
  2363. * 覆盖 http 与 stdio 两种形态——两者的凭证投递通道不同,但"是否官方鉴权"
  2364. * 的判定同源。调用方若只关心某一形态,需自行再判 `config.type`(如 createOfficialAuthFetch
  2365. * 只处理 http、_meta 注入只处理 stdio)。
  2366. */
  2367. function isOfficialAuthConfig(config: McpServerConfig): boolean {
  2368. return (
  2369. (config.type === "http" || config.type === "stdio") &&
  2370. config.auth?.type === "zcode_official" &&
  2371. config.auth.provider === "jwt_token" &&
  2372. config.official !== undefined
  2373. );
  2374. }
  2375. function hasAuthorizationHeader(headers: Record<string, string> | undefined): boolean {
  2376. if (!headers) return false;
  2377. return Object.keys(headers).some((name) => name.toLowerCase() === "authorization");
  2378. }
  2379. function createBoundedTextBuffer(maxChars: number): {
  2380. append(text: string): void;
  2381. read(): string;
  2382. } {
  2383. let value = "";
  2384. return {
  2385. append(text: string) {
  2386. if (!text) return;
  2387. value = `${value}${text}`;
  2388. if (value.length > maxChars) {
  2389. value = value.slice(-maxChars);
  2390. }
  2391. },
  2392. read() {
  2393. return value;
  2394. },
  2395. };
  2396. }
  2397. function sanitizeMcpStdioStderr(text: string): string {
  2398. text = stripVTControlCharacters(text);
  2399. // 插件常给敏感环境变量加前缀,例如 API_TOKEN、VE_SPEECH_MCP_TOKEN,不能只匹配裸 token。
  2400. const sensitiveKey = String.raw`(?:[a-z0-9_.-]*[_-])?(?:api[_-]?key|access[_-]?key|secret(?:[_-]?key)?|private[_-]?key|token|password|passwd|pass|mysql_pass|mysql_password)`;
  2401. let result = text.replace(/(bearer\s+)[^\s"']+/gi, "$1[Redacted]");
  2402. result = result.replace(
  2403. /(\bauthorization\b\s*[:=]\s*)(bearer\s+)?[^\r\n]+/gi,
  2404. (_match, prefix: string, bearer: string | undefined) =>
  2405. `${prefix}${bearer ? "Bearer " : ""}[Redacted]`,
  2406. );
  2407. result = result.replace(new RegExp(`([?&]${sensitiveKey}=)[^&\\s]+`, "gi"), "$1[Redacted]");
  2408. // 引号中的凭证可能包含空格或转义引号,必须整体替换,不能只遮住第一个词。
  2409. const quotedValue = String.raw`(["'])(?:\\.|(?!\2)[^\\\r\n])*\2`;
  2410. result = result.replace(
  2411. new RegExp(String.raw`(["']${sensitiveKey}["']\s*:\s*)${quotedValue}`, "gi"),
  2412. "$1$2[Redacted]$2",
  2413. );
  2414. result = result.replace(
  2415. new RegExp(String.raw`(\b${sensitiveKey}\b\s*[:=]\s*)${quotedValue}`, "gi"),
  2416. "$1$2[Redacted]$2",
  2417. );
  2418. result = result.replace(
  2419. new RegExp(`(\\b${sensitiveKey}\\b\\s*[:=]\\s*)(["']?)[^\\s"',;)}]+`, "gi"),
  2420. "$1$2[Redacted]",
  2421. );
  2422. return result.replace(/([a-z][a-z0-9+.-]*:\/\/)[^:\s/@]+:[^@\s/]+@/gi, "$1[Redacted]@");
  2423. }
  2424. function getStdioTransportPid(transport?: McpTransport): number | undefined {
  2425. if (!(transport instanceof StdioClientTransport)) return undefined;
  2426. const pid = transport.pid;
  2427. return typeof pid === "number" && Number.isInteger(pid) && pid > 0 ? pid : undefined;
  2428. }
  2429. function getStdioTransportExitInfo(transport?: McpTransport):
  2430. | {
  2431. exitCode: number | null;
  2432. signal: NodeJS.Signals | null;
  2433. }
  2434. | undefined {
  2435. return transport instanceof ProcessTreeStdioClientTransport ? transport.processExit : undefined;
  2436. }
  2437. function isStdioTransportProcessAlive(transport?: McpTransport): boolean {
  2438. return transport instanceof ProcessTreeStdioClientTransport && transport.processAlive;
  2439. }
  2440. function isRecord(value: unknown): value is Record<string, unknown> {
  2441. return typeof value === "object" && value !== null && !Array.isArray(value);
  2442. }
  2443. // server 回了 JSON-RPC 错误响应(数字 code)说明请求走通了、连接是活的;
  2444. // SDK 本地错误(SdkError,字符串 code:REQUEST_TIMEOUT / CONNECTION_CLOSED / NOT_CONNECTED
  2445. // / SEND_FAILED)才代表 transport 已断。code 类型判断兜底 instanceof 在多份 SDK 实例下失效的情况。
  2446. function isPeerAnsweredError(error: unknown): boolean {
  2447. if (error instanceof ProtocolError) return true;
  2448. return isRecord(error) && typeof error.code === "number";
  2449. }