ai-agentmanager 1.41.0 → 1.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/update.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Updating from the app: a button in the top bar when a newer release is out, and "Update and
2
2
  // restart" in About. The daemon installs it (git checkout of the release tag, or npm install -g)
3
- // and restarts onto it; this page then waits for it to come back and reloads. It works the same
3
+ // and restarts onto it; this page shows each step, waits for it to come back and reloads. It works the same
4
4
  // from a phone over remote access: the install runs on the computer.
5
5
 
6
6
  export function initUpdate({ api, esc, toast, $ }) {
@@ -17,6 +17,16 @@ export function initUpdate({ api, esc, toast, $ }) {
17
17
  }
18
18
  $('#about-auto').checked = s?.check !== false;
19
19
  $('#about-install').hidden = !ready;
20
+ // An update started from another page or device: follow it here too.
21
+ if (s?.updating && s.progress?.step === 'install' && !run) {
22
+ run = { phase: 'install', to: s.progress.to, from: s.progress.from, startedAt: Date.parse(s.progress.startedAt), progress: s.progress };
23
+ api('GET', '/about').then((a) => {
24
+ run.pid = a.daemon.pid;
25
+ draw();
26
+ if (!dialog.open) dialog.showModal();
27
+ follow();
28
+ }, () => (run = null));
29
+ }
20
30
  }
21
31
 
22
32
  async function load() {
@@ -27,40 +37,118 @@ export function initUpdate({ api, esc, toast, $ }) {
27
37
  }
28
38
  }
29
39
 
30
- async function waitForRestart(from) {
31
- for (let i = 0; i < 300; i++) {
32
- await new Promise((r) => setTimeout(r, 2000));
40
+ // The update window: asks first, then follows the install on the daemon step by step (what npm
41
+ // is doing, how long it has taken), the restart, and the page's reload; an error stays on screen
42
+ // with the command to run by hand.
43
+ const dialog = $('#update-dialog');
44
+ let run = null; // { to, from, pid, phase: 'ask' | 'install' | 'restart' | 'failed' | 'late', progress, startedAt, error, manual }
45
+ let ticking = null;
46
+
47
+ const took = (since) => {
48
+ const s = Math.max(0, Math.round((Date.now() - since) / 1000));
49
+ return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${String(s % 60).padStart(2, '0')} s`;
50
+ };
51
+
52
+ function draw() {
53
+ if (!run) return;
54
+ const { phase, progress: p } = run;
55
+ $('#update-title').textContent = phase === 'ask' ? `Update to ${run.to}?` : phase === 'failed' ? `Update to ${run.to} failed` : `Updating to ${run.to}`;
56
+ const body = $('#update-body');
57
+ const actions = $('#update-actions');
58
+ if (phase === 'ask') {
59
+ body.innerHTML = `<p>Version ${esc(run.to)} is out (you have ${esc(run.from)}).</p>
60
+ <p class="hint">Running agents are closed and resume on the new version. It usually takes a minute or two, and longer when the update spans several releases or many agents are open. You'll see each step here.</p>`;
61
+ actions.innerHTML = '<button type="button" class="ghost" data-up="cancel">Cancel</button><button type="button" class="primary" data-up="go">Update and restart</button>';
62
+ return;
63
+ }
64
+ if (phase === 'failed') {
65
+ body.innerHTML = `<p class="error">${esc(run.error)}</p>
66
+ ${run.manual ? `<p class="hint">Nothing was changed. You can also install it in a terminal:</p><p><code>${esc(run.manual)}</code></p>` : '<p class="hint">Nothing was restarted.</p>'}`;
67
+ actions.innerHTML = '<button type="button" class="ghost" data-up="cancel">Close</button><button type="button" class="primary" data-up="go">Try again</button>';
68
+ return;
69
+ }
70
+ const installing = phase === 'install';
71
+ const fetched = p?.fetched ? `${p.fetched} package${p.fetched === 1 ? '' : 's'} fetched` : '';
72
+ const detail = [fetched, p?.detail].filter(Boolean).join(' · ');
73
+ const step = (state, label, hint = '') => `<li class="${state}"><span>${state === 'done' ? '✓' : state === 'now' ? '●' : '○'}</span><span>${label}</span>${hint ? `<span class="hint">${hint}</span>` : ''}</li>`;
74
+ body.innerHTML = `<div class="update-bar"><span></span></div>
75
+ <ul class="update-steps">
76
+ ${step(installing ? 'now' : 'done', `Install ${esc(run.to)}${p?.kind === 'git' ? ' (git checkout)' : ' (npm)'}`, installing ? `${took(run.startedAt)}${detail ? ` · ${esc(detail)}` : ''}` : '')}
77
+ ${step(installing ? '' : 'now', 'Restart the daemon', installing ? 'Agents close and resume on the new version' : `${took(run.restartAt)} · closing agents, starting ${esc(run.to)}, resuming them`)}
78
+ ${step('', 'Reload this page')}
79
+ </ul>
80
+ ${phase === 'late' ? '<p class="error">The daemon has not come back yet. Check <code>~/.agentmanager/daemon.log</code>, or run <code>agentmgr restart</code> in a terminal.</p>' : '<p class="hint">Keep this page open; it reloads by itself. Closing it does not stop the update.</p>'}`;
81
+ actions.innerHTML = '<button type="button" class="ghost" data-up="cancel">Hide</button>';
82
+ }
83
+
84
+ /** Follow an update that is running on the daemon until this page reloads on the new version. */
85
+ function follow() {
86
+ clearInterval(ticking);
87
+ let busy = false;
88
+ ticking = setInterval(async () => {
89
+ if (!run || busy) return;
90
+ busy = true;
33
91
  try {
34
- const a = await api('GET', '/about');
35
- if (a.daemon.pid !== from) return location.reload();
92
+ if (run.phase === 'install') {
93
+ const s = await api('GET', '/update');
94
+ const p = s.progress;
95
+ if (p) run.progress = p;
96
+ if (p?.step === 'failed') Object.assign(run, { phase: 'failed', error: p.error, manual: p.manual });
97
+ else if (p?.step === 'restart' || (!s.updating && !p)) Object.assign(run, { phase: 'restart', restartAt: Date.now() });
98
+ } else if (run.phase === 'restart' || run.phase === 'late') {
99
+ const a = await api('GET', '/about');
100
+ if (a.daemon.pid !== run.pid) return location.reload();
101
+ if (Date.now() - run.restartAt > 10 * 60_000) run.phase = 'late';
102
+ }
36
103
  } catch {
37
- // Down while it restarts.
104
+ // No answer: it is restarting.
105
+ if (run.phase === 'install') Object.assign(run, { phase: 'restart', restartAt: Date.now() });
106
+ } finally {
107
+ busy = false;
38
108
  }
39
- }
40
- toast('The daemon has not come back yet; check ~/.agentmanager/daemon.log', 8000);
109
+ if (run.phase === 'failed') {
110
+ clearInterval(ticking);
111
+ $('#update-btn').disabled = $('#about-install').disabled = false;
112
+ }
113
+ draw();
114
+ }, 1000);
41
115
  }
42
116
 
43
- async function install() {
44
- if (!state?.newer) return;
45
- if (!confirm(`Update to ${state.latest} and restart?\n\nRunning agents are closed and resume on the new version. This takes a minute or two with many agents.`)) return;
46
- const before = (await api('GET', '/about')).daemon.pid;
117
+ async function start() {
118
+ Object.assign(run, { phase: 'install', startedAt: Date.now(), progress: null, error: null });
47
119
  $('#update-btn').disabled = $('#about-install').disabled = true;
48
- toast(`Installing ${state.latest}…`, 60_000);
120
+ draw();
49
121
  try {
122
+ run.pid = (await api('GET', '/about')).daemon.pid;
50
123
  const r = await api('POST', '/update');
51
124
  if (r.upToDate) {
125
+ dialog.close();
126
+ $('#update-btn').disabled = $('#about-install').disabled = false;
52
127
  toast(`${r.current} is the newest release`);
53
128
  return load();
54
129
  }
55
- toast(`Installed ${r.to}; restarting… (agents resume)`, 600_000);
56
- await waitForRestart(before);
130
+ run.to = r.to;
131
+ follow();
57
132
  } catch (err) {
58
- toast(`Update failed: ${err.message}`, 10_000);
59
- } finally {
133
+ Object.assign(run, { phase: 'failed', error: err.message, manual: null });
60
134
  $('#update-btn').disabled = $('#about-install').disabled = false;
135
+ draw();
61
136
  }
62
137
  }
63
138
 
139
+ function install() {
140
+ if (!state?.newer) return;
141
+ if (!run || run.phase === 'ask' || run.phase === 'failed') run = { phase: 'ask', to: state.latest, from: state.current };
142
+ draw();
143
+ if (!dialog.open) dialog.showModal();
144
+ }
145
+
146
+ dialog.addEventListener('click', (e) => {
147
+ const act = e.target.closest('[data-up]')?.dataset.up;
148
+ if (act === 'cancel') dialog.close();
149
+ else if (act === 'go') start();
150
+ });
151
+
64
152
  /** "Check for updates" in About: the daemon's check, and whether it can update itself. */
65
153
  async function check() {
66
154
  const s = await api('POST', '/update/check');
package/src/cli.js CHANGED
@@ -821,6 +821,70 @@ export async function main(argv) {
821
821
  }
822
822
  });
823
823
 
824
+ const mcp = program.command('mcp').description("MCP servers and their tools as Claude Code has them in an agent's folder (or your home folder), and running one");
825
+ mcp
826
+ .command('list', { isDefault: true })
827
+ .description('List the MCP servers, their status and tools')
828
+ .argument('[agent]', "an agent: its folder's servers too (default: your home folder)")
829
+ .option('-r, --refresh', "start the folder's MCP session again (reads the configuration again)")
830
+ .option('--json', 'print JSON')
831
+ .action(async (ref, opts) => {
832
+ await daemon();
833
+ const a = ref ? await resolveAgent(ref) : null;
834
+ const r = await api('GET', `/mcp?agent=${encodeURIComponent(a?.id ?? 'home')}${opts.refresh ? '&refresh=1' : ''}`);
835
+ if (opts.json) return console.log(JSON.stringify(r, null, 2));
836
+ if (r.error) console.log(red(r.error));
837
+ if (!r.servers.length) return console.log(dim(`No MCP servers in ${r.dir}.`));
838
+ console.log(dim(`In ${r.dir}:`));
839
+ for (const s of r.servers) {
840
+ console.log(`${bold(s.name)} ${s.status === 'connected' ? green(s.status) : yellow(s.status)} ${dim([s.source, s.target].filter(Boolean).join(' '))}`);
841
+ for (const t of s.tools) console.log(` ${t.name}${t.readOnly ? dim(' read-only') : ''}${t.destructive ? red(' destructive') : ''}`);
842
+ }
843
+ });
844
+ mcp
845
+ .command('run')
846
+ .description("Run a tool in the folder's MCP session: JSON arguments (or none) call it directly; plain words go through a one-off Claude Code call allowed only that tool. --session tells the agent to use it")
847
+ .argument('<agent>', 'the agent, or "home" for your home folder')
848
+ .argument('<server>')
849
+ .argument('<tool>')
850
+ .argument('[request...]', `its arguments as JSON ('{"query":"x"}'), or what it should do in plain words`)
851
+ .option('-s, --session', 'tell the agent to use it in its session instead')
852
+ .action(async (ref, server, tool, request, opts) => {
853
+ await daemon();
854
+ const agent = ref === 'home' ? 'home' : (await resolveAgent(ref)).id;
855
+ const input = request.join(' ');
856
+ const { parseArgs } = await import('./mcp.js');
857
+ const r = await api('POST', '/mcp/run', { agent, server, tool, input, where: opts.session ? 'session' : parseArgs(input) ? 'direct' : 'workspace' });
858
+ if (r.where === 'session') return console.log(`${green('✓')} asked ${r.agent.name} to use ${r.tool}; its answer is in the session`);
859
+ console.log(r.text);
860
+ console.log(dim(`(${r.tool}, ${(r.ms / 1000).toFixed(1)} s, ${r.where === 'direct' ? 'called directly' : 'through Claude Code'})`));
861
+ if (r.isError) process.exitCode = 1;
862
+ });
863
+ mcp
864
+ .command('signin')
865
+ .description("Sign in to a server that needs it: prints the address to open. Claude Code keeps the sign-in")
866
+ .argument('<agent>', 'the agent, or "home" for your home folder')
867
+ .argument('<server>')
868
+ .action(async (ref, server) => {
869
+ await daemon();
870
+ const agent = ref === 'home' ? 'home' : (await resolveAgent(ref)).id;
871
+ const r = await api('POST', '/mcp/signin', { agent, server });
872
+ if (!r.url) return console.log(`${green('✓')} ${server} is already signed in`);
873
+ console.log(`Open this to sign in to ${bold(server)}:\n${r.url}`);
874
+ console.log(dim(r.callback ? `When you finish there it connects by itself; check with: agentmgr mcp reconnect ${ref} ${server}` : `Then connect it again: agentmgr mcp reconnect ${ref} ${server}`));
875
+ });
876
+ mcp
877
+ .command('reconnect')
878
+ .description('Connect one server again (after signing in, or when it failed) and show its status')
879
+ .argument('<agent>', 'the agent, or "home" for your home folder')
880
+ .argument('<server>')
881
+ .action(async (ref, server) => {
882
+ await daemon();
883
+ const agent = ref === 'home' ? 'home' : (await resolveAgent(ref)).id;
884
+ const s = (await api('POST', '/mcp/reconnect', { agent, server })).servers.find((x) => x.name === server);
885
+ console.log(`${bold(server)} ${s?.status === 'connected' ? green(s.status) : yellow(s?.status ?? 'not listed')}${s ? dim(` ${s.tools.length} tools`) : ''}`);
886
+ });
887
+
824
888
  program
825
889
  .command('review')
826
890
  .description("Start a reviewer agent on someone else's pull request: it asks the critical questions and finds what blocks approval; nothing is posted")
@@ -2697,7 +2761,10 @@ export async function main(argv) {
2697
2761
  if (!info.newer) return console.log(`${green('✓')} ${info.current} is the newest release`);
2698
2762
  if (info.blocker) throw new Error(`${info.latest} is available, but: ${info.blocker}`);
2699
2763
  if (opts.check) return console.log(`${yellow(info.latest)} is available (you have ${info.current}); install it: agentmgr update`);
2700
- const r = await up.installUpdate({ log: (m) => console.log(dim(m)) });
2764
+ // A line per package npm fetches, as a count that moves while a long install runs.
2765
+ let fetched = 0;
2766
+ const onLine = (line) => /^npm http /.test(line) && process.stdout.isTTY && process.stdout.write(`\r${dim(` ${++fetched} packages fetched`)}`);
2767
+ const r = await up.installUpdate({ info, log: (m) => console.log(dim(m)), onLine }).finally(() => fetched && process.stdout.write('\n'));
2701
2768
  console.log(`${green('✓')} installed ${r.to} (was ${r.from})`);
2702
2769
  if (!(await health())) return console.log(dim('The daemon is not running; it starts on the new version next time'));
2703
2770
  outliveTerminal();
package/src/manager.js CHANGED
@@ -2522,16 +2522,17 @@ export class AgentManager extends EventEmitter {
2522
2522
  }
2523
2523
 
2524
2524
  /** One tool-less, read-only call to an engine; resolves to its text output. */
2525
- oneShot(agent, text, { engine, model, timeoutMs = 300_000, tools }) {
2525
+ oneShot(agent, text, { engine, model, timeoutMs = 300_000, tools, cwd = paths.home }) {
2526
2526
  // Some engines take the prompt as an argument instead of on stdin, and some need their extra
2527
2527
  // arguments after a subcommand (oneShotExtra: they place them). `tools`: Claude Code only, a
2528
- // call that may use just these connector tools (and none of its own).
2528
+ // call that may use just these connector tools (and none of its own). `cwd`: where it runs, which
2529
+ // decides the project MCP servers it loads.
2529
2530
  const extra = engine.extraArgs(this.config);
2530
2531
  const args = tools
2531
2532
  ? [...extra, ...engine.connectorArgs(this.config, { model, tools })]
2532
2533
  : engine.oneShotExtra ? engine.oneShotArgs(this.config, { model, prompt: text, extra }) : [...extra, ...engine.oneShotArgs(this.config, { model, prompt: text })];
2533
2534
  return new Promise((resolve, reject) => {
2534
- const child = spawn(engine.bin(this.config), args, { cwd: paths.home, env: this.childEnv(agent), stdio: ['pipe', 'pipe', 'pipe'] });
2535
+ const child = spawn(engine.bin(this.config), args, { cwd, env: this.childEnv(agent), stdio: ['pipe', 'pipe', 'pipe'] });
2535
2536
  let out = '';
2536
2537
  let err = '';
2537
2538
  const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
package/src/mcp.js ADDED
@@ -0,0 +1,381 @@
1
+ // MCP servers and their tools as Claude Code sees them in a folder: user, project and local
2
+ // servers, claude.ai connectors and plugins' servers. Each folder gets its own MCP session: one
3
+ // Claude Code process, apart from any agent's, spoken to through Claude Code's control protocol.
4
+ // It lists the servers, signs in to one, reconnects one and calls a tool directly, all without a
5
+ // model call. A tool can also run in an agent's session, or once through Claude Code (which works
6
+ // out the arguments from plain words) with only that tool allowed.
7
+ import os from 'node:os';
8
+ import { spawn } from 'node:child_process';
9
+ import { DEFAULT_ENGINE, ENGINES } from './engines/index.js';
10
+
11
+ /** An MCP session closes after this long unused (it starts again when next asked). */
12
+ export const IDLE_MS = 15 * 60_000;
13
+ const RUN_TIMEOUT_MS = 5 * 60_000;
14
+ const KEEP_RUNS = 30;
15
+ const err = (status, message) => Object.assign(new Error(message), { status });
16
+
17
+ /** Claude Code's name for a tool: mcp__<server>__<tool>, other characters in the server name as "_". */
18
+ export const toolId = (server, tool) => `mcp__${String(server).replace(/[^\w-]/g, '_')}__${tool}`;
19
+
20
+ const SECRET = /key|token|secret|passw|auth|bearer|cookie|credential/i;
21
+
22
+ /** Where a server runs, without secrets: the command line (values of secret-looking flags hidden), or the URL without its query. */
23
+ export function targetOf(config = {}) {
24
+ if (config.url) {
25
+ try {
26
+ const u = new URL(config.url);
27
+ return `${u.origin}${u.pathname}`;
28
+ } catch {
29
+ return '';
30
+ }
31
+ }
32
+ if (!config.command) return '';
33
+ const args = (config.args ?? []).map(String);
34
+ const shown = args.map((a, i) => {
35
+ const flag = a.match(/^(--?[\w-]+)=/)?.[1];
36
+ if (flag) return SECRET.test(flag) ? `${flag}=•••` : a;
37
+ if (/^-/.test(args[i - 1] ?? '') && SECRET.test(args[i - 1])) return '•••';
38
+ return /^[\w-]{32,}$/.test(a) ? '•••' : a;
39
+ });
40
+ return [config.command, ...shown].join(' ');
41
+ }
42
+
43
+ /** One server for the UI: no env, headers or other config values. */
44
+ export function serverView(s) {
45
+ const transport = s.transport ?? s.config?.type ?? null;
46
+ return {
47
+ name: String(s.name),
48
+ status: s.status ?? 'unknown',
49
+ scope: s.scope ?? null,
50
+ source: s.source ?? null,
51
+ transport,
52
+ target: targetOf(s.config),
53
+ version: s.serverInfo?.version ?? null,
54
+ error: s.error ? String(s.error).slice(0, 300) : null,
55
+ // Signing in is OAuth, which only servers reached over HTTP have.
56
+ canSignIn: ['http', 'sse', 'claudeai-proxy'].includes(transport) || Boolean(s.config?.url),
57
+ tools: (s.tools ?? []).map((t) => ({
58
+ name: String(t.name),
59
+ id: toolId(s.name, t.name),
60
+ title: t.annotations?.title ?? null,
61
+ readOnly: t.annotations?.readOnlyHint === true,
62
+ destructive: t.annotations?.destructiveHint === true,
63
+ })),
64
+ };
65
+ }
66
+
67
+ /** What a tool returned, as text: its text parts, other parts named, and whether it reported an error. */
68
+ export function resultText(result = {}) {
69
+ const parts = (result.content ?? []).map((c) =>
70
+ c.type === 'text' ? String(c.text ?? '') : c.type === 'resource' ? String(c.resource?.text ?? `[resource ${c.resource?.uri ?? ''}]`) : `[${c.type ?? 'content'}${c.mimeType ? ` ${c.mimeType}` : ''}]`,
71
+ );
72
+ if (!parts.length && result.structuredContent !== undefined) parts.push(JSON.stringify(result.structuredContent, null, 2));
73
+ return { text: parts.join('\n').slice(0, 200_000) || '(no output)', isError: result.isError === true };
74
+ }
75
+
76
+ /**
77
+ * The arguments typed for a direct call: empty or a JSON object means "call it with these"; anything
78
+ * else is a request in plain words, for Claude Code to work the arguments out from.
79
+ */
80
+ export function parseArgs(input) {
81
+ const text = String(input ?? '').trim();
82
+ if (!text) return {};
83
+ if (!text.startsWith('{')) return null;
84
+ try {
85
+ const v = JSON.parse(text);
86
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * One folder's MCP session: a Claude Code process in stream-json mode that is only ever sent
94
+ * control requests (never a message, so it makes no model call). It stays up between requests, so
95
+ * servers stay connected and a sign-in's callback has somewhere to land.
96
+ */
97
+ export class McpSession {
98
+ constructor({ bin, args = [], cwd, env, onClose = () => {} }) {
99
+ this.waiting = new Map(); // request id -> { resolve, reject, timer }
100
+ this.n = 0;
101
+ this.closed = false;
102
+ this.startedAt = Date.now();
103
+ this.usedAt = Date.now();
104
+ this.child = spawn(bin, [...args, '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--no-session-persistence'], {
105
+ cwd,
106
+ env,
107
+ stdio: ['pipe', 'pipe', 'pipe'],
108
+ });
109
+ // An idle session never keeps the daemon from exiting; it ends when its input closes.
110
+ this.child.unref();
111
+ for (const pipe of [this.child.stdin, this.child.stdout, this.child.stderr]) pipe.unref?.();
112
+ let buf = '';
113
+ let stderr = '';
114
+ this.child.stdout.on('data', (d) => {
115
+ buf += d;
116
+ const lines = buf.split('\n');
117
+ buf = lines.pop();
118
+ for (const line of lines) {
119
+ let m;
120
+ try {
121
+ m = JSON.parse(line);
122
+ } catch {
123
+ continue;
124
+ }
125
+ if (m.type !== 'control_response') continue;
126
+ const r = m.response ?? {};
127
+ const w = this.waiting.get(r.request_id);
128
+ if (!w) continue;
129
+ this.waiting.delete(r.request_id);
130
+ clearTimeout(w.timer);
131
+ if (r.subtype === 'error') w.reject(err(502, String(r.error ?? 'Claude Code refused the request')));
132
+ else w.resolve(r.response ?? {});
133
+ }
134
+ });
135
+ this.child.stderr.on('data', (d) => (stderr = `${stderr}${d}`.slice(-2000)));
136
+ this.child.stdin.on('error', () => {});
137
+ const end = (why) => {
138
+ if (this.closed) return;
139
+ this.closed = true;
140
+ for (const w of this.waiting.values()) {
141
+ clearTimeout(w.timer);
142
+ w.reject(err(502, why));
143
+ }
144
+ this.waiting.clear();
145
+ onClose();
146
+ };
147
+ this.child.on('error', (e) => end(`Claude Code could not start: ${e.message}`));
148
+ this.child.on('close', (code) => end(`Claude Code's MCP session stopped (exit ${code})${stderr.trim() ? `: ${stderr.trim().slice(-300)}` : ''}`));
149
+ this.ready = this.request({ subtype: 'initialize' }, 30_000);
150
+ this.ready.catch(() => this.close());
151
+ }
152
+
153
+ request(request, timeoutMs = 30_000) {
154
+ if (this.closed) return Promise.reject(err(502, "Claude Code's MCP session has stopped; refresh the list"));
155
+ this.usedAt = Date.now();
156
+ const id = `r${++this.n}`;
157
+ return new Promise((resolve, reject) => {
158
+ const timer = setTimeout(() => {
159
+ this.waiting.delete(id);
160
+ reject(err(504, `Claude Code did not answer (${request.subtype}) in ${Math.round(timeoutMs / 1000)} s`));
161
+ }, timeoutMs);
162
+ this.waiting.set(id, { resolve, reject, timer });
163
+ this.child.stdin.write(`${JSON.stringify({ type: 'control_request', request_id: id, request })}\n`);
164
+ });
165
+ }
166
+
167
+ /** The servers, asked again while any is still connecting (up to `waitMs`). */
168
+ async status({ waitMs = 20_000 } = {}) {
169
+ await this.ready;
170
+ const until = Date.now() + waitMs;
171
+ for (;;) {
172
+ const servers = (await this.request({ subtype: 'mcp_status' })).mcpServers ?? [];
173
+ if (!servers.some((s) => s.status === 'pending') || Date.now() > until) return servers;
174
+ await new Promise((r) => setTimeout(r, 700));
175
+ }
176
+ }
177
+
178
+ async call(tool, args, timeoutMs = RUN_TIMEOUT_MS) {
179
+ await this.ready;
180
+ return this.request({ subtype: 'mcp_call', tool, arguments: args }, timeoutMs);
181
+ }
182
+
183
+ async reconnect(serverName) {
184
+ await this.ready;
185
+ return this.request({ subtype: 'mcp_reconnect', serverName }, 60_000);
186
+ }
187
+
188
+ /** Start signing in: { authUrl, callbackExpected, callbackPort } (the callback lands on this process). */
189
+ async authenticate(serverName) {
190
+ await this.ready;
191
+ return this.request({ subtype: 'mcp_authenticate', serverName }, 60_000);
192
+ }
193
+
194
+ /** The address the sign-in ended on, when its redirect could not reach this computer. */
195
+ async callback(serverName, callbackUrl) {
196
+ await this.ready;
197
+ return this.request({ subtype: 'mcp_oauth_callback_url', serverName, callbackUrl }, 60_000);
198
+ }
199
+
200
+ close() {
201
+ if (!this.closed) this.child.kill();
202
+ }
203
+ }
204
+
205
+ /** The one-off call through Claude Code: use the tool for the request, and report what it returned. */
206
+ export function runPrompt(id, input) {
207
+ return [
208
+ `Use the MCP tool ${id} for the request below, calling it as few times as needed (once if you can).`,
209
+ "Work out its arguments from the request and the tool's description.",
210
+ '',
211
+ `Request: ${input?.trim() || '(none: call it with no arguments, or the simplest valid ones)'}`,
212
+ '',
213
+ 'Then reply with what the tool returned, as it is (for long output, the part that answers the request),',
214
+ 'and one last line with the arguments you used. If the tool fails or is not available, say so and why.',
215
+ ].join('\n');
216
+ }
217
+
218
+ /** What an agent is told to run a tool in its session. */
219
+ export const sessionMessage = (id, input) => `Use the MCP tool ${id}${input?.trim() ? ` for this: ${input.trim()}` : ''}. Show me what it returned.`;
220
+
221
+ export class Mcp {
222
+ constructor({ manager, homeDir = os.homedir(), idleMs = IDLE_MS }) {
223
+ this.manager = manager;
224
+ this.homeDir = homeDir;
225
+ this.idleMs = idleMs;
226
+ this.sessions = new Map(); // folder -> McpSession
227
+ this.lists = new Map(); // folder -> { at, servers }
228
+ this.runs = new Map(); // folder -> the last runs, newest first
229
+ this.sweep = setInterval(() => {
230
+ for (const s of this.sessions.values()) if (Date.now() - s.usedAt > this.idleMs && !s.waiting.size) s.close();
231
+ }, 60_000);
232
+ this.sweep.unref?.();
233
+ }
234
+
235
+ /** Where the tools run: an agent's folder, or the home folder (user servers and connectors). */
236
+ where(ref) {
237
+ if (!ref || ref === 'home') return { agent: null, dir: this.homeDir };
238
+ const agent = this.manager.mustGet(ref);
239
+ return { agent, dir: agent.workdir ?? agent.planning?.dir ?? this.homeDir };
240
+ }
241
+
242
+ /** The folder's MCP session, started if it has none (or `fresh`: a new one, which reads the configuration again). */
243
+ session(agent, dir, { fresh = false } = {}) {
244
+ let s = this.sessions.get(dir);
245
+ if (s && (fresh || s.closed)) {
246
+ s.close();
247
+ s = null;
248
+ }
249
+ if (!s) {
250
+ const engine = ENGINES[DEFAULT_ENGINE];
251
+ s = new McpSession({
252
+ bin: engine.bin(this.manager.config),
253
+ args: engine.extraArgs(this.manager.config),
254
+ cwd: dir,
255
+ env: this.manager.childEnv(agent),
256
+ onClose: () => this.sessions.get(dir) === s && this.sessions.delete(dir),
257
+ });
258
+ this.sessions.set(dir, s);
259
+ }
260
+ return s;
261
+ }
262
+
263
+ view(agent, dir, extra = {}) {
264
+ const list = this.lists.get(dir);
265
+ const s = this.sessions.get(dir);
266
+ return {
267
+ agent: agent ? { id: agent.id, name: agent.name, engine: agent.engine ?? DEFAULT_ENGINE, running: Boolean(this.manager.runtimes.get(agent.id)?.pty) } : null,
268
+ dir,
269
+ at: list ? new Date(list.at).toISOString() : null,
270
+ servers: list?.servers ?? [],
271
+ session: s && !s.closed ? { startedAt: new Date(s.startedAt).toISOString() } : null,
272
+ runs: this.runs.get(dir) ?? [],
273
+ error: null,
274
+ ...extra,
275
+ };
276
+ }
277
+
278
+ async list(ref, { refresh = false } = {}) {
279
+ const { agent, dir } = this.where(ref);
280
+ try {
281
+ const servers = await this.session(agent, dir, { fresh: refresh }).status();
282
+ this.lists.set(dir, { at: Date.now(), servers: servers.map(serverView).sort((a, b) => a.name.localeCompare(b.name)) });
283
+ return this.view(agent, dir);
284
+ } catch (e) {
285
+ return this.view(agent, dir, { error: e.message });
286
+ }
287
+ }
288
+
289
+ /** The server, from the last list for that folder. */
290
+ server(dir, name) {
291
+ const s = this.lists.get(dir)?.servers.find((x) => x.name === name);
292
+ if (!s) throw err(404, `No MCP server "${name}" here; refresh the list`);
293
+ return s;
294
+ }
295
+
296
+ /** The tool, checked against the last list for that folder. */
297
+ tool(dir, server, tool) {
298
+ const s = this.server(dir, server);
299
+ const t = s.tools.find((x) => x.name === tool);
300
+ if (!t) throw err(404, `No tool "${tool}" on the MCP server "${server}" here; refresh the list`);
301
+ if (s.status !== 'connected') throw err(409, `The MCP server "${server}" is ${s.status}`);
302
+ return t;
303
+ }
304
+
305
+ /** Connect one server again (after signing in, or when it failed), and list them all. */
306
+ async reconnect(ref, name) {
307
+ const { agent, dir } = this.where(ref);
308
+ if (!this.lists.has(dir)) await this.list(ref);
309
+ this.server(dir, String(name ?? ''));
310
+ await this.session(agent, dir).reconnect(name);
311
+ return this.list(ref);
312
+ }
313
+
314
+ /**
315
+ * Start signing in to a server: the address to open. Claude Code keeps the tokens (the app never
316
+ * sees them); its sign-in page comes back to a port on this computer, which the session listens on.
317
+ */
318
+ async signIn(ref, name) {
319
+ const { agent, dir } = this.where(ref);
320
+ if (!this.lists.has(dir)) await this.list(ref);
321
+ const s = this.server(dir, String(name ?? ''));
322
+ if (!s.canSignIn) throw err(409, `"${s.name}" runs as a command on this computer; it has no sign-in`);
323
+ const r = await this.session(agent, dir).authenticate(s.name);
324
+ if (!r.authUrl) return { server: s.name, url: null, signedIn: true };
325
+ return { server: s.name, url: String(r.authUrl), callback: r.callbackExpected === true, local: r.callbackExpected === true && r.redirectScheme !== 'custom' };
326
+ }
327
+
328
+ /** Finish a sign-in whose redirect could not reach this computer: the address the browser ended on. */
329
+ async signInCallback(ref, name, url) {
330
+ const { agent, dir } = this.where(ref);
331
+ this.server(dir, String(name ?? ''));
332
+ await this.session(agent, dir).callback(name, String(url ?? '').trim());
333
+ return this.list(ref);
334
+ }
335
+
336
+ record(dir, run) {
337
+ const list = [run, ...(this.runs.get(dir) ?? [])].slice(0, KEEP_RUNS);
338
+ this.runs.set(dir, list);
339
+ return run;
340
+ }
341
+
342
+ /**
343
+ * Run a tool. "direct": called in the folder's MCP session with these arguments (no model call).
344
+ * "workspace": once through Claude Code, which works the arguments out from plain words, with
345
+ * only that tool allowed. "session": the agent is told to use it.
346
+ */
347
+ async run(ref, { server, tool, input = '', where = 'direct' } = {}) {
348
+ const { agent, dir } = this.where(ref);
349
+ if (!this.lists.has(dir)) await this.list(ref);
350
+ const t = this.tool(dir, String(server ?? ''), String(tool ?? ''));
351
+ input = String(input ?? '').slice(0, 8000);
352
+ if (where === 'session') {
353
+ if (!agent) throw err(400, 'Pick an agent to run it in its session');
354
+ if ((agent.engine ?? DEFAULT_ENGINE) !== DEFAULT_ENGINE) throw err(409, 'Running MCP tools in the session works for Claude Code agents');
355
+ return { where, tool: t.id, agent: this.manager.tell(agent.id, sessionMessage(t.id, input), { source: 'mcp' }) };
356
+ }
357
+ if (where !== 'workspace' && where !== 'direct') throw err(400, 'where must be "direct", "workspace" or "session"');
358
+ const args = where === 'direct' ? parseArgs(input) : null;
359
+ if (where === 'direct' && !args) throw err(400, 'To call it directly, give its arguments as a JSON object (or nothing); plain words go through Claude Code');
360
+ const scope = { agent: agent ? this.manager.auditView(agent) : null, dir, tool: t.id, input, where };
361
+ this.manager.plugins.check('mcp.run', scope);
362
+ this.manager.plugins.emit('mcp.run', scope);
363
+ const t0 = Date.now();
364
+ const base = { where, server: String(server), name: t.name, tool: t.id, input };
365
+ const done = (out) => this.record(dir, { ...base, ...out, ms: Date.now() - t0, at: new Date().toISOString() });
366
+ try {
367
+ if (where === 'direct') return done(resultText(await this.session(agent, dir).call(t.id, args)));
368
+ const engine = ENGINES[DEFAULT_ENGINE];
369
+ const text = await this.manager.oneShot(agent, runPrompt(t.id, input), { engine, model: this.manager.config.explainModel, tools: [t.id], cwd: dir, timeoutMs: RUN_TIMEOUT_MS });
370
+ return done({ text, isError: false });
371
+ } catch (e) {
372
+ done({ text: e.message, isError: true });
373
+ throw e;
374
+ }
375
+ }
376
+
377
+ close() {
378
+ clearInterval(this.sweep);
379
+ for (const s of this.sessions.values()) s.close();
380
+ }
381
+ }