@causyne/agent 1.20.120 → 1.20.121

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.
Files changed (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Causyne Agent — Headless / CI Automation CLI Runner
3
+ *
4
+ * Provides non-interactive single-task execution (`-p/--print`, `run`),
5
+ * bounded stdin piping, per-invocation overrides (`--model`, `--provider`,
6
+ * `--max-turns`, `--permission-mode`) without mutating saved config, and
7
+ * machine-readable output formats (`text`, `json`, `stream-json`).
8
+ */
9
+
10
+ import { AgentLoop, type AgentLoopEventSink } from './agentLoop.js';
11
+ import { safeDisplay } from './tui/text.js';
12
+
13
+ export type HeadlessOutputFormat = 'text' | 'json' | 'stream-json';
14
+ export type AutonomyModeCode = 'A' | 'B' | 'C';
15
+
16
+ export const MAX_STDIN_PROMPT_BYTES = 1_048_576;
17
+ export const MAX_HEADLESS_TURNS = 500;
18
+
19
+ export interface HeadlessToolRecord {
20
+ tool: string;
21
+ status: 'started' | 'completed' | 'error';
22
+ error?: string | undefined;
23
+ }
24
+
25
+ export interface HeadlessUsageSummary {
26
+ inputTokens?: number | undefined;
27
+ outputTokens?: number | undefined;
28
+ totalTokens?: number | undefined;
29
+ estimatedCostUsd?: number | undefined;
30
+ }
31
+
32
+ export interface HeadlessRunResult {
33
+ ok: boolean;
34
+ status: 'completed' | 'incomplete' | 'error';
35
+ taskId: string;
36
+ sessionId: string | null;
37
+ provider: string;
38
+ model: string;
39
+ response: string;
40
+ error: string | null;
41
+ steps: number;
42
+ toolCalls: HeadlessToolRecord[];
43
+ usage: HeadlessUsageSummary | null;
44
+ durationMs: number;
45
+ }
46
+
47
+ export interface HeadlessLoopLike {
48
+ config?: { provider?: string; model?: string; autonomyMode?: string };
49
+ memoryManager?: { sessionId?: string | null };
50
+ stepsCompleted?: number;
51
+ _causyneTaskOutcome?: string;
52
+ autonomyOverride?: string | null;
53
+ providerOverride?: string | null;
54
+ modelOverride?: string | null;
55
+ maxStepsCeiling?: number | null;
56
+ waitForApproval?: (toolCallId: string) => Promise<boolean>;
57
+ waitForDecision?: (request: unknown) => Promise<unknown>;
58
+ run: () => Promise<void>;
59
+ }
60
+
61
+ export interface HeadlessRunOptions {
62
+ outputFormat?: HeadlessOutputFormat | string | undefined;
63
+ model?: string | undefined;
64
+ provider?: string | undefined;
65
+ maxTurns?: number | string | undefined;
66
+ permissionMode?: string | undefined;
67
+ workspaceRoot?: string | undefined;
68
+ stdout?: { write: (chunk: string) => unknown } | undefined;
69
+ stderr?: { write: (chunk: string) => unknown } | undefined;
70
+ loopFactory?: ((sink: AgentLoopEventSink, taskId: string, prompt: string) => HeadlessLoopLike) | undefined;
71
+ }
72
+
73
+ export function parseOutputFormat(raw?: unknown): HeadlessOutputFormat {
74
+ if (raw === undefined || raw === null || raw === '') return 'text';
75
+ const normalized = String(raw).trim().toLowerCase();
76
+ if (normalized === 'text' || normalized === 'json' || normalized === 'stream-json') {
77
+ return normalized;
78
+ }
79
+ throw new Error(`Invalid --output-format "${raw}". Expected one of: text, json, stream-json.`);
80
+ }
81
+
82
+ export function parsePermissionMode(raw?: unknown): AutonomyModeCode | undefined {
83
+ if (raw === undefined || raw === null || raw === '') return undefined;
84
+ const normalized = String(raw).trim().toUpperCase();
85
+ if (normalized === 'A' || normalized === 'SUPERVISED' || normalized === 'STRICT') return 'A';
86
+ if (normalized === 'B' || normalized === 'BALANCED' || normalized === 'DEFAULT') return 'B';
87
+ if (normalized === 'C' || normalized === 'AUTONOMOUS' || normalized === 'AUTO') return 'C';
88
+ throw new Error(`Invalid --permission-mode "${raw}". Expected A (supervised), B (balanced), or C (autonomous).`);
89
+ }
90
+
91
+ export function parseMaxTurns(raw?: unknown): number | undefined {
92
+ if (raw === undefined || raw === null || raw === '') return undefined;
93
+ const parsed = typeof raw === 'number' ? raw : Number.parseInt(String(raw).trim(), 10);
94
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_HEADLESS_TURNS) {
95
+ throw new Error(`Invalid --max-turns "${raw}". Expected an integer between 1 and ${MAX_HEADLESS_TURNS}.`);
96
+ }
97
+ return parsed;
98
+ }
99
+
100
+ export function composeHeadlessPrompt(
101
+ promptArg: string | boolean | undefined,
102
+ stdinText: string
103
+ ): string {
104
+ const cleanStdin = stdinText.trim();
105
+ const rawPrompt = typeof promptArg === 'string' ? promptArg.trim() : '';
106
+ const effectivePrompt = rawPrompt === '-' ? '' : rawPrompt;
107
+
108
+ if (effectivePrompt && cleanStdin) {
109
+ return `${effectivePrompt}\n\n<stdin>\n${cleanStdin}\n</stdin>`;
110
+ }
111
+ if (effectivePrompt) return effectivePrompt;
112
+ if (cleanStdin) return cleanStdin;
113
+ return '';
114
+ }
115
+
116
+ export async function readBoundedStdin(
117
+ stream: NodeJS.ReadableStream & { isTTY?: boolean } = process.stdin,
118
+ maxBytes = MAX_STDIN_PROMPT_BYTES
119
+ ): Promise<string> {
120
+ if (!stream || stream.isTTY) return '';
121
+
122
+ return await new Promise<string>((resolve, reject) => {
123
+ const chunks: Buffer[] = [];
124
+ let totalBytes = 0;
125
+ let truncated = false;
126
+
127
+ const onData = (chunk: Buffer | string): void => {
128
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
129
+ if (truncated) return;
130
+ const remaining = maxBytes - totalBytes;
131
+ if (buf.length <= remaining) {
132
+ chunks.push(buf);
133
+ totalBytes += buf.length;
134
+ } else {
135
+ if (remaining > 0) chunks.push(buf.subarray(0, remaining));
136
+ totalBytes = maxBytes;
137
+ truncated = true;
138
+ }
139
+ };
140
+
141
+ const cleanup = (): void => {
142
+ stream.removeListener('data', onData);
143
+ stream.removeListener('end', onEnd);
144
+ stream.removeListener('error', onError);
145
+ };
146
+
147
+ const onEnd = (): void => {
148
+ cleanup();
149
+ const text = Buffer.concat(chunks).toString('utf8');
150
+ resolve(truncated ? `${text}\n\n[stdin truncated at ${maxBytes} bytes]` : text);
151
+ };
152
+
153
+ const onError = (err: Error): void => {
154
+ cleanup();
155
+ reject(err);
156
+ };
157
+
158
+ stream.on('data', onData);
159
+ stream.on('end', onEnd);
160
+ stream.on('error', onError);
161
+ });
162
+ }
163
+
164
+ function isRecord(value: unknown): value is Record<string, unknown> {
165
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
166
+ }
167
+
168
+ export class HeadlessEventSink implements AgentLoopEventSink {
169
+ readyState = 1;
170
+ response = '';
171
+ errors: string[] = [];
172
+ toolCalls: HeadlessToolRecord[] = [];
173
+ usage: HeadlessUsageSummary | null = null;
174
+
175
+ private readonly format: HeadlessOutputFormat;
176
+ private readonly stdout: { write: (chunk: string) => unknown };
177
+ private streamedPrefix = '';
178
+
179
+ constructor(
180
+ format: HeadlessOutputFormat,
181
+ stdout: { write: (chunk: string) => unknown } = process.stdout
182
+ ) {
183
+ this.format = format;
184
+ this.stdout = stdout;
185
+ }
186
+
187
+ private emitStreamLine(payload: Record<string, unknown>): void {
188
+ if (this.format !== 'stream-json') return;
189
+ this.stdout.write(`${JSON.stringify(payload)}\n`);
190
+ }
191
+
192
+ send(data: string): void {
193
+ let parsed: unknown;
194
+ try {
195
+ parsed = JSON.parse(data);
196
+ } catch {
197
+ return;
198
+ }
199
+ if (!isRecord(parsed) || typeof parsed.type !== 'string') return;
200
+
201
+ const type = parsed.type;
202
+
203
+ if (type === 'agent_message') {
204
+ const content = typeof parsed.content === 'string' ? safeDisplay(parsed.content) : '';
205
+ const streaming = Boolean(parsed.streaming);
206
+ if (streaming) {
207
+ const delta = content.startsWith(this.streamedPrefix)
208
+ ? content.slice(this.streamedPrefix.length)
209
+ : content;
210
+ this.streamedPrefix = content;
211
+ this.response = content;
212
+ if (delta) {
213
+ this.emitStreamLine({ type: 'delta', text: delta });
214
+ }
215
+ } else {
216
+ this.streamedPrefix = '';
217
+ if (content) {
218
+ this.response = content;
219
+ this.emitStreamLine({ type: 'message', role: 'assistant', text: content });
220
+ }
221
+ }
222
+ return;
223
+ }
224
+
225
+ if (type === 'step_start') {
226
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
227
+ this.toolCalls.push({ tool, status: 'started' });
228
+ this.emitStreamLine({ type: 'tool_call', tool });
229
+ return;
230
+ }
231
+
232
+ if (type === 'step_complete') {
233
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
234
+ const last = [...this.toolCalls].reverse().find(entry => entry.tool === tool && entry.status === 'started');
235
+ if (last) last.status = 'completed';
236
+ else this.toolCalls.push({ tool, status: 'completed' });
237
+ this.emitStreamLine({ type: 'tool_result', tool, ok: true });
238
+ return;
239
+ }
240
+
241
+ if (type === 'step_error') {
242
+ const tool = typeof parsed.tool === 'string' ? safeDisplay(parsed.tool) : 'tool';
243
+ const errText = typeof parsed.error === 'string' ? safeDisplay(parsed.error) : 'Tool failed';
244
+ const last = [...this.toolCalls].reverse().find(entry => entry.tool === tool && entry.status === 'started');
245
+ if (last) {
246
+ last.status = 'error';
247
+ last.error = errText;
248
+ } else {
249
+ this.toolCalls.push({ tool, status: 'error', error: errText });
250
+ }
251
+ this.emitStreamLine({ type: 'tool_result', tool, ok: false, error: errText });
252
+ return;
253
+ }
254
+
255
+ if (type === 'error') {
256
+ const message = typeof parsed.message === 'string' ? safeDisplay(parsed.message) : 'Unknown error';
257
+ this.errors.push(message);
258
+ this.emitStreamLine({ type: 'error', message });
259
+ return;
260
+ }
261
+
262
+ if (type === 'usage_update') {
263
+ const summary: HeadlessUsageSummary = {};
264
+ if (typeof parsed.inputTokens === 'number') summary.inputTokens = parsed.inputTokens;
265
+ if (typeof parsed.outputTokens === 'number') summary.outputTokens = parsed.outputTokens;
266
+ if (typeof parsed.totalTokens === 'number') summary.totalTokens = parsed.totalTokens;
267
+ if (typeof parsed.estimatedCostUsd === 'number') summary.estimatedCostUsd = parsed.estimatedCostUsd;
268
+ if (Object.keys(summary).length > 0) {
269
+ this.usage = summary;
270
+ this.emitStreamLine({ type: 'usage', ...summary });
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ export async function runHeadlessTask(
277
+ taskPrompt: string,
278
+ options: HeadlessRunOptions = {}
279
+ ): Promise<HeadlessRunResult> {
280
+ const startedAt = Date.now();
281
+ const format = parseOutputFormat(options.outputFormat);
282
+ const permissionMode = parsePermissionMode(options.permissionMode);
283
+ const maxTurns = parseMaxTurns(options.maxTurns);
284
+ const stdout = options.stdout ?? process.stdout;
285
+ const stderr = options.stderr ?? process.stderr;
286
+
287
+ const cleanPrompt = String(taskPrompt ?? '').trim();
288
+ const taskId = `cli_headless_${startedAt}`;
289
+ const sink = new HeadlessEventSink(format, stdout);
290
+
291
+ if (!cleanPrompt) {
292
+ const emptyResult: HeadlessRunResult = {
293
+ ok: false,
294
+ status: 'error',
295
+ taskId,
296
+ sessionId: null,
297
+ provider: '',
298
+ model: '',
299
+ response: '',
300
+ error: 'No prompt provided. Pass a prompt argument or pipe input on stdin.',
301
+ steps: 0,
302
+ toolCalls: [],
303
+ usage: null,
304
+ durationMs: Date.now() - startedAt
305
+ };
306
+ if (format === 'json' || format === 'stream-json') {
307
+ stdout.write(`${JSON.stringify(format === 'stream-json' ? { type: 'result', ...emptyResult } : emptyResult)}\n`);
308
+ } else {
309
+ stderr.write(`${emptyResult.error}\n`);
310
+ }
311
+ process.exitCode = 2;
312
+ return emptyResult;
313
+ }
314
+
315
+ const loop: HeadlessLoopLike = options.loopFactory
316
+ ? options.loopFactory(sink, taskId, cleanPrompt)
317
+ : new AgentLoop(sink, taskId, cleanPrompt, {
318
+ ...(options.workspaceRoot ? { workspaceRoot: options.workspaceRoot } : {}),
319
+ ...(options.provider ? { provider: options.provider } : {}),
320
+ ...(options.model ? { model: options.model } : {})
321
+ });
322
+
323
+ if (permissionMode) loop.autonomyOverride = permissionMode;
324
+ if (options.provider) loop.providerOverride = options.provider;
325
+ if (options.model) loop.modelOverride = options.model;
326
+ if (maxTurns !== undefined) loop.maxStepsCeiling = maxTurns;
327
+
328
+ // Non-interactive approval boundary: never hang waiting for a TTY prompt.
329
+ loop.waitForApproval = async () => false;
330
+ loop.waitForDecision = async () => null;
331
+
332
+ if (format === 'stream-json') {
333
+ stdout.write(`${JSON.stringify({
334
+ type: 'start',
335
+ taskId,
336
+ provider: options.provider || loop.config?.provider || '',
337
+ model: options.model || loop.config?.model || ''
338
+ })}\n`);
339
+ }
340
+
341
+ let fatalError: string | null = null;
342
+ try {
343
+ await loop.run();
344
+ } catch (err: unknown) {
345
+ fatalError = safeDisplay(err instanceof Error ? err.message : String(err));
346
+ }
347
+
348
+ const completed = fatalError === null && loop._causyneTaskOutcome === 'completed';
349
+ const lastError = fatalError ?? (sink.errors.length > 0 ? sink.errors[sink.errors.length - 1] ?? null : null);
350
+ const result: HeadlessRunResult = {
351
+ ok: completed,
352
+ status: fatalError ? 'error' : (completed ? 'completed' : 'incomplete'),
353
+ taskId,
354
+ sessionId: loop.memoryManager?.sessionId ?? null,
355
+ provider: String(options.provider || loop.config?.provider || ''),
356
+ model: String(options.model || loop.config?.model || ''),
357
+ response: sink.response,
358
+ error: completed ? null : (lastError || 'No verified task completion was recorded.'),
359
+ steps: typeof loop.stepsCompleted === 'number' ? loop.stepsCompleted : 0,
360
+ toolCalls: sink.toolCalls,
361
+ usage: sink.usage,
362
+ durationMs: Date.now() - startedAt
363
+ };
364
+
365
+ if (format === 'json') {
366
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
367
+ } else if (format === 'stream-json') {
368
+ stdout.write(`${JSON.stringify({ type: 'result', ...result })}\n`);
369
+ } else {
370
+ if (result.response) {
371
+ stdout.write(result.response.endsWith('\n') ? result.response : `${result.response}\n`);
372
+ }
373
+ if (!result.ok && result.error) {
374
+ stderr.write(`${result.error}\n`);
375
+ }
376
+ }
377
+
378
+ process.exitCode = result.ok ? 0 : 1;
379
+ return result;
380
+ }
@@ -3,6 +3,7 @@ import { pathToFileURL } from 'node:url';
3
3
  import { Client, SSEClientTransport, SdkError, SdkErrorCode, SdkHttpError, StreamableHTTPClientTransport, UnauthorizedError } from '@modelcontextprotocol/client';
4
4
  import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
5
5
  import { getPackageVersion } from '../version.js';
6
+ import { MAX_GLOB_PATTERN_CHARS, MAX_MCP_SERVER_INSTRUCTIONS_CHARS, MAX_MCP_TOOL_DESCRIPTION_CHARS, MAX_TOOLS_PER_MCP_SERVER, sanitizeMcpInputSchema, sanitizeMcpMetadataText, sanitizeMcpToolName } from './mcpSecurity.js';
6
7
  const DEFAULT_TIMEOUT_MS = 30_000;
7
8
  const MAX_TIMEOUT_MS = 10 * 60_000;
8
9
  const STDERR_LIMIT_BYTES = 8 * 1024;
@@ -37,14 +38,13 @@ function validateStringArray(value, label) {
37
38
  return null;
38
39
  }
39
40
  function normalizeTool(tool) {
40
- if (typeof tool.name !== 'string' || tool.name.trim().length === 0)
41
+ const safeName = sanitizeMcpToolName(tool.name);
42
+ if (!safeName)
41
43
  return null;
42
- const inputSchema = isRecord(tool.inputSchema)
43
- ? tool.inputSchema
44
- : { type: 'object', properties: {} };
44
+ const inputSchema = sanitizeMcpInputSchema(tool.inputSchema);
45
45
  const normalized = {
46
- name: tool.name,
47
- description: typeof tool.description === 'string' ? tool.description : '',
46
+ name: safeName,
47
+ description: sanitizeMcpMetadataText(tool.description, MAX_MCP_TOOL_DESCRIPTION_CHARS),
48
48
  inputSchema
49
49
  };
50
50
  if (isRecord(tool.annotations))
@@ -221,6 +221,13 @@ export class McpClient {
221
221
  const problem = validateStringArray(definition.tools[key], `\`tools.${key}\``);
222
222
  if (problem)
223
223
  return problem;
224
+ const patterns = definition.tools[key];
225
+ if (patterns.length > 256) {
226
+ return `\`tools.${key}\` must contain at most 256 patterns`;
227
+ }
228
+ if (patterns.some(pattern => pattern.length > MAX_GLOB_PATTERN_CHARS)) {
229
+ return `\`tools.${key}\` patterns must be at most ${MAX_GLOB_PATTERN_CHARS} characters`;
230
+ }
224
231
  }
225
232
  }
226
233
  }
@@ -250,8 +257,9 @@ export class McpClient {
250
257
  catch (error) {
251
258
  await this.dispose();
252
259
  const state = isAuthenticationError(error) ? 'needs_auth' : 'failed';
253
- const suffix = this.stderrTail.trim() ? `: ${this.stderrTail.trim().slice(-600)}` : '';
254
- const message = `${errorMessage(error)}${suffix}`;
260
+ const safeTail = sanitizeMcpMetadataText(this.stderrTail.trim().slice(-600), 600);
261
+ const suffix = safeTail ? `: ${safeTail}` : '';
262
+ const message = `${sanitizeMcpMetadataText(errorMessage(error), 1000)}${suffix}`;
255
263
  this.setStatus({ state, error: message });
256
264
  throw new McpConnectionError(state, message, { cause: error });
257
265
  }
@@ -482,15 +490,34 @@ export class McpClient {
482
490
  }
483
491
  captureServer(client, transport) {
484
492
  const server = client.getServerVersion();
485
- this.serverInfo = server ? { name: server.name, version: server.version } : null;
486
- this.instructions = client.getInstructions()?.trim() || null;
493
+ this.serverInfo = server
494
+ ? {
495
+ name: sanitizeMcpMetadataText(server.name, 128),
496
+ version: sanitizeMcpMetadataText(server.version, 64)
497
+ }
498
+ : null;
499
+ const rawInstructions = client.getInstructions()?.trim();
500
+ this.instructions = rawInstructions
501
+ ? sanitizeMcpMetadataText(rawInstructions, MAX_MCP_SERVER_INSTRUCTIONS_CHARS)
502
+ : null;
487
503
  const status = { state: 'connected', connectedAt: Date.now() };
488
504
  if (transport)
489
505
  status.transport = transport;
490
506
  this.setStatus(status);
491
507
  }
492
508
  replaceTools(tools) {
493
- this.tools = tools.map(normalizeTool).filter((tool) => tool !== null);
509
+ const nextTools = [];
510
+ const seenNames = new Set();
511
+ for (const rawTool of tools) {
512
+ if (nextTools.length >= MAX_TOOLS_PER_MCP_SERVER)
513
+ break;
514
+ const normalized = normalizeTool(rawTool);
515
+ if (!normalized || seenNames.has(normalized.name))
516
+ continue;
517
+ seenNames.add(normalized.name);
518
+ nextTools.push(normalized);
519
+ }
520
+ this.tools = nextTools;
494
521
  this.onToolsChanged?.([...this.tools]);
495
522
  }
496
523
  setStatus(status) {
@@ -16,6 +16,15 @@ import {
16
16
  import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
17
17
 
18
18
  import { getPackageVersion } from '../version.js';
19
+ import {
20
+ MAX_GLOB_PATTERN_CHARS,
21
+ MAX_MCP_SERVER_INSTRUCTIONS_CHARS,
22
+ MAX_MCP_TOOL_DESCRIPTION_CHARS,
23
+ MAX_TOOLS_PER_MCP_SERVER,
24
+ sanitizeMcpInputSchema,
25
+ sanitizeMcpMetadataText,
26
+ sanitizeMcpToolName
27
+ } from './mcpSecurity.js';
19
28
 
20
29
  const DEFAULT_TIMEOUT_MS = 30_000;
21
30
  const MAX_TIMEOUT_MS = 10 * 60_000;
@@ -105,13 +114,12 @@ function validateStringArray(value: unknown, label: string): string | null {
105
114
  }
106
115
 
107
116
  function normalizeTool(tool: Tool): McpToolDefinition | null {
108
- if (typeof tool.name !== 'string' || tool.name.trim().length === 0) return null;
109
- const inputSchema = isRecord(tool.inputSchema)
110
- ? tool.inputSchema
111
- : { type: 'object', properties: {} };
117
+ const safeName = sanitizeMcpToolName(tool.name);
118
+ if (!safeName) return null;
119
+ const inputSchema = sanitizeMcpInputSchema(tool.inputSchema);
112
120
  const normalized: McpToolDefinition = {
113
- name: tool.name,
114
- description: typeof tool.description === 'string' ? tool.description : '',
121
+ name: safeName,
122
+ description: sanitizeMcpMetadataText(tool.description, MAX_MCP_TOOL_DESCRIPTION_CHARS),
115
123
  inputSchema
116
124
  };
117
125
  if (isRecord(tool.annotations)) normalized.annotations = tool.annotations;
@@ -293,6 +301,13 @@ export class McpClient {
293
301
  if (definition.tools[key] !== undefined) {
294
302
  const problem = validateStringArray(definition.tools[key], `\`tools.${key}\``);
295
303
  if (problem) return problem;
304
+ const patterns = definition.tools[key] as string[];
305
+ if (patterns.length > 256) {
306
+ return `\`tools.${key}\` must contain at most 256 patterns`;
307
+ }
308
+ if (patterns.some(pattern => pattern.length > MAX_GLOB_PATTERN_CHARS)) {
309
+ return `\`tools.${key}\` patterns must be at most ${MAX_GLOB_PATTERN_CHARS} characters`;
310
+ }
296
311
  }
297
312
  }
298
313
  }
@@ -322,8 +337,9 @@ export class McpClient {
322
337
  } catch (error) {
323
338
  await this.dispose();
324
339
  const state = isAuthenticationError(error) ? 'needs_auth' : 'failed';
325
- const suffix = this.stderrTail.trim() ? `: ${this.stderrTail.trim().slice(-600)}` : '';
326
- const message = `${errorMessage(error)}${suffix}`;
340
+ const safeTail = sanitizeMcpMetadataText(this.stderrTail.trim().slice(-600), 600);
341
+ const suffix = safeTail ? `: ${safeTail}` : '';
342
+ const message = `${sanitizeMcpMetadataText(errorMessage(error), 1000)}${suffix}`;
327
343
  this.setStatus({ state, error: message });
328
344
  throw new McpConnectionError(state, message, { cause: error });
329
345
  }
@@ -550,15 +566,32 @@ export class McpClient {
550
566
 
551
567
  private captureServer(client: Client, transport: McpConnectionStatus['transport']): void {
552
568
  const server = client.getServerVersion();
553
- this.serverInfo = server ? { name: server.name, version: server.version } : null;
554
- this.instructions = client.getInstructions()?.trim() || null;
569
+ this.serverInfo = server
570
+ ? {
571
+ name: sanitizeMcpMetadataText(server.name, 128),
572
+ version: sanitizeMcpMetadataText(server.version, 64)
573
+ }
574
+ : null;
575
+ const rawInstructions = client.getInstructions()?.trim();
576
+ this.instructions = rawInstructions
577
+ ? sanitizeMcpMetadataText(rawInstructions, MAX_MCP_SERVER_INSTRUCTIONS_CHARS)
578
+ : null;
555
579
  const status: McpConnectionStatus = { state: 'connected', connectedAt: Date.now() };
556
580
  if (transport) status.transport = transport;
557
581
  this.setStatus(status);
558
582
  }
559
583
 
560
584
  private replaceTools(tools: Tool[]): void {
561
- this.tools = tools.map(normalizeTool).filter((tool): tool is McpToolDefinition => tool !== null);
585
+ const nextTools: McpToolDefinition[] = [];
586
+ const seenNames = new Set<string>();
587
+ for (const rawTool of tools) {
588
+ if (nextTools.length >= MAX_TOOLS_PER_MCP_SERVER) break;
589
+ const normalized = normalizeTool(rawTool);
590
+ if (!normalized || seenNames.has(normalized.name)) continue;
591
+ seenNames.add(normalized.name);
592
+ nextTools.push(normalized);
593
+ }
594
+ this.tools = nextTools;
562
595
  this.onToolsChanged?.([...this.tools]);
563
596
  }
564
597
 
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { McpClient, McpConnectionError } from './mcpClient.js';
3
+ import { globMatchesSafe } from './mcpSecurity.js';
3
4
  import { loadConfig, saveConfig } from '../config.js';
4
5
  import { auditLog } from '../auditLog.js';
5
6
  const NAMESPACE = 'mcp__';
@@ -83,11 +84,7 @@ function consentRecord(value) {
83
84
  return { digest: value.digest, grantedAt: value.grantedAt };
84
85
  }
85
86
  function globMatches(name, pattern) {
86
- const source = pattern
87
- .replace(/[.+^${}()|[\]\\]/g, '\\$&')
88
- .replaceAll('*', '.*')
89
- .replaceAll('?', '.');
90
- return new RegExp(`^${source}$`, 'u').test(name);
87
+ return globMatchesSafe(name, pattern);
91
88
  }
92
89
  function toolAllowed(server, toolName) {
93
90
  const include = server.tools?.include;
@@ -8,6 +8,7 @@ import {
8
8
  type McpToolCallResult,
9
9
  type McpToolDefinition
10
10
  } from './mcpClient.js';
11
+ import { globMatchesSafe } from './mcpSecurity.js';
11
12
  import { loadConfig, saveConfig } from '../config.js';
12
13
  import { auditLog } from '../auditLog.js';
13
14
 
@@ -101,11 +102,7 @@ function consentRecord(value: unknown): ConsentRecord | null {
101
102
  }
102
103
 
103
104
  function globMatches(name: string, pattern: string): boolean {
104
- const source = pattern
105
- .replace(/[.+^${}()|[\]\\]/g, '\\$&')
106
- .replaceAll('*', '.*')
107
- .replaceAll('?', '.');
108
- return new RegExp(`^${source}$`, 'u').test(name);
105
+ return globMatchesSafe(name, pattern);
109
106
  }
110
107
 
111
108
  function toolAllowed(server: McpServerDefinition, toolName: string): boolean {