@thegitai/cli 1.0.0-preview.54 → 1.0.0-preview.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -97,6 +97,108 @@ turn ends with an error that names what was interrupted, notes that some actions
97
97
  may already have completed, and leaves anything you had queued in the composer
98
98
  rather than sending it on top of a turn whose outcome is unknown.
99
99
 
100
+ ## MCP servers
101
+
102
+ Connect external tools with the Model Context Protocol (MCP). TheGitAI supports
103
+ local **stdio** servers and remote **Streamable HTTP** servers through the
104
+ official MCP SDK. Setup uses familiar `mcp` commands:
105
+
106
+ ```bash
107
+ # Remote documentation tools
108
+ ai mcp add --transport http context7 https://mcp.context7.com/mcp
109
+
110
+ # Local browser tools in a separate, temporary browser profile
111
+ ai mcp add playwright -- npx -y @playwright/mcp@latest --headless --isolated
112
+
113
+ ai mcp list
114
+ ai mcp get context7
115
+ ai mcp disable playwright
116
+ ai mcp enable playwright
117
+ ai mcp remove playwright
118
+ ```
119
+
120
+ Inside a chat, run **`/mcp`** to connect and see each server's status and tools.
121
+ Configured tools are connected in parallel and made available to the active
122
+ model. Tool lists are cached for one minute and refreshed when the server reports
123
+ a change. Failed connections wait one minute before retrying; `/mcp` retries
124
+ immediately, and a check you cancel is retried on the next turn. Ask normally, or name the server when you want it used—for
125
+ example, “Use Context7 to check the current API for this library.” Configuration
126
+ changes apply on the next turn or `/mcp`; they do not change an in-flight turn.
127
+ `ai mcp list` shows configuration without starting servers. `get` shows metadata
128
+ without printing URLs, arguments, or credential values.
129
+
130
+ For authentication, use headers or explicitly pass environment variables:
131
+
132
+ ```bash
133
+ # Set CONTEXT7_API_KEY in your environment first. Single quotes keep the
134
+ # placeholder in the config instead of saving the secret itself.
135
+ ai mcp add --transport http docs https://mcp.context7.com/mcp \
136
+ --header 'Authorization: Bearer ${CONTEXT7_API_KEY}'
137
+
138
+ ai mcp add --env SERVICE_TOKEN='${SERVICE_TOKEN}' local-tools -- my-mcp-server
139
+ ```
140
+
141
+ The short flags `-t`, `-e` and `-H` mean `--transport`, `--env` and `--header`.
142
+ `-s user` / `--scope user` is accepted; project and local scopes are unavailable.
143
+
144
+ Values support `${VARIABLE}` and `${VARIABLE:-default}` expansion when connecting.
145
+ Missing variables produce a visible connection error. Local servers inherit a
146
+ small standard environment (such as PATH and HOME); explicitly pass service
147
+ credentials with `--env`. A local server starts in the current repository.
148
+
149
+ To reuse a server's JSON setup instructions:
150
+
151
+ ```bash
152
+ ai mcp add-json docs '{"type":"http","url":"https://mcp.context7.com/mcp"}'
153
+ ai mcp add-json local-tools '{"command":"my-mcp-server","args":[],"env":{}}'
154
+ ```
155
+
156
+ Configuration is saved for your user on this machine, in `mcp.json` under the
157
+ TheGitAI state directory. `ai mcp list` prints the exact path. On Linux and macOS,
158
+ the default is `~/.local/state/thegitai/mcp.json` (or under `XDG_STATE_HOME`);
159
+ on Windows it is `%LOCALAPPDATA%\thegitai\mcp.json`. The file uses an
160
+ `mcpServers` object keyed by server name; each
161
+ entry accepts `disabled` and an optional `timeout` in milliseconds (1,000–300,000,
162
+ default 60,000). The CLI does not load project `.mcp.json` files.
163
+
164
+ **Approvals and limits:** Default mode asks before each MCP call; you can approve
165
+ one call or allow that specific server/tool for the session. `/new` clears these
166
+ grants. Bypass mode approves MCP calls automatically. Plan mode blocks MCP calls,
167
+ including tools a server labels read-only. Adding a local server authorizes
168
+ starting its configured program; only add servers you trust. MCP servers can
169
+ access files or external services using their own permissions, and their changes
170
+ are not covered by TheGitAI's file-edit undo.
171
+
172
+ Server credentials and connection settings stay on your machine. Discovered tool
173
+ names, descriptions and schemas, call arguments, and results are used for your
174
+ model requests. Text, structured results, and images are supported. Audio and
175
+ binary resources are reported as unsupported. Timeouts or disconnects can leave
176
+ an action's outcome unknown; TheGitAI does not automatically repeat MCP calls.
177
+
178
+ This release supports MCP **tools**, up to 128 tools / 100 KiB of definitions per
179
+ turn (about 25,600 estimated tokens). Tool descriptions can contain up to 4,096
180
+ characters. Servers are admitted in configuration order; a server exceeding a
181
+ limit is shown as unavailable in `/mcp` while chat continues with the other tools.
182
+ Invalid server entries are shown individually and can be disabled or removed with
183
+ `ai mcp`. Invalid JSON disables MCP tools for the turn and is shown by `/mcp`;
184
+ repair the file before using configuration commands.
185
+
186
+ MCP results share a 25,000 estimated-token limit across text and structured
187
+ content, enough for a typical browser page snapshot to arrive whole. Larger
188
+ results keep the start and end of their long text blocks, mark the omitted
189
+ middle and report the original size, so the agent can request a narrower query;
190
+ short blocks stay whole. Duplicate JSON text accompanying a structured result is
191
+ included once.
192
+
193
+ The SDK client runtime is bundled with the CLI at reviewed versions; installing
194
+ MCP support adds no runtime npm dependencies.
195
+
196
+ Browser-based OAuth login, standalone MCP resources/prompts, older SSE-only
197
+ servers, and plugin installation are not included. Context7 may require an API key
198
+ or impose rate limits; Playwright requires a supported installed browser.
199
+
200
+ Run `ai mcp --help` for the command reference.
201
+
100
202
  ## Chrome browser control
101
203
 
102
204
  The TheGitAI Chrome extension is separately installed. After installing it,
package/dist/bin/ai.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { runMcpCommand } from '../src/mcp-command.js';
2
3
  import chalk from '../src/colors.js';
3
4
  import { ServerApi } from '../src/api/index.js';
4
5
  import { DEFAULT_THEGITAI_HOST } from '../src/api/default-host.js';
@@ -130,6 +131,10 @@ function requireInteractiveTerminal() {
130
131
  return true;
131
132
  }
132
133
  export async function main() {
134
+ if (process.argv[2] === 'mcp') {
135
+ console.log(runMcpCommand(process.argv.slice(3)));
136
+ return;
137
+ }
133
138
  const { autoYes, help, version, usage, command, session: sessionIdentifier, listSessions, unknownOption, prompt, } = parseArgs(process.argv);
134
139
  if (version) {
135
140
  console.log(formatVersionLine());
@@ -1,3 +1,4 @@
1
+ import { sessionMcp } from '../mcp-client.js';
1
2
  import { readProjectModelEfforts, projectModelEffort } from '../project-model-preferences.js';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { drainBackgroundJobNotifications } from '../background-jobs.js';
@@ -746,6 +747,7 @@ export async function sendServerUserMessage({ config, session, input, jobFollowU
746
747
  }
747
748
  const request = {
748
749
  clientTurnId: randomUUID(),
750
+ mcpTools: await sessionMcp(session).discover(signal),
749
751
  modelId: session.modelId,
750
752
  reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, config.serverUrl, session.env), session.modelId),
751
753
  session: snapshotForServer(session),
@@ -36,6 +36,20 @@ const HELP_MARKDOWN = [
36
36
  '- `ai --usage` — show account usage percentage and reset times',
37
37
  '- `ai logout` — sign out',
38
38
  '',
39
+ '## MCP servers',
40
+ '',
41
+ '- `ai mcp add <name> -- <command> [args...]` — connect a local MCP server',
42
+ '- `ai mcp add --transport http <name> <url>` — connect a remote MCP server',
43
+ '- `ai mcp --help` — configuration, headers, environment variables and commands',
44
+ '- Short setup flags: `-t` transport, `-e` environment, `-H` header, `-s user` scope.',
45
+ '- `/mcp` — check connections and available tools; changes apply next turn',
46
+ '- Default mode asks before MCP calls; approvals can cover one tool for the session.',
47
+ '- Bypass mode also approves MCP calls. Plan mode blocks MCP calls.',
48
+ '- Invalid servers are reported individually; chat continues with available tools.',
49
+ '- `/mcp` retries connections; tool lists are cached for one minute.',
50
+ '- MCP supports tools over stdio and Streamable HTTP. OAuth, prompts and resources',
51
+ ' are not supported yet. Add only servers you trust.',
52
+ '',
39
53
  '## Sessions',
40
54
  '',
41
55
  '- `ai --list-sessions` — list saved sessions for this repo',
@@ -125,6 +139,7 @@ const HELP_MARKDOWN = [
125
139
  ' best matches and counts the rest; **↑/↓** chooses, **Tab** or **Enter**',
126
140
  ' accepts, **Esc** closes it.',
127
141
  '- `/help` — show this help',
142
+ '- `/mcp` — check MCP connections and list available tools',
128
143
  '- `/about` — show version and platform info',
129
144
  '- `/report` — file a bug privately through the TheGitAI website in your',
130
145
  ' browser (sign in with your existing account)',
@@ -0,0 +1,335 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { Client, StdioClientTransport, getDefaultEnvironment, StreamableHTTPClientTransport, AjvJsonSchemaValidator, ToolListChangedNotificationSchema, } from './mcp-sdk.js';
3
+ import { expandMcpValue, readMcpConfig, validateMcpServer, } from './mcp-config.js';
4
+ import { mcpToolName, mcpCatalogueError, } from './mcp-types.js';
5
+ import { ensurePermission } from './permissions.js';
6
+ import { getCliVersion } from './version.js';
7
+ const REFRESH_MS = 60000;
8
+ const RETRY_MS = 60000;
9
+ export function createMcpConnections(rootDir, env) {
10
+ const entries = new Map();
11
+ const shutdown = new AbortController();
12
+ let pending;
13
+ let configError = '';
14
+ let advertised = new Set();
15
+ const expand = (value) => expandMcpValue(value, env);
16
+ const expandMap = (value = {}) => Object.fromEntries(Object.entries(value).map(([key, item]) => [key, expand(item)]));
17
+ const fingerprint = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
18
+ async function close() {
19
+ shutdown.abort();
20
+ await pending?.catch(() => { });
21
+ await Promise.allSettled([...entries.values()].map((entry) => entry.client?.close()));
22
+ entries.clear();
23
+ }
24
+ function safeError(error, value) {
25
+ let message = error instanceof Error ? error.message : String(error);
26
+ const config = value && typeof value === 'object'
27
+ ? value
28
+ : {};
29
+ const values = (value) => value && typeof value === 'object' && !Array.isArray(value) ? Object.values(value) : [];
30
+ const secrets = [config.url, ...values(config.env), ...values(config.headers)].filter((item) => typeof item === 'string');
31
+ for (const value of secrets) {
32
+ let secret = value;
33
+ try {
34
+ secret = expand(value);
35
+ }
36
+ catch { }
37
+ if (secret)
38
+ message = message.split(secret).join('[redacted]');
39
+ }
40
+ return message.replace(/[\u0000-\u001f\u007f]/g, ' ').slice(0, 1000);
41
+ }
42
+ async function refresh(name, value, signal, force) {
43
+ let entry = entries.get(name);
44
+ try {
45
+ const item = validateMcpServer(name, value);
46
+ if (item.disabled) {
47
+ await entry?.client?.close();
48
+ entries.delete(name);
49
+ return;
50
+ }
51
+ const resolved = validateMcpServer(name, item.type === 'stdio'
52
+ ? {
53
+ ...item,
54
+ command: expand(item.command),
55
+ args: (item.args ?? []).map(expand),
56
+ env: expandMap(item.env),
57
+ }
58
+ : {
59
+ ...item,
60
+ url: expand(item.url),
61
+ headers: expandMap(item.headers),
62
+ });
63
+ const digest = fingerprint(resolved);
64
+ if (entry && entry.fingerprint !== digest) {
65
+ await entry.client?.close().catch(() => { });
66
+ entries.delete(name);
67
+ entry = undefined;
68
+ }
69
+ if (entry && !force) {
70
+ if (entry.status !== 'connected' && Date.now() < entry.retryAt)
71
+ return;
72
+ if (entry.status === 'connected' &&
73
+ !entry.dirty &&
74
+ Date.now() - entry.refreshedAt < REFRESH_MS)
75
+ return;
76
+ }
77
+ if (!entry?.client || entry.status !== 'connected') {
78
+ await entry?.client?.close().catch(() => { });
79
+ const client = new Client({ name: 'thegitai', version: getCliVersion() }, { capabilities: {} });
80
+ entry = {
81
+ config: item,
82
+ fingerprint: digest,
83
+ client,
84
+ tools: entry?.tools ?? new Map(),
85
+ status: 'connecting',
86
+ refreshedAt: 0,
87
+ retryAt: 0,
88
+ dirty: true,
89
+ };
90
+ entries.set(name, entry);
91
+ const current = entry;
92
+ client.onclose = () => {
93
+ if (current.client !== client)
94
+ return;
95
+ current.status = 'disconnected';
96
+ current.retryAt = Date.now() + RETRY_MS;
97
+ };
98
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => {
99
+ current.dirty = true;
100
+ });
101
+ const transport = resolved.type === 'stdio'
102
+ ? new StdioClientTransport({
103
+ command: resolved.command,
104
+ args: resolved.args,
105
+ env: {
106
+ ...Object.fromEntries(Object.keys(getDefaultEnvironment()).flatMap((key) => env[key] === undefined ? [] : [[key, env[key]]])),
107
+ ...resolved.env,
108
+ },
109
+ cwd: rootDir,
110
+ stderr: 'pipe',
111
+ })
112
+ : new StreamableHTTPClientTransport(new URL(resolved.url), {
113
+ requestInit: { headers: resolved.headers },
114
+ });
115
+ if (transport instanceof StdioClientTransport)
116
+ transport.stderr?.on('data', () => { });
117
+ await client.connect(transport, { timeout: 15000, signal });
118
+ entry.status = 'connected';
119
+ }
120
+ const tools = new Map();
121
+ let cursor;
122
+ const cursors = new Set();
123
+ entry.dirty = false;
124
+ do {
125
+ const page = await entry.client.listTools(cursor ? { cursor } : undefined, { timeout: 15000, signal });
126
+ for (const tool of page.tools) {
127
+ const nameForModel = mcpToolName(name, tool.name);
128
+ if (tools.has(nameForModel))
129
+ throw new Error('Server returned duplicate tool names.');
130
+ const definition = {
131
+ name: nameForModel,
132
+ serverName: name,
133
+ toolName: tool.name,
134
+ description: tool.description ?? '',
135
+ inputSchema: tool.inputSchema,
136
+ };
137
+ const catalogueError = mcpCatalogueError([
138
+ ...[...tools.values()].map((item) => item.definition),
139
+ definition,
140
+ ]);
141
+ if (catalogueError)
142
+ throw new Error(catalogueError);
143
+ const schemaHash = fingerprint(tool.inputSchema);
144
+ const previous = entry.tools.get(nameForModel);
145
+ tools.set(nameForModel, {
146
+ definition,
147
+ schemaHash,
148
+ validate: previous?.schemaHash === schemaHash
149
+ ? previous.validate
150
+ : new AjvJsonSchemaValidator().getValidator(tool.inputSchema),
151
+ });
152
+ }
153
+ cursor = page.nextCursor;
154
+ if (cursor && cursors.has(cursor))
155
+ throw new Error('Server repeated a tool-list cursor.');
156
+ if (cursor)
157
+ cursors.add(cursor);
158
+ } while (cursor);
159
+ entry.tools = tools;
160
+ entry.refreshedAt = Date.now();
161
+ entry.retryAt = 0;
162
+ }
163
+ catch (error) {
164
+ if (!entry) {
165
+ entry = {
166
+ fingerprint: fingerprint(value),
167
+ tools: new Map(),
168
+ status: '',
169
+ refreshedAt: 0,
170
+ retryAt: 0,
171
+ dirty: false,
172
+ };
173
+ entries.set(name, entry);
174
+ }
175
+ const cancelled = signal.aborted;
176
+ const failedClient = entry.client;
177
+ entry.client = undefined;
178
+ await failedClient?.close().catch(() => { });
179
+ entry.status = cancelled
180
+ ? 'not connected'
181
+ : `failed: ${safeError(error, value)}`;
182
+ entry.tools.clear();
183
+ entry.retryAt = cancelled ? 0 : Date.now() + RETRY_MS;
184
+ signal.throwIfAborted();
185
+ }
186
+ }
187
+ async function discoverImpl(signal, force) {
188
+ signal.throwIfAborted();
189
+ let config;
190
+ try {
191
+ config = readMcpConfig(env);
192
+ configError = '';
193
+ }
194
+ catch (error) {
195
+ configError = safeError(error, {});
196
+ advertised.clear();
197
+ await Promise.allSettled([...entries.values()].map((entry) => entry.client?.close()));
198
+ entries.clear();
199
+ return [];
200
+ }
201
+ for (const [name, entry] of entries) {
202
+ const value = config.mcpServers[name];
203
+ if (!Object.hasOwn(config.mcpServers, name) ||
204
+ (value &&
205
+ typeof value === 'object' &&
206
+ 'disabled' in value &&
207
+ value.disabled === true)) {
208
+ await entry.client?.close().catch(() => { });
209
+ entries.delete(name);
210
+ }
211
+ }
212
+ await Promise.allSettled(Object.entries(config.mcpServers).map(([name, value]) => refresh(name, value, signal, force)));
213
+ signal.throwIfAborted();
214
+ const tools = [];
215
+ for (const name of Object.keys(config.mcpServers)) {
216
+ const entry = entries.get(name);
217
+ if (!entry || entry.status !== 'connected')
218
+ continue;
219
+ const definitions = [...entry.tools.values()].map((tool) => tool.definition);
220
+ entry.catalogueError = mcpCatalogueError([...tools, ...definitions]);
221
+ if (!entry.catalogueError)
222
+ tools.push(...definitions);
223
+ }
224
+ advertised = new Set(tools.map((tool) => tool.name));
225
+ return tools.sort((a, b) => a.name.localeCompare(b.name));
226
+ }
227
+ function discover(signal, options = {}) {
228
+ const combined = signal
229
+ ? AbortSignal.any([signal, shutdown.signal])
230
+ : shutdown.signal;
231
+ combined.throwIfAborted();
232
+ if (!pending)
233
+ pending = discoverImpl(combined, options.force === true).finally(() => {
234
+ pending = undefined;
235
+ });
236
+ return pending;
237
+ }
238
+ async function execute(session, call) {
239
+ const match = advertised.has(call.name)
240
+ ? [...entries.entries()].find(([, entry]) => entry.tools.has(call.name) && entry.status === 'connected')
241
+ : undefined;
242
+ if (!match)
243
+ return {
244
+ ok: false,
245
+ error: 'MCP tool is unavailable. Check /mcp.',
246
+ failureCategory: 'unknown_tool',
247
+ };
248
+ const [serverName, entry] = match;
249
+ const tool = entry.tools.get(call.name);
250
+ if (session.agentMode === 'plan')
251
+ return {
252
+ ok: false,
253
+ error: 'MCP calls are unavailable in Plan mode.',
254
+ failureCategory: 'policy_blocked',
255
+ };
256
+ const validation = tool.validate(call.args);
257
+ if (!validation.valid)
258
+ return {
259
+ ok: false,
260
+ error: validation.errorMessage,
261
+ failureCategory: 'invalid_argument',
262
+ };
263
+ const denied = await ensurePermission(session, {
264
+ bucket: 'mcp',
265
+ mcpTool: JSON.stringify([entry.fingerprint, call.name]),
266
+ mcpLabel: label(call.name),
267
+ title: label(call.name) ?? `MCP: ${serverName}`,
268
+ body: JSON.stringify(call.args, null, 2),
269
+ }, call.name);
270
+ if (denied)
271
+ return denied;
272
+ session.turnAbortSignal?.throwIfAborted();
273
+ try {
274
+ const result = await entry.client.callTool({ name: tool.definition.toolName, arguments: call.args }, undefined, {
275
+ signal: session.turnAbortSignal,
276
+ timeout: entry.config?.timeout ?? 60000,
277
+ });
278
+ return {
279
+ ok: result.isError !== true,
280
+ mcpResult: result,
281
+ ...(result.isError
282
+ ? {
283
+ error: 'MCP server reported a tool error.',
284
+ failureCategory: 'external_service',
285
+ }
286
+ : {}),
287
+ };
288
+ }
289
+ catch (error) {
290
+ return {
291
+ ok: false,
292
+ error: safeError(error, entry.config),
293
+ outcomeUnknown: true,
294
+ failureCategory: 'external_service',
295
+ };
296
+ }
297
+ }
298
+ function label(name) {
299
+ for (const entry of entries.values()) {
300
+ const tool = entry.tools.get(name)?.definition;
301
+ if (tool)
302
+ return `MCP: ${tool.serverName} / ${tool.toolName.replace(/[\u0000-\u001f\u007f]/g, ' ')}`;
303
+ }
304
+ return undefined;
305
+ }
306
+ function status() {
307
+ let config;
308
+ try {
309
+ config = readMcpConfig(env);
310
+ }
311
+ catch (error) {
312
+ return `MCP configuration failed: ${safeError(error, {})}\nChat can continue without MCP tools.`;
313
+ }
314
+ const lines = Object.entries(config.mcpServers).map(([name, value]) => {
315
+ const entry = entries.get(name);
316
+ const disabled = value &&
317
+ typeof value === 'object' &&
318
+ 'disabled' in value &&
319
+ value.disabled === true;
320
+ return `${name.replace(/[\u0000-\u001f\u007f]/g, ' ')} · ${disabled ? 'disabled' : entry?.catalogueError ? `unavailable: ${entry.catalogueError}` : (entry?.status ?? 'not connected')}${entry?.status === 'connected' && !entry.catalogueError ? ` · ${entry.tools.size} tools\n${[...entry.tools.values()].map((tool) => ` ${tool.definition.toolName.replace(/[\u0000-\u001f\u007f]/g, ' ')}`).join('\n')}` : ''}`;
321
+ });
322
+ return [
323
+ configError,
324
+ ...(lines.length ? lines : ['No MCP servers configured.']),
325
+ '',
326
+ 'Configure with ai mcp add / remove / enable / disable.',
327
+ ]
328
+ .filter(Boolean)
329
+ .join('\n');
330
+ }
331
+ return { discover, execute, status, label, close };
332
+ }
333
+ export function sessionMcp(session) {
334
+ return (session.mcp ??= createMcpConnections(session.rootDir, session.env));
335
+ }
@@ -0,0 +1,176 @@
1
+ import { mcpConfigPath, readMcpConfig, validateMcpServer, writeMcpConfig, } from './mcp-config.js';
2
+ export const MCP_HELP = `MCP servers (saved for your user account on this machine):
3
+ ai mcp add <name> -- <command> [args...]
4
+ ai mcp add --transport http <name> <url> [--header 'Name: value']
5
+ ai mcp add --env KEY=value <name> -- <command> [args...]
6
+ Options: -t/--transport, -e/--env, -H/--header, -s/--scope user
7
+ ai mcp add-json <name> '<JSON configuration>'
8
+ ai mcp list
9
+ ai mcp get <name>
10
+ ai mcp remove <name>
11
+ ai mcp enable <name>
12
+ ai mcp disable <name>
13
+
14
+ Use /mcp inside a session to check connections and available tools.
15
+ Local servers run on your machine. Add only servers you trust.
16
+ HTTP supports headers; browser-based OAuth sign-in is not supported yet.`;
17
+ export function runMcpCommand(args, env = process.env) {
18
+ const [action, ...input] = args;
19
+ const rest = [];
20
+ for (let index = 0; index < input.length; index++) {
21
+ const token = input[index];
22
+ if (token === '--') {
23
+ rest.push(...input.slice(index));
24
+ break;
25
+ }
26
+ if (token === '--scope' || token === '-s') {
27
+ const scope = input[++index];
28
+ if (scope !== 'user')
29
+ throw new Error('Only --scope user is supported. Project and local MCP scope are not available.');
30
+ }
31
+ else
32
+ rest.push(token);
33
+ }
34
+ if (!action || action === '--help' || action === '-h')
35
+ return MCP_HELP;
36
+ const config = readMcpConfig(env);
37
+ if (action === 'list' && rest.length === 0) {
38
+ return [
39
+ mcpConfigPath(env),
40
+ ...Object.entries(config.mcpServers).map(([name, value]) => {
41
+ if (value && typeof value === 'object' && 'disabled' in value && value.disabled === true)
42
+ return `${name} · disabled`;
43
+ try {
44
+ const item = validateMcpServer(name, value);
45
+ return `${name} · ${item.type} · ${item.disabled ? 'disabled' : 'enabled'}`;
46
+ }
47
+ catch (error) {
48
+ return `${name} · failed: ${String(error.message)}`;
49
+ }
50
+ }),
51
+ ...(Object.keys(config.mcpServers).length
52
+ ? []
53
+ : ['No MCP servers configured.']),
54
+ 'Use /mcp in a session to check connections.',
55
+ ].join('\n');
56
+ }
57
+ if (action === 'add' || action === 'add-json') {
58
+ let name;
59
+ let value;
60
+ if (action === 'add-json') {
61
+ if (rest.length !== 2)
62
+ throw new Error('Usage: ai mcp add-json <name> <JSON>');
63
+ name = rest[0];
64
+ try {
65
+ value = JSON.parse(rest[1]);
66
+ }
67
+ catch {
68
+ throw new Error('Invalid MCP JSON configuration.');
69
+ }
70
+ }
71
+ else {
72
+ const positional = [];
73
+ const vars = {};
74
+ const headers = {};
75
+ let transport = 'stdio';
76
+ let command = [];
77
+ for (let i = 0; i < rest.length; i++) {
78
+ const token = rest[i];
79
+ const arg = {
80
+ '-t': '--transport',
81
+ '-e': '--env',
82
+ '-H': '--header',
83
+ '-s': '--scope',
84
+ }[token] ?? token;
85
+ if (arg === '--') {
86
+ command = rest.slice(i + 1);
87
+ break;
88
+ }
89
+ if (['--transport', '--env', '--header'].includes(arg)) {
90
+ const value = rest[++i];
91
+ if (!value)
92
+ throw new Error(`Missing value for ${arg}.`);
93
+ if (arg === '--transport')
94
+ transport = value;
95
+ else {
96
+ const separator = arg === '--env' ? '=' : ':';
97
+ const at = value.indexOf(separator);
98
+ if (at < 1)
99
+ throw new Error(`Expected ${arg === '--env' ? 'KEY=value' : 'Name: value'} for ${arg}.`);
100
+ (arg === '--env' ? vars : headers)[value.slice(0, at).trim()] =
101
+ value.slice(at + 1).trim();
102
+ }
103
+ }
104
+ else if (arg.startsWith('-'))
105
+ throw new Error(`Unknown MCP option: ${arg}`);
106
+ else
107
+ positional.push(arg);
108
+ }
109
+ name = positional[0] ?? '';
110
+ if (transport === 'http' &&
111
+ positional.length === 2 &&
112
+ !command.length &&
113
+ !Object.keys(vars).length)
114
+ value = { type: 'http', url: positional[1], headers };
115
+ else if (transport === 'stdio' &&
116
+ positional.length === 1 &&
117
+ command.length &&
118
+ !Object.keys(headers).length)
119
+ value = {
120
+ type: 'stdio',
121
+ command: command[0],
122
+ args: command.slice(1),
123
+ env: vars,
124
+ };
125
+ else
126
+ throw new Error(MCP_HELP);
127
+ }
128
+ if (Object.hasOwn(config.mcpServers, name))
129
+ throw new Error(`MCP server ${name} already exists. Remove it before replacing it.`);
130
+ Object.defineProperty(config.mcpServers, name, {
131
+ value: validateMcpServer(name, value),
132
+ enumerable: true,
133
+ configurable: true,
134
+ writable: true,
135
+ });
136
+ }
137
+ else {
138
+ const name = rest[0] ?? '';
139
+ if (rest.length !== 1 ||
140
+ !['get', 'remove', 'enable', 'disable'].includes(action))
141
+ throw new Error(MCP_HELP);
142
+ if (!Object.hasOwn(config.mcpServers, name))
143
+ throw new Error(`Unknown MCP server: ${name}`);
144
+ const raw = config.mcpServers[name];
145
+ if (action === 'remove') {
146
+ delete config.mcpServers[name];
147
+ }
148
+ else if (action === 'disable') {
149
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
150
+ throw new Error('This entry cannot be disabled. Remove it with ai mcp remove.');
151
+ config.mcpServers[name] = { ...raw, disabled: true };
152
+ }
153
+ else {
154
+ const item = validateMcpServer(name, raw);
155
+ if (action === 'get')
156
+ return JSON.stringify({
157
+ name,
158
+ type: item.type,
159
+ disabled: item.disabled === true,
160
+ timeout: item.timeout ?? 60000,
161
+ ...(item.type === 'stdio'
162
+ ? {
163
+ command: item.command,
164
+ argumentCount: item.args?.length ?? 0,
165
+ environmentVariables: Object.keys(item.env ?? {}),
166
+ }
167
+ : { headerNames: Object.keys(item.headers ?? {}) }),
168
+ configFile: mcpConfigPath(env),
169
+ }, null, 2);
170
+ item.disabled = false;
171
+ config.mcpServers[name] = item;
172
+ }
173
+ }
174
+ writeMcpConfig(config, env);
175
+ return `MCP configuration saved to ${mcpConfigPath(env)}. Changes apply on the next turn or /mcp.`;
176
+ }