@1xops/command-center 0.4.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.
Potentially problematic release.
This version of @1xops/command-center might be problematic. Click here for more details.
- package/LICENSE +191 -0
- package/README.md +141 -0
- package/dist/config.js +126 -0
- package/dist/files.js +200 -0
- package/dist/index.js +66 -0
- package/dist/log.js +5 -0
- package/dist/policy.js +141 -0
- package/dist/processes.js +206 -0
- package/dist/search-worker.js +14 -0
- package/dist/search.js +339 -0
- package/dist/server.js +296 -0
- package/dist/system.js +71 -0
- package/dist/version.js +5 -0
- package/icon.png +0 -0
- package/package.json +59 -0
package/dist/search.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Worker } from 'node:worker_threads';
|
|
5
|
+
import { validatePath } from './policy.js';
|
|
6
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', '.venv', '__pycache__', 'dist', 'build', '.next', 'target']);
|
|
7
|
+
const NODE_MAX_FILE_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
let rgAvailable;
|
|
9
|
+
function hasRipgrep() {
|
|
10
|
+
rgAvailable ??= new Promise((resolve) => execFile('rg', ['--version'], (error) => resolve(!error)));
|
|
11
|
+
return rgAvailable;
|
|
12
|
+
}
|
|
13
|
+
function ripgrep(root, input, signal, onMatch) {
|
|
14
|
+
const args = input.kind === 'files'
|
|
15
|
+
? ['--files', '--color', 'never']
|
|
16
|
+
: ['--line-number', '--no-heading', '--color', 'never', '--max-columns', '500'];
|
|
17
|
+
if (input.glob)
|
|
18
|
+
args.push('--glob', input.glob);
|
|
19
|
+
if (input.kind === 'content') {
|
|
20
|
+
if (input.ignoreCase)
|
|
21
|
+
args.push('--ignore-case');
|
|
22
|
+
if (input.literal)
|
|
23
|
+
args.push('--fixed-strings');
|
|
24
|
+
args.push('--regexp', input.pattern);
|
|
25
|
+
}
|
|
26
|
+
args.push('--', root);
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
const child = spawn('rg', args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
29
|
+
const matches = [];
|
|
30
|
+
let buffered = '';
|
|
31
|
+
let stderr = '';
|
|
32
|
+
let truncated = false;
|
|
33
|
+
let timedOut = false;
|
|
34
|
+
const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, input.timeoutMs);
|
|
35
|
+
// An abort that arrived before the spawn would never fire the listener, so check first.
|
|
36
|
+
if (signal?.aborted)
|
|
37
|
+
child.kill('SIGKILL');
|
|
38
|
+
else
|
|
39
|
+
signal?.addEventListener('abort', () => child.kill('SIGKILL'), { once: true });
|
|
40
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => {
|
|
41
|
+
buffered += chunk;
|
|
42
|
+
const lines = buffered.split('\n');
|
|
43
|
+
buffered = lines.pop() ?? '';
|
|
44
|
+
for (const line of lines) {
|
|
45
|
+
// In files mode rg lists every file; filter names by the pattern here.
|
|
46
|
+
if (input.kind === 'files' && !nameMatches(line, input))
|
|
47
|
+
continue;
|
|
48
|
+
if (matches.length >= input.maxResults) {
|
|
49
|
+
truncated = true;
|
|
50
|
+
child.kill('SIGKILL');
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
matches.push(line);
|
|
54
|
+
onMatch?.(line);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
|
|
58
|
+
child.on('error', (error) => { clearTimeout(timer); reject(error); });
|
|
59
|
+
child.on('close', (code) => {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
// rg exits 1 for "no matches" and 2 for errors (bad regex, unreadable files). Errors with
|
|
62
|
+
// no results fail the call; errors alongside results are reported as warnings.
|
|
63
|
+
if (code === 2 && !truncated && !timedOut && matches.length === 0)
|
|
64
|
+
return reject(new Error(`ripgrep: ${stderr.trim()}`));
|
|
65
|
+
const warnings = code === 2 ? stderr.trim().split('\n').slice(0, 5).map((l) => `ripgrep: ${l}`) : [];
|
|
66
|
+
resolve({ engine: 'ripgrep', matches, truncated, timedOut, warnings });
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** File-name search is plain text, so no user regular expression runs on the main thread. */
|
|
71
|
+
function nameMatches(file, input) {
|
|
72
|
+
const name = path.basename(file);
|
|
73
|
+
return input.ignoreCase ? name.toLowerCase().includes(input.pattern.toLowerCase()) : name.includes(input.pattern);
|
|
74
|
+
}
|
|
75
|
+
function globToRegExp(glob) {
|
|
76
|
+
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
|
|
77
|
+
return new RegExp(`^${escaped}$`);
|
|
78
|
+
}
|
|
79
|
+
export async function nodeSearch(root, input, onMatch) {
|
|
80
|
+
const deadline = Date.now() + input.timeoutMs;
|
|
81
|
+
const matcher = input.literal
|
|
82
|
+
? undefined
|
|
83
|
+
: new RegExp(input.pattern, input.ignoreCase ? 'i' : '');
|
|
84
|
+
const needle = input.ignoreCase ? input.pattern.toLowerCase() : input.pattern;
|
|
85
|
+
const globRe = input.glob ? globToRegExp(input.glob) : undefined;
|
|
86
|
+
const result = { engine: 'node', matches: [], truncated: false, timedOut: false, warnings: [] };
|
|
87
|
+
const skipped = { large: 0, binary: 0, unreadable: 0, unreadableFolders: 0 };
|
|
88
|
+
const contains = (text) => (matcher ? matcher.test(text) : (input.ignoreCase ? text.toLowerCase() : text).includes(needle));
|
|
89
|
+
async function visit(file) {
|
|
90
|
+
if (globRe && !globRe.test(path.basename(file)))
|
|
91
|
+
return;
|
|
92
|
+
if (input.kind === 'files') {
|
|
93
|
+
if (nameMatches(file, input)) {
|
|
94
|
+
if (result.matches.length >= input.maxResults) {
|
|
95
|
+
result.truncated = true;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
result.matches.push(file);
|
|
99
|
+
onMatch?.(file);
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
let buffer;
|
|
104
|
+
try {
|
|
105
|
+
if ((await stat(file)).size > NODE_MAX_FILE_BYTES) {
|
|
106
|
+
skipped.large++;
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
buffer = await readFile(file);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
skipped.unreadable++;
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (buffer.subarray(0, 8192).includes(0)) {
|
|
116
|
+
skipped.binary++;
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const lines = buffer.toString('utf8').split('\n');
|
|
120
|
+
for (let i = 0; i < lines.length; i++) {
|
|
121
|
+
if (!contains(lines[i] ?? ''))
|
|
122
|
+
continue;
|
|
123
|
+
if (result.matches.length >= input.maxResults) {
|
|
124
|
+
result.truncated = true;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const match = `${file}:${i + 1}:${(lines[i] ?? '').slice(0, 500)}`;
|
|
128
|
+
result.matches.push(match);
|
|
129
|
+
onMatch?.(match);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async function walk(dir) {
|
|
133
|
+
let items;
|
|
134
|
+
try {
|
|
135
|
+
items = await readdir(dir, { withFileTypes: true });
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
skipped.unreadableFolders++;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
for (const item of items) {
|
|
142
|
+
if (result.truncated)
|
|
143
|
+
return;
|
|
144
|
+
if (Date.now() > deadline) {
|
|
145
|
+
result.timedOut = true;
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const full = path.join(dir, item.name);
|
|
149
|
+
if (item.isDirectory()) {
|
|
150
|
+
if (!SKIP_DIRS.has(item.name))
|
|
151
|
+
await walk(full);
|
|
152
|
+
}
|
|
153
|
+
else if (item.isFile())
|
|
154
|
+
await visit(full);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const info = await stat(root);
|
|
158
|
+
if (info.isFile())
|
|
159
|
+
await visit(root);
|
|
160
|
+
else
|
|
161
|
+
await walk(root);
|
|
162
|
+
if (skipped.unreadable)
|
|
163
|
+
result.warnings.push(`${skipped.unreadable} file(s) could not be read`);
|
|
164
|
+
if (skipped.unreadableFolders)
|
|
165
|
+
result.warnings.push(`${skipped.unreadableFolders} folder(s) could not be read`);
|
|
166
|
+
if (skipped.large)
|
|
167
|
+
result.warnings.push(`${skipped.large} file(s) over ${NODE_MAX_FILE_BYTES / 1024 / 1024} MiB skipped (install ripgrep to search them)`);
|
|
168
|
+
if (skipped.binary)
|
|
169
|
+
result.warnings.push(`${skipped.binary} binary file(s) skipped`);
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The built-in search in a worker thread, terminated if it outlives the timeout or is aborted.
|
|
174
|
+
* The worker sends matches in batches as it finds them; a stopped or timed-out search returns
|
|
175
|
+
* what it found so far.
|
|
176
|
+
*/
|
|
177
|
+
export function nodeSearchInWorker(root, input, signal, onMatch) {
|
|
178
|
+
return new Promise((resolve, reject) => {
|
|
179
|
+
const found = [];
|
|
180
|
+
let settled = false;
|
|
181
|
+
const worker = new Worker(new URL('./search-worker.js', import.meta.url), { workerData: { root, input } });
|
|
182
|
+
const finish = (outcome) => {
|
|
183
|
+
if (settled)
|
|
184
|
+
return;
|
|
185
|
+
settled = true;
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
signal?.removeEventListener('abort', onAbort);
|
|
188
|
+
void worker.terminate();
|
|
189
|
+
outcome();
|
|
190
|
+
};
|
|
191
|
+
const partial = (timedOut, warning) => ({ engine: 'node', matches: found, truncated: false, timedOut, warnings: [warning] });
|
|
192
|
+
const onAbort = () => finish(() => resolve(partial(false, 'stopped')));
|
|
193
|
+
const timer = setTimeout(() => finish(() => resolve(partial(true, `stopped after ${input.timeoutMs} ms; try a simpler pattern, literal: true, or install ripgrep`))), input.timeoutMs + 1000);
|
|
194
|
+
if (signal?.aborted) {
|
|
195
|
+
onAbort();
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
199
|
+
worker.on('message', (message) => {
|
|
200
|
+
if ('batch' in message) {
|
|
201
|
+
for (const m of message.batch) {
|
|
202
|
+
found.push(m);
|
|
203
|
+
onMatch?.(m);
|
|
204
|
+
}
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (message.ok)
|
|
208
|
+
finish(() => resolve({ ...message.result, matches: found }));
|
|
209
|
+
else
|
|
210
|
+
finish(() => reject(new Error(message.error)));
|
|
211
|
+
});
|
|
212
|
+
worker.once('error', (error) => finish(() => reject(error)));
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
export async function search(input, signal, onMatch) {
|
|
216
|
+
const root = await validatePath(input.path);
|
|
217
|
+
if (input.kind === 'content' && !input.literal) {
|
|
218
|
+
// Compiling checks the syntax and is safe; matching runs in ripgrep or in the worker.
|
|
219
|
+
try {
|
|
220
|
+
new RegExp(input.pattern);
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
throw new Error(`invalid regular expression: ${error.message}; set literal: true to search plain text`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return (await hasRipgrep()) ? ripgrep(root, input, signal, onMatch) : nodeSearchInWorker(root, input, signal, onMatch);
|
|
227
|
+
}
|
|
228
|
+
// ---- Paged searches ------------------------------------------------------------------------
|
|
229
|
+
// start_search runs a search in the background and keeps its results for paging, so a large
|
|
230
|
+
// result set is read a page at a time and results show while it still runs. Bounded: at most
|
|
231
|
+
// MAX_SEARCHES kept (the least recently read finished one makes room for a new one), and each is
|
|
232
|
+
// dropped IDLE_MS after its last read. stop_search ends a search and keeps what it found; a second
|
|
233
|
+
// stop_search frees it.
|
|
234
|
+
const MAX_SEARCHES = 10;
|
|
235
|
+
const IDLE_MS = 10 * 60_000;
|
|
236
|
+
const sessions = new Map();
|
|
237
|
+
let nextId = 1;
|
|
238
|
+
function drop(s) {
|
|
239
|
+
s.controller.abort();
|
|
240
|
+
sessions.delete(s.id);
|
|
241
|
+
}
|
|
242
|
+
function sweep() {
|
|
243
|
+
const now = Date.now();
|
|
244
|
+
for (const s of sessions.values())
|
|
245
|
+
if (now - s.lastUsed > IDLE_MS)
|
|
246
|
+
drop(s);
|
|
247
|
+
if (sessions.size === 0 && sweeper) {
|
|
248
|
+
clearInterval(sweeper);
|
|
249
|
+
sweeper = undefined;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
let sweeper;
|
|
253
|
+
/** Makes room for one more search, or throws when every kept search is still running. */
|
|
254
|
+
function reserve() {
|
|
255
|
+
sweep();
|
|
256
|
+
if (sessions.size < MAX_SEARCHES)
|
|
257
|
+
return;
|
|
258
|
+
const idle = [...sessions.values()].filter((s) => s.finished).sort((a, b) => a.lastUsed - b.lastUsed)[0];
|
|
259
|
+
if (!idle)
|
|
260
|
+
throw new Error(`${MAX_SEARCHES} searches are still running; stop_search one first`);
|
|
261
|
+
drop(idle);
|
|
262
|
+
}
|
|
263
|
+
function page(s, offset, length) {
|
|
264
|
+
s.lastUsed = Date.now();
|
|
265
|
+
const base = {
|
|
266
|
+
id: s.id, running: !s.finished, stopped: s.stopped, offset, matches: s.matches.slice(offset, offset + length),
|
|
267
|
+
totalSoFar: s.matches.length, truncated: s.result?.truncated ?? false, timedOut: s.result?.timedOut ?? false,
|
|
268
|
+
warnings: s.result?.warnings ?? [],
|
|
269
|
+
};
|
|
270
|
+
return s.error ? { ...base, error: s.error } : base;
|
|
271
|
+
}
|
|
272
|
+
/** Waits for the search to finish or for `want` results, whichever comes first, up to `ms`. */
|
|
273
|
+
async function waitFor(s, want, ms) {
|
|
274
|
+
const deadline = Date.now() + ms;
|
|
275
|
+
while (!s.finished && s.matches.length < want && Date.now() < deadline) {
|
|
276
|
+
await Promise.race([s.done, new Promise((r) => setTimeout(r, Math.min(50, deadline - Date.now())).unref())]);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function validatePattern(input) {
|
|
280
|
+
if (input.kind === 'content' && !input.literal) {
|
|
281
|
+
try {
|
|
282
|
+
new RegExp(input.pattern);
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
throw new Error(`invalid regular expression: ${error.message}; set literal: true to search plain text`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Validates first (a bad path or pattern fails the call), then runs in the background and
|
|
291
|
+
* returns as soon as the first page is full, the search finishes, or waitMs passes.
|
|
292
|
+
*/
|
|
293
|
+
export async function startSearch(input, waitMs, pageSize) {
|
|
294
|
+
validatePattern(input);
|
|
295
|
+
await validatePath(input.path);
|
|
296
|
+
// Reserved after the last await, so concurrent calls cannot exceed MAX_SEARCHES.
|
|
297
|
+
reserve();
|
|
298
|
+
const id = `search-${nextId++}`;
|
|
299
|
+
const controller = new AbortController();
|
|
300
|
+
const s = { id, input, controller, done: Promise.resolve(), matches: [], finished: false, stopped: false, lastUsed: Date.now() };
|
|
301
|
+
s.done = search(input, controller.signal, (m) => { s.matches.push(m); }).then((r) => { s.result = r; }, (e) => { s.error = e instanceof Error ? e.message : String(e); }).finally(() => { s.finished = true; });
|
|
302
|
+
sessions.set(id, s);
|
|
303
|
+
sweeper ??= setInterval(sweep, 60_000).unref();
|
|
304
|
+
await waitFor(s, pageSize, waitMs);
|
|
305
|
+
return page(s, 0, pageSize);
|
|
306
|
+
}
|
|
307
|
+
export async function moreResults(id, offset, length, waitMs) {
|
|
308
|
+
sweep();
|
|
309
|
+
const s = sessions.get(id);
|
|
310
|
+
if (!s)
|
|
311
|
+
throw new Error(`no search with id ${id} (searches are kept for ${IDLE_MS / 60_000} minutes after the last read)`);
|
|
312
|
+
await waitFor(s, offset + length, waitMs);
|
|
313
|
+
return page(s, offset, length);
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* The first call stops the search (if still running) and keeps what it found, readable with
|
|
317
|
+
* moreResults; a second call frees the results.
|
|
318
|
+
*/
|
|
319
|
+
export async function stopSearch(id) {
|
|
320
|
+
const s = sessions.get(id);
|
|
321
|
+
if (!s)
|
|
322
|
+
return undefined;
|
|
323
|
+
if (s.stopped) {
|
|
324
|
+
drop(s);
|
|
325
|
+
return page(s, 0, 0);
|
|
326
|
+
}
|
|
327
|
+
s.stopped = true;
|
|
328
|
+
s.controller.abort();
|
|
329
|
+
await s.done;
|
|
330
|
+
return page(s, 0, 0);
|
|
331
|
+
}
|
|
332
|
+
/** True while a search with this id is kept. */
|
|
333
|
+
export function sessionsKept(id) {
|
|
334
|
+
return sessions.has(id);
|
|
335
|
+
}
|
|
336
|
+
export function stopAllSearches() {
|
|
337
|
+
for (const s of [...sessions.values()])
|
|
338
|
+
drop(s);
|
|
339
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { AGENT_SETTABLE_KEYS, allowedDirectoriesSource, configPath, getConfig, setConfigValue } from './config.js';
|
|
4
|
+
import { createDirectory, editBlock, fileInfo, listDirectory, moveFile, readTextOrImage, writeText } from './files.js';
|
|
5
|
+
import { interact, listSessions, readOutput, startProcess, terminate } from './processes.js';
|
|
6
|
+
import { moreResults, search, sessionsKept, startSearch, stopSearch } from './search.js';
|
|
7
|
+
import { listProcesses } from './system.js';
|
|
8
|
+
import { SERVER_NAME, VERSION } from './version.js';
|
|
9
|
+
const INSTRUCTIONS = `Command Center runs terminal commands in persistent sessions and reads and edits text files on this machine.
|
|
10
|
+
Use start_process for builds, tests, logs and REPLs (python3 -i, node -i), then interact_with_process and read_process_output.
|
|
11
|
+
File tools work in text; for PDF, Office files and images, use the client's own document features.
|
|
12
|
+
Every path must be inside allowedDirectories and every command outside blockedCommands; only a person can change those, in ${'`'}~/.command-center/config.json${'`'}.`;
|
|
13
|
+
const timeout = (fallback) => z.number().int().min(0).max(600_000).default(fallback).describe('Milliseconds to wait for output before returning');
|
|
14
|
+
const processOutput = {
|
|
15
|
+
pid: z.number().int(),
|
|
16
|
+
output: z.string(),
|
|
17
|
+
running: z.boolean(),
|
|
18
|
+
exitCode: z.number().int().nullable(),
|
|
19
|
+
truncated: z.boolean().describe('true when output older than the last 1 MiB was dropped'),
|
|
20
|
+
};
|
|
21
|
+
function text(value) {
|
|
22
|
+
return { content: [{ type: 'text', text: value }] };
|
|
23
|
+
}
|
|
24
|
+
function processResult(result) {
|
|
25
|
+
const status = result.running ? 'running' : `exited with code ${result.exitCode}`;
|
|
26
|
+
const head = `pid ${result.pid} ${status}${result.truncated ? ' (older output dropped)' : ''}`;
|
|
27
|
+
return { content: [{ type: 'text', text: result.output ? `${head}\n${result.output}` : head }], structuredContent: { ...result } };
|
|
28
|
+
}
|
|
29
|
+
export function createServer() {
|
|
30
|
+
const server = new McpServer({ name: SERVER_NAME, version: VERSION, title: '1xOps Command Center' }, { instructions: INSTRUCTIONS });
|
|
31
|
+
// ---- Processes -------------------------------------------------------------------------
|
|
32
|
+
server.registerTool('start_process', {
|
|
33
|
+
title: 'Start process',
|
|
34
|
+
description: 'Runs a command in the configured shell as a persistent session and returns its first output. The session keeps running after the call returns; use its pid with interact_with_process, read_process_output and force_terminate.',
|
|
35
|
+
inputSchema: {
|
|
36
|
+
command: z.string().min(1).describe('Command line, for example "npm test" or "python3 -i"'),
|
|
37
|
+
timeout_ms: timeout(5000),
|
|
38
|
+
cwd: z.string().optional().describe('Working directory; defaults to the server process directory'),
|
|
39
|
+
},
|
|
40
|
+
outputSchema: processOutput,
|
|
41
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
42
|
+
}, async ({ command, timeout_ms, cwd }) => processResult(await startProcess(command, timeout_ms, cwd)));
|
|
43
|
+
server.registerTool('interact_with_process', {
|
|
44
|
+
title: 'Send input to a process',
|
|
45
|
+
description: 'Writes a line of input to a running session (a shell, REPL or prompt) and returns the output that follows, including anything not yet read.',
|
|
46
|
+
inputSchema: { pid: z.number().int(), input: z.string(), timeout_ms: timeout(8000) },
|
|
47
|
+
outputSchema: processOutput,
|
|
48
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
49
|
+
}, async ({ pid, input, timeout_ms }) => processResult(await interact(pid, input, timeout_ms)));
|
|
50
|
+
server.registerTool('read_process_output', {
|
|
51
|
+
title: 'Read process output',
|
|
52
|
+
description: 'Returns output produced since the last read, waiting up to timeout_ms for new output when there is none.',
|
|
53
|
+
inputSchema: { pid: z.number().int(), timeout_ms: timeout(2000) },
|
|
54
|
+
outputSchema: processOutput,
|
|
55
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
56
|
+
}, async ({ pid, timeout_ms }) => processResult(await readOutput(pid, timeout_ms)));
|
|
57
|
+
server.registerTool('force_terminate', {
|
|
58
|
+
title: 'Stop process',
|
|
59
|
+
description: 'Stops a session and its child processes (SIGTERM, then SIGKILL after 2 s) and returns its last output.',
|
|
60
|
+
inputSchema: { pid: z.number().int() },
|
|
61
|
+
outputSchema: processOutput,
|
|
62
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
63
|
+
}, async ({ pid }) => processResult(await terminate(pid)));
|
|
64
|
+
server.registerTool('list_sessions', {
|
|
65
|
+
title: 'List sessions',
|
|
66
|
+
description: 'Lists the sessions this server started, running or finished, with unread output counts.',
|
|
67
|
+
outputSchema: {
|
|
68
|
+
sessions: z.array(z.object({
|
|
69
|
+
pid: z.number().int(), command: z.string(), cwd: z.string(), running: z.boolean(),
|
|
70
|
+
exitCode: z.number().int().nullable(), runtimeMs: z.number(), unreadChars: z.number().int(),
|
|
71
|
+
})),
|
|
72
|
+
},
|
|
73
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
74
|
+
}, async () => {
|
|
75
|
+
const sessions = listSessions();
|
|
76
|
+
const lines = sessions.map((s) => `${s.pid}\t${s.running ? 'running' : `exit ${s.exitCode}`}\t${Math.round(s.runtimeMs / 1000)}s\t${s.command}`);
|
|
77
|
+
return { content: [{ type: 'text', text: lines.join('\n') || 'no sessions' }], structuredContent: { sessions } };
|
|
78
|
+
});
|
|
79
|
+
// ---- Files -----------------------------------------------------------------------------
|
|
80
|
+
server.registerTool('read_file', {
|
|
81
|
+
title: 'Read file',
|
|
82
|
+
description: 'Reads a text file by lines (offset is 0-based; a negative offset reads from the end, e.g. -100 for the last 100 lines) or returns an image (png, jpg, gif, webp). Other binary files are refused.',
|
|
83
|
+
inputSchema: {
|
|
84
|
+
path: z.string().min(1),
|
|
85
|
+
offset: z.number().int().default(0),
|
|
86
|
+
length: z.number().int().min(1).optional().describe('Lines to return; capped at fileReadLineLimit'),
|
|
87
|
+
},
|
|
88
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
89
|
+
}, async ({ path, offset, length }) => {
|
|
90
|
+
const result = await readTextOrImage(path, offset, length);
|
|
91
|
+
if (result.kind === 'image')
|
|
92
|
+
return { content: [{ type: 'image', data: result.data, mimeType: result.mimeType }] };
|
|
93
|
+
return text(`[${result.path}: lines ${result.fromLine}-${result.toLine} of ${result.totalLines}]\n${result.text}`);
|
|
94
|
+
});
|
|
95
|
+
server.registerTool('read_multiple_files', {
|
|
96
|
+
title: 'Read several files',
|
|
97
|
+
description: 'Reads up to 20 text files from the start (up to fileReadLineLimit lines each). A file that cannot be read is reported without failing the others.',
|
|
98
|
+
inputSchema: { paths: z.array(z.string().min(1)).min(1).max(20) },
|
|
99
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
100
|
+
}, async ({ paths }) => {
|
|
101
|
+
const parts = [];
|
|
102
|
+
for (const p of paths) {
|
|
103
|
+
try {
|
|
104
|
+
const result = await readTextOrImage(p);
|
|
105
|
+
if (result.kind === 'image')
|
|
106
|
+
parts.push({ type: 'text', text: `--- ${result.path} (image)` }, { type: 'image', data: result.data, mimeType: result.mimeType });
|
|
107
|
+
else
|
|
108
|
+
parts.push({ type: 'text', text: `--- ${result.path}: lines ${result.fromLine}-${result.toLine} of ${result.totalLines}\n${result.text}` });
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
parts.push({ type: 'text', text: `--- ${p}: ${error.message}` });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return { content: parts };
|
|
115
|
+
});
|
|
116
|
+
server.registerTool('write_file', {
|
|
117
|
+
title: 'Write file',
|
|
118
|
+
description: 'Writes text to a file (mode "rewrite" replaces it, "append" adds to the end), creating parent folders. Content over fileWriteLineLimit lines is refused: write it in chunks with "append".',
|
|
119
|
+
inputSchema: { path: z.string().min(1), content: z.string(), mode: z.enum(['rewrite', 'append']).default('rewrite') },
|
|
120
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
121
|
+
}, async ({ path, content, mode }) => {
|
|
122
|
+
const result = await writeText(path, content, mode);
|
|
123
|
+
return text(`${mode === 'append' ? 'appended' : 'wrote'} ${result.lines} lines to ${result.path}`);
|
|
124
|
+
});
|
|
125
|
+
server.registerTool('edit_block', {
|
|
126
|
+
title: 'Edit text in a file',
|
|
127
|
+
description: 'Replaces old_string with new_string when it occurs exactly expected_replacements times. Otherwise nothing changes and the reply shows the count, or the closest passage when there is no exact match.',
|
|
128
|
+
inputSchema: {
|
|
129
|
+
file_path: z.string().min(1),
|
|
130
|
+
old_string: z.string().min(1),
|
|
131
|
+
new_string: z.string(),
|
|
132
|
+
expected_replacements: z.number().int().min(1).default(1),
|
|
133
|
+
},
|
|
134
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
135
|
+
}, async ({ file_path, old_string, new_string, expected_replacements }) => text(await editBlock(file_path, old_string, new_string, expected_replacements)));
|
|
136
|
+
server.registerTool('list_directory', {
|
|
137
|
+
title: 'List directory',
|
|
138
|
+
description: 'Lists a folder recursively to the given depth, marking [DIR], [FILE] and [LINK]; stops at 1000 entries.',
|
|
139
|
+
inputSchema: { path: z.string().min(1), depth: z.number().int().min(1).max(5).default(2) },
|
|
140
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
141
|
+
}, async ({ path, depth }) => {
|
|
142
|
+
const result = await listDirectory(path, depth);
|
|
143
|
+
return text(`${result.path}\n${result.entries.join('\n')}${result.truncated ? '\n[stopped at 1000 entries; list a subfolder]' : ''}`);
|
|
144
|
+
});
|
|
145
|
+
server.registerTool('get_file_info', {
|
|
146
|
+
title: 'File information',
|
|
147
|
+
description: 'Returns type, size, times, permissions and, for text files, the line count.',
|
|
148
|
+
inputSchema: { path: z.string().min(1) },
|
|
149
|
+
outputSchema: {
|
|
150
|
+
path: z.string(), type: z.string(), size: z.number(), modified: z.string(), created: z.string(), mode: z.string(),
|
|
151
|
+
lines: z.number().int().optional(),
|
|
152
|
+
},
|
|
153
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
154
|
+
}, async ({ path }) => {
|
|
155
|
+
const info = await fileInfo(path);
|
|
156
|
+
return { content: [{ type: 'text', text: JSON.stringify(info, null, 2) }], structuredContent: info };
|
|
157
|
+
});
|
|
158
|
+
server.registerTool('create_directory', {
|
|
159
|
+
title: 'Create directory',
|
|
160
|
+
description: 'Creates a folder and any missing parents; an existing folder is left as it is.',
|
|
161
|
+
inputSchema: { path: z.string().min(1) },
|
|
162
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
163
|
+
}, async ({ path }) => text(`created ${await createDirectory(path)}`));
|
|
164
|
+
server.registerTool('move_file', {
|
|
165
|
+
title: 'Move or rename',
|
|
166
|
+
description: 'Moves or renames a file or folder. Refuses when the destination already exists.',
|
|
167
|
+
inputSchema: { source: z.string().min(1), destination: z.string().min(1) },
|
|
168
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
169
|
+
}, async ({ source, destination }) => {
|
|
170
|
+
const moved = await moveFile(source, destination);
|
|
171
|
+
return text(`moved ${moved.from} to ${moved.to}`);
|
|
172
|
+
});
|
|
173
|
+
// ---- Search ----------------------------------------------------------------------------
|
|
174
|
+
server.registerTool('search', {
|
|
175
|
+
title: 'Search files',
|
|
176
|
+
description: 'Searches file contents (kind "content", one "file:line:text" per match; pattern is a regular expression unless literal is true) or file names (kind "files"; pattern is plain text in the name) under a folder. Uses ripgrep when it is installed (respects .gitignore), otherwise a built-in search that skips .git, node_modules and build folders.',
|
|
177
|
+
inputSchema: {
|
|
178
|
+
path: z.string().min(1),
|
|
179
|
+
pattern: z.string().min(1).describe('Regular expression, or plain text when literal is true'),
|
|
180
|
+
kind: z.enum(['content', 'files']).default('content'),
|
|
181
|
+
glob: z.string().optional().describe('Only files whose name matches, e.g. "*.ts"'),
|
|
182
|
+
ignore_case: z.boolean().default(false),
|
|
183
|
+
literal: z.boolean().default(false),
|
|
184
|
+
max_results: z.number().int().min(1).max(1000).default(100),
|
|
185
|
+
timeout_ms: z.number().int().min(100).max(120_000).default(30_000),
|
|
186
|
+
},
|
|
187
|
+
outputSchema: { engine: z.enum(['ripgrep', 'node']), matches: z.array(z.string()), truncated: z.boolean(), timedOut: z.boolean(), warnings: z.array(z.string()) },
|
|
188
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
189
|
+
}, async (args) => {
|
|
190
|
+
const result = await search({
|
|
191
|
+
path: args.path, pattern: args.pattern, kind: args.kind, glob: args.glob, ignoreCase: args.ignore_case,
|
|
192
|
+
literal: args.literal, maxResults: args.max_results, timeoutMs: args.timeout_ms,
|
|
193
|
+
});
|
|
194
|
+
const notes = [result.truncated && `stopped at ${args.max_results} results`, result.timedOut && `stopped after ${args.timeout_ms} ms`, ...result.warnings].filter(Boolean);
|
|
195
|
+
const body = result.matches.join('\n') || 'no matches';
|
|
196
|
+
return { content: [{ type: 'text', text: notes.length ? `${body}\n[${notes.join('; ')}]` : body }], structuredContent: { ...result } };
|
|
197
|
+
});
|
|
198
|
+
const searchInput = {
|
|
199
|
+
path: z.string().min(1),
|
|
200
|
+
pattern: z.string().min(1).describe('Regular expression, or plain text when literal is true'),
|
|
201
|
+
kind: z.enum(['content', 'files']).default('content'),
|
|
202
|
+
glob: z.string().optional().describe('Only files whose name matches, e.g. "*.ts"'),
|
|
203
|
+
ignore_case: z.boolean().default(false),
|
|
204
|
+
literal: z.boolean().default(false),
|
|
205
|
+
};
|
|
206
|
+
const pageOutput = {
|
|
207
|
+
id: z.string(), running: z.boolean(), stopped: z.boolean(), offset: z.number().int(), matches: z.array(z.string()), totalSoFar: z.number().int(),
|
|
208
|
+
truncated: z.boolean(), timedOut: z.boolean(), warnings: z.array(z.string()), error: z.string().optional(),
|
|
209
|
+
};
|
|
210
|
+
const pageResult = (p) => {
|
|
211
|
+
const state = p.error ? `failed: ${p.error}` : p.running ? 'still running' : p.stopped ? `stopped, ${p.totalSoFar} results kept` : `finished, ${p.totalSoFar} results${p.truncated ? ' (stopped at max_results)' : ''}${p.timedOut ? ' (stopped at timeout)' : ''}`;
|
|
212
|
+
const range = p.matches.length ? `results ${p.offset + 1}-${p.offset + p.matches.length}` : 'no results in this page';
|
|
213
|
+
return { content: [{ type: 'text', text: `${p.id} ${state}; ${range}\n${p.matches.join('\n')}`.trimEnd() }], structuredContent: { ...p } };
|
|
214
|
+
};
|
|
215
|
+
server.registerTool('start_search', {
|
|
216
|
+
title: 'Start a paged search',
|
|
217
|
+
description: 'Starts a large search in the background (same options as search, up to 10000 results) and returns an id with the first page as soon as it is full. Results can be read while the search runs. Read further pages with get_more_search_results; end it early with stop_search. Use search instead for small result sets.',
|
|
218
|
+
inputSchema: {
|
|
219
|
+
...searchInput,
|
|
220
|
+
max_results: z.number().int().min(1).max(10_000).default(2000),
|
|
221
|
+
timeout_ms: z.number().int().min(100).max(600_000).default(120_000),
|
|
222
|
+
page_size: z.number().int().min(1).max(500).default(100),
|
|
223
|
+
wait_ms: z.number().int().min(0).max(60_000).default(3000).describe('How long to wait for results before returning'),
|
|
224
|
+
},
|
|
225
|
+
outputSchema: pageOutput,
|
|
226
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
227
|
+
}, async (args) => pageResult(await startSearch({
|
|
228
|
+
path: args.path, pattern: args.pattern, kind: args.kind, glob: args.glob, ignoreCase: args.ignore_case,
|
|
229
|
+
literal: args.literal, maxResults: args.max_results, timeoutMs: args.timeout_ms,
|
|
230
|
+
}, args.wait_ms, args.page_size)));
|
|
231
|
+
server.registerTool('get_more_search_results', {
|
|
232
|
+
title: 'Next page of a search',
|
|
233
|
+
description: 'Returns results offset..offset+length of a search started with start_search, waiting up to wait_ms for them while it is still running.',
|
|
234
|
+
inputSchema: {
|
|
235
|
+
id: z.string().min(1),
|
|
236
|
+
offset: z.number().int().min(0).default(0),
|
|
237
|
+
length: z.number().int().min(1).max(500).default(100),
|
|
238
|
+
wait_ms: z.number().int().min(0).max(60_000).default(3000),
|
|
239
|
+
},
|
|
240
|
+
outputSchema: pageOutput,
|
|
241
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
242
|
+
}, async ({ id, offset, length, wait_ms }) => pageResult(await moreResults(id, offset, length, wait_ms)));
|
|
243
|
+
server.registerTool('stop_search', {
|
|
244
|
+
title: 'Stop a search',
|
|
245
|
+
description: 'Stops a search started with start_search if it is still running; the results found so far stay readable with get_more_search_results. Calling it again on the same id frees the results.',
|
|
246
|
+
inputSchema: { id: z.string().min(1) },
|
|
247
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
248
|
+
}, async ({ id }) => {
|
|
249
|
+
const stopped = await stopSearch(id);
|
|
250
|
+
if (!stopped)
|
|
251
|
+
return text(`no search with id ${id}`);
|
|
252
|
+
return text(sessionsKept(id) ? `stopped ${id}; ${stopped.totalSoFar} results kept (call again to free them)` : `freed ${id}`);
|
|
253
|
+
});
|
|
254
|
+
// ---- System ----------------------------------------------------------------------------
|
|
255
|
+
server.registerTool('list_processes', {
|
|
256
|
+
title: 'List system processes',
|
|
257
|
+
description: 'Lists the operating system\'s processes (pid, parent pid, name, memory), largest memory first. Read-only; stop a session this server started with force_terminate.',
|
|
258
|
+
inputSchema: {
|
|
259
|
+
filter: z.string().optional().describe('Only processes whose name contains this text (case-insensitive)'),
|
|
260
|
+
limit: z.number().int().min(1).max(2000).default(50),
|
|
261
|
+
},
|
|
262
|
+
outputSchema: {
|
|
263
|
+
total: z.number().int(),
|
|
264
|
+
processes: z.array(z.object({ pid: z.number().int(), ppid: z.number().int(), name: z.string(), memoryKb: z.number() })),
|
|
265
|
+
},
|
|
266
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
267
|
+
}, async ({ filter, limit }) => {
|
|
268
|
+
const result = await listProcesses(filter, limit);
|
|
269
|
+
const lines = result.processes.map((p) => `${p.pid}\t${p.ppid}\t${Math.round(p.memoryKb / 1024)} MB\t${p.name}`);
|
|
270
|
+
return { content: [{ type: 'text', text: `${result.total} processes${filter ? ` matching "${filter}"` : ''}; showing ${lines.length}\npid\tppid\tmemory\tname\n${lines.join('\n')}` }], structuredContent: result };
|
|
271
|
+
});
|
|
272
|
+
// ---- Config ----------------------------------------------------------------------------
|
|
273
|
+
server.registerTool('get_config', {
|
|
274
|
+
title: 'Show settings',
|
|
275
|
+
description: 'Shows the active settings and the file they come from.',
|
|
276
|
+
outputSchema: {
|
|
277
|
+
file: z.string(), allowedDirectoriesFrom: z.string(), allowedDirectories: z.array(z.string()), blockedCommands: z.array(z.string()), defaultShell: z.string(),
|
|
278
|
+
fileReadLineLimit: z.number().int(), fileWriteLineLimit: z.number().int(), version: z.string(),
|
|
279
|
+
},
|
|
280
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
281
|
+
}, async () => {
|
|
282
|
+
const view = { file: configPath(), allowedDirectoriesFrom: allowedDirectoriesSource(), ...getConfig(), version: VERSION };
|
|
283
|
+
return { content: [{ type: 'text', text: JSON.stringify(view, null, 2) }], structuredContent: view };
|
|
284
|
+
});
|
|
285
|
+
server.registerTool('set_config_value', {
|
|
286
|
+
title: 'Change a setting',
|
|
287
|
+
description: `Changes ${AGENT_SETTABLE_KEYS.join(' or ')}. allowedDirectories, blockedCommands and defaultShell are refused: only a person can change them, in the config file.`,
|
|
288
|
+
// Required (unlike z.unknown()), so a missing value is an error, never a silent reset.
|
|
289
|
+
inputSchema: { key: z.string().min(1), value: z.union([z.number(), z.string(), z.array(z.string())]).describe('New value, e.g. 2000 for a line limit') },
|
|
290
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
291
|
+
}, async ({ key, value }) => {
|
|
292
|
+
await setConfigValue(key, value);
|
|
293
|
+
return text(`${key} set to ${JSON.stringify(value)} in ${configPath()}`);
|
|
294
|
+
});
|
|
295
|
+
return server;
|
|
296
|
+
}
|