返回源码地图

packages/coding-agent/src/extensions/mcp/config.ts

v1.0.1 · a7229ddc2181 · 09/20:1.0.1设置型项目覆盖与完整entry的区别

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * MCP server configuration.
3 *
4 * Servers are read from `mcp.json` in the agent directory and, for trusted projects, from
5 * `<project>/.pi/mcp.json`. Both use the `mcpServers` shape shared by other MCP clients, so
6 * existing configurations can be copied over. Project entries replace global entries with the
7 * same name.
8 *
9 * A project entry without `command`, `url`, or `type` overrides only `enabled`, `exposure`, and
10 * `toolExposure` of the global server with the same name, for example to turn it off in one project:
11 * `{ "mcpServers": { "internal-tools": { "enabled": false } } }`. The rest of the global entry is kept,
12 * including credentials the project could not set itself.
13 *
14 * ```json
15 * {
16 * "mcpServers": {
17 * "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] },
18 * "docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer ${DOCS_TOKEN}" } },
19 * "sentry": { "url": "https://mcp.sentry.dev/mcp" }
20 * }
21 * }
22 * ```
23 *
24 * HTTP servers without an `Authorization` header use OAuth when they answer 401 (sign in with `/mcp`).
25 * `"auth": { "provider": "<provider>" }` sends the token of a `/login` provider instead. Project files
26 * cannot use it, so a repository cannot pick where the credential goes.
27 *
28 * The top-level `autoEnableCodemode` (default true) activates the codemode tool when a server
29 * with `codemode` exposure connects. A project value overrides the global one.
30 */
31
32import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
33import { dirname, join } from "node:path";
34import { CONFIG_DIR_NAME } from "../../config.ts";
35import {
36 type McpExposure,
37 type McpServerConfig,
38 mcpNamespace,
39 validateMcpServerConfig,
40} from "../../core/mcp-servers.ts";
41
42export type {
43 McpExposure,
44 McpHttpServerConfig,
45 McpOAuthConfig,
46 McpServerConfig,
47 McpStdioServerConfig,
48} from "../../core/mcp-servers.ts";
49export { getMcpToolExposure } from "../../core/mcp-servers.ts";
50
51export interface McpServerEntry {
52 name: string;
53 config: McpServerConfig;
54 /** Config file that defined the entry, or the path of the extension that registered it. */
55 source: string;
56 /**
57 * The global or the project `mcp.json`, or `extension` for servers registered with
58 * `pi.registerMcpServer()`. Changes to extension servers are not saved.
59 */
60 scope?: "global" | "project" | "extension";
61 /** Project `mcp.json` with an override of this global server's `enabled`, `exposure`, or `toolExposure`. */
62 override?: string;
63}
64
65export interface LoadedMcpConfig {
66 servers: McpServerEntry[];
67 /** Activate the codemode tool when `codemode` servers connect. Default: true. */
68 autoEnableCodemode?: boolean;
69 errors: string[];
70 /** The project `mcp.json` when the project is trusted, where `/mcp` saves project overrides. */
71 projectConfig?: string;
72}
73
74const OVERRIDE_KEYS = ["enabled", "exposure", "toolExposure"];
75
76/** Whether an entry overrides a server defined elsewhere instead of defining one. */
77function isOverride(value: Record<string, unknown>): boolean {
78 return value.command === undefined && value.url === undefined && value.type === undefined;
79}
80
81function isRecord(value: unknown): value is Record<string, unknown> {
82 return typeof value === "object" && value !== null && !Array.isArray(value);
83}
84
85interface McpConfigState {
86 servers: Map<string, McpServerEntry>;
87 autoEnableCodemode?: boolean;
88 errors: string[];
89}
90
91function readConfigFile(path: string, scope: "global" | "project", state: McpConfigState): void {
92 const { servers, errors } = state;
93 if (!existsSync(path)) return;
94 let parsed: unknown;
95 try {
96 parsed = JSON.parse(readFileSync(path, "utf8"));
97 } catch (error) {
98 errors.push(`${path}: ${error instanceof Error ? error.message : String(error)}`);
99 return;
100 }
101 if (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {
102 errors.push(`${path}: expected an object with an "mcpServers" object`);
103 return;
104 }
105 if (typeof parsed.autoEnableCodemode === "boolean") state.autoEnableCodemode = parsed.autoEnableCodemode;
106 else if (parsed.autoEnableCodemode !== undefined) errors.push(`${path}: autoEnableCodemode must be a boolean`);
107 for (const [name, value] of Object.entries(parsed.mcpServers ?? {})) {
108 if (scope === "project" && isRecord(value) && isOverride(value)) {
109 const base = servers.get(name);
110 const extra = Object.keys(value).filter((key) => !OVERRIDE_KEYS.includes(key));
111 if (!base) {
112 errors.push(`${path}: server "${name}" needs "command" or "url", or a global server to override`);
113 } else if (extra.length > 0) {
114 errors.push(`${path}: server "${name}": an override can only set ${OVERRIDE_KEYS.join(", ")}`);
115 } else {
116 const config = validateMcpServerConfig(name, { ...base.config, ...value });
117 if (typeof config === "string") errors.push(`${path}: ${config}`);
118 else servers.set(name, { ...base, config, override: path });
119 }
120 continue;
121 }
122 const config = validateMcpServerConfig(name, value);
123 if (typeof config === "string") {
124 errors.push(`${path}: ${config}`);
125 continue;
126 }
127 // Names that differ only in `-` and `_` would share a namespace.
128 const clash = [...servers.keys()].find((other) => other !== name && mcpNamespace(other) === mcpNamespace(name));
129 if (clash) {
130 errors.push(`${path}: server "${name}" conflicts with "${clash}"`);
131 continue;
132 }
133 if (scope === "project" && "url" in config && config.auth) {
134 errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);
135 continue;
136 }
137 servers.set(name, { name, config, source: path, scope });
138 }
139}
140
141/**
142 * Load global and (when trusted) project MCP configuration. Disabled servers are included with
143 * `enabled: false`, so they can be enabled again.
144 */
145export function loadMcpConfig(options: { agentDir: string; cwd: string; projectTrusted: boolean }): LoadedMcpConfig {
146 const state: McpConfigState = { servers: new Map(), errors: [] };
147 readConfigFile(join(options.agentDir, "mcp.json"), "global", state);
148 const projectConfig = options.projectTrusted ? join(options.cwd, CONFIG_DIR_NAME, "mcp.json") : undefined;
149 if (projectConfig) readConfigFile(projectConfig, "project", state);
150 return {
151 servers: [...state.servers.values()],
152 ...(state.autoEnableCodemode === undefined ? {} : { autoEnableCodemode: state.autoEnableCodemode }),
153 errors: state.errors,
154 ...(projectConfig ? { projectConfig } : {}),
155 };
156}
157
158/** Settings `/mcp` changes. `enabled: true` and `exposure: "codemode"` are the defaults and remove the key. */
159export interface McpServerConfigPatch {
160 enabled?: boolean;
161 exposure?: McpExposure;
162}
163
164/**
165 * Change one server's settings in the `mcp.json` that defines or overrides it. With `override`, a
166 * missing entry is added as an override. Overrides keep default values, since they replace the global
167 * server's. Other content is kept; the file is rewritten with its indentation.
168 */
169export function updateMcpServerConfig(
170 path: string,
171 name: string,
172 patch: McpServerConfigPatch,
173 options: { override?: boolean } = {},
174): void {
175 editMcpServers(path, (servers, parsed) => {
176 let server = servers?.[name];
177 if (server === undefined && options.override) {
178 server = {};
179 parsed.mcpServers = { ...servers, [name]: server };
180 }
181 if (!isRecord(server)) throw new Error(`${path} does not define MCP server "${name}"`);
182 const keepDefaults = isOverride(server);
183 if (patch.enabled !== undefined) {
184 if (patch.enabled && !keepDefaults) delete server.enabled;
185 else server.enabled = patch.enabled;
186 }
187 if (patch.exposure !== undefined) {
188 if (patch.exposure === "codemode" && !keepDefaults) delete server.exposure;
189 else server.exposure = patch.exposure;
190 }
191 return true;
192 });
193}
194
195/**
196 * Add a server to an `mcp.json`, creating the file when missing. An existing entry with the same
197 * name is replaced. Returns true when an entry was replaced.
198 */
199export function addMcpServerConfig(path: string, name: string, config: McpServerConfig): boolean {
200 let replaced = false;
201 editMcpServers(path, (servers, parsed) => {
202 const target = servers ?? {};
203 replaced = target[name] !== undefined;
204 target[name] = config;
205 parsed.mcpServers = target;
206 return true;
207 });
208 return replaced;
209}
210
211/** Remove a server from an `mcp.json`. Returns false when the file does not define it. */
212export function removeMcpServerConfig(path: string, name: string): boolean {
213 if (!existsSync(path)) return false;
214 let removed = false;
215 editMcpServers(path, (servers) => {
216 if (!servers || servers[name] === undefined) return false;
217 delete servers[name];
218 removed = true;
219 return true;
220 });
221 return removed;
222}
223
224/**
225 * Read an `mcp.json` (an empty config when missing), let `edit` change its `mcpServers`, and write
226 * it back with its indentation when `edit` returns true. Other content is kept.
227 */
228function editMcpServers(
229 path: string,
230 edit: (servers: Record<string, unknown> | undefined, parsed: Record<string, unknown>) => boolean,
231): void {
232 const text = existsSync(path) ? readFileSync(path, "utf8") : undefined;
233 const parsed: unknown = text === undefined ? {} : JSON.parse(text);
234 if (!isRecord(parsed) || (parsed.mcpServers !== undefined && !isRecord(parsed.mcpServers))) {
235 throw new Error(`${path}: expected an object with an "mcpServers" object`);
236 }
237 const servers = isRecord(parsed.mcpServers) ? parsed.mcpServers : undefined;
238 if (!edit(servers, parsed)) return;
239 const indent = (text && /^([ \t]+)\S/m.exec(text)?.[1]) || " ";
240 mkdirSync(dirname(path), { recursive: true });
241 writeFileSync(path, `${JSON.stringify(parsed, null, indent)}\n`);
242}