@@ -1,9 +1,9 @@
11 /**
22 * Model Context Protocol client discovery and tool integration.
33 *
4- * mini-coder connects to configured Streamable HTTP MCP servers at startup,
5- * imports their tools, and exposes those tools through the normal pi-ai tool
6- * interface.
4+ * mini-coder tracks configured Streamable HTTP MCP servers, connects enabled
5+ * ones when needed, imports their tools, and exposes those tools through the
6+ * normal pi-ai tool interface.
77 *
88 * @module
99 */
@@ -144,14 +144,29 @@ const defaultMcpRuntime: McpRuntime = {
144144 },
145145 };
146146
147-/** A connected MCP server whose tools are available to the agent. */
148-export interface ConnectedMcpServer {
147+async function noopClose(): Promise<void> {}
148+
149+/** A configured MCP server and its current runtime connection state. */
150+export interface McpServerState {
149151 /** User-configured server identifier from `settings.json`. */
150152 name: string;
151153 /** Absolute Streamable HTTP endpoint URL. */
152154 url: string;
153- /** Whether this server's tools are currently exposed to new turns. */
155+ /** Whether this server should be available to future turns. */
154156 enabled: boolean;
157+ /** Whether mini-coder currently has an active connection to this server. */
158+ connected: boolean;
159+ /** pi-ai tool definitions derived from the server's tool list. */
160+ tools: Tool[];
161+ /** Tool name → handler map for calling the remote MCP tools. */
162+ toolHandlers: Map<string, ToolHandler>;
163+ /** Close the underlying MCP transport when connected. */
164+ close(): Promise<void>;
165+}
166+
167+interface McpConnectionState {
168+ /** Non-fatal warnings encountered while importing tools. */
169+ warnings: string[];
155170 /** pi-ai tool definitions derived from the server's tool list. */
156171 tools: Tool[];
157172 /** Tool name → handler map for calling the remote MCP tools. */
@@ -161,93 +176,197 @@ export interface ConnectedMcpServer {
161176 }
162177
163178 interface McpDiscoveryResult {
164- /** Successfully connected MCP servers with imported tools. */
165- servers: ConnectedMcpServer[];
179+ /** MCP servers kept in runtime state after startup discovery. */
180+ servers: McpServerState[];
166181 /** Non-fatal startup warnings for skipped or unreachable servers. */
167182 warnings: string[];
168183 }
169184
185+function createDisconnectedMcpServer(
186+ entry: NonNullable<McpSettings["servers"]>[number],
187+): McpServerState {
188+ return {
189+ name: entry.name,
190+ url: entry.url,
191+ enabled: entry.enabled,
192+ connected: false,
193+ tools: [],
194+ toolHandlers: new Map(),
195+ close: noopClose,
196+ };
197+}
198+
199+function resetMcpServerConnection(server: McpServerState): void {
200+ server.connected = false;
201+ server.tools = [];
202+ server.toolHandlers = new Map();
203+ server.close = noopClose;
204+}
205+
206+function parseMcpServerUrl(rawUrl: string): URL | null {
207+ try {
208+ return new URL(rawUrl);
209+ } catch {
210+ return null;
211+ }
212+}
213+
170214 /**
171- * Connect all configured MCP servers and import their tool definitions.
215+ * Connect a configured MCP server and populate its imported tools.
172216 *
173- * Invalid or unreachable servers do not fail startup. They are skipped and
174- * returned as warnings instead.
217+ * On failure the server is left disconnected and the returned warnings describe
218+ * why the connection was skipped.
219+ *
220+ * @param server - Runtime MCP server state to connect.
221+ * @param runtime - Internal runtime injection for tests.
222+ * @returns Non-fatal warnings produced while connecting or importing tools.
223+ */
224+export async function connectMcpServer(
225+ server: McpServerState,
226+ runtime: McpRuntime = defaultMcpRuntime,
227+): Promise<string[]> {
228+ if (server.connected) {
229+ return [];
230+ }
231+
232+ const connection = await createMcpServerConnection(
233+ server.name,
234+ server.url,
235+ runtime,
236+ );
237+
238+ if (!("tools" in connection)) {
239+ resetMcpServerConnection(server);
240+ return [connection.warning];
241+ }
242+
243+ server.connected = true;
244+ server.tools = connection.tools;
245+ server.toolHandlers = connection.toolHandlers;
246+ server.close = connection.close;
247+ return connection.warnings;
248+}
249+
250+/**
251+ * Disconnect an MCP server and clear its imported tool state.
252+ *
253+ * @param server - Runtime MCP server state to disconnect.
254+ */
255+export async function disconnectMcpServer(
256+ server: McpServerState,
257+): Promise<void> {
258+ if (!server.connected) {
259+ return;
260+ }
261+
262+ const close = server.close;
263+ resetMcpServerConnection(server);
264+ await close();
265+}
266+
267+/**
268+ * Connect enabled MCP servers at startup while keeping disabled ones in state.
269+ *
270+ * Invalid or unreachable servers do not fail startup. Enabled servers that
271+ * cannot connect are skipped with warnings. Disabled servers stay disconnected
272+ * until the user turns them back on.
175273 *
176274 * @param settings - Optional MCP settings from `settings.json`.
177275 * @param runtime - Internal runtime injection for tests.
178- * @returns Connected servers plus any non-fatal warnings.
276+ * @returns MCP server state plus any non-fatal startup warnings.
179277 */
180278 export async function discoverMcpServers(
181279 settings: McpSettings | undefined,
182280 runtime: McpRuntime = defaultMcpRuntime,
183281 ): Promise<McpDiscoveryResult> {
184- const servers: ConnectedMcpServer[] = [];
282+ const servers: McpServerState[] = [];
185283 const warnings: string[] = [];
186284
187285 for (const entry of settings?.servers ?? []) {
188- let url: URL;
189- try {
190- url = new URL(entry.url);
191- } catch {
286+ if (!parseMcpServerUrl(entry.url)) {
192287 warnings.push(`MCP server "${entry.name}": invalid URL (${entry.url})`);
193288 continue;
194289 }
195290
196- const transport = runtime.createTransport(url);
197- const client = runtime.createClient();
291+ const server = createDisconnectedMcpServer(entry);
292+ if (!entry.enabled) {
293+ servers.push(server);
294+ continue;
295+ }
198296
199- try {
200- await client.connect(transport, { timeout: MCP_DISCOVERY_TIMEOUT_MS });
201- const listedTools = await listAllTools(client);
297+ const connectWarnings = await connectMcpServer(server, runtime);
298+ warnings.push(...connectWarnings);
299+ if (!server.connected) {
300+ continue;
301+ }
202302
203- if (listedTools.length === 0) {
204- warnings.push(
205- `MCP server "${entry.name}" exposes no tools and was skipped.`,
206- );
207- await closeQuietly(transport);
208- continue;
209- }
303+ servers.push(server);
304+ }
210305
211- const tools: Tool[] = [];
212- const toolHandlers = new Map<string, ToolHandler>();
213-
214- for (const listedTool of listedTools) {
215- const { tool, handler } = createMcpTool(entry.name, listedTool, client);
216- if (toolHandlers.has(tool.name)) {
217- warnings.push(
218- `MCP server "${entry.name}": duplicate tool name "${listedTool.name}" was skipped.`,
219- );
220- continue;
221- }
222- tools.push(tool);
223- toolHandlers.set(tool.name, handler);
224- }
306+ return { servers, warnings };
307+}
225308
226- if (tools.length === 0) {
309+async function createMcpServerConnection(
310+ serverName: string,
311+ serverUrl: string,
312+ runtime: McpRuntime,
313+): Promise<McpConnectionState | { warning: string }> {
314+ const url = parseMcpServerUrl(serverUrl);
315+ if (!url) {
316+ return {
317+ warning: `MCP server "${serverName}": invalid URL (${serverUrl})`,
318+ };
319+ }
320+
321+ const transport = runtime.createTransport(url);
322+ const client = runtime.createClient();
323+
324+ try {
325+ await client.connect(transport, { timeout: MCP_DISCOVERY_TIMEOUT_MS });
326+ const listedTools = await listAllTools(client);
327+
328+ if (listedTools.length === 0) {
329+ await closeQuietly(transport);
330+ return {
331+ warning: `MCP server "${serverName}" exposes no tools and was skipped.`,
332+ };
333+ }
334+
335+ const warnings: string[] = [];
336+ const tools: Tool[] = [];
337+ const toolHandlers = new Map<string, ToolHandler>();
338+
339+ for (const listedTool of listedTools) {
340+ const { tool, handler } = createMcpTool(serverName, listedTool, client);
341+ if (toolHandlers.has(tool.name)) {
227342 warnings.push(
228- `MCP server "${entry.name}" exposes no usable tools and was skipped.`,
343+ `MCP server "${serverName}": duplicate tool name "${listedTool.name}" was skipped.`,
229344 );
230- await closeQuietly(transport);
231345 continue;
232346 }
347+ tools.push(tool);
348+ toolHandlers.set(tool.name, handler);
349+ }
233350
234- servers.push({
235- name: entry.name,
236- url: entry.url,
237- enabled: entry.enabled,
238- tools,
239- toolHandlers,
240- close: () => transport.close(),
241- });
242- } catch (error) {
243- warnings.push(
244- `MCP server "${entry.name}": ${getErrorMessage(error)} (${entry.url})`,
245- );
351+ if (tools.length === 0) {
246352 await closeQuietly(transport);
353+ return {
354+ warning: `MCP server "${serverName}" exposes no usable tools and was skipped.`,
355+ };
247356 }
248- }
249357
250- return { servers, warnings };
358+ return {
359+ warnings,
360+ tools,
361+ toolHandlers,
362+ close: () => transport.close(),
363+ };
364+ } catch (error) {
365+ await closeQuietly(transport);
366+ return {
367+ warning: `MCP server "${serverName}": ${getErrorMessage(error)} (${serverUrl})`,
368+ };
369+ }
251370 }
252371
253372 async function listAllTools(client: McpClientLike): Promise<McpListedTool[]> {