@thegitai/cli 1.0.0-preview.8 → 1.0.0
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/LICENSE +1 -1
- package/README.md +301 -15
- package/dist/bin/ai.js +142 -112
- package/dist/bin/browser-host.js +284 -0
- package/dist/src/agent-mode.js +33 -7
- package/dist/src/api/auth.js +8 -2
- package/dist/src/api/browser-login.js +147 -35
- package/dist/src/api/chat.js +703 -166
- package/dist/src/api/contracts.js +55 -1
- package/dist/src/api/default-host.js +1 -0
- package/dist/src/api/http.js +168 -8
- package/dist/src/api/models.js +47 -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 +268 -0
- package/dist/src/browser/chrome-profiles.js +73 -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 +8 -14
- 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 +26 -4
- package/dist/src/help-text.js +152 -41
- package/dist/src/install-id.js +32 -0
- 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 +46 -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 +62 -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 +12 -4
- package/dist/src/signin.js +58 -0
- package/dist/src/skills/discovery.js +280 -0
- package/dist/src/skills/frontmatter.js +192 -0
- package/dist/src/skills/install.js +394 -0
- package/dist/src/skills/types.js +43 -0
- package/dist/src/skills-command.js +71 -0
- package/dist/src/tool-executor.js +41 -51
- package/dist/src/tools/browser.js +928 -0
- package/dist/src/tools/delete-file.js +21 -5
- package/dist/src/tools/index.js +34 -10
- package/dist/src/tools/patch-file.js +14 -29
- package/dist/src/tools/read-file.js +7 -1
- 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 +1 -2
- 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/shell-diagnostics.js +246 -72
- package/dist/src/tools/str-replace.js +14 -29
- package/dist/src/tools/undo-edit.js +2 -7
- package/dist/src/tools/use-skill.js +38 -0
- package/dist/src/tools/write-file.js +69 -14
- package/dist/src/ui/prompt-history-store.js +1 -1
- package/dist/src/ui/repl.js +1155 -301
- package/dist/src/ui/slash-commands.js +140 -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 +903 -304
- 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 +266 -61
- 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 +25 -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,32 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { getClientStateDir } from './client-state.js';
|
|
5
|
+
const INSTALL_ID_PATTERN = /^[a-f0-9]{32}$/;
|
|
6
|
+
let cached;
|
|
7
|
+
function readInstallId(file) {
|
|
8
|
+
try {
|
|
9
|
+
const value = readFileSync(file, 'utf8').trim();
|
|
10
|
+
return INSTALL_ID_PATTERN.test(value) ? value : null;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function getInstallId(env = process.env) {
|
|
17
|
+
if (cached !== undefined)
|
|
18
|
+
return cached;
|
|
19
|
+
const file = path.join(getClientStateDir(env), 'install-id');
|
|
20
|
+
const existing = readInstallId(file);
|
|
21
|
+
if (existing)
|
|
22
|
+
return (cached = existing);
|
|
23
|
+
try {
|
|
24
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
25
|
+
const id = randomBytes(16).toString('hex');
|
|
26
|
+
writeFileSync(file, `${id}\n`, { mode: 0o600, flag: 'wx' });
|
|
27
|
+
return (cached = id);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return (cached = readInstallId(file));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { getBackgroundJob, hasUnreportedBackgroundJobUpdate } from './background-jobs.js';
|
|
2
|
+
export const MAX_CHAINED_JOB_FOLLOW_UPS = 3;
|
|
3
|
+
function exitedOnItsOwn(id, sessionId) {
|
|
4
|
+
const job = getBackgroundJob(id, { sessionId });
|
|
5
|
+
return job !== null && job.status !== 'running' && job.status !== 'killed';
|
|
6
|
+
}
|
|
7
|
+
export function decideJobFollowUp(jobIds, chainedFollowUps, sessionId) {
|
|
8
|
+
if (!jobIds.some((id) => exitedOnItsOwn(id, sessionId)))
|
|
9
|
+
return 'wait';
|
|
10
|
+
return chainedFollowUps >= MAX_CHAINED_JOB_FOLLOW_UPS ? 'stop' : 'start';
|
|
11
|
+
}
|
|
12
|
+
export function remainingJobWait(jobIds, sessionId) {
|
|
13
|
+
return jobIds.filter((id) => {
|
|
14
|
+
const job = getBackgroundJob(id, { sessionId });
|
|
15
|
+
if (job?.status === 'running')
|
|
16
|
+
return true;
|
|
17
|
+
return exitedOnItsOwn(id, sessionId) && hasUnreportedBackgroundJobUpdate(id, { sessionId });
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
export function createJobWaitTracker(sessionId) {
|
|
21
|
+
let waiting = [];
|
|
22
|
+
let chained = 0;
|
|
23
|
+
return {
|
|
24
|
+
get waiting() {
|
|
25
|
+
return waiting;
|
|
26
|
+
},
|
|
27
|
+
turnStarted(jobFollowUp) {
|
|
28
|
+
chained = jobFollowUp ? chained + 1 : 0;
|
|
29
|
+
},
|
|
30
|
+
turnEnded(waitingForJobs) {
|
|
31
|
+
waiting = waitingForJobs ? [...waitingForJobs] : remainingJobWait(waiting, sessionId());
|
|
32
|
+
},
|
|
33
|
+
takeDecision() {
|
|
34
|
+
const decision = decideJobFollowUp(waiting, chained, sessionId());
|
|
35
|
+
if (decision !== 'wait')
|
|
36
|
+
waiting = [];
|
|
37
|
+
return decision;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -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
|
+
}
|