xonecas.io
64875
Mc

mini-coder / commit aa4298f

feat: add MCP support and /mcp toggles

xonecas2026-04-19 aa4298fc238930e5511f7dd543b35967859f85d4 parent b452dd5

15 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

README.md+34−6
@@ -39,7 +39,7 @@ $ mc
3939
4040 ## Tools
4141
42-Six built-in tools, plus a conditional read-only image tool:
42+Six built-in tools, plus a conditional read-only image tool and any configured MCP tools:
4343
4444 - **`shell`** — runs commands in the user's shell. Returns stdout, stderr, and exit code. Large output is truncated to protect model context.
4545 - **`read`** — reads UTF-8 text files from disk, optionally by line window.
@@ -48,8 +48,7 @@ Six built-in tools, plus a conditional read-only image tool:
4848 - **`todoWrite`** — creates or updates the session todo list incrementally and returns the full current snapshot.
4949 - **`todoRead`** — returns the full current session todo list snapshot.
5050 - **`readImage`** — reads PNG, JPEG, GIF, and WebP files as model input. Only registered when the active model supports images.
51-
52-Plugins can add more tools, but the core stays intentionally small.
51+- **Configured MCP tools** — tools discovered from `settings.json` Streamable HTTP MCP servers. Imported tool names are prefixed with the server name, for example `docs__search`.
5352
5453 ## Features
5554
@@ -59,7 +58,7 @@ Plugins can add more tools, but the core stays intentionally small.
5958 - **Reasoning and verbosity controls** — toggle thinking visibility and verbose tool rendering on demand. Preferences persist across launches.
6059 - **[AGENTS.md](https://agents.md) support** — project-specific instructions discovered root-to-leaf, with `~/.agents/` for global instructions.
6160 - **[Agent Skills](https://agentskills.io)** — skill catalogs exposed in the prompt. `/skill:name` injects a skill body into the next user message.
62-- **Plugins** — optional tools, integrations, theme overrides, and prompt suffixes without bloating the core.
61+- **Settings-driven MCP tools** — connect Streamable HTTP MCP servers from `~/.config/mini-coder/settings.json` and expose their tools directly in the core runtime.
6362
6463 ## Commands
6564
@@ -72,11 +71,12 @@ Plugins can add more tools, but the core stays intentionally small.
7271 | `/undo` | Remove the last conversational turn without touching filesystem changes. |
7372 | `/reasoning` | Show or hide model thinking. The setting is saved and restored on launch. |
7473 | `/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. |
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. |
7878 | `/effort` | Choose low, medium, high, or xhigh reasoning effort. |
79-| `/help` | Show commands, current toggles, loaded AGENTS.md files, skills, and plugins. |
79+| `/help` | Show commands, current toggles, loaded AGENTS.md files, skills, and MCP servers with on/off state. |
8080
8181 ## Key bindings
8282
@@ -108,7 +108,35 @@ $ printf '%s\n' 'fix the failing tests' | mc
108108 - Without `--json`, keeps stdout script-friendly by writing only the final assistant text there, while lightweight assistant commentary snippets from tool-use turns go to stderr.
109109 - With `--json`, writes NDJSON events for completed assistant/tool-result messages plus `done` / `error` / `aborted` outcomes; queued `user_message` events may also appear. Streaming deltas are omitted.
110110 - Headless runs still persist like normal sessions and show up in `/session` history for that working directory.
111-- Interactive slash commands such as `/model`, `/session`, and `/help` are not available in headless mode.
111+- Interactive slash commands such as `/model`, `/session`, `/mcp`, and `/help` are not available in headless mode.
112+
113+## Settings
114+
115+Global defaults live in `~/.config/mini-coder/settings.json`.
116+
117+```json
118+{
119+ "customProviders": [
120+ {
121+ "name": "lm-studio",
122+ "baseUrl": "http://127.0.0.1:1234/v1"
123+ }
124+ ],
125+ "mcp": {
126+ "servers": [
127+ {
128+ "name": "docs",
129+ "url": "http://127.0.0.1:8787/mcp"
130+ }
131+ ]
132+ }
133+}
134+```
135+
136+- `mcp.servers` currently supports Streamable HTTP MCP endpoints.
137+- 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.
112140
113141 ## Docs
114142
TODO.md+3−4
@@ -7,17 +7,16 @@ The spec and code are the sources of truth; this file is just the verified backl
77
88 ## Open issues:
99
10-## MCP + theme config plan
10+## Theme config plan
1111
12-- [ ] Extend the existing `settings.json` schema/loader with `mcp` config, following the same config-file model as `customProviders` (`src/settings.ts`, `src/index.ts`, `spec.md`)
13-- [ ] Add first-party MCP client support using an official npm package and register the resulting tools from built-in runtime code instead of a plugin layer (`src/index.ts`, `src/tools.ts`, `src/agent.ts`, `spec.md`)
1412 - [ ] Extend the existing `settings.json` schema/loader with `theme` overrides and merge them into the active UI theme (`src/settings.ts`, `src/theme.ts`, `src/index.ts`, `spec.md`)
15-- [ ] Update tests and user-facing docs/help for the new `settings.json`-based MCP/theme setup and remove plugin references (`src/index.test.ts`, `src/ui/help.ts`, `README.md`, `spec.md`)
13+- [ ] Update tests and user-facing docs/help for the `settings.json`-based theme setup (`src/index.test.ts`, `src/ui/help.ts`, `README.md`, `spec.md`)
1614
1715 ## Verified UX / behavior debt
1816
1917 - [ ] Prevent `/session` from switching sessions mid-run (`src/ui/commands.ts`, `src/ui/agent.ts`)
2018 - [ ] Preserve the current slash-command draft when opening command autocomplete instead of clearing the input (`src/ui.ts`, `src/ui/commands.ts`)
19+- [ ] Persist `/mcp` enabled/disabled state across app restarts (`src/settings.ts`, `src/index.ts`, `src/ui/commands.ts`, `spec.md`)
2120
2221 ## Product backlog
2322
spec.md+41−9
@@ -57,7 +57,7 @@ This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom
5757
5858 ## Tools
5959
60-Six built-in tools, plus a conditional read-only image tool.
60+Six built-in tools, plus a conditional read-only image tool and any tools imported from configured MCP servers.
6161
6262 ### `shell`
6363
@@ -145,6 +145,18 @@ Implementation details:
145145 - Returns `ImageContent` in the tool result (pi-ai's `ToolResultMessage.content` supports images natively).
146146 - Only registered when the current model supports image input. Hidden from models that don't.
147147
148+### Configured MCP tools
149+
150+When `settings.json` includes `mcp.servers`, mini-coder connects to each configured Streamable HTTP MCP endpoint at startup and imports its advertised tools.
151+
152+Implementation details:
153+
154+- Only MCP **tools** are imported. MCP prompts and resources are not surfaced in the UI yet.
155+- Imported tool names are prefixed as `<serverName>__<toolName>` so they stay stable and avoid collisions with built-ins and other servers.
156+- Tool input schemas are forwarded from MCP JSON Schema into pi-ai tool definitions.
157+- Tool calls execute through the MCP client and preserve text/image output directly. Unsupported MCP content kinds are summarized as text.
158+- Empty, unreachable, invalid, or tool-less MCP servers do not block startup; they are skipped with a warning.
159+
148160 ## Community standards
149161
150162 ### AGENTS.md
@@ -774,11 +786,12 @@ add tests for undo_
774786 | `/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. …
775787 | `/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. …
776788 | `/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. …
789+| `/mcp` | Interactive MCP server selector. Lists discovered MCP servers with their current on/off state. Selecting a server toggles it for future turns 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. …
777790 | `/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. …
778791 | `/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. …
779792 | `/logout` | Interactive OAuth logout. Shows a selector with logged-in OAuth providers. Selecting one clears its saved credentials. …
780793 | `/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`). …
781-| `/help` | List available commands, including the current on/off state of `/reasoning` and `/verbose`, plus loaded AGENTS.md files and discovered skills. …
794+| `/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. …
782795
783796 Commands are discoverable when the input starts with `/`: pressing `Tab` in that state switches from file-path autocomplete to interactive command select/filter.
784797
@@ -801,7 +814,7 @@ Prompt source in headless mode:
801814 - If headless mode was selected because `stdout` is not a TTY but `stdin` is still interactive, startup fails with a clear error unless `-p` was provided. Headless mode does not fall back to an interactive prompt.
802815 - Empty or whitespace-only headless input is an error.
803816
804-Input parsing in headless mode reuses the same rules as the interactive input area for plain text, `/skill:name`, and standalone image-file paths. Interactive slash commands such as `/model`, `/session`, `/new`, `/fork`, `/undo`, `/login`, `/logout`, `/effort`, `/todo`, and `/help` are not available in headless mode and should fail clearly rather than attempting to open interactive UI.
817+Input parsing in headless mode reuses the same rules as the interactive input area for plain text, `/skill:name`, and standalone image-file paths. Interactive slash commands such as `/model`, `/session`, `/new`, `/fork`, `/undo`, `/login`, `/logout`, `/effort`, `/mcp`, `/todo`, and `/help` are not available in headless mode and should fail clearly rather than attempting to open interactive UI.
805818
806819 ### Headless text output
807820
@@ -846,17 +859,22 @@ On launch, mini-coder:
846859 - Each returned model is added to the launch's available model list as `provider/model`, where `provider` is the configured custom provider name.
847860 - Invalid entries are dropped while loading settings. Duplicate custom provider names keep the first entry.
848861 - 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.
849-4. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
862+4. Connects user-configured MCP servers from `settings.json`.
863+ - Each entry must provide a `name` and Streamable HTTP endpoint `url`.
864+ - Invalid entries are dropped while loading settings. Duplicate MCP server names keep the first entry.
865+ - Startup imports only MCP tools. Imported names are exposed to the model as `<serverName>__<toolName>`.
866+ - 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.
867+5. Selects the startup model, effort, reasoning visibility, and verbose mode from those settings when available.
850868 - `defaultModel`: if the saved provider/model is currently available, use it; otherwise fall back to the first available model for this launch.
851869 - `defaultEffort`: if valid, use it; otherwise fall back to `medium`.
852870 - `showReasoning`: if present, use it; otherwise fall back to `true`.
853871 - `verbose`: if present, use it; otherwise fall back to `false`.
854-5. Loads AGENTS.md files and skills.
855-6. Selects the launch mode:
872+6. Loads AGENTS.md files and skills.
873+7. Selects the launch mode:
856874 - Interactive TUI when `stdin` and `stdout` are both TTYs and `-p` was not provided.
857875 - Headless one-shot mode otherwise.
858-7. In interactive mode, renders the UI with an empty conversation log, a minimal `mini-coder` empty-state banner (showing the packaged version when available, otherwise a simple dev label), and the status bar populated.
859-8. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
876+8. In interactive mode, renders the UI with an empty conversation log, a minimal `mini-coder` empty-state banner (showing the packaged version when available, otherwise a simple dev label), and the status bar populated.
877+9. Starts a new session only when a prompt is actually submitted (no 0-message sessions in the DB).
860878
861879 The empty-state banner is only shown while the conversation log has no messages. In headless mode, stdout is reserved for the final assistant text response by default, with any lightweight non-JSON activity snippets going to stderr, or NDJSON event output when `--json` is used.
862880
@@ -877,7 +895,15 @@ mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`
877895 "name": "lm-studio",
878896 "baseUrl": "http://127.0.0.1:1234/v1"
879897 }
880- ]
898+ ],
899+ "mcp": {
900+ "servers": [
901+ {
902+ "name": "docs",
903+ "url": "http://127.0.0.1:8787/mcp"
904+ }
905+ ]
906+ }
881907 }
882908 ```
883909
@@ -893,6 +919,12 @@ mini-coder persists global user defaults in `~/.config/mini-coder/settings.json`
893919 - Each `customProviders` entry has a `name`, `baseUrl`, and optional `apiKey`. The `name` becomes the provider prefix shown in model ids such as `lm-studio/qwen3-coder`.
894920 - Unreachable or invalid custom providers do not block startup; mini-coder skips them and shows a warning in the interactive log.
895921 - Custom providers are discovered only at startup. There is currently no interactive slash command to add or remove them.
922+- `mcp.servers` is an optional array of user-configured Streamable HTTP MCP endpoints.
923+- Each `mcp.servers` entry has a `name` and `url`. `name` must be a simple identifier (`A-Z`, `a-z`, `0-9`, `_`, `-`) because it becomes the imported tool prefix, for example `docs__search`.
924+- 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.
925+- MCP server discovery is startup-only. `/mcp` can toggle already-discovered servers on or off for future turns during the current app run, but there is still no interactive slash command to add, remove, or reload servers.
926+- `/mcp` changes only the current in-memory runtime state. It does not persist a setting change.
927+- Only MCP tools are imported today; MCP prompts and resources are not surfaced yet.
896928
897929 ## Session persistence
898930
src/headless.test.ts+1−0
@@ -58,6 +58,7 @@ function createTestState(): AppState {
5858 showReasoning: true,
5959 verbose: false,
6060 versionLabel: "dev",
61+ mcpServers: [],
6162 customModels: [],
6263 startupWarnings: [],
6364 };
src/index.test.ts+118−1
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { pathToFileURL } from "node:url";
6-import type { Model } from "@mariozechner/pi-ai";
6+import { type Model, Type } from "@mariozechner/pi-ai";
77 import {
88 type AppState,
99 buildToolList,
@@ -55,6 +55,7 @@ function createTestState(): AppState {
5555 showReasoning: true,
5656 verbose: false,
5757 versionLabel: "dev",
58+ mcpServers: [],
5859 customModels: [],
5960 startupWarnings: [],
6061 };
@@ -506,6 +507,122 @@ test("buildToolList uses validated built-in handlers and gates readImage by mode
506507 }
507508 });
508509
510+test("buildToolList includes connected MCP tools alongside built-ins", async () => {
511+ const state = createTestState();
512+ try {
513+ state.model = {
514+ id: "test-model",
515+ name: "test-model",
516+ api: "openai-completions",
517+ provider: "test-provider",
518+ baseUrl: "http://localhost:1234/v1",
519+ reasoning: false,
520+ input: ["text"],
521+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
522+ contextWindow: 8192,
523+ maxTokens: 4096,
524+ };
525+ state.mcpServers = [
526+ {
527+ name: "docs",
528+ url: "http://docs.test/mcp",
529+ enabled: true,
530+ tools: [
531+ {
532+ name: "docs__search",
533+ description: "[MCP docs] Search the docs",
534+ parameters: Type.Object({
535+ query: Type.String(),
536+ }),
537+ },
538+ ],
539+ toolHandlers: new Map([
540+ [
541+ "docs__search",
542+ async (args) => ({
543+ content: [
544+ {
545+ type: "text",
546+ text: JSON.stringify(args),
547+ },
548+ ],
549+ isError: false,
550+ }),
551+ ],
552+ ]),
553+ close: async () => {},
554+ },
555+ ];
556+
557+ const toolList = buildToolList(state);
558+
559+ expect(toolList.tools.map((tool) => tool.name)).toContain("docs__search");
560+ const toolResult = await toolList.toolHandlers.get("docs__search")!(
561+ { query: "routing" },
562+ state.cwd,
563+ );
564+ expect(toolResult).toEqual({
565+ content: [{ type: "text", text: '{"query":"routing"}' }],
566+ isError: false,
567+ });
568+ } finally {
569+ state.db.close();
570+ }
571+});
572+
573+test("buildToolList excludes disabled MCP servers", () => {
574+ const state = createTestState();
575+ try {
576+ state.model = {
577+ id: "test-model",
578+ name: "test-model",
579+ api: "openai-completions",
580+ provider: "test-provider",
581+ baseUrl: "http://localhost:1234/v1",
582+ reasoning: false,
583+ input: ["text"],
584+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
585+ contextWindow: 8192,
586+ maxTokens: 4096,
587+ };
588+ state.mcpServers = [
589+ {
590+ name: "docs",
591+ url: "http://docs.test/mcp",
592+ enabled: false,
593+ tools: [
594+ {
595+ name: "docs__search",
596+ description: "[MCP docs] Search the docs",
597+ parameters: Type.Object({
598+ query: Type.String(),
599+ }),
600+ },
601+ ],
602+ toolHandlers: new Map([
603+ [
604+ "docs__search",
605+ async () => ({
606+ content: [{ type: "text", text: "ignored" }],
607+ isError: false,
608+ }),
609+ ],
610+ ]),
611+ close: async () => {},
612+ },
613+ ];
614+
615+ const toolList = buildToolList(state);
616+
617+ expect(toolList.tools.map((tool) => tool.name)).not.toContain(
618+ "docs__search",
619+ );
620+ expect(toolList.toolHandlers.has("docs__search")).toBe(false);
621+ } finally {
622+ state.db.close();
623+ }
624+});
625+
509626 // ---------------------------------------------------------------------------
510627 // getAvailableModels with custom models
511628 // ---------------------------------------------------------------------------
src/index.ts+25−6
@@ -1,9 +1,9 @@
11 /**
22 * Entry point for mini-coder.
33 *
4- * Discovers available LLM providers, loads prompt context (AGENTS.md,
5- * skills, and theme), opens the session database, selects a model, and
6- * starts the TUI.
4+ * Discovers available LLM providers, connects configured MCP tools,
5+ * loads prompt context (AGENTS.md, skills, and theme), opens the session
6+ * database, selects a model, and starts the TUI.
77 *
88 * @module
99 */
@@ -32,6 +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";
3536 import { canonicalizePath } from "./paths.ts";
3637 import {
3738 type AgentsMdFile,
@@ -358,6 +359,7 @@ function selectModel(
358359 function buildTools(
359360 model: Model<string>,
360361 messages: AppState["messages"],
362+ mcpServers: readonly ConnectedMcpServer[],
361363 ): { tools: Tool[]; toolHandlers: Map<string, ToolHandler> } {
362364 const tools: Tool[] = [
363365 shellTool,
@@ -376,6 +378,17 @@ function buildTools(
376378 [todoReadTool.name, createTodoReadToolHandler(messages)],
377379 ]);
378380
381+ for (const server of mcpServers) {
382+ if (!server.enabled) {
383+ continue;
384+ }
385+
386+ tools.push(...server.tools);
387+ for (const [name, handler] of server.toolHandlers) {
388+ toolHandlers.set(name, handler);
389+ }
390+ }
391+
379392 // Conditionally register readImage for vision-capable models
380393 if (model.input.includes("image")) {
381394 tools.push(readImageTool);
@@ -506,9 +519,11 @@ export interface AppState {
506519 showReasoning: boolean;
507520 /** Whether to show full (un-truncated) tool output. */
508521 verbose: boolean;
522+ /** Discovered MCP servers, including their current enabled/disabled state. */
523+ mcpServers: ConnectedMcpServer[];
509524 /** Models discovered from custom OpenAI-compatible providers. */
510525 customModels: Model<string>[];
511- /** Warnings from startup (e.g. unreachable custom providers). */
526+ /** Warnings from startup (e.g. unreachable custom providers or MCP servers). */
512527 startupWarnings: string[];
513528 }
514529
@@ -541,6 +556,8 @@ export async function init(): Promise<AppState> {
541556 providers.set(name, key);
542557 }
543558
559+ const mcpResult = await discoverMcpServers(settings.mcp);
560+
544561 const builtInModels = listAvailableModels(providers);
545562 const availableModels = [...builtInModels, ...customResult.models];
546563 const startup = resolveStartupSettings(
@@ -580,8 +597,9 @@ export async function init(): Promise<AppState> {
580597 queuedUserMessages: [],
581598 showReasoning: startup.showReasoning,
582599 verbose: startup.verbose,
600+ mcpServers: mcpResult.servers,
583601 customModels: customResult.models,
584- startupWarnings: customResult.warnings,
602+ startupWarnings: [...customResult.warnings, ...mcpResult.warnings],
585603 };
586604 }
587605
@@ -628,7 +646,7 @@ export function buildToolList(state: AppState): {
628646 toolHandlers: Map<string, ToolHandler>;
629647 } {
630648 if (!state.model) return { tools: [], toolHandlers: new Map() };
631- return buildTools(state.model, state.messages);
649+ return buildTools(state.model, state.messages, state.mcpServers);
632650 }
633651
634652 /**
@@ -677,6 +695,7 @@ export function getAvailableModels(state: AppState): Model<string>[] {
677695
678696 /** Clean up resources on shutdown. */
679697 export async function shutdown(state: AppState): Promise<void> {
698+ await Promise.allSettled(state.mcpServers.map((server) => server.close()));
680699 state.db.close();
681700 }
682701
src/input.ts+1−0
@@ -23,6 +23,7 @@ export const COMMANDS = [
2323 "undo",
2424 "reasoning",
2525 "verbose",
26+ "mcp",
2627 "todo",
2728 "login",
2829 "logout",
src/mcp.test.ts+257−0
@@ -0,0 +1,257 @@
1+import { expect, test } from "bun:test";
2+import { discoverMcpServers } from "./mcp.ts";
3+
4+interface FakeTransport {
5+ close(): Promise<void>;
6+ url: string;
7+}
8+
9+interface FakeToolPage {
10+ tools: Array<{
11+ description?: string;
12+ inputSchema: {
13+ properties?: Record<string, object>;
14+ required?: string[];
15+ type: "object";
16+ };
17+ name: string;
18+ }>;
19+ nextCursor?: string;
20+}
21+
22+type FakeToolResult =
23+ | {
24+ content: Array<
25+ | {
26+ type: "text";
27+ text: string;
28+ }
29+ | {
30+ type: "image";
31+ data: string;
32+ mimeType: string;
33+ }
34+ >;
35+ structuredContent?: unknown;
36+ isError?: boolean;
37+ }
38+ | {
39+ toolResult: unknown;
40+ };
41+
42+interface FakeServerBehavior {
43+ closeCalls: number;
44+ connectError?: Error;
45+ pages?: FakeToolPage[];
46+ results?: Record<string, FakeToolResult | Error>;
47+ toolCalls: Array<{
48+ arguments?: Record<string, unknown>;
49+ name: string;
50+ }>;
51+}
52+
53+function createFakeRuntime(servers: Record<string, FakeServerBehavior>) {
54+ return {
55+ createTransport(url: URL): FakeTransport {
56+ const behavior = servers[url.toString()];
57+ if (!behavior) {
58+ throw new Error(`Unexpected MCP URL in test: ${url}`);
59+ }
60+
61+ return {
62+ url: url.toString(),
63+ close: async () => {
64+ behavior.closeCalls += 1;
65+ },
66+ };
67+ },
68+ createClient() {
69+ let behavior: FakeServerBehavior | null = null;
70+ let pageIndex = 0;
71+
72+ return {
73+ async connect(transport: FakeTransport) {
74+ behavior = servers[transport.url] ?? null;
75+ if (!behavior) {
76+ throw new Error(
77+ `Unexpected MCP transport in test: ${transport.url}`,
78+ );
79+ }
80+ if (behavior.connectError) {
81+ throw behavior.connectError;
82+ }
83+ },
84+ async listTools() {
85+ if (!behavior) {
86+ throw new Error("MCP client used before connect");
87+ }
88+
89+ const page = behavior.pages?.[pageIndex] ?? { tools: [] };
90+ pageIndex += 1;
91+ return page;
92+ },
93+ async callTool(params: {
94+ arguments?: Record<string, unknown>;
95+ name: string;
96+ }) {
97+ if (!behavior) {
98+ throw new Error("MCP client used before connect");
99+ }
100+
101+ behavior.toolCalls.push(params);
102+ const result = behavior.results?.[params.name];
103+ if (result instanceof Error) {
104+ throw result;
105+ }
106+ return result ?? { content: [] };
107+ },
108+ };
109+ },
110+ };
111+}
112+
113+test("discoverMcpServers_reachableServer_importsPrefixedToolsAndExecutesCalls", async () => {
114+ const behavior: FakeServerBehavior = {
115+ closeCalls: 0,
116+ pages: [
117+ {
118+ tools: [
119+ {
120+ name: "search",
121+ description: "Search the docs",
122+ inputSchema: {
123+ type: "object",
124+ properties: {
125+ query: { type: "string" },
126+ },
127+ required: ["query"],
128+ },
129+ },
130+ ],
131+ },
132+ ],
133+ results: {
134+ search: {
135+ content: [{ type: "text", text: "Found it" }],
136+ },
137+ },
138+ toolCalls: [],
139+ };
140+
141+ const result = await discoverMcpServers(
142+ {
143+ servers: [{ name: "docs", url: "http://docs.test/mcp" }],
144+ },
145+ createFakeRuntime({ "http://docs.test/mcp": behavior }),
146+ );
147+
148+ expect(result.warnings).toEqual([]);
149+ expect(result.servers).toHaveLength(1);
150+
151+ const server = result.servers[0]!;
152+ expect(server.name).toBe("docs");
153+ expect(server.enabled).toBe(true);
154+ expect(server.tools.map((tool) => tool.name)).toEqual(["docs__search"]);
155+ expect(server.tools[0]?.description).toBe("[MCP docs] Search the docs");
156+
157+ const handler = server.toolHandlers.get("docs__search");
158+ expect(handler).toBeDefined();
159+ await expect(handler!({}, "/tmp")).rejects.toThrow(/Validation failed/);
160+
161+ const toolResult = await handler!({ query: "routing" }, "/tmp");
162+ expect(toolResult).toEqual({
163+ content: [{ type: "text", text: "Found it" }],
164+ details: undefined,
165+ isError: false,
166+ });
167+ expect(behavior.toolCalls).toEqual([
168+ {
169+ name: "search",
170+ arguments: { query: "routing" },
171+ },
172+ ]);
173+});
174+
175+test("discoverMcpServers_structuredFallbackResult_formatsStructuredContent", async () => {
176+ const behavior: FakeServerBehavior = {
177+ closeCalls: 0,
178+ pages: [
179+ {
180+ tools: [
181+ {
182+ name: "inspect",
183+ inputSchema: {
184+ type: "object",
185+ properties: {},
186+ },
187+ },
188+ ],
189+ },
190+ ],
191+ results: {
192+ inspect: {
193+ content: [],
194+ structuredContent: { ok: true, count: 2 },
195+ isError: true,
196+ },
197+ },
198+ toolCalls: [],
199+ };
200+
201+ const result = await discoverMcpServers(
202+ {
203+ servers: [{ name: "state", url: "http://state.test/mcp" }],
204+ },
205+ createFakeRuntime({ "http://state.test/mcp": behavior }),
206+ );
207+
208+ const handler = result.servers[0]?.toolHandlers.get("state__inspect");
209+ const toolResult = await handler!({}, "/tmp");
210+
211+ expect(toolResult).toEqual({
212+ content: [
213+ {
214+ type: "text",
215+ text: JSON.stringify({ ok: true, count: 2 }, null, 2),
216+ },
217+ ],
218+ details: { structuredContent: { ok: true, count: 2 } },
219+ isError: true,
220+ });
221+});
222+
223+test("discoverMcpServers_invalidOrUnusableServers_skipsThemWithWarningsAndCleanup", async () => {
224+ const emptyBehavior: FakeServerBehavior = {
225+ closeCalls: 0,
226+ pages: [{ tools: [] }],
227+ toolCalls: [],
228+ };
229+ const failingBehavior: FakeServerBehavior = {
230+ closeCalls: 0,
231+ connectError: new Error("connect failed"),
232+ toolCalls: [],
233+ };
234+
235+ const result = await discoverMcpServers(
236+ {
237+ servers: [
238+ { name: "bad-url", url: "not-a-url" },
239+ { name: "empty", url: "http://empty.test/mcp" },
240+ { name: "down", url: "http://down.test/mcp" },
241+ ],
242+ },
243+ createFakeRuntime({
244+ "http://empty.test/mcp": emptyBehavior,
245+ "http://down.test/mcp": failingBehavior,
246+ }),
247+ );
248+
249+ expect(result.servers).toEqual([]);
250+ expect(result.warnings).toEqual([
251+ 'MCP server "bad-url": invalid URL (not-a-url)',
252+ 'MCP server "empty" exposes no tools and was skipped.',
253+ 'MCP server "down": connect failed (http://down.test/mcp)',
254+ ]);
255+ expect(emptyBehavior.closeCalls).toBe(1);
256+ expect(failingBehavior.closeCalls).toBe(1);
257+});
src/mcp.ts+490−0
@@ -0,0 +1,490 @@
1+/**
2+ * Model Context Protocol client discovery and tool integration.
3+ *
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.
7+ *
8+ * @module
9+ */
10+
11+import type { Static, Tool, ToolCall, TSchema } from "@mariozechner/pi-ai";
12+import { Type, validateToolArguments } from "@mariozechner/pi-ai";
13+import { Client } from "@modelcontextprotocol/sdk/client";
14+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
15+import type { ToolHandler, ToolUpdateCallback } from "./agent.ts";
16+import { getErrorMessage } from "./errors.ts";
17+import type { McpSettings } from "./settings.ts";
18+import { type ToolExecResult, textResult } from "./tool-common.ts";
19+
20+const MCP_DISCOVERY_TIMEOUT_MS = 3_000;
21+
22+interface McpListedTool {
23+ /** JSON Schema describing the tool input object. */
24+ inputSchema: {
25+ properties?: Record<string, object>;
26+ required?: string[];
27+ type: "object";
28+ [key: string]: unknown;
29+ };
30+ /** Human-readable tool description when provided by the server. */
31+ description?: string;
32+ /** Server-defined MCP tool name. */
33+ name: string;
34+}
35+
36+type McpCallToolResult =
37+ | {
38+ /** Tool content blocks returned by the MCP server. */
39+ content: McpToolResultContent[];
40+ /** Optional structured data returned alongside content. */
41+ structuredContent?: unknown;
42+ /** Whether the server marked this result as an error. */
43+ isError?: boolean;
44+ }
45+ | {
46+ /** Compatibility payload from older MCP tool result formats. */
47+ toolResult: unknown;
48+ };
49+
50+type McpToolResultContent =
51+ | {
52+ type: "text";
53+ text: string;
54+ }
55+ | {
56+ type: "image";
57+ data: string;
58+ mimeType: string;
59+ }
60+ | {
61+ type: "audio";
62+ data: string;
63+ mimeType: string;
64+ }
65+ | {
66+ type: "resource";
67+ resource:
68+ | {
69+ uri: string;
70+ text: string;
71+ mimeType?: string;
72+ }
73+ | {
74+ uri: string;
75+ blob: string;
76+ mimeType?: string;
77+ };
78+ }
79+ | {
80+ type: "resource_link";
81+ uri: string;
82+ name: string;
83+ description?: string;
84+ mimeType?: string;
85+ size?: number;
86+ title?: string;
87+ };
88+
89+type McpProgress = {
90+ /** Current completed work units reported by the server. */
91+ progress: number;
92+ /** Total work units when the server reports them. */
93+ total?: number;
94+ /** Optional human-readable progress message. */
95+ message?: string;
96+};
97+
98+interface McpTransportLike {
99+ close(): Promise<void>;
100+}
101+
102+interface McpClientLike {
103+ connect(
104+ transport: McpTransportLike,
105+ options?: { timeout?: number },
106+ ): Promise<void>;
107+ listTools(
108+ params?: { cursor?: string },
109+ options?: { timeout?: number },
110+ ): Promise<{
111+ tools: McpListedTool[];
112+ nextCursor?: string;
113+ }>;
114+ callTool(
115+ params: {
116+ name: string;
117+ arguments?: Record<string, unknown>;
118+ },
119+ resultSchema?: undefined,
120+ options?: {
121+ signal?: AbortSignal;
122+ onprogress?: (progress: McpProgress) => void;
123+ },
124+ ): Promise<McpCallToolResult>;
125+}
126+
127+interface McpRuntime {
128+ createClient(): McpClientLike;
129+ createTransport(url: URL): McpTransportLike;
130+}
131+
132+const defaultMcpRuntime: McpRuntime = {
133+ createClient() {
134+ return new Client(
135+ {
136+ name: "mini-coder",
137+ version: "0.0.0",
138+ },
139+ { capabilities: {} },
140+ );
141+ },
142+ createTransport(url) {
143+ return new StreamableHTTPClientTransport(url);
144+ },
145+};
146+
147+/** A connected MCP server whose tools are available to the agent. */
148+export interface ConnectedMcpServer {
149+ /** User-configured server identifier from `settings.json`. */
150+ name: string;
151+ /** Absolute Streamable HTTP endpoint URL. */
152+ url: string;
153+ /** Whether this server's tools are currently exposed to new turns. */
154+ enabled: boolean;
155+ /** pi-ai tool definitions derived from the server's tool list. */
156+ tools: Tool[];
157+ /** Tool name → handler map for calling the remote MCP tools. */
158+ toolHandlers: Map<string, ToolHandler>;
159+ /** Close the underlying MCP transport. */
160+ close(): Promise<void>;
161+}
162+
163+interface McpDiscoveryResult {
164+ /** Successfully connected MCP servers with imported tools. */
165+ servers: ConnectedMcpServer[];
166+ /** Non-fatal startup warnings for skipped or unreachable servers. */
167+ warnings: string[];
168+}
169+
170+/**
171+ * Connect all configured MCP servers and import their tool definitions.
172+ *
173+ * Invalid or unreachable servers do not fail startup. They are skipped and
174+ * returned as warnings instead.
175+ *
176+ * @param settings - Optional MCP settings from `settings.json`.
177+ * @param runtime - Internal runtime injection for tests.
178+ * @returns Connected servers plus any non-fatal warnings.
179+ */
180+export async function discoverMcpServers(
181+ settings: McpSettings | undefined,
182+ runtime: McpRuntime = defaultMcpRuntime,
183+): Promise<McpDiscoveryResult> {
184+ const servers: ConnectedMcpServer[] = [];
185+ const warnings: string[] = [];
186+
187+ for (const entry of settings?.servers ?? []) {
188+ let url: URL;
189+ try {
190+ url = new URL(entry.url);
191+ } catch {
192+ warnings.push(`MCP server "${entry.name}": invalid URL (${entry.url})`);
193+ continue;
194+ }
195+
196+ const transport = runtime.createTransport(url);
197+ const client = runtime.createClient();
198+
199+ try {
200+ await client.connect(transport, { timeout: MCP_DISCOVERY_TIMEOUT_MS });
201+ const listedTools = await listAllTools(client);
202+
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+ }
210+
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+ }
225+
226+ if (tools.length === 0) {
227+ warnings.push(
228+ `MCP server "${entry.name}" exposes no usable tools and was skipped.`,
229+ );
230+ await closeQuietly(transport);
231+ continue;
232+ }
233+
234+ servers.push({
235+ name: entry.name,
236+ url: entry.url,
237+ enabled: true,
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+ );
246+ await closeQuietly(transport);
247+ }
248+ }
249+
250+ return { servers, warnings };
251+}
252+
253+async function listAllTools(client: McpClientLike): Promise<McpListedTool[]> {
254+ const tools: McpListedTool[] = [];
255+ let cursor: string | undefined;
256+
257+ do {
258+ const page = await client.listTools(cursor ? { cursor } : undefined, {
259+ timeout: MCP_DISCOVERY_TIMEOUT_MS,
260+ });
261+ tools.push(...page.tools);
262+ cursor = page.nextCursor;
263+ } while (cursor);
264+
265+ return tools;
266+}
267+
268+function createMcpTool(
269+ serverName: string,
270+ listedTool: McpListedTool,
271+ client: McpClientLike,
272+): {
273+ tool: Tool;
274+ handler: ToolHandler;
275+} {
276+ const toolName = `${serverName}__${listedTool.name}`;
277+ const tool: Tool = {
278+ name: toolName,
279+ description: listedTool.description
Cut short: this commit's diff is over 1000 lines.
src/settings.test.ts+76−0
Cut short: this commit's diff is over 1000 lines.
src/settings.ts+82−1
Cut short: this commit's diff is over 1000 lines.
src/ui.test.ts+1−0
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.test.ts+111−2
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.ts+49−0
Cut short: this commit's diff is over 1000 lines.
src/ui/help.ts+15−0
Cut short: this commit's diff is over 1000 lines.