index.ts 98 KB

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