xonecas.io
64875
Mc

mini-coder / commit 1a739f2

fix: avoid connecting disabled MCP servers on startup

xonecas2026-04-19 1a739f21075907ae235b6a7d6692d92676a9228b parent 326697c

10 files changed

README.md+6−4
@@ -71,7 +71,7 @@ Six built-in tools, plus a conditional read-only image tool and any configured M
7171 | `/undo` | Remove the last conversational turn without touching filesystem changes. |
7272 | `/reasoning` | Show or hide model thinking. The setting is saved and restored on launch. |
7373 | `/verbose` | Expand shell output plus edit previews and edit errors in the conversation log. |
74-| `/mcp` | Open the MCP server picker and toggle discovered servers on or off for future turns. |
74+| `/mcp` | Open the MCP server picker and toggle configured servers on or off for future turns. |
7575 | `/todo` | Show the current session todo list in the conversation log as a UI-only checklist block. |
7676 | `/login` | Sign in with a supported OAuth provider. |
7777 | `/logout` | Remove saved OAuth credentials for a logged-in provider. |
@@ -126,7 +126,8 @@ Global defaults live in `~/.config/mini-coder/settings.json`.
126126 "servers": [
127127 {
128128 "name": "docs",
129- "url": "http://127.0.0.1:8787/mcp"
129+ "url": "http://127.0.0.1:8787/mcp",
130+ "enabled": true
130131 }
131132 ]
132133 }
@@ -135,8 +136,9 @@ Global defaults live in `~/.config/mini-coder/settings.json`.
135136
136137 - `mcp.servers` currently supports Streamable HTTP MCP endpoints.
137138 - Each server `name` becomes the imported tool prefix, so a remote `search` tool appears as `docs__search`.
138-- MCP servers are connected at startup; invalid or unreachable ones are skipped with a warning.
139-- `/mcp` can temporarily enable or disable discovered MCP servers for future turns during the current app run.
139+- MCP servers with `enabled: true` connect at startup; disabled ones stay disconnected until you turn them back on.
140+- Invalid MCP URLs are skipped immediately, and enabled servers that are unreachable are skipped with a warning.
141+- `/mcp` can enable or disable configured MCP servers during the current app run, and that on/off state is persisted.
140142
141143 ## Docs
142144
spec.md+12−10
@@ -147,17 +147,18 @@ Implementation details:
147147
148148 ### Configured MCP tools
149149
150-When `settings.json` includes `mcp.servers`, mini-coder connects to each configured Streamable HTTP MCP endpoint at startup and imports its advertised tools.
150+When `settings.json` includes `mcp.servers`, mini-coder keeps those Streamable HTTP MCP endpoints in runtime state, connects enabled ones when needed, and imports their advertised tools.
151151
152152 Implementation details:
153153
154154 - Only MCP **tools** are imported. MCP prompts and resources are not surfaced in the UI yet.
155155 - Each configured server entry stores a `name`, `url`, and `enabled` flag. When `enabled` is omitted while loading older configs, it defaults to `true`.
156-- Disabled servers are still discovered at startup so `/mcp` can re-enable them without reconnecting; the flag only controls whether their imported tools are exposed to new turns.
156+- Disabled servers stay disconnected at startup. They still appear in `/mcp`, and turning one back on reconnects it on demand before exposing its tools to new turns.
157+- Turning a server off disconnects it and removes its imported tools from future turns.
157158 - Imported tool names are prefixed as `<serverName>__<toolName>` so they stay stable and avoid collisions with built-ins and other servers.
158159 - Tool input schemas are forwarded from MCP JSON Schema into pi-ai tool definitions.
159160 - Tool calls execute through the MCP client and preserve text/image output directly. Unsupported MCP content kinds are summarized as text.
160-- Empty, unreachable, invalid, or tool-less MCP servers do not block startup; they are skipped with a warning.
161+- Invalid MCP URLs are skipped immediately. Enabled servers that are unreachable, empty, or tool-less do not block startup; they are skipped with a warning.
161162
162163 ## Community standards
163164
@@ -788,12 +789,12 @@ add tests for undo_
788789 | `/undo` | Remove the last conversational turn from history: the most recent user message and all assistant/tool messages that followed in that turn. Persisted UI messages are not part of turns and are not removed by `/undo`. Context-only — does not revert filesystem changes. …
789790 | `/reasoning` | Toggle display of model thinking/reasoning content in the log. The new on/off state is persisted immediately and restored on launch. When no setting exists yet, reasoning defaults to shown. …
790791 | `/verbose` | Toggle [verbose tool rendering](#verbose-tool-rendering) for shell previews/results, read previews/results, grep previews/results, edit previews, and edit errors. Successful edit results stay compact regardless of this setting. Todo tool results always render in full. …
791-| `/mcp` | Interactive MCP server selector. Lists discovered MCP servers with their current on/off state. Selecting a server toggles it for future turns, persists the new on/off state immediately, and appends a UI-only notice with the exact tool delta, for example `Disabled MCP server "docs" (-3 tools).` Discovery and connection still happen only at startup; `/mcp` does not add, remove, or reload servers. …
792+| `/mcp` | Interactive MCP server selector. Lists configured MCP servers with their current on/off state. Selecting a server toggles it for future turns, persists the new on/off state immediately, and appends a UI-only notice with the exact tool delta, for example `Disabled MCP server "docs" (-3 tools).` Turning a server on reconnects it on demand; turning it off disconnects it. `/mcp` still does not add, remove, or reload server definitions. …
792793 | `/todo` | Append the current session todo list to the conversation pane as a UI-only checklist block. The message is persisted with the session, excluded from model context, and does not create a session by itself when no session exists yet. …
793794 | `/login` | Interactive OAuth login. Shows a selector with available OAuth providers and their login status (logged in / not logged in). Selecting a provider starts the browser-based OAuth flow. Uses pi-ai's OAuth registry. Credentials are persisted to the app data directory and used for provider discovery on subsequent launches. …
794795 | `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
795796 | `/effort` | Interactive effort selector. Shows the four reasoning levels (`low`, `medium`, `high`, `xhigh`) with the current level highlighted. Updates the status bar immediately, and the selected effort is persisted immediately as the user's global default. The session record's `effort` field is not updated (it reflects the initial choice, like `/model`). …
796-| `/help` | List available commands, including the current on/off state of `/reasoning`, `/verbose`, and discovered MCP servers, plus loaded AGENTS.md files and discovered skills. …
797+| `/help` | List available commands, including the current on/off state of `/reasoning`, `/verbose`, and configured MCP servers, plus loaded AGENTS.md files and discovered skills. …
797798
798799 Commands are discoverable when the input starts with `/`: pressing `Tab` in that state switches from file-path autocomplete to interactive command select/filter.
799800
@@ -861,11 +862,12 @@ On launch, mini-coder:
861862 - Each returned model is added to the launch's available model list as `provider/model`, where `provider` is the configured custom provider name.
862863 - Invalid entries are dropped while loading settings. Duplicate custom provider names keep the first entry.
863864 - If an endpoint is unreachable, returns a non-2xx response, or the custom provider name conflicts with an already-available built-in provider, startup continues and a warning is added to the UI log.
864-4. Connects user-configured MCP servers from `settings.json`.
865+4. Loads user-configured MCP servers from `settings.json`.
865866 - Each entry must provide a `name` and Streamable HTTP endpoint `url`. It also stores an `enabled` flag; older entries that omit it default to enabled.
866867 - Invalid entries are dropped while loading settings. Duplicate MCP server names keep the first entry.
867- - Startup imports only MCP tools. Imported names are exposed to the model as `<serverName>__<toolName>`, and only servers whose `enabled` flag is on are exposed to new turns.
868- - If a server URL is invalid, the endpoint is unreachable, or the server exposes no tools, startup continues and a warning is added to the UI log.
868+ - Startup connects only servers whose `enabled` flag is on. Imported MCP tool names are exposed to the model as `<serverName>__<toolName>`.
869+ - Disabled servers stay listed in runtime state so `/mcp` can reconnect them on demand later in the same app run.
870+ - If an enabled server URL is invalid, the endpoint is unreachable, or the server exposes no tools, startup continues and a warning is added to the UI log.
869871 5. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
870872 - `defaultModel`: if the saved provider/model is currently available, use it; otherwise fall back to the first available model for this launch.
871873 - `defaultEffort`: if valid, use it; otherwise fall back to `medium`.
@@ -923,8 +925,8 @@ mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`
923925 - Custom providers are discovered only at startup. There is currently no interactive slash command to add or remove them.
924926 - `mcp.servers` is an optional array of user-configured Streamable HTTP MCP endpoints.
925927 - Each `mcp.servers` entry has a `name`, `url`, and `enabled` flag. `name` must be a simple identifier (`A-Z`, `a-z`, `0-9`, `_`, `-`) because it becomes the imported tool prefix, for example `docs__search`. Older entries that omit `enabled` default to `true` when loaded.
926-- Invalid MCP entries are dropped while loading settings. Unreachable, invalid-URL, or tool-less MCP servers do not block startup; mini-coder skips them and shows a warning in the interactive log.
927-- MCP server discovery is startup-only. `/mcp` can toggle already-discovered servers on or off for future turns during the current app run, and that on/off state is persisted back to `settings.json`, but there is still no interactive slash command to add, remove, or reload servers.
928+- Invalid MCP entries are dropped while loading settings. Invalid MCP URLs are skipped immediately. Enabled MCP servers that are unreachable or tool-less do not block startup; mini-coder skips them and shows a warning in the interactive log.
929+- MCP server definitions are loaded at startup. `/mcp` can toggle configured servers on or off for future turns during the current app run, and that on/off state is persisted back to `settings.json`. Turning a server on reconnects it on demand; turning it off disconnects it. There is still no interactive slash command to add, remove, or reload server definitions.
928930 - Only MCP tools are imported today; MCP prompts and resources are not surfaced yet.
929931
930932 ## Session persistence
src/index.test.ts+2−0
@@ -527,6 +527,7 @@ test("buildToolList includes connected MCP tools alongside built-ins", async ()
527527 name: "docs",
528528 url: "http://docs.test/mcp",
529529 enabled: true,
530+ connected: true,
530531 tools: [
531532 {
532533 name: "docs__search",
@@ -590,6 +591,7 @@ test("buildToolList excludes disabled MCP servers", () => {
590591 name: "docs",
591592 url: "http://docs.test/mcp",
592593 enabled: false,
594+ connected: false,
593595 tools: [
594596 {
595597 name: "docs__search",
src/index.ts+6−6
@@ -1,7 +1,7 @@
11 /**
22 * Entry point for mini-coder.
33 *
4- * Discovers available LLM providers, connects configured MCP tools,
4+ * Discovers available LLM providers, loads configured MCP tools,
55 * loads prompt context (AGENTS.md, skills, and theme), opens the session
66 * database, selects a model, and starts the TUI.
77 *
@@ -32,7 +32,7 @@ import {
3232 } from "./cli.ts";
3333 import { getErrorMessage } from "./errors.ts";
3434 import { type GitState, getGitState } from "./git.ts";
35-import { type ConnectedMcpServer, discoverMcpServers } from "./mcp.ts";
35+import { discoverMcpServers, type McpServerState } from "./mcp.ts";
3636 import { canonicalizePath } from "./paths.ts";
3737 import {
3838 type AgentsMdFile,
@@ -359,7 +359,7 @@ function selectModel(
359359 function buildTools(
360360 model: Model<string>,
361361 messages: AppState["messages"],
362- mcpServers: readonly ConnectedMcpServer[],
362+ mcpServers: readonly McpServerState[],
363363 ): { tools: Tool[]; toolHandlers: Map<string, ToolHandler> } {
364364 const tools: Tool[] = [
365365 shellTool,
@@ -379,7 +379,7 @@ function buildTools(
379379 ]);
380380
381381 for (const server of mcpServers) {
382- if (!server.enabled) {
382+ if (!server.enabled || !server.connected) {
383383 continue;
384384 }
385385
@@ -519,8 +519,8 @@ export interface AppState {
519519 showReasoning: boolean;
520520 /** Whether to show full (un-truncated) tool output. */
521521 verbose: boolean;
522- /** Discovered MCP servers, including their current enabled/disabled state. */
523- mcpServers: ConnectedMcpServer[];
522+ /** Configured MCP servers, including their current enabled/disabled state. */
523+ mcpServers: McpServerState[];
524524 /** Models discovered from custom OpenAI-compatible providers. */
525525 customModels: Model<string>[];
526526 /** Warnings from startup (e.g. unreachable custom providers or MCP servers). */
src/mcp.test.ts+22−5
@@ -1,5 +1,5 @@
11 import { expect, test } from "bun:test";
2-import { discoverMcpServers } from "./mcp.ts";
2+import { connectMcpServer, discoverMcpServers } from "./mcp.ts";
33
44 interface FakeTransport {
55 close(): Promise<void>;
@@ -41,6 +41,7 @@ type FakeToolResult =
4141
4242 interface FakeServerBehavior {
4343 closeCalls: number;
44+ connectCalls: number;
4445 connectError?: Error;
4546 pages?: FakeToolPage[];
4647 results?: Record<string, FakeToolResult | Error>;
@@ -77,6 +78,7 @@ function createFakeRuntime(servers: Record<string, FakeServerBehavior>) {
7778 `Unexpected MCP transport in test: ${transport.url}`,
7879 );
7980 }
81+ behavior.connectCalls += 1;
8082 if (behavior.connectError) {
8183 throw behavior.connectError;
8284 }
@@ -113,6 +115,7 @@ function createFakeRuntime(servers: Record<string, FakeServerBehavior>) {
113115 test("discoverMcpServers_reachableServer_importsPrefixedToolsAndExecutesCalls", async () => {
114116 const behavior: FakeServerBehavior = {
115117 closeCalls: 0,
118+ connectCalls: 0,
116119 pages: [
117120 {
118121 tools: [
@@ -151,6 +154,7 @@ test("discoverMcpServers_reachableServer_importsPrefixedToolsAndExecutesCalls",
151154 const server = result.servers[0]!;
152155 expect(server.name).toBe("docs");
153156 expect(server.enabled).toBe(true);
157+ expect(server.connected).toBe(true);
154158 expect(server.tools.map((tool) => tool.name)).toEqual(["docs__search"]);
155159 expect(server.tools[0]?.description).toBe("[MCP docs] Search the docs");
156160
@@ -172,9 +176,10 @@ test("discoverMcpServers_reachableServer_importsPrefixedToolsAndExecutesCalls",
172176 ]);
173177 });
174178
175-test("discoverMcpServers_structuredFallbackResult_formatsStructuredContent", async () => {
179+test("discoverMcpServers_disabledServer_staysDisconnectedUntilEnabled", async () => {
176180 const behavior: FakeServerBehavior = {
177181 closeCalls: 0,
182+ connectCalls: 0,
178183 pages: [
179184 {
180185 tools: [
@@ -197,6 +202,7 @@ test("discoverMcpServers_structuredFallbackResult_formatsStructuredContent", asy
197202 },
198203 toolCalls: [],
199204 };
205+ const runtime = createFakeRuntime({ "http://state.test/mcp": behavior });
200206
201207 const result = await discoverMcpServers(
202208 {
@@ -204,12 +210,21 @@ test("discoverMcpServers_structuredFallbackResult_formatsStructuredContent", asy
204210 { name: "state", url: "http://state.test/mcp", enabled: false },
205211 ],
206212 },
207- createFakeRuntime({ "http://state.test/mcp": behavior }),
213+ runtime,
208214 );
209215
210- expect(result.servers[0]?.enabled).toBe(false);
216+ const server = result.servers[0]!;
217+ expect(server.enabled).toBe(false);
218+ expect(server.connected).toBe(false);
219+ expect(server.tools).toEqual([]);
220+ expect(behavior.connectCalls).toBe(0);
221+
222+ expect(await connectMcpServer(server, runtime)).toEqual([]);
223+ expect(server.connected).toBe(true);
224+ expect(server.tools.map((tool) => tool.name)).toEqual(["state__inspect"]);
225+ expect(behavior.connectCalls).toBe(1);
211226
212- const handler = result.servers[0]?.toolHandlers.get("state__inspect");
227+ const handler = server.toolHandlers.get("state__inspect");
213228 const toolResult = await handler!({}, "/tmp");
214229
215230 expect(toolResult).toEqual({
@@ -227,11 +242,13 @@ test("discoverMcpServers_structuredFallbackResult_formatsStructuredContent", asy
227242 test("discoverMcpServers_invalidOrUnusableServers_skipsThemWithWarningsAndCleanup", async () => {
228243 const emptyBehavior: FakeServerBehavior = {
229244 closeCalls: 0,
245+ connectCalls: 0,
230246 pages: [{ tools: [] }],
231247 toolCalls: [],
232248 };
233249 const failingBehavior: FakeServerBehavior = {
234250 closeCalls: 0,
251+ connectCalls: 0,
235252 connectError: new Error("connect failed"),
236253 toolCalls: [],
237254 };
src/mcp.ts+179−60
@@ -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[]> {
src/settings.ts+1−1
@@ -61,7 +61,7 @@ export interface UserSettings {
6161 verbose?: boolean;
6262 /** Custom OpenAI-compatible provider endpoints. */
6363 customProviders?: CustomProvider[];
64- /** MCP server connections to import tools from at startup. */
64+ /** MCP server definitions to manage and connect when enabled. */
6565 mcp?: McpSettings;
6666 }
6767
src/ui/commands.test.ts+69−30
@@ -362,7 +362,7 @@ describe("ui/commands", () => {
362362 }
363363 });
364364
365- test("/mcp toggles the selected server and appends explicit tool deltas", () => {
365+ test("/mcp toggles the selected server, persists it, and reconnects when re-enabled", async () => {
366366 const state = createTestState();
367367 state.model = {
368368 id: "test-model",
@@ -376,25 +376,34 @@ describe("ui/commands", () => {
376376 contextWindow: 8192,
377377 maxTokens: 4096,
378378 };
379+
380+ const docsTools = [
381+ {
382+ name: "docs__search",
383+ description: "[MCP docs] Search the docs",
384+ parameters: Type.Object({}),
385+ },
386+ {
387+ name: "docs__fetch",
388+ description: "[MCP docs] Fetch a page",
389+ parameters: Type.Object({}),
390+ },
391+ ];
392+ const docsHandlers = new Map();
393+ let disconnectCalls = 0;
394+ let connectCalls = 0;
395+
379396 state.mcpServers = [
380397 {
381398 name: "docs",
382399 url: "http://docs.test/mcp",
383400 enabled: true,
384- tools: [
385- {
386- name: "docs__search",
387- description: "[MCP docs] Search the docs",
388- parameters: Type.Object({}),
389- },
390- {
391- name: "docs__fetch",
392- description: "[MCP docs] Fetch a page",
393- parameters: Type.Object({}),
394- },
395- ],
396- toolHandlers: new Map(),
397- close: async () => {},
401+ connected: true,
402+ tools: docsTools,
403+ toolHandlers: docsHandlers,
404+ close: async () => {
405+ disconnectCalls += 1;
406+ },
398407 },
399408 ];
400409 state.settings = saveSettings(state.settingsPath, {
@@ -418,23 +427,44 @@ describe("ui/commands", () => {
418427 text: string;
419428 sessionId: string | null;
420429 }> = [];
421- const controller = createCommandController({
422- openOverlay: (nextOverlay) => {
423- runtimeState.overlay = nextOverlay;
424- },
425- dismissOverlay: () => {
426- runtimeState.overlay = null;
430+ const controller = createCommandController(
431+ {
432+ openOverlay: (nextOverlay) => {
433+ runtimeState.overlay = nextOverlay;
434+ },
435+ dismissOverlay: () => {
436+ runtimeState.overlay = null;
437+ },
438+ setInputValue: () => {},
439+ appendInfoMessage: (text, nextState) => {
440+ appended.push({ text, sessionId: nextState.session?.id ?? null });
441+ },
442+ appendTodoMessage: () => {},
443+ scrollConversationToBottom: () => {},
444+ requestRender: () => {},
445+ reloadPromptContext: async () => {},
446+ openInBrowser: () => {},
427447 },
428- setInputValue: () => {},
429- appendInfoMessage: (text, nextState) => {
430- appended.push({ text, sessionId: nextState.session?.id ?? null });
448+ {
449+ connectMcpServer: async (server) => {
450+ connectCalls += 1;
451+ server.connected = true;
452+ server.tools = docsTools;
453+ server.toolHandlers = docsHandlers;
454+ server.close = async () => {
455+ disconnectCalls += 1;
456+ };
457+ return [];
458+ },
459+ disconnectMcpServer: async (server) => {
460+ await server.close();
461+ server.connected = false;
462+ server.tools = [];
463+ server.toolHandlers = new Map();
464+ server.close = async () => {};
465+ },
431466 },
432- appendTodoMessage: () => {},
433- scrollConversationToBottom: () => {},
434- requestRender: () => {},
435- reloadPromptContext: async () => {},
436- openInBrowser: () => {},
437- });
467+ );
438468
439469 try {
440470 expect(controller.handleCommand("mcp", state)).toBe(true);
@@ -444,9 +474,12 @@ describe("ui/commands", () => {
444474 "docs__search",
445475 );
446476 renderSelect(firstOverlay).props.onKeyPress?.("enter");
477+ await Promise.resolve();
478+ await Promise.resolve();
447479
448480 expect(runtimeState.overlay).toBeNull();
449481 expect(state.mcpServers[0]?.enabled).toBe(false);
482+ expect(state.mcpServers[0]?.connected).toBe(false);
450483 expect(state.settings.mcp).toEqual({
451484 servers: [
452485 {
@@ -477,6 +510,7 @@ describe("ui/commands", () => {
477510 ],
478511 },
479512 });
513+ expect(disconnectCalls).toBe(1);
480514 expect(appended).toEqual([
481515 {
482516 text: 'Disabled MCP server "docs" (-2 tools).',
@@ -490,8 +524,12 @@ describe("ui/commands", () => {
490524 expect(controller.handleCommand("mcp", state)).toBe(true);
491525 const secondOverlay = expectOverlay(runtimeState.overlay);
492526 renderSelect(secondOverlay).props.onKeyPress?.("enter");
527+ await Promise.resolve();
528+ await Promise.resolve();
493529
494530 expect(state.mcpServers[0]?.enabled).toBe(true);
531+ expect(state.mcpServers[0]?.connected).toBe(true);
532+ expect(connectCalls).toBe(1);
495533 expect(loadSettings(state.settingsPath)).toEqual({
496534 mcp: {
497535 servers: [
@@ -527,6 +565,7 @@ describe("ui/commands", () => {
527565 name: "docs",
528566 url: "http://docs.test/mcp",
529567 enabled: false,
568+ connected: false,
530569 tools: [],
531570 toolHandlers: new Map(),
532571 close: async () => {},
src/ui/commands.ts+71−5
@@ -18,6 +18,7 @@ import { getErrorMessage } from "../errors.ts";
1818 import type { AppState } from "../index.ts";
1919 import { getAvailableModels, saveOAuthCredentials } from "../index.ts";
2020 import { COMMANDS } from "../input.ts";
21+import { connectMcpServer, disconnectMcpServer } from "../mcp.ts";
2122 import {
2223 clearConversationState,
2324 forkSession,
@@ -75,6 +76,22 @@ interface UiCommandRuntime {
7576 openInBrowser: (url: string) => void;
7677 }
7778
79+interface UiCommandDeps {
80+ /** Connect a configured MCP server on demand. */
81+ connectMcpServer: (
82+ server: AppState["mcpServers"][number],
83+ ) => Promise<string[]>;
84+ /** Disconnect an MCP server and clear its imported tools. */
85+ disconnectMcpServer: (
86+ server: AppState["mcpServers"][number],
87+ ) => Promise<void>;
88+}
89+
90+const defaultUiCommandDeps: UiCommandDeps = {
91+ connectMcpServer,
92+ disconnectMcpServer,
93+};
94+
7895 /** Public command actions consumed by `ui.ts` and unit tests. */
7996 interface UiCommandController {
8097 /** Apply a model selection and persist it to settings. */
@@ -223,10 +240,11 @@ function formatMcpServerLabel(server: AppState["mcpServers"][number]): string {
223240
224241 function formatMcpToggleMessage(
225242 server: AppState["mcpServers"][number],
243+ toolCount: number,
226244 ): string {
227245 const action = server.enabled ? "Enabled" : "Disabled";
228- const delta = `${server.enabled ? "+" : "-"}${server.tools.length}`;
229- const toolSuffix = server.tools.length === 1 ? "tool" : "tools";
246+ const delta = `${server.enabled ? "+" : "-"}${toolCount}`;
247+ const toolSuffix = toolCount === 1 ? "tool" : "tools";
230248 return `${action} MCP server "${server.name}" (${delta} ${toolSuffix}).`;
231249 }
232250
@@ -257,14 +275,64 @@ function persistMcpServerSettings(
257275 });
258276 }
259277
278+async function toggleMcpServer(
279+ server: AppState["mcpServers"][number],
280+ state: AppState,
281+ runtime: UiCommandRuntime,
282+ deps: UiCommandDeps,
283+): Promise<void> {
284+ try {
285+ if (server.enabled) {
286+ const toolCount = server.tools.length;
287+ await deps.disconnectMcpServer(server);
288+ server.enabled = false;
289+ persistMcpServerSettings(state, server);
290+ runtime.appendInfoMessage(
291+ formatMcpToggleMessage(server, toolCount),
292+ state,
293+ );
294+ runtime.requestRender("normal");
295+ return;
296+ }
297+
298+ const warnings = await deps.connectMcpServer(server);
299+ if (!server.connected) {
300+ for (const warning of warnings) {
301+ runtime.appendInfoMessage(warning, state);
302+ }
303+ runtime.requestRender("normal");
304+ return;
305+ }
306+
307+ server.enabled = true;
308+ persistMcpServerSettings(state, server);
309+ runtime.appendInfoMessage(
310+ formatMcpToggleMessage(server, server.tools.length),
311+ state,
312+ );
313+ for (const warning of warnings) {
314+ runtime.appendInfoMessage(warning, state);
315+ }
316+ runtime.requestRender("normal");
317+ } catch (error) {
318+ runtime.appendInfoMessage(
319+ `MCP server "${server.name}": ${getErrorMessage(error)}`,
320+ state,
321+ );
322+ runtime.requestRender("normal");
323+ }
324+}
325+
260326 /**
261327 * Create the UI command controller bound to the current UI runtime hooks.
262328 *
263329 * @param runtime - State mutation and rendering hooks owned by `ui.ts`.
330+ * @param deps - Internal MCP command dependencies, mainly for tests.
264331 * @returns Command actions for slash commands and overlays.
265332 */
266333 export function createCommandController(
267334 runtime: UiCommandRuntime,
335+ deps: UiCommandDeps = defaultUiCommandDeps,
268336 ): UiCommandController {
269337 const openSelectOverlay = (
270338 state: AppState,
@@ -523,9 +591,7 @@ export function createCommandController(
523591 );
524592 runtime.dismissOverlay();
525593 if (server) {
526- server.enabled = !server.enabled;
527- persistMcpServerSettings(state, server);
528- runtime.appendInfoMessage(formatMcpToggleMessage(server), state);
594+ void toggleMcpServer(server, state, runtime, deps);
529595 }
530596 },
531597 );
src/ui/help.ts+2−2
@@ -22,7 +22,7 @@ export interface HelpRenderState {
2222 showReasoning: AppState["showReasoning"];
2323 /** Whether verbose tool rendering is enabled in the log. */
2424 verbose: AppState["verbose"];
25- /** Connected MCP servers discovered at startup. */
25+ /** Configured MCP servers and their current on/off state. */
2626 mcpServers: AppState["mcpServers"];
2727 }
2828
@@ -36,7 +36,7 @@ export const COMMAND_DESCRIPTIONS: Record<string, string> = {
3636 undo: "Undo last turn",
3737 reasoning: "Toggle thinking display",
3838 verbose: "Toggle verbose tool rendering",
39- mcp: "Toggle discovered MCP servers",
39+ mcp: "Toggle configured MCP servers",
4040 todo: "Show the current todo list",
4141 login: "OAuth login",
4242 logout: "OAuth logout",