@thegitai/cli 1.0.0-preview.53 → 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 +119 -0
- package/dist/bin/ai.js +5 -0
- package/dist/src/api/chat.js +4 -0
- package/dist/src/help-text.js +16 -1
- 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/permissions.js +16 -3
- package/dist/src/project-key.js +11 -0
- package/dist/src/project-model-preferences.js +74 -0
- package/dist/src/reasoning-effort.js +27 -0
- package/dist/src/session-store.js +2 -10
- package/dist/src/session.js +2 -1
- package/dist/src/tool-executor.js +10 -3
- package/dist/src/ui/repl.js +45 -16
- package/dist/src/ui/slash-commands.js +2 -1
- package/dist/src/ui/tui/build-frame.js +85 -34
- package/dist/src/ui/tui/model-label.js +13 -0
- package/dist/src/ui/tui/shell-input.js +19 -0
- package/dist/vendor/mcp/LICENSES.txt +414 -0
- package/dist/vendor/mcp/client.cjs +82 -0
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -55,6 +55,23 @@ CLI login tokens use a rolling 48-hour inactivity timeout. If one expires during
|
|
|
55
55
|
any server request, the CLI removes the expired credential and signs you in
|
|
56
56
|
again on the next run.
|
|
57
57
|
|
|
58
|
+
## Models and reasoning effort
|
|
59
|
+
|
|
60
|
+
Type `/model` to choose a model with **↑ / ↓** and adjust its reasoning effort
|
|
61
|
+
with **← / →** in the same panel: **Default / Low / Balanced / Deep**.
|
|
62
|
+
**Enter** saves the selected model's choice for this project; **Esc** cancels.
|
|
63
|
+
Each model remembers its own choice across new and resumed sessions.
|
|
64
|
+
The picker and footer show the effort beside the model name. The footer labels
|
|
65
|
+
agent mode separately as `Mode: ...`; narrow terminals place it on the next
|
|
66
|
+
line, keeping both settings visible while idle and working.
|
|
67
|
+
|
|
68
|
+
Default uses TheGitAI's current recommended setting for the model. Low favors
|
|
69
|
+
quicker responses, Balanced balances depth and speed, and Deep favors thorough
|
|
70
|
+
reasoning and may take longer and cost more. Choosing Default again clears your
|
|
71
|
+
override. Switching models preserves your conversation.
|
|
72
|
+
An invalid project preference file loads Default effort; saving refuses to
|
|
73
|
+
overwrite it until the file is repaired or removed.
|
|
74
|
+
|
|
58
75
|
## When the connection drops
|
|
59
76
|
|
|
60
77
|
A dropped connection does not end your turn. The CLI shows
|
|
@@ -80,6 +97,108 @@ turn ends with an error that names what was interrupted, notes that some actions
|
|
|
80
97
|
may already have completed, and leaves anything you had queued in the composer
|
|
81
98
|
rather than sending it on top of a turn whose outcome is unknown.
|
|
82
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
|
+
|
|
83
202
|
## Chrome browser control
|
|
84
203
|
|
|
85
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());
|
package/dist/src/api/chat.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { sessionMcp } from '../mcp-client.js';
|
|
2
|
+
import { readProjectModelEfforts, projectModelEffort } from '../project-model-preferences.js';
|
|
1
3
|
import { randomUUID } from 'node:crypto';
|
|
2
4
|
import { drainBackgroundJobNotifications } from '../background-jobs.js';
|
|
3
5
|
import { cancelActiveCommand } from '../executor.js';
|
|
@@ -745,7 +747,9 @@ export async function sendServerUserMessage({ config, session, input, jobFollowU
|
|
|
745
747
|
}
|
|
746
748
|
const request = {
|
|
747
749
|
clientTurnId: randomUUID(),
|
|
750
|
+
mcpTools: await sessionMcp(session).discover(signal),
|
|
748
751
|
modelId: session.modelId,
|
|
752
|
+
reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, config.serverUrl, session.env), session.modelId),
|
|
749
753
|
session: snapshotForServer(session),
|
|
750
754
|
input: requestInputBase,
|
|
751
755
|
backgroundJobUpdate: backgroundJobUpdate || undefined,
|
package/dist/src/help-text.js
CHANGED
|
@@ -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,11 +139,12 @@ 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)',
|
|
131
146
|
'- `/usage` — show account usage percentage and reset times',
|
|
132
|
-
'- `/model` —
|
|
147
|
+
'- `/model` — ↑/↓ picks a model, ←/→ adjusts effort; Enter saves for this project, Esc cancels',
|
|
133
148
|
'- `/model <id>` — switch the active model without clearing history',
|
|
134
149
|
'- `/resume` — resume a saved session for this repo',
|
|
135
150
|
'- `/jobs` — manage long-running commands like dev servers and watchers:',
|
|
@@ -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
|
+
}
|