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

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.
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { getUnquotedShellText } from './agent-mode.js';
2
- export const PERMISSION_BUCKETS = ['create', 'edit', 'delete', 'run', 'browse'];
2
+ export const PERMISSION_BUCKETS = ['create', 'edit', 'delete', 'run', 'browse', 'mcp'];
3
3
  export function createSessionGrants() {
4
4
  return { buckets: [], commandPrefixes: [], origins: [] };
5
5
  }
@@ -12,6 +12,8 @@ export function bucketActionLabel(bucket) {
12
12
  return 'delete files';
13
13
  if (bucket === 'browse')
14
14
  return 'act on any website';
15
+ if (bucket === 'mcp')
16
+ return 'use MCP tools';
15
17
  return 'run commands';
16
18
  }
17
19
  export function originForUrl(url) {
@@ -218,6 +220,8 @@ export function buildPermissionOptions(bucket, command, origin) {
218
220
  return options;
219
221
  }
220
222
  function declinedSubject(bucket) {
223
+ if (bucket === 'mcp')
224
+ return { noun: 'MCP tool call', effect: 'The MCP tool was not called' };
221
225
  if (bucket === 'run') {
222
226
  return { noun: 'command', effect: 'Nothing was executed' };
223
227
  }
@@ -250,6 +254,8 @@ function declinedResponse(bucket, toolName, extra) {
250
254
  export async function ensurePermission(context, request, toolName, extra = {}) {
251
255
  if (context.autoYes)
252
256
  return null;
257
+ if (request.mcpTool && context.grants?.mcpTools?.includes(request.mcpTool))
258
+ return null;
253
259
  if (isBucketGranted(context.grants, request.bucket))
254
260
  return null;
255
261
  if (request.bucket === 'run' &&
@@ -268,13 +274,20 @@ export async function ensurePermission(context, request, toolName, extra = {}) {
268
274
  error: `requestPermission is required when autoYes is false (${toolName})`,
269
275
  };
270
276
  }
271
- const options = buildPermissionOptions(request.bucket, request.command, request.origin);
277
+ const options = request.mcpTool ? [
278
+ { label: 'Approve once', decision: { kind: 'once' } },
279
+ { label: 'Allow this MCP tool for the session', decision: { kind: 'always-mcp-tool', tool: request.mcpTool } },
280
+ { label: 'Deny', decision: { kind: 'deny' } },
281
+ ] : buildPermissionOptions(request.bucket, request.command, request.origin);
272
282
  const decision = await context.requestPermission({ ...request, options });
273
283
  if (decision.kind === 'deny') {
274
284
  return declinedResponse(request.bucket, toolName, extra);
275
285
  }
276
286
  if (context.grants) {
277
- if (decision.kind === 'always-bucket') {
287
+ if (decision.kind === 'always-mcp-tool' && decision.tool === request.mcpTool) {
288
+ (context.grants.mcpTools ??= []).push(decision.tool);
289
+ }
290
+ else if (decision.kind === 'always-bucket') {
278
291
  grantBucket(context.grants, request.bucket);
279
292
  }
280
293
  else if (decision.kind === 'always-prefix') {
@@ -99,8 +99,9 @@ export function clearConversation(session) {
99
99
  safety: createSessionSafetyState(),
100
100
  };
101
101
  }
102
- export async function disposeSession(_session) {
102
+ export async function disposeSession(session) {
103
103
  closeBrowserBridge();
104
+ await session.mcp?.close();
104
105
  }
105
106
  export function switchModel(session, modelId) {
106
107
  session.modelId = Number(modelId);
@@ -1,3 +1,5 @@
1
+ import { isMcpToolName } from './mcp-types.js';
2
+ import { sessionMcp } from './mcp-client.js';
1
3
  import { drainBackgroundJobNotifications, getBackgroundJob, } from './background-jobs.js';
2
4
  import { canStoreEditSnapshot, isEditToolName, isGitWorkTree, MAX_EDIT_JOURNAL_RECORDS, operationFromSnapshots, readFileEditSnapshot, } from './edit-journal.js';
3
5
  import { clearEditFailure, collectCommandMutations, captureMutationBaseline, ensureActiveCheckpoint, recordEditFailure, recordSessionEdit, rememberCheckpointFiles, } from './session-safety.js';
@@ -42,9 +44,9 @@ function toolCallSummary(call) {
42
44
  return args.query.slice(0, 120);
43
45
  return '';
44
46
  }
45
- export function formatToolCallForStatus(call) {
47
+ export function formatToolCallForStatus(call, label = call.name) {
46
48
  const summary = toolCallSummary(call);
47
- return summary ? `Tool: ${call.name} ${summary}` : `Tool: ${call.name}`;
49
+ return summary ? `Tool: ${label} ${summary}` : `Tool: ${label}`;
48
50
  }
49
51
  function getEditToolFilePath(call) {
50
52
  const args = call.args && typeof call.args === 'object' ? call.args : {};
@@ -214,7 +216,7 @@ function recordAssistantEdit(session, call, result, before) {
214
216
  }
215
217
  export async function executeLocalToolCall(session, call) {
216
218
  session.turnAbortSignal?.throwIfAborted();
217
- session.onStatus(formatToolCallForStatus(call));
219
+ session.onStatus(formatToolCallForStatus(call, session.mcp?.label(call.name)));
218
220
  try {
219
221
  const agentModeBlocked = buildAgentModeToolBlockedResult(session.agentMode, call);
220
222
  if (agentModeBlocked) {
@@ -222,6 +224,11 @@ export async function executeLocalToolCall(session, call) {
222
224
  session.onToolEvent?.({ call, result });
223
225
  return result;
224
226
  }
227
+ if (isMcpToolName(call.name)) {
228
+ const result = await sessionMcp(session).execute(session, call);
229
+ session.onToolEvent?.({ call, result });
230
+ return result;
231
+ }
225
232
  const rawEditFilePath = isEditToolName(call.name)
226
233
  ? getEditToolFilePath(call)
227
234
  : '';
@@ -1,3 +1,4 @@
1
+ import { sessionMcp } from '../mcp-client.js';
1
2
  import { projectModelEffort, readProjectModelEfforts, saveProjectModelEffort } from '../project-model-preferences.js';
2
3
  import { REASONING_EFFORT_LABELS } from '../reasoning-effort.js';
3
4
  import { basename } from 'node:path';
@@ -707,7 +708,7 @@ function buildFileChangeEntry(event) {
707
708
  title: `Edited ${filePath}${summary}`,
708
709
  };
709
710
  }
710
- export function buildWorkingToolEntry(event) {
711
+ export function buildWorkingToolEntry(event, label = event.call.name) {
711
712
  const { call, result } = event;
712
713
  const failed = result?.ok !== true && result?.skipped !== true;
713
714
  const kind = result?.ok === true ? 'tool' : 'system';
@@ -756,7 +757,7 @@ export function buildWorkingToolEntry(event) {
756
757
  }
757
758
  const args = formatToolArgs(call, result);
758
759
  return {
759
- body: `${call.name}${args ? ` ${args}` : ''}${state(` -> ${formatToolResultState(result)}`)}${error}`,
760
+ body: `${label}${args ? ` ${args}` : ''}${state(` -> ${formatToolResultState(result)}`)}${error}`,
760
761
  kind,
761
762
  title: 'Tool',
762
763
  };
@@ -2592,6 +2593,27 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2592
2593
  requestExit();
2593
2594
  return;
2594
2595
  }
2596
+ if (input === '/mcp') {
2597
+ const connections = sessionMcp(session);
2598
+ const controller = new AbortController();
2599
+ activeTurnAbort = controller;
2600
+ store.update((current) => ({ ...current, busy: true, status: 'Checking MCP servers...', activeTurnInput: '/mcp' }));
2601
+ try {
2602
+ await connections.discover(controller.signal, { force: true });
2603
+ appendStaticEntry({ body: connections.status(), kind: 'system', title: 'MCP servers' });
2604
+ }
2605
+ catch (error) {
2606
+ appendStaticEntry({ body: controller.signal.aborted ? 'MCP discovery cancelled.' : String(error.message), kind: 'system', title: 'MCP servers' });
2607
+ }
2608
+ finally {
2609
+ if (activeTurnAbort === controller)
2610
+ activeTurnAbort = null;
2611
+ store.update((current) => ({ ...current, busy: false, activeTurnInput: '', status: '' }));
2612
+ await remountTui();
2613
+ }
2614
+ await flushQueuedMessage();
2615
+ return;
2616
+ }
2595
2617
  if (input === '/help') {
2596
2618
  appendStaticEntry({
2597
2619
  body: formatInteractiveHelpText(),
@@ -3071,7 +3093,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3071
3093
  appendTurnAwareEntry(entry);
3072
3094
  return;
3073
3095
  }
3074
- store.appendWorkingTool(buildWorkingToolEntry(event));
3096
+ store.appendWorkingTool(buildWorkingToolEntry(event, session.mcp?.label(event.call.name)));
3075
3097
  };
3076
3098
  const syncBackgroundJobsState = () => {
3077
3099
  const expandedId = store.getState().jobsPickerExpandedId;
@@ -3161,6 +3183,13 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3161
3183
  title: 'Approvals',
3162
3184
  });
3163
3185
  }
3186
+ else if (decision.kind === 'always-mcp-tool') {
3187
+ appendTurnAwareEntry({
3188
+ body: `Allowed for the rest of this session: ${request.mcpLabel ?? request.title}.`,
3189
+ kind: 'system',
3190
+ title: 'Approvals',
3191
+ });
3192
+ }
3164
3193
  else if (decision.kind === 'always-origin') {
3165
3194
  appendTurnAwareEntry({
3166
3195
  body: `Allowed for the rest of this session: browser actions on ${decision.origin}.`,
@@ -7,6 +7,7 @@ export const SLASH_COMMANDS = [
7
7
  description: 'Open the session picker to resume a previous session',
8
8
  },
9
9
  { command: '/new', description: 'start a new conversation; this session remains saved' },
10
+ { command: '/mcp', description: 'Check MCP connections and available tools' },
10
11
  { command: '/jobs', description: 'Background jobs: pick to view output or kill' },
11
12
  {
12
13
  command: '/notify',
@@ -1,4 +1,4 @@
1
- import { displayWidth, line, padToWidth, plainLine, sliceToWidth, span, wrapText, wrapToWidth, } from './text.js';
1
+ import { displayWidth, expandTabs, line, padToWidth, plainLine, sliceToWidth, span, wrapText, wrapToWidth, } from './text.js';
2
2
  const MIN_TABLE_COLUMN_WIDTH = 3;
3
3
  function tableRowOverhead(columnCount) {
4
4
  return 3 * columnCount + 1;
@@ -178,10 +178,10 @@ function parseMarkdownTableBlock(lines, startIndex) {
178
178
  };
179
179
  }
180
180
  function splitFormattedLines(body) {
181
- const lines = String(body ?? '')
181
+ const normalizedBody = String(body ?? '')
182
182
  .replace(/\r\n/g, '\n')
183
- .replace(/\r/g, '\n')
184
- .split('\n');
183
+ .replace(/\r/g, '\n');
184
+ const lines = expandTabs(normalizedBody).split('\n');
185
185
  const formatted = [];
186
186
  let inCodeBlock = false;
187
187
  for (let index = 0; index < lines.length; index++) {
@@ -410,7 +410,7 @@ export function renderFormattedBodyLines(body, width, kind) {
410
410
  if (prev && prev.kind !== 'code' && prev.kind !== 'blank') {
411
411
  output.push(plainLine(''));
412
412
  }
413
- for (const wrapped of wrapText(formattedLine.text || ' ', bodyWidth)) {
413
+ for (const wrapped of wrapText(formattedLine.text || ' ', Math.max(1, width - 4))) {
414
414
  output.push(plainLine(` ${wrapped}`, { color: 'cyan' }));
415
415
  }
416
416
  const next = formatted[index + 1];
@@ -446,16 +446,17 @@ export function renderPreformattedBodyLines(body, width, kind) {
446
446
  const bodyColor = kind === 'error' ? 'red' : undefined;
447
447
  const bodyWidth = Math.max(1, width - 8);
448
448
  const output = [];
449
- const normalizedBody = String(body ?? '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
449
+ const normalizedBody = expandTabs(String(body ?? '').replace(/\r\n/g, '\n').replace(/\r/g, '\n'));
450
450
  for (const rawLine of normalizedBody.split('\n')) {
451
451
  if (rawLine === '') {
452
452
  output.push(plainLine(''));
453
453
  continue;
454
454
  }
455
455
  let remaining = rawLine;
456
- while (remaining.length > bodyWidth) {
457
- output.push(plainLine(` ${remaining.slice(0, bodyWidth)}`, { color: bodyColor }));
458
- remaining = remaining.slice(bodyWidth);
456
+ while (displayWidth(remaining) > bodyWidth) {
457
+ const head = sliceToWidth(remaining, bodyWidth);
458
+ output.push(plainLine(` ${head}`, { color: bodyColor }));
459
+ remaining = remaining.slice(head.length);
459
460
  }
460
461
  output.push(plainLine(` ${remaining}`, { color: bodyColor }));
461
462
  }
@@ -1,17 +1,42 @@
1
- const CSI_PATTERN = /\u001B\[[0-9;?]*[ -\/]*[@-~]/g;
2
- const OSC_PATTERN = /\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)?/g;
3
- const CONTROL_CHAR_PATTERN = /[\u0000-\u0008\u000B-\u001F\u007F]/g;
1
+ const CSI_PATTERN = /(?:\u001B\[|\u009B)[0-?]*[ -\/]*[@-~]/g;
2
+ const OSC_PATTERN = /(?:\u001B\]|\u009D)[^\u0007\u001B\u009C]*(?:\u0007|\u001B\\|\u009C)?/g;
3
+ const STRING_CONTROL_PATTERN = /(?:\u001B[PX^_]|[\u0090\u0098\u009E\u009F])[^\u001B\u009C]*(?:\u001B\\|\u009C)?/g;
4
+ const ESC_PATTERN = /\u001B[ -\/]*[0-~]/g;
5
+ const CONTROL_CHAR_PATTERN = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g;
4
6
  export function stripControlCharacters(text) {
5
7
  return String(text ?? '')
6
8
  .replace(OSC_PATTERN, '')
9
+ .replace(STRING_CONTROL_PATTERN, '')
7
10
  .replace(CSI_PATTERN, '')
11
+ .replace(ESC_PATTERN, '')
8
12
  .replace(CONTROL_CHAR_PATTERN, '');
9
13
  }
14
+ export function expandTabs(text, initialColumn = 0) {
15
+ let column = initialColumn;
16
+ return stripControlCharacters(text).split(/(\t|\n)/).map((part) => {
17
+ if (part === '\n') {
18
+ column = 0;
19
+ return part;
20
+ }
21
+ if (part === '\t') {
22
+ const spaces = 8 - column % 8;
23
+ column += spaces;
24
+ return ' '.repeat(spaces);
25
+ }
26
+ column += displayWidth(part);
27
+ return part;
28
+ }).join('');
29
+ }
10
30
  export function span(text, style = {}) {
11
31
  return { text: stripControlCharacters(text), ...style };
12
32
  }
13
33
  export function line(...spans) {
14
- return { spans };
34
+ let column = 0;
35
+ return { spans: spans.map((part) => {
36
+ const text = expandTabs(part.text.replace(/\n/g, ' '), column);
37
+ column += displayWidth(text);
38
+ return { ...part, text };
39
+ }) };
15
40
  }
16
41
  export function plainLine(text, style = {}) {
17
42
  return line(span(text, style));
@@ -21,7 +46,7 @@ export function wrapText(text, width) {
21
46
  if (!text)
22
47
  return [''];
23
48
  const lines = [];
24
- for (const rawLine of text.split('\n')) {
49
+ for (const rawLine of expandTabs(text).split('\n')) {
25
50
  let remaining = rawLine;
26
51
  while (displayWidth(remaining) > safeWidth) {
27
52
  const head = sliceToWidth(remaining, safeWidth);
@@ -152,7 +177,7 @@ export function padToWidth(text, width) {
152
177
  export function wrapToWidth(text, width) {
153
178
  const limit = Math.max(1, Math.floor(width));
154
179
  const out = [];
155
- for (const rawLine of String(text ?? '').split('\n')) {
180
+ for (const rawLine of expandTabs(text).split('\n')) {
156
181
  let current = '';
157
182
  const flush = () => {
158
183
  out.push(current);