mcp.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /**
  2. * MCP (Model Context Protocol) types for ZCode
  3. * Based on the original Tauri implementation
  4. */
  5. import type { SettingsDirectoryLocation } from "./settings-source.js";
  6. import type { McpServerFailureKind } from "./zcode-protocol/index.js";
  7. // CUA official plugin 身份常量(port 自 feat;UI 设置面板 + bootstrap 复用以避免字面量漂移)。
  8. export const ZCODE_CUA_OFFICIAL_PLUGIN_ID = "computer-use@zcode-plugins-official";
  9. // CUA server 身份串(port 自 feat mcp.ts):server key = 模型可见工具前缀段(刻意不带 zcode-);
  10. // namespace name = official plugin 运行时命名空间 plugin:<pluginId>:<serverKey>。
  11. export const ZCODE_CUA_OFFICIAL_MCP_NAMESPACE_NAME = "plugin:computer-use:computer-use";
  12. // 插件身份 env key:resolver(adapters/src/plugins/mcp.ts)权威写入 loaded.id,manifest/user env 不可覆盖。
  13. // bootstrap + cli/plugin-host-command.ts 复用此常量识别 official zcode-cua plugin server,避免字面量漂移。
  14. export const ZCODE_PLUGIN_ID_ENV_KEY = "ZCODE_PLUGIN_ID";
  15. export type McpSource =
  16. | "mcp"
  17. | "zcodeagentmcp"
  18. | "claudeclimcp"
  19. | "geminiclimcp"
  20. | "codexclimcp"
  21. | "opencodemcp";
  22. export type CliMcpSource = Exclude<McpSource, "mcp">;
  23. export type McpScope = "common" | "user" | "workspace";
  24. export type McpFileFormat = "json" | "toml";
  25. // Single MCP server configuration
  26. export interface McpServerConfig {
  27. type?: string; // Supports stdio, http, sse, streamableHttp, etc.
  28. url?: string; // HTTP/SSE server URL
  29. command?: string; // stdio server command
  30. args?: string[]; // stdio server arguments
  31. env?: Record<string, string>; // stdio server environment variables
  32. headers?: Record<string, string>; // HTTP/SSE server request headers
  33. http_headers?: Record<string, string>; // 兼容旧配置字段,历史 BigModel MCP 配置会把鉴权头写在这里
  34. oauth?: McpOAuthConfig; // HTTP/SSE OAuth 机器凭据配置
  35. // Linear specific fields
  36. apiKey?: string;
  37. projectId?: string;
  38. issueType?: string;
  39. // Figma specific fields
  40. personalAccessToken?: string;
  41. fileId?: string;
  42. nodeId?: string;
  43. // Sentry specific fields
  44. organizationName?: string;
  45. projectName?: string;
  46. dsn?: string;
  47. // Context7 specific fields
  48. apiEndpoint?: string;
  49. [key: string]: any;
  50. }
  51. export type McpServerStatus = "connected" | "disconnected" | "error" | "connecting" | "unknown";
  52. export interface CliMcpConfig {
  53. mcpServers: Record<string, McpServerConfig>;
  54. projects: Record<string, Record<string, McpServerConfig>>;
  55. }
  56. export interface SaveCliMcpToUserDirectoryRequest {
  57. action: "upsert" | "delete" | "set-enabled";
  58. source: CliMcpSource;
  59. name: string;
  60. config?: McpServerConfig;
  61. enabled?: boolean;
  62. projectPath?: string;
  63. location?: SettingsDirectoryLocation;
  64. }
  65. export interface NativeMcpFileReference {
  66. format: McpFileFormat;
  67. filePath: string;
  68. }
  69. export interface NativeMcpServerRecord {
  70. source: McpSource;
  71. scope: McpScope;
  72. name: string;
  73. config: McpServerConfig;
  74. enabled?: boolean;
  75. projectPath?: string;
  76. location?: SettingsDirectoryLocation;
  77. file?: NativeMcpFileReference;
  78. }
  79. export interface LoadCliMcpFromUserDirectoryRequest {
  80. workspacePath?: string;
  81. }
  82. export interface LoadCliMcpFromUserDirectoryResult {
  83. servers: NativeMcpServerRecord[];
  84. }
  85. export interface MigrateLegacyCommonMcpRequest {
  86. legacyStorageDir?: string;
  87. }
  88. export interface MigrateLegacyCommonMcpResult {
  89. servers: Record<string, McpServerConfig>;
  90. sourcePath?: string;
  91. /** 旧数据中发现的 MCP 配置总数 */
  92. totalCount: number;
  93. /** 成功导入的数量 */
  94. importedCount: number;
  95. /** 因已存在而跳过的数量 */
  96. skippedCount: number;
  97. }
  98. export interface McpConfig {
  99. mcp: {
  100. mcpServers: Record<string, McpServerConfig>;
  101. };
  102. zcodeagentmcp: CliMcpConfig;
  103. claudeclimcp: CliMcpConfig;
  104. geminiclimcp: CliMcpConfig;
  105. codexclimcp: CliMcpConfig;
  106. opencodemcp: CliMcpConfig;
  107. }
  108. export interface ZCodeMcpServer {
  109. id: string;
  110. name: string;
  111. config: McpServerConfig;
  112. enabled: boolean;
  113. changed?: boolean;
  114. status?: McpServerStatus;
  115. lastConnected?: Date;
  116. error?: string;
  117. failureKind?: McpServerFailureKind;
  118. serverRequestId?: string;
  119. toolCount?: number;
  120. authorization?: {
  121. type: "oauth_authorization_code";
  122. authorizationUrl: string;
  123. startedAt: string;
  124. };
  125. source: McpSource;
  126. projectPath?: string;
  127. scope: McpScope;
  128. location?: SettingsDirectoryLocation;
  129. file?: NativeMcpFileReference;
  130. }
  131. export interface McpServerListItem {
  132. id: string;
  133. name: string;
  134. enabled: boolean;
  135. status: McpServerStatus;
  136. hasConfig: boolean;
  137. error?: string;
  138. toolCount?: number;
  139. source: McpSource;
  140. projectPath?: string;
  141. scope: McpScope;
  142. file?: NativeMcpFileReference;
  143. }
  144. export interface McpTestResult {
  145. success: boolean;
  146. error?: string;
  147. tools?: Array<{
  148. name: string;
  149. description?: string;
  150. input_schema?: any;
  151. }>;
  152. serverInfo?: {
  153. name: string;
  154. version: string;
  155. };
  156. response_time?: number;
  157. }
  158. export type ZCodeAgentMcpServer =
  159. | {
  160. name: string;
  161. command: string;
  162. args: string[];
  163. env: Array<{ name: string; value: string }>;
  164. isolation?: "session" | "workspace";
  165. protocolVersion?: "legacy" | "auto" | "2026-07-28";
  166. timeoutMs?: number;
  167. }
  168. | {
  169. name: string;
  170. type: "http" | "sse";
  171. url: string;
  172. isolation?: "session" | "workspace";
  173. protocolVersion?: "legacy" | "auto" | "2026-07-28";
  174. headers: Array<{ name: string; value: string }>;
  175. oauth?: McpOAuthConfig;
  176. timeoutMs?: number;
  177. };
  178. export interface McpClientCredentialsOAuthConfig {
  179. type: "client_credentials";
  180. clientId: string;
  181. clientSecret: string;
  182. clientName?: string;
  183. scope?: string;
  184. }
  185. export interface McpAuthorizationCodeOAuthConfig {
  186. type: "authorization_code";
  187. clientId?: string;
  188. clientSecret?: string;
  189. clientName?: string;
  190. redirectPath?: string;
  191. scope?: string;
  192. }
  193. export type McpOAuthConfig = McpAuthorizationCodeOAuthConfig | McpClientCredentialsOAuthConfig;
  194. export function getMcpServerRequestHeaders(
  195. config: McpServerConfig,
  196. ): Record<string, string> | undefined {
  197. return config.headers ?? config.http_headers;
  198. }
  199. // zcode-cua MCP server 识别的单一事实源。desktop 产品 broker resolver(@zcode/services 的
  200. // mcpBrokerInjection)与 CLI bootstrap(apps/zcode-cli 的 mcp-config)两条注入入口必须用
  201. // 完全一致的判定;否则同一 MCP 配置在不同入口行为不同,可能漏注入 product broker,让
  202. // Python/uvx 自己持有 macOS TCC 权限(违反 fail-closed 边界)。改这里即同时改两条链路。
  203. function zcodeCuaArgLeaf(value: string): string {
  204. // 先去掉结尾的路径分隔符再取叶子:`.../zcode-cua/` 直接 split 会得到空串叶子 → 漏判 → fail-open。
  205. return (
  206. value
  207. .replace(/[\\/]+$/, "")
  208. .split(/[\\/]/)
  209. .pop() ?? value
  210. );
  211. }
  212. // 单个候选串是否为 zcode-cua 的包规格。PyPI 视 `_`/`-` 等价,故先把下划线归一成短横(zcode_cua →
  213. // zcode-cua);覆盖 uv/npm 的 `@version`、pip 的 `==version`、extras `[...]`、git 的 `.git`/`.git@`,
  214. // 以及 `python -m zcode_cua.server` 这种点号子模块(`zcode-cua.<submodule>`)。fail-closed 边界宁可
  215. // 过判也不漏判;仍不会误判 `zcode-cua-proxy`(短横续接,不以 `.`/`@`/`[`/`==` 边界续接)。
  216. function matchesZCodeCuaSpec(candidate: string): boolean {
  217. const c = candidate.replace(/_/g, "-");
  218. return (
  219. c === "zcode-cua" ||
  220. c.startsWith("zcode-cua[") ||
  221. c.startsWith("zcode-cua@") ||
  222. c.startsWith("zcode-cua==") ||
  223. // `.` 分支同时覆盖 `zcode-cua.git` / `zcode-cua.git@v1` 与 `zcode-cua.server` 等 python 子模块。
  224. c.startsWith("zcode-cua.")
  225. );
  226. }
  227. /**
  228. * MCP server 的 command 是否指向 zcode-cua。用与 args 相同的包规格判定(并比对路径叶子),
  229. * 覆盖 `command: "zcode-cua"`、`/opt/bin/zcode-cua`,以及把包规格直接当 command 的写法
  230. * (`zcode-cua@1.2.3` 等)。对 fail-closed 边界宁可过判也不漏判。
  231. */
  232. export function isZCodeCuaMcpCommand(command: string): boolean {
  233. return matchesZCodeCuaSpec(command) || matchesZCodeCuaSpec(zcodeCuaArgLeaf(command));
  234. }
  235. /**
  236. * 单个 arg 是否为 zcode-cua 的包规格。覆盖 `zcode-cua`、`zcode-cua[macos]`、`zcode-cua@1.2.3`、
  237. * `zcode-cua==1.2.3`、`zcode_cua`,以及 git / 本地路径形态(`.../zcode-cua`、`zcode-cua.git`、
  238. * `git+https://.../zcode-cua.git@v1`)。同时比对原始值与路径叶子,覆盖 `--from <path>`、`--from <git-url>`。
  239. */
  240. export function isZCodeCuaMcpPackageArg(value: string): boolean {
  241. return matchesZCodeCuaSpec(value) || matchesZCodeCuaSpec(zcodeCuaArgLeaf(value));
  242. }
  243. export function convertToZCodeAgentMcpServer(
  244. name: string,
  245. config: McpServerConfig,
  246. ): ZCodeAgentMcpServer | null {
  247. let inferredType = config.type;
  248. if (!inferredType) {
  249. if (config.command) inferredType = "stdio";
  250. else if (config.url) inferredType = "http";
  251. }
  252. const isStdio = inferredType === "stdio";
  253. if (isStdio && config.command) {
  254. // Windows 上 agent 通常用 shell: true 启动子进程,
  255. // "cmd /c npx ..." 会被双重包裹成 "cmd.exe /c cmd /c npx ..." 导致连接失败。
  256. // 这里把 cmd /c 包衣拆掉,直接使用内部命令。
  257. let command = config.command;
  258. let args = config.args || [];
  259. // 自动检测平台:Node.js 用 process.platform,浏览器用 navigator.platform
  260. const isWin32 =
  261. (typeof process !== "undefined" && process.platform === "win32") ||
  262. (typeof navigator !== "undefined" && /win/i.test(navigator.platform));
  263. if (isWin32) {
  264. const lowerCmd = command.toLowerCase();
  265. const unwrappedCommand = args[1];
  266. if ((lowerCmd === "cmd" || lowerCmd === "cmd.exe") && args[0] === "/c" && unwrappedCommand) {
  267. // noUncheckedIndexedAccess 下 args[1] 即使经过 length 判断也仍是 string | undefined。
  268. // 先显式取值并判空,既满足类型收窄,也避免把空命令传给 ZCode Agent。
  269. command = unwrappedCommand;
  270. args = args.slice(2);
  271. }
  272. }
  273. return {
  274. name,
  275. command,
  276. args,
  277. env: config.env
  278. ? Object.entries(config.env).map(([key, value]) => ({
  279. name: key,
  280. value,
  281. }))
  282. : [],
  283. // MCP 设置页会把 timeoutMs 写入 config;session/create 走协议 DTO 时
  284. // 只能透传正整数,否则 strict protocol schema 会把存量非法配置从“忽略”变成“创建失败”。
  285. ...(isValidMcpTimeoutMs(config.timeoutMs) ? { timeoutMs: config.timeoutMs } : {}),
  286. ...(isMcpIsolation(config.isolation) ? { isolation: config.isolation } : {}),
  287. ...(isMcpProtocolVersion(config.protocolVersion)
  288. ? { protocolVersion: config.protocolVersion }
  289. : {}),
  290. };
  291. } else if (config.url && inferredType) {
  292. const normalizedType: "http" | "sse" = inferredType === "sse" ? "sse" : "http";
  293. const headers = getMcpServerRequestHeaders(config);
  294. return {
  295. name,
  296. type: normalizedType,
  297. url: config.url,
  298. headers: headers
  299. ? Object.entries(headers).map(([key, value]) => ({
  300. name: key,
  301. value,
  302. }))
  303. : [],
  304. ...(isValidMcpOAuthConfig(config.oauth) ? { oauth: config.oauth } : {}),
  305. // HTTP/SSE MCP 与 stdio 一样需要保留超时配置,避免 UI 保存后真实 session 丢字段。
  306. ...(isValidMcpTimeoutMs(config.timeoutMs) ? { timeoutMs: config.timeoutMs } : {}),
  307. ...(isMcpIsolation(config.isolation) ? { isolation: config.isolation } : {}),
  308. ...(isMcpProtocolVersion(config.protocolVersion)
  309. ? { protocolVersion: config.protocolVersion }
  310. : {}),
  311. };
  312. }
  313. return null;
  314. }
  315. function isValidMcpTimeoutMs(value: unknown): value is number {
  316. return typeof value === "number" && Number.isInteger(value) && value > 0;
  317. }
  318. function isMcpIsolation(value: unknown): value is "session" | "workspace" {
  319. return value === "session" || value === "workspace";
  320. }
  321. function isMcpProtocolVersion(value: unknown): value is "legacy" | "auto" | "2026-07-28" {
  322. return value === "legacy" || value === "auto" || value === "2026-07-28";
  323. }
  324. function isValidMcpOAuthConfig(value: unknown): value is McpOAuthConfig {
  325. if (!isRecord(value)) return false;
  326. if (
  327. value.type === "client_credentials" &&
  328. typeof value.clientId === "string" &&
  329. value.clientId.trim().length > 0 &&
  330. typeof value.clientSecret === "string" &&
  331. value.clientSecret.trim().length > 0
  332. ) {
  333. return (
  334. (value.clientName === undefined || typeof value.clientName === "string") &&
  335. (value.scope === undefined || typeof value.scope === "string")
  336. );
  337. }
  338. if (value.type === "authorization_code") {
  339. return (
  340. (value.clientId === undefined || typeof value.clientId === "string") &&
  341. (value.clientSecret === undefined || typeof value.clientSecret === "string") &&
  342. (value.clientName === undefined || typeof value.clientName === "string") &&
  343. (value.redirectPath === undefined || typeof value.redirectPath === "string") &&
  344. (value.scope === undefined || typeof value.scope === "string")
  345. );
  346. }
  347. return false;
  348. }
  349. function isRecord(value: unknown): value is Record<string, unknown> {
  350. return typeof value === "object" && value !== null && !Array.isArray(value);
  351. }