@thegitai/cli 1.0.0-preview.6 → 1.0.0-preview.60
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 +229 -7
- package/dist/bin/ai.js +140 -111
- package/dist/bin/browser-host.js +265 -0
- package/dist/src/agent-mode.js +32 -7
- package/dist/src/api/auth.js +8 -2
- package/dist/src/api/browser-login.js +147 -35
- package/dist/src/api/chat.js +691 -166
- package/dist/src/api/contracts.js +55 -1
- package/dist/src/api/default-host.js +1 -0
- package/dist/src/api/http.js +139 -8
- package/dist/src/api/models.js +34 -9
- package/dist/src/api/startup-handshake.js +36 -0
- package/dist/src/api/turn-recovery.js +189 -0
- package/dist/src/background-jobs.js +8 -2
- package/dist/src/browser/bridge.js +262 -0
- package/dist/src/browser/framing.js +42 -0
- package/dist/src/browser/native-host.js +219 -0
- package/dist/src/browser/protocol.js +46 -0
- package/dist/src/browser/session-bridge.js +130 -0
- package/dist/src/cli-args.js +19 -5
- package/dist/src/client-environment.js +2 -0
- package/dist/src/core/clipboard.js +7 -13
- package/dist/src/core/image-limits.js +56 -0
- package/dist/src/core/image-path-extractor.js +70 -3
- package/dist/src/core/session-image-store.js +246 -0
- package/dist/src/edit-journal.js +33 -2
- package/dist/src/executor.js +25 -3
- package/dist/src/help-text.js +128 -22
- package/dist/src/job-follow-up.js +40 -0
- package/dist/src/mcp-client.js +335 -0
- package/dist/src/mcp-command.js +176 -0
- package/dist/src/mcp-config.js +123 -0
- package/dist/src/mcp-sdk.js +3 -0
- package/dist/src/mcp-types.js +26 -0
- package/dist/src/patcher.js +43 -4
- package/dist/src/permissions.js +301 -0
- package/dist/src/preferences.js +39 -0
- package/dist/src/project-key.js +11 -0
- package/dist/src/project-model-preferences.js +74 -0
- package/dist/src/quota-notice.js +35 -0
- package/dist/src/reasoning-effort.js +27 -0
- package/dist/src/session-safety.js +0 -12
- package/dist/src/session-store.js +123 -30
- package/dist/src/session.js +20 -4
- package/dist/src/signin.js +58 -0
- package/dist/src/tool-executor.js +23 -49
- package/dist/src/tools/browser.js +641 -0
- package/dist/src/tools/delete-file.js +20 -4
- package/dist/src/tools/index.js +32 -10
- package/dist/src/tools/patch-file.js +12 -26
- package/dist/src/tools/read-file.js +5 -0
- package/dist/src/tools/read-image-file.js +85 -0
- package/dist/src/tools/replace-document-text.js +28 -18
- package/dist/src/tools/restore-checkpoint.js +0 -1
- package/dist/src/tools/run-command.js +14 -71
- package/dist/src/tools/run-node-script.js +12 -81
- package/dist/src/tools/save-generated-image.js +120 -0
- package/dist/src/tools/str-replace.js +12 -26
- package/dist/src/tools/undo-edit.js +1 -6
- package/dist/src/tools/write-file.js +67 -11
- package/dist/src/ui/prompt-history-store.js +1 -1
- package/dist/src/ui/repl.js +1017 -299
- package/dist/src/ui/slash-commands.js +122 -0
- package/dist/src/ui/tui/attention.js +25 -0
- package/dist/src/ui/tui/bridge.js +38 -5
- package/dist/src/ui/tui/build-frame.js +807 -270
- package/dist/src/ui/tui/composer-layout.js +76 -0
- package/dist/src/ui/tui/desktop-notification.js +118 -0
- package/dist/src/ui/tui/markdown-render.js +21 -11
- package/dist/src/ui/tui/model-label.js +13 -0
- package/dist/src/ui/tui/shell-input.js +275 -73
- package/dist/src/ui/tui/shortcuts.js +61 -0
- package/dist/src/ui/tui/terminal-theme.js +28 -0
- package/dist/src/ui/tui/text.js +31 -6
- package/dist/src/ui/tui/user-input.js +593 -0
- package/dist/src/update-check.js +205 -0
- package/dist/src/usage-notice.js +52 -0
- package/dist/src/usage.js +5 -2
- package/dist/src/utils.js +13 -0
- package/dist/src/version.js +52 -2
- package/dist/vendor/mcp/LICENSES.txt +414 -0
- package/dist/vendor/mcp/client.cjs +82 -0
- package/package.json +22 -9
- package/dist/src/project-index.js +0 -233
- package/dist/src/tools/code-intel.js +0 -472
- package/dist/src/tools/find-symbol.js +0 -70
- package/dist/src/tools/hover-symbol.js +0 -95
- package/dist/src/tools/list-symbols.js +0 -55
- package/dist/src/tools/search-code.js +0 -37
- package/dist/src/tools/signature-help.js +0 -118
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { getClientStateDir } from './client-state.js';
|
|
5
|
+
export function mcpConfigPath(env = process.env) {
|
|
6
|
+
return path.join(getClientStateDir(env), 'mcp.json');
|
|
7
|
+
}
|
|
8
|
+
function stringMap(value) {
|
|
9
|
+
return (!!value &&
|
|
10
|
+
typeof value === 'object' &&
|
|
11
|
+
!Array.isArray(value) &&
|
|
12
|
+
Object.values(value).every((item) => typeof item === 'string'));
|
|
13
|
+
}
|
|
14
|
+
export function validateMcpServer(name, value) {
|
|
15
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name)) {
|
|
16
|
+
throw new Error('MCP server names must contain 1–64 letters, numbers, underscores or hyphens.');
|
|
17
|
+
}
|
|
18
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
19
|
+
throw new Error(`Invalid MCP configuration for ${name}.`);
|
|
20
|
+
}
|
|
21
|
+
const item = value;
|
|
22
|
+
const type = item.type ?? (item.command ? 'stdio' : 'http');
|
|
23
|
+
const allowed = new Set([
|
|
24
|
+
'type',
|
|
25
|
+
'disabled',
|
|
26
|
+
'timeout',
|
|
27
|
+
...(type === 'stdio' ? ['command', 'args', 'env'] : ['url', 'headers']),
|
|
28
|
+
]);
|
|
29
|
+
if (Object.keys(item).some((key) => !allowed.has(key))) {
|
|
30
|
+
throw new Error(`Unknown MCP configuration field for ${name}. Supported transports: stdio and http.`);
|
|
31
|
+
}
|
|
32
|
+
if (item.disabled !== undefined && typeof item.disabled !== 'boolean')
|
|
33
|
+
throw new Error(`Invalid disabled flag for ${name}.`);
|
|
34
|
+
if (item.timeout !== undefined &&
|
|
35
|
+
(!Number.isInteger(item.timeout) ||
|
|
36
|
+
Number(item.timeout) < 1000 ||
|
|
37
|
+
Number(item.timeout) > 300000)) {
|
|
38
|
+
throw new Error(`MCP timeout for ${name} must be 1000–300000 milliseconds.`);
|
|
39
|
+
}
|
|
40
|
+
const common = {
|
|
41
|
+
disabled: item.disabled,
|
|
42
|
+
timeout: item.timeout,
|
|
43
|
+
};
|
|
44
|
+
if (type === 'stdio' &&
|
|
45
|
+
typeof item.command === 'string' &&
|
|
46
|
+
item.command.trim()) {
|
|
47
|
+
if (item.args !== undefined &&
|
|
48
|
+
(!Array.isArray(item.args) ||
|
|
49
|
+
!item.args.every((arg) => typeof arg === 'string')))
|
|
50
|
+
throw new Error(`Invalid args for ${name}.`);
|
|
51
|
+
if (item.env !== undefined &&
|
|
52
|
+
(!stringMap(item.env) ||
|
|
53
|
+
Object.keys(item.env).some((key) => !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key))))
|
|
54
|
+
throw new Error(`Invalid env for ${name}.`);
|
|
55
|
+
return {
|
|
56
|
+
...common,
|
|
57
|
+
type,
|
|
58
|
+
command: item.command,
|
|
59
|
+
args: item.args,
|
|
60
|
+
env: item.env,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (type === 'http' && typeof item.url === 'string') {
|
|
64
|
+
const hasVariable = /\$\{[a-zA-Z_][a-zA-Z0-9_]*(?::-[^}]*)?\}/.test(item.url);
|
|
65
|
+
const url = hasVariable ? null : new URL(item.url);
|
|
66
|
+
if (url &&
|
|
67
|
+
(!['http:', 'https:'].includes(url.protocol) ||
|
|
68
|
+
url.username ||
|
|
69
|
+
url.password))
|
|
70
|
+
throw new Error(`Invalid HTTP URL for ${name}. Use headers for authentication.`);
|
|
71
|
+
if (item.headers !== undefined && !stringMap(item.headers))
|
|
72
|
+
throw new Error(`Invalid headers for ${name}.`);
|
|
73
|
+
return {
|
|
74
|
+
...common,
|
|
75
|
+
type,
|
|
76
|
+
url: item.url,
|
|
77
|
+
headers: item.headers,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
throw new Error(`MCP server ${name} needs a stdio command or HTTP URL.`);
|
|
81
|
+
}
|
|
82
|
+
export function readMcpConfig(env = process.env) {
|
|
83
|
+
let raw;
|
|
84
|
+
try {
|
|
85
|
+
raw = readFileSync(mcpConfigPath(env), 'utf8');
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
if (error.code === 'ENOENT')
|
|
89
|
+
return { mcpServers: {} };
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
let config;
|
|
93
|
+
try {
|
|
94
|
+
config = JSON.parse(raw);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw new Error(`Invalid JSON in ${mcpConfigPath(env)}.`);
|
|
98
|
+
}
|
|
99
|
+
if (!config?.mcpServers ||
|
|
100
|
+
typeof config.mcpServers !== 'object' ||
|
|
101
|
+
Array.isArray(config.mcpServers))
|
|
102
|
+
throw new Error('MCP configuration needs an mcpServers object.');
|
|
103
|
+
return config;
|
|
104
|
+
}
|
|
105
|
+
export function writeMcpConfig(config, env = process.env) {
|
|
106
|
+
const file = mcpConfigPath(env);
|
|
107
|
+
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
108
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
109
|
+
writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, {
|
|
110
|
+
mode: 0o600,
|
|
111
|
+
flag: 'wx',
|
|
112
|
+
});
|
|
113
|
+
renameSync(temporary, file);
|
|
114
|
+
chmodSync(file, 0o600);
|
|
115
|
+
}
|
|
116
|
+
export function expandMcpValue(value, env) {
|
|
117
|
+
return value.replace(/\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([^}]*))?\}/g, (_match, name, fallback) => {
|
|
118
|
+
const resolved = env[name] ?? fallback;
|
|
119
|
+
if (resolved === undefined)
|
|
120
|
+
throw new Error(`Missing environment variable ${name}.`);
|
|
121
|
+
return resolved;
|
|
122
|
+
});
|
|
123
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
const sdk = createRequire(import.meta.url)('../vendor/mcp/client.cjs');
|
|
3
|
+
export const { Client, StdioClientTransport, StreamableHTTPClientTransport, AjvJsonSchemaValidator, getDefaultEnvironment, ToolListChangedNotificationSchema, } = sdk;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
export function mcpToolName(serverName, toolName) {
|
|
3
|
+
const label = `${serverName}_${toolName}`
|
|
4
|
+
.replace(/[^a-zA-Z0-9_]/g, '_')
|
|
5
|
+
.slice(0, 36);
|
|
6
|
+
const digest = createHash('sha256')
|
|
7
|
+
.update(JSON.stringify([serverName, toolName]))
|
|
8
|
+
.digest('hex')
|
|
9
|
+
.slice(0, 16);
|
|
10
|
+
return `mcp_${label}_${digest}`;
|
|
11
|
+
}
|
|
12
|
+
export function isMcpToolName(value) {
|
|
13
|
+
return typeof value === 'string' && value.startsWith('mcp_');
|
|
14
|
+
}
|
|
15
|
+
export const MCP_MAX_TOOLS = 128;
|
|
16
|
+
export const MCP_MAX_CATALOGUE_BYTES = 100 * 1024;
|
|
17
|
+
export const MCP_MAX_DESCRIPTION_CHARS = 4096;
|
|
18
|
+
export function mcpCatalogueError(tools) {
|
|
19
|
+
if (tools.length > MCP_MAX_TOOLS)
|
|
20
|
+
return `More than ${MCP_MAX_TOOLS} MCP tools.`;
|
|
21
|
+
if (tools.some((tool) => tool.description.length > MCP_MAX_DESCRIPTION_CHARS))
|
|
22
|
+
return `An MCP tool description exceeds ${MCP_MAX_DESCRIPTION_CHARS} characters.`;
|
|
23
|
+
if (Buffer.byteLength(JSON.stringify(tools), 'utf8') > MCP_MAX_CATALOGUE_BYTES)
|
|
24
|
+
return 'MCP tool definitions exceed 100 KiB (approximately 25,600 tokens).';
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|