返回源码地图

packages/coding-agent/src/core/mcp-servers.ts

v1.0.1 · a7229ddc2181 · 09/20:OAuth clientRegistration配置边界

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

1/**
2 * MCP server configuration and the servers extensions register with `pi.registerMcpServer()`.
3 *
4 * The core only validates and stores registrations. The MCP extension (built in, or another
5 * extension that handles `mcp_servers_change`) connects them next to the servers from `mcp.json`.
6 */
7
8/**
9 * - `codemode`: tools are callable from codemode scripts but neither declared to the model nor
10 * listed in the codemode description, which lists only the server's namespace. Scripts find them
11 * with `searchTools()`. `codemode-deferred` is accepted as an alias.
12 * - `deferred`: not declared to the model until the `tool_search` tool loads them; the model then
13 * calls them directly. Does not need codemode.
14 * - `direct`: tools are declared to the model like any other tool (and callable from codemode).
15 * - `hidden`: tools are registered but unreachable.
16 */
17export type McpExposure = "codemode" | "deferred" | "direct" | "hidden";
18
19const MCP_EXPOSURES: readonly string[] = ["codemode", "deferred", "direct", "hidden"] satisfies McpExposure[];
20
21/** Older exposure names, accepted in configs and replaced by their current name when validated. */
22const MCP_EXPOSURE_ALIASES: Readonly<Record<string, McpExposure>> = { "codemode-deferred": "codemode" };
23
24interface McpServerConfigBase {
25 /** Default: `codemode`. */
26 exposure?: McpExposure;
27 /**
28 * What the server offers, in a sentence. The `mcp_servers` system prompt section lists the server
29 * with it, tool search ranks the server's tools by it, and codemode's `describeNamespace()` returns it.
30 */
31 description?: string;
32 /**
33 * Exposure of single tools, overriding `exposure`. Keys are tool names as the server offers them,
34 * or patterns where `*` matches any characters. An exact name wins over patterns; among patterns
35 * the first match in the object wins. `hidden` removes tools, so `"exposure": "hidden"` with
36 * overrides for a few tools exposes only those.
37 */
38 toolExposure?: Record<string, McpExposure>;
39 /** Set to false to keep the entry without connecting. Default: true. */
40 enabled?: boolean;
41 /** Per-request timeout in seconds. Progress notifications from the server reset it. Default: 60. */
42 timeout?: number;
43}
44
45export interface McpStdioServerConfig extends McpServerConfigBase {
46 type?: "stdio";
47 command: string;
48 args?: string[];
49 /** Values may reference environment variables (`${NAME}`) or commands (`!cmd`). */
50 env?: Record<string, string>;
51 /** Relative paths resolve against the session working directory. */
52 cwd?: string;
53}
54
55/** OAuth client settings for servers that do not support dynamic client registration. */
56export interface McpOAuthConfig {
57 /** Pre-registered client id. Without it, pi registers a client with the authorization server. */
58 clientId?: string;
59 /** May reference environment variables (`${NAME}`) or commands (`!cmd`). */
60 clientSecret?: string;
61 /**
62 * Port of the loopback callback server, for clients registered with a fixed redirect URI. Without
63 * `callbackUrl`, the redirect URI is `http://127.0.0.1:<port>/callback`.
64 */
65 callbackPort?: number;
66 /**
67 * Redirect URI registered for `clientId`, for example `http://localhost:8080/oauth/callback`. It must
68 * be an `http` URI on `localhost`, `127.0.0.1`, or `[::1]`. Without a port, the callback server
69 * listens on `callbackPort` or a free port, which is added to the URI (RFC 8252).
70 */
71 callbackUrl?: string;
72 /** Scopes to request, separated by spaces. Default: the scopes the server advertises. */
73 scope?: string;
74 /**
75 * `client_name` sent with dynamic client registration, for servers that only accept known clients.
76 * Default: `pi`.
77 */
78 clientName?: string;
79 /**
80 * How pi identifies itself without `clientId`. `dcr` (default): dynamic client registration. `cimd`:
81 * pi's Client ID Metadata Document on pi.dev, for authorization servers that allow pi by that URL. The
82 * server must support it for public clients, and the callback must use the default path `/callback`.
83 */
84 clientRegistration?: "dcr" | "cimd";
85 /**
86 * Authorization server metadata document (RFC 8414 or OpenID Connect discovery) to use instead of
87 * discovery through the server, for servers that advertise a wrong authorization server or none.
88 * The document is trusted as configured. Must use https, except on loopback hosts.
89 */
90 authServerMetadataUrl?: string;
91}
92
93const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
94
95/** Whether a redirect URI can be served by pi's loopback callback server. */
96export function isLoopbackRedirectUri(value: string): boolean {
97 if (!URL.canParse(value)) return false;
98 const url = new URL(value);
99 return url.protocol === "http:" && LOOPBACK_HOSTS.includes(url.hostname) && url.search === "" && url.hash === "";
100}
101
102export interface McpHttpServerConfig extends McpServerConfigBase {
103 type?: "http";
104 url: string;
105 /** Values may reference environment variables (`${NAME}`) or commands (`!cmd`). */
106 headers?: Record<string, string>;
107 oauth?: McpOAuthConfig;
108 /**
109 * Send the token of a pi provider (`/login <provider>`) instead of using OAuth. Not allowed in project
110 * `mcp.json` files, and requires https except on loopback hosts, since it sends the credential to `url`.
111 */
112 auth?: { provider: string };
113}
114
115export type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig;
116
117const SERVER_NAME = /^[A-Za-z0-9_-]+$/;
118
119/** Namespace of a server's tools: `mcp__<server>` with `-` replaced by `_`, like the tool names. */
120export function mcpNamespace(server: string): string {
121 return `mcp__${server.replace(/-/g, "_")}`;
122}
123
124function isRecord(value: unknown): value is Record<string, unknown> {
125 return typeof value === "object" && value !== null && !Array.isArray(value);
126}
127
128function isStringRecord(value: unknown): value is Record<string, string> {
129 return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
130}
131
132function validateOAuth(value: unknown): string | undefined {
133 if (value === undefined) return undefined;
134 if (!isRecord(value)) return "oauth must be an object";
135 if (value.clientId !== undefined && typeof value.clientId !== "string") return "oauth.clientId must be a string";
136 if (value.clientSecret !== undefined && typeof value.clientSecret !== "string") {
137 return "oauth.clientSecret must be a string";
138 }
139 const port = value.callbackPort;
140 if (port !== undefined && (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535)) {
141 return "oauth.callbackPort must be a port number";
142 }
143 if (value.callbackUrl !== undefined) {
144 if (typeof value.callbackUrl !== "string" || !isLoopbackRedirectUri(value.callbackUrl)) {
145 return "oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";
146 }
147 const urlPort = new URL(value.callbackUrl).port;
148 if (urlPort && port !== undefined && Number(urlPort) !== port) {
149 return "oauth.callbackUrl and oauth.callbackPort name different ports";
150 }
151 }
152 if (value.scope !== undefined && typeof value.scope !== "string") return "oauth.scope must be a string";
153 if (value.clientName !== undefined && (typeof value.clientName !== "string" || !value.clientName.trim())) {
154 return "oauth.clientName must be a non-empty string";
155 }
156 if (value.clientRegistration !== undefined && value.clientRegistration !== "dcr") {
157 if (value.clientRegistration !== "cimd") return 'oauth.clientRegistration must be "dcr" or "cimd"';
158 if (value.clientId !== undefined || value.clientName !== undefined) {
159 return 'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';
160 }
161 const callback = typeof value.callbackUrl === "string" ? new URL(value.callbackUrl) : undefined;
162 if (callback && (callback.hostname === "[::1]" || callback.pathname !== "/callback")) {
163 return 'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback';
164 }
165 }
166 const metadataUrl = value.authServerMetadataUrl;
167 if (metadataUrl !== undefined) {
168 const url = typeof metadataUrl === "string" && URL.canParse(metadataUrl) ? new URL(metadataUrl) : undefined;
169 if (!url || !(url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK_HOSTS.includes(url.hostname)))) {
170 return "oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]";
171 }
172 }
173 return undefined;
174}
175
176function isExposure(value: unknown): value is McpExposure {
177 return typeof value === "string" && MCP_EXPOSURES.includes(value);
178}
179
180/** The exposure an alias stands for; other values are returned unchanged. */
181function resolveExposureAlias(value: unknown): unknown {
182 return typeof value === "string" ? (MCP_EXPOSURE_ALIASES[value] ?? value) : value;
183}
184
185/** A copy of the server entry with exposure aliases replaced by their current names. */
186function resolveExposureAliases(value: Record<string, unknown>): Record<string, unknown> {
187 const { exposure, toolExposure } = value;
188 const resolved: Record<string, unknown> = { ...value };
189 if (exposure !== undefined) resolved.exposure = resolveExposureAlias(exposure);
190 if (isRecord(toolExposure)) {
191 resolved.toolExposure = Object.fromEntries(
192 Object.entries(toolExposure).map(([tool, entry]) => [tool, resolveExposureAlias(entry)]),
193 );
194 }
195 return resolved;
196}
197
198function toolPatternRegExp(pattern: string): RegExp {
199 const source = pattern
200 .split("*")
201 .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
202 .join(".*");
203 return new RegExp(`^${source}$`);
204}
205
206/** Exposure of one tool of a server: its `toolExposure` entry, else the server's `exposure`. */
207export function getMcpToolExposure(config: McpServerConfig, toolName: string): McpExposure {
208 const overrides = config.toolExposure ?? {};
209 const exact = overrides[toolName];
210 if (exact !== undefined) return exact;
211 for (const [pattern, exposure] of Object.entries(overrides)) {
212 if (pattern.includes("*") && toolPatternRegExp(pattern).test(toolName)) return exposure;
213 }
214 return config.exposure ?? "codemode";
215}
216
217/**
218 * Validate one server entry of the `mcpServers` shape. Returns a copy of the config with exposure
219 * aliases resolved, or an error message.
220 */
221export function validateMcpServerConfig(name: string, raw: unknown): McpServerConfig | string {
222 if (!SERVER_NAME.test(name)) return `invalid server name "${name}" (use letters, digits, "_" and "-")`;
223 if (!isRecord(raw)) return `server "${name}" must be an object`;
224 const value = resolveExposureAliases(raw);
225 const { type, exposure, enabled, timeout, toolExposure, description } = value;
226 const exposures = MCP_EXPOSURES.map((value) => `"${value}"`).join(", ");
227 if (exposure !== undefined && !isExposure(exposure)) {
228 return `server "${name}": exposure must be one of ${exposures}`;
229 }
230 if (toolExposure !== undefined) {
231 if (!isRecord(toolExposure)) return `server "${name}": toolExposure must map tool names to exposures`;
232 for (const [tool, value] of Object.entries(toolExposure)) {
233 if (!isExposure(value)) return `server "${name}": toolExposure "${tool}" must be one of ${exposures}`;
234 }
235 }
236 if (enabled !== undefined && typeof enabled !== "boolean") return `server "${name}": enabled must be a boolean`;
237 if (description !== undefined && typeof description !== "string") {
238 return `server "${name}": description must be a string`;
239 }
240 if (timeout !== undefined && (typeof timeout !== "number" || !(timeout > 0))) {
241 return `server "${name}": timeout must be a positive number of seconds`;
242 }
243 if (type === "sse") return `server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;
244
245 if (typeof value.url === "string" && (type === undefined || type === "http" || type === "streamable-http")) {
246 if (!URL.canParse(value.url) || !/^https?:$/.test(new URL(value.url).protocol)) {
247 return `server "${name}": url must be an http or https URL`;
248 }
249 if (value.headers !== undefined && !isStringRecord(value.headers)) {
250 return `server "${name}": headers must map names to strings`;
251 }
252 const oauthError = validateOAuth(value.oauth);
253 if (oauthError) return `server "${name}": ${oauthError}`;
254 if (value.auth !== undefined) {
255 if (!isRecord(value.auth) || typeof value.auth.provider !== "string" || !value.auth.provider) {
256 return `server "${name}": auth.provider must be a provider name`;
257 }
258 const url = new URL(value.url);
259 if (url.protocol !== "https:" && !LOOPBACK_HOSTS.includes(url.hostname)) {
260 return `server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`;
261 }
262 }
263 return value as unknown as McpHttpServerConfig;
264 }
265 if (typeof value.command === "string" && (type === undefined || type === "stdio")) {
266 if (
267 value.args !== undefined &&
268 !(Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string"))
269 ) {
270 return `server "${name}": args must be an array of strings`;
271 }
272 if (value.env !== undefined && !isStringRecord(value.env))
273 return `server "${name}": env must map names to strings`;
274 if (value.cwd !== undefined && typeof value.cwd !== "string") return `server "${name}": cwd must be a string`;
275 return value as unknown as McpStdioServerConfig;
276 }
277 return `server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`;
278}
279
280/** A server an extension registered with `pi.registerMcpServer()`. */
281export interface RegisteredMcpServer {
282 name: string;
283 config: McpServerConfig;
284 /** Path of the extension that registered the server. */
285 extensionPath: string;
286}
287
288/** Servers registered by the extensions of one runtime. */
289export class McpServerRegistry {
290 private readonly servers = new Map<string, RegisteredMcpServer>();
291 private changeListener: (() => void) | undefined;
292
293 /** Register or replace a server. The caller checks ownership. */
294 register(server: RegisteredMcpServer): void {
295 this.servers.set(server.name, server);
296 this.changeListener?.();
297 }
298
299 /** Remove a server registered by `extensionPath`. Servers of other extensions are left alone. */
300 unregister(name: string, extensionPath: string): void {
301 if (this.servers.get(name)?.extensionPath !== extensionPath) return;
302 this.servers.delete(name);
303 this.changeListener?.();
304 }
305
306 get(name: string): RegisteredMcpServer | undefined {
307 return this.servers.get(name);
308 }
309
310 /** Copies of the registered servers, in registration order. */
311 list(): RegisteredMcpServer[] {
312 return [...this.servers.values()].map((server) => ({ ...server, config: structuredClone(server.config) }));
313 }
314
315 /** Called after every change. The runner sets it when it binds, to emit `mcp_servers_change`. */
316 setChangeListener(listener: (() => void) | undefined): void {
317 this.changeListener = listener;
318 }
319}