@koalaauto/agentchannel 3.63.1 → 3.64.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/dist/src/caps.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { dirname, isAbsolute, join } from 'node:path';
2
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, isAbsolute, join } from 'node:path';
4
4
  import { killGroup } from './adapters/procgroup.js';
5
5
  /**
6
6
  * Host capabilities (decisions §34): commands the agent's owner declares in `<AGENTCHANNEL_HOME>/capabilities.json` so that the
@@ -21,6 +21,140 @@ import { killGroup } from './adapters/procgroup.js';
21
21
  */
22
22
  export const CAPS_FILE = 'capabilities.json';
23
23
  export const CAPS_SERVER = 'caps';
24
+ /** Server names a declared MCP server cannot take: the runner's own servers and the account apps it turns off. */
25
+ export const RESERVED_SERVERS = ['caps', 'ach', 'codex_apps', 'claude_ai'];
26
+ const TOOL = /^[A-Za-z0-9_.-]{1,64}$/;
27
+ const strMap = (v) => v === undefined || (!!v && typeof v === 'object' && !Array.isArray(v) && Object.values(v).every((x) => typeof x === 'string'));
28
+ /** One MCP declaration checked; a problem string, or undefined when it is usable. Pure. */
29
+ export function mcpProblem(m) {
30
+ if (!m || typeof m !== 'object')
31
+ return 'mcp: not an object';
32
+ if (typeof m.name !== 'string' || !NAME.test(m.name))
33
+ return `mcp name ${JSON.stringify(m.name)}: lowercase letters, digits and _ only`;
34
+ const at = `${m.name}:`;
35
+ if (RESERVED_SERVERS.includes(m.name))
36
+ return `${at} the name is taken (${RESERVED_SERVERS.join(', ')})`;
37
+ if (typeof m.description !== 'string' || !m.description.trim())
38
+ return `${at} description is required`;
39
+ if ((m.url === undefined) === (m.command === undefined))
40
+ return `${at} give either url or command`;
41
+ if (m.url !== undefined) {
42
+ let u;
43
+ try {
44
+ u = new URL(m.url);
45
+ }
46
+ catch {
47
+ return `${at} url is not a URL`;
48
+ }
49
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname);
50
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local))
51
+ return `${at} url must be https (http only for localhost)`;
52
+ if (m.env !== undefined || m.cwd !== undefined)
53
+ return `${at} env and cwd are for a command`;
54
+ }
55
+ else {
56
+ if (!Array.isArray(m.command) || !m.command.length || m.command.some((t) => typeof t !== 'string' || !t))
57
+ return `${at} command must be a list of strings`;
58
+ if (m.headers !== undefined || m.oauth !== undefined)
59
+ return `${at} headers and oauth are for a url`;
60
+ if (m.cwd !== undefined && (typeof m.cwd !== 'string' || !isAbsolute(m.cwd)))
61
+ return `${at} cwd must be an absolute path`;
62
+ }
63
+ if (!strMap(m.headers))
64
+ return `${at} headers must map names to strings`;
65
+ if (!strMap(m.env))
66
+ return `${at} env must map names to strings`;
67
+ if (m.oauth !== undefined && typeof m.oauth !== 'boolean') {
68
+ if (!m.oauth || typeof m.oauth !== 'object' || Array.isArray(m.oauth))
69
+ return `${at} oauth must be true or an object`;
70
+ for (const k of Object.keys(m.oauth))
71
+ if (!['scope', 'client_id', 'client_secret'].includes(k))
72
+ return `${at} oauth.${k} is not known (scope, client_id, client_secret)`;
73
+ if (!strMap(m.oauth))
74
+ return `${at} oauth values must be strings`;
75
+ }
76
+ if (!Array.isArray(m.tools) || !m.tools.length)
77
+ return `${at} tools must list the tools runs may use (\`ach caps tools ${m.name}\` shows them)`;
78
+ for (const t of m.tools)
79
+ if (typeof t !== 'string' || !TOOL.test(t))
80
+ return `${at} tool ${JSON.stringify(t)} is not a tool name`;
81
+ if (new Set(m.tools).size !== m.tools.length)
82
+ return `${at} a tool is listed twice`;
83
+ if (m.timeout !== undefined && !(typeof m.timeout === 'number' && m.timeout > 0 && m.timeout <= 3600))
84
+ return `${at} timeout must be 1..3600 seconds`;
85
+ return undefined;
86
+ }
87
+ /** "name" and "description" of a SKILL.md's front matter. Pure. */
88
+ export function skillFrontMatter(text) {
89
+ const m = text.replace(/^\uFEFF/, '').match(/^---\r?\n([\s\S]*?)\r?\n---/);
90
+ if (!m)
91
+ return {};
92
+ const out = {};
93
+ const lines = m[1].split(/\r?\n/);
94
+ for (let i = 0; i < lines.length; i++) {
95
+ const kv = lines[i].match(/^(name|description):\s*(.*)$/);
96
+ if (!kv)
97
+ continue;
98
+ let v = kv[2].trim();
99
+ if (v === '|' || v === '>' || v === '>-' || v === '|-') {
100
+ const block = [];
101
+ while (i + 1 < lines.length && /^\s+/.test(lines[i + 1]))
102
+ block.push(lines[++i].trim());
103
+ v = block.join(' ');
104
+ }
105
+ out[kv[1]] = v.replace(/^(['"])([\s\S]*)\1$/, '$2');
106
+ }
107
+ return out;
108
+ }
109
+ const SKILL_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
110
+ /** The skills under one declared path: the folder itself when it has a SKILL.md, else its sub-folders that have one (a plugin's skills/ too). */
111
+ export function skillsAt(path) {
112
+ if (typeof path !== 'string' || !isAbsolute(path))
113
+ return { skills: [], problems: [`skills: ${JSON.stringify(path)} must be an absolute path`] };
114
+ if (!existsSync(path))
115
+ return { skills: [], problems: [`skills: ${path} does not exist`] };
116
+ const one = (dir) => {
117
+ let fm;
118
+ try {
119
+ fm = skillFrontMatter(readFileSync(join(dir, 'SKILL.md'), 'utf8'));
120
+ }
121
+ catch (e) {
122
+ return `skills: ${dir}: ${e?.message ?? e}`;
123
+ }
124
+ const name = (fm.name ?? basename(dir)).trim();
125
+ if (!SKILL_NAME.test(name))
126
+ return `skills: ${dir}: name ${JSON.stringify(name)}: lowercase letters, digits, - and _ only`;
127
+ if (!fm.description?.trim())
128
+ return `skills: ${dir}: SKILL.md has no description`;
129
+ return { name, description: fm.description.trim(), dir };
130
+ };
131
+ const dirs = existsSync(join(path, 'SKILL.md'))
132
+ ? [path]
133
+ : (() => {
134
+ const base = existsSync(join(path, 'skills')) && !existsSync(join(path, 'SKILL.md')) && statSync(join(path, 'skills')).isDirectory() ? join(path, 'skills') : path;
135
+ try {
136
+ return readdirSync(base, { withFileTypes: true })
137
+ .filter((e) => (e.isDirectory() || e.isSymbolicLink()) && existsSync(join(base, e.name, 'SKILL.md')))
138
+ .map((e) => join(base, e.name))
139
+ .sort();
140
+ }
141
+ catch {
142
+ return [];
143
+ }
144
+ })();
145
+ if (!dirs.length)
146
+ return { skills: [], problems: [`skills: ${path} has no SKILL.md, in it or in its folders`] };
147
+ const skills = [];
148
+ const problems = [];
149
+ for (const d of dirs) {
150
+ const r = one(d);
151
+ if (typeof r === 'string')
152
+ problems.push(r);
153
+ else
154
+ skills.push(r);
155
+ }
156
+ return { skills, problems };
157
+ }
24
158
  const NAME = /^[a-z][a-z0-9_]{0,47}$/;
25
159
  const ARG = /^[a-z][a-z0-9_]{0,31}$/;
26
160
  const PLACEHOLDER = /\{([a-z][a-z0-9_]{0,31}(?:\.[a-z][a-z0-9_]{0,31})?)\}/g;
@@ -102,30 +236,63 @@ export function capProblem(c) {
102
236
  return `${at} max_output must be at least 1000 bytes`;
103
237
  return undefined;
104
238
  }
105
- /** The declarations of a capabilities file (`{"capabilities": [...]}`), the broken ones left out with a reason. A missing file is no capabilities. */
239
+ /**
240
+ * The declarations of a capabilities file (`{"capabilities": [...], "mcp": [...], "skills": [...]}`, every part optional), the
241
+ * broken ones left out with a reason. A missing file is nothing declared.
242
+ */
106
243
  export function loadCaps(file) {
244
+ const none = { caps: [], mcp: [], skills: [], problems: [] };
107
245
  if (!existsSync(file))
108
- return { caps: [], problems: [] };
246
+ return none;
109
247
  let j;
110
248
  try {
111
249
  j = JSON.parse(readFileSync(file, 'utf8'));
112
250
  }
113
251
  catch (e) {
114
- return { caps: [], problems: [`${file}: ${e?.message ?? e}`] };
252
+ return { ...none, problems: [`${file}: ${e?.message ?? e}`] };
115
253
  }
116
- const list = Array.isArray(j?.capabilities) ? j.capabilities : undefined;
117
- if (!list)
118
- return { caps: [], problems: [`${file}: expected {"capabilities": [...]}`] };
119
- const caps = [];
254
+ if (!j || typeof j !== 'object' || Array.isArray(j))
255
+ return { ...none, problems: [`${file}: expected {"capabilities": [...], "mcp": [...], "skills": [...]}`] };
120
256
  const problems = [];
121
- for (const c of list) {
257
+ const listOf = (k) => {
258
+ if (j[k] === undefined)
259
+ return [];
260
+ if (Array.isArray(j[k]))
261
+ return j[k];
262
+ problems.push(`${file}: "${k}" must be a list`);
263
+ return [];
264
+ };
265
+ const caps = [];
266
+ for (const c of listOf('capabilities')) {
122
267
  const p = capProblem(c) ?? (caps.some((x) => x.name === c.name) ? `${c.name}: declared twice` : undefined);
123
268
  if (p)
124
269
  problems.push(p);
125
270
  else
126
271
  caps.push(c);
127
272
  }
128
- return { caps, problems };
273
+ const mcp = [];
274
+ for (const m of listOf('mcp')) {
275
+ const p = mcpProblem(m) ?? (mcp.some((x) => x.name === m.name) ? `${m.name}: declared twice` : undefined);
276
+ if (p)
277
+ problems.push(p);
278
+ else
279
+ mcp.push(m);
280
+ }
281
+ const skills = [];
282
+ for (const path of listOf('skills')) {
283
+ const r = skillsAt(path);
284
+ problems.push(...r.problems);
285
+ for (const s of r.skills) {
286
+ if (skills.some((x) => x.name === s.name))
287
+ problems.push(`skills: ${s.name} is declared twice (${s.dir})`);
288
+ else
289
+ skills.push(s);
290
+ }
291
+ }
292
+ if (!caps.length && !mcp.length && !skills.length && j.capabilities === undefined && j.mcp === undefined && j.skills === undefined) {
293
+ problems.push(`${file}: expected {"capabilities": [...], "mcp": [...], "skills": [...]}`);
294
+ }
295
+ return { caps, mcp, skills, problems };
129
296
  }
130
297
  /** The argv (and stdin) of one call, or an error the agent can act on. `sys`: the values the server fills ({run.task}…). Pure. */
131
298
  export function buildCall(cap, input, sys = {}) {
@@ -176,7 +343,9 @@ export function buildCall(cap, input, sys = {}) {
176
343
  /** The environment of a capability's command: no run token, no hub credentials, the real HOME. Pure. */
177
344
  export function capEnv(base, home, extra = {}) {
178
345
  const env = {};
179
- for (const k of ['PATH', 'LANG', 'LANGUAGE', 'TERM', 'SHELL', 'USER', 'LOGNAME', 'TZ', 'SystemRoot', 'ComSpec', 'PATHEXT']) {
346
+ // Windows: what npx, node and most programs need to start (where programs and their per-user data are)
347
+ const win = ['SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT', 'ProgramData', 'ProgramFiles', 'ProgramFiles(x86)', 'APPDATA', 'LOCALAPPDATA', 'TEMP', 'TMP'];
348
+ for (const k of ['PATH', 'Path', 'LANG', 'LANGUAGE', 'TERM', 'SHELL', 'USER', 'LOGNAME', 'TZ', ...win]) {
180
349
  const v = base[k];
181
350
  if (v !== undefined)
182
351
  env[k] = v;
@@ -186,6 +355,8 @@ export function capEnv(base, home, extra = {}) {
186
355
  env[k] = v;
187
356
  if (home)
188
357
  env.HOME = home;
358
+ if (home && base.USERPROFILE !== undefined)
359
+ env.USERPROFILE = home;
189
360
  return { ...env, ...extra };
190
361
  }
191
362
  function kb(n) {
@@ -303,32 +474,40 @@ export async function runCap(cap, input, o) {
303
474
  log({ exit, ms, bytes: stdout.length, ...(timedOut ? { timeout: true } : {}), ...(file ? { file } : {}) });
304
475
  return { ok, exit, text: parts.filter((p) => p !== '').join('\n'), ...(file ? { file } : {}) };
305
476
  }
306
- /** Trusted prompt text about the run's capabilities. Pure. */
307
- export function capsPromptText(tools) {
308
- if (!tools.length)
309
- return '';
310
- const confirmed = tools.filter((t) => t.confirm).map((t) => t.name);
311
- return [
312
- `Host capabilities: your owner set these up on this machine as tools of the "${CAPS_SERVER}" MCP server. They run outside your sandbox with your owner's access and need no approval:`,
313
- ...tools.map((t) => `- ${t.name}: ${t.description.split('\n')[0]}`),
314
- ...(confirmed.length ? [`These run only once the person who asked for the work confirmed that exact call: ${confirmed.join(', ')}. First ask them with a decision request that carries the action (MCP request_decision with action {capability, args}, or \`ach ask-human "<question>" --action <capability> --arg k=v …\`), wait for their reply, then call the tool with the same arguments. One confirmation runs it once.`] : []),
315
- 'When a question needs data this directory cannot reach (a database, logs, an internal API), use them instead of saying you cannot reach it. Their arguments are checked against what your owner declared; a large output is saved to a file the result names.',
316
- ].join('\n');
477
+ /** Trusted prompt text about the run's tools. `skillPaths`: the runtime does not load skills itself, so the prompt lists them. Pure. */
478
+ export function capsPromptText(t, o = {}) {
479
+ const out = [];
480
+ const caps = t.servers.find((s) => s.name === CAPS_SERVER);
481
+ if (caps?.tools.length) {
482
+ const confirmed = caps.tools.filter((x) => x.confirm).map((x) => x.name);
483
+ out.push(`Host capabilities: your owner set these up on this machine as tools of the "${CAPS_SERVER}" MCP server. They run outside your sandbox with your owner's access and need no approval:`, ...caps.tools.map((x) => `- ${x.name}: ${x.description.split('\n')[0]}`), ...(confirmed.length ? [`These run only once the person who asked for the work confirmed that exact call: ${confirmed.join(', ')}. First ask them with a decision request that carries the action (MCP request_decision with action {capability, args}, or \`ach ask-human "<question>" --action <capability> --arg k=v …\`), wait for their reply, then call the tool with the same arguments. One confirmation runs it once.`] : []), 'When a question needs data this directory cannot reach (a database, logs, an internal API), use them instead of saying you cannot reach it. Their arguments are checked against what your owner declared; a large output is saved to a file the result names.');
484
+ }
485
+ const mcp = t.servers.filter((s) => s.name !== CAPS_SERVER);
486
+ if (mcp.length) {
487
+ out.push('MCP servers your owner connected for your runs (each is an MCP server of that name; its tools need no approval):', ...mcp.map((s) => `- ${s.name}: ${(s.description ?? '').split('\n')[0]} Tools: ${s.tools.map((x) => x.name).join(', ')}`), 'Use them for what they cover instead of calling the service\'s API another way. A tool that is not listed is not available.');
488
+ }
489
+ if (t.skills.length && o.skillPaths) {
490
+ out.push('Skills your owner gave you: when a task matches one, read its SKILL.md first and follow it (its other files are beside it).', ...t.skills.map((k) => `- ${k.name}: ${k.description.split('\n')[0]} (${join(k.dir, 'SKILL.md')})`));
491
+ }
492
+ return out.join('\n');
317
493
  }
318
- /** argv of `ach caps-serve` for one run. Pure. */
494
+ /** argv of `ach caps-serve` for one run (`mcp`: serve that declared MCP server instead of the commands). Pure. */
319
495
  export function capsServeArgs(o) {
320
496
  return [
321
497
  'caps-serve',
322
498
  '--file', o.file,
323
499
  '--home', o.home,
500
+ ...(o.mcp ? ['--mcp', o.mcp] : []),
324
501
  ...(o.realHome ? ['--real-home', o.realHome] : []),
325
502
  ...(o.outDir ? ['--out', o.outDir] : []),
326
503
  ...(o.log ? ['--log', o.log] : []),
327
504
  ...Object.entries(o.context ?? {}).flatMap(([k, v]) => ['--context', `${k}=${v}`]),
328
505
  ];
329
506
  }
330
- /** The stdio MCP server of `ach caps-serve`: one tool per declared capability. */
507
+ /** The stdio MCP server of `ach caps-serve`: one tool per declared capability (`--mcp <name>`: that declared MCP server, capsmcp.ts). */
331
508
  export async function serveCaps(argv) {
509
+ if (argv.includes('--mcp'))
510
+ return (await import('./capsmcp.js')).serveMcpProxy(argv);
332
511
  const opt = (name) => {
333
512
  const i = argv.indexOf(name);
334
513
  return i >= 0 ? argv[i + 1] : undefined;
@@ -0,0 +1,19 @@
1
+ import type { SkillDecl } from './caps.js';
2
+ /**
3
+ * decisions §38: the skills an owner declared, as one run gets them. The owner's folders are not readable in the sandbox, so
4
+ * every run gets a copy in its TMPDIR laid out as a Claude Code plugin (`<tmp>/ach-plugin/.claude-plugin/plugin.json`,
5
+ * `skills/<name>/`): Claude loads it as a plugin, Codex finds each skill linked from its CODEX_HOME's `skills/`, other
6
+ * runtimes read the list in the prompt.
7
+ */
8
+ export declare const SKILLS_PLUGIN = "owner";
9
+ /**
10
+ * Copy the skills into `<tmpDir>/ach-plugin`. Returns the plugin folder and the skills with `dir` pointing at their copy; a
11
+ * skill that cannot be copied is left out with a reason.
12
+ */
13
+ export declare function copySkills(skills: SkillDecl[], tmpDir: string): {
14
+ pluginDir: string;
15
+ skills: SkillDecl[];
16
+ problems: string[];
17
+ };
18
+ /** Codex: link each copied skill into `<codexHome>/skills` (replaced on every run: an undeclared skill does not linger). */
19
+ export declare function linkCodexSkills(codexHome: string, skills: SkillDecl[], platform?: NodeJS.Platform): void;
@@ -0,0 +1,76 @@
1
+ import { cpSync, mkdirSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /**
4
+ * decisions §38: the skills an owner declared, as one run gets them. The owner's folders are not readable in the sandbox, so
5
+ * every run gets a copy in its TMPDIR laid out as a Claude Code plugin (`<tmp>/ach-plugin/.claude-plugin/plugin.json`,
6
+ * `skills/<name>/`): Claude loads it as a plugin, Codex finds each skill linked from its CODEX_HOME's `skills/`, other
7
+ * runtimes read the list in the prompt.
8
+ */
9
+ export const SKILLS_PLUGIN = 'owner';
10
+ /** a skill folder bigger than this is not copied (a skill is instructions and small scripts, not data) */
11
+ const MAX_BYTES = 50 * 1024 * 1024;
12
+ const SKIP = new Set(['.git', 'node_modules', '.venv', '__pycache__']);
13
+ function sizeOf(dir, limit) {
14
+ let total = 0;
15
+ const walk = (d) => {
16
+ for (const e of readdirSync(d, { withFileTypes: true })) {
17
+ if (SKIP.has(e.name))
18
+ continue;
19
+ const p = join(d, e.name);
20
+ const st = statSync(p);
21
+ if (st.isDirectory())
22
+ walk(p);
23
+ else
24
+ total += st.size;
25
+ if (total > limit)
26
+ return;
27
+ }
28
+ };
29
+ walk(dir);
30
+ return total;
31
+ }
32
+ /**
33
+ * Copy the skills into `<tmpDir>/ach-plugin`. Returns the plugin folder and the skills with `dir` pointing at their copy; a
34
+ * skill that cannot be copied is left out with a reason.
35
+ */
36
+ export function copySkills(skills, tmpDir) {
37
+ const pluginDir = join(tmpDir, 'ach-plugin');
38
+ rmSync(pluginDir, { recursive: true, force: true });
39
+ mkdirSync(join(pluginDir, '.claude-plugin'), { recursive: true });
40
+ writeFileSync(join(pluginDir, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: SKILLS_PLUGIN, version: '1.0.0', description: "Skills the agent's owner declared (AgentChannel)" }, null, 2));
41
+ const out = [];
42
+ const problems = [];
43
+ for (const s of skills) {
44
+ try {
45
+ if (sizeOf(s.dir, MAX_BYTES) > MAX_BYTES) {
46
+ problems.push(`skills: ${s.name} is larger than ${MAX_BYTES / 1024 / 1024} MB; not given to runs`);
47
+ continue;
48
+ }
49
+ const dst = join(pluginDir, 'skills', s.name);
50
+ cpSync(s.dir, dst, { recursive: true, dereference: true, filter: (src) => !SKIP.has(src.split(/[\\/]/).pop() ?? '') });
51
+ out.push({ ...s, dir: dst });
52
+ }
53
+ catch (e) {
54
+ problems.push(`skills: ${s.name}: ${e?.message ?? e}`);
55
+ }
56
+ }
57
+ return { pluginDir, skills: out, problems };
58
+ }
59
+ /** Codex: link each copied skill into `<codexHome>/skills` (replaced on every run: an undeclared skill does not linger). */
60
+ export function linkCodexSkills(codexHome, skills, platform = process.platform) {
61
+ const dir = join(codexHome, 'skills');
62
+ rmSync(dir, { recursive: true, force: true });
63
+ if (!skills.length)
64
+ return;
65
+ mkdirSync(dir, { recursive: true });
66
+ for (const s of skills) {
67
+ const dst = join(dir, s.name);
68
+ try {
69
+ // a junction needs no rights on Windows
70
+ symlinkSync(s.dir, dst, platform === 'win32' ? 'junction' : 'dir');
71
+ }
72
+ catch {
73
+ cpSync(s.dir, dst, { recursive: true });
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,36 @@
1
+ import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
2
+ import { type McpDecl } from './caps.js';
3
+ export interface UpstreamOptions {
4
+ home: string;
5
+ realHome?: string;
6
+ baseEnv?: Record<string, string | undefined>;
7
+ }
8
+ /** A connected MCP client to a declared server. HTTP: streamable first, SSE when the server answers only that. */
9
+ export declare function connectUpstream(decl: McpDecl, o: UpstreamOptions): Promise<Client>;
10
+ export interface UpstreamTool {
11
+ name: string;
12
+ description?: string;
13
+ inputSchema: Record<string, unknown>;
14
+ annotations?: {
15
+ readOnlyHint?: boolean;
16
+ destructiveHint?: boolean;
17
+ title?: string;
18
+ };
19
+ }
20
+ /** Every tool the server offers (all pages). */
21
+ export declare function upstreamTools(client: Client): Promise<UpstreamTool[]>;
22
+ /** The declared tools the server really has, and the declared ones it does not. Pure. */
23
+ export declare function pickTools(decl: McpDecl, offered: UpstreamTool[]): {
24
+ tools: UpstreamTool[];
25
+ missing: string[];
26
+ };
27
+ /** A tool result with every text part above `max` characters saved to a file in `outDir` (named in its place). */
28
+ export declare function capResult(result: any, o: {
29
+ outDir?: string;
30
+ server: string;
31
+ tool: string;
32
+ max?: number;
33
+ now?: number;
34
+ }): any;
35
+ /** The stdio MCP server of `ach caps-serve --mcp <name>`. */
36
+ export declare function serveMcpProxy(argv: string[]): Promise<void>;
@@ -0,0 +1,193 @@
1
+ import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { capEnv, loadCaps } from './caps.js';
4
+ /**
5
+ * decisions §38: `ach caps-serve --mcp <name>`, the stdio MCP server a run gets for one MCP server its owner declared. It runs
6
+ * outside the run's sandbox (the runtime starts it), connects to the real server with the owner's credentials (headers, env,
7
+ * the OAuth login of `ach caps login`), and offers only the declared tools, each with the real server's own schema. A call is
8
+ * forwarded as is and logged to caps.log; text above MAX_TEXT goes to a file in the run's TMPDIR. The run sees neither the
9
+ * server's address nor its credentials.
10
+ */
11
+ const MAX_TEXT = 60_000;
12
+ const DEFAULT_TIMEOUT = 300;
13
+ /** under the runtimes' own wait for a server to start (30 s) */
14
+ const CONNECT_MS = 20_000;
15
+ /** A connected MCP client to a declared server. HTTP: streamable first, SSE when the server answers only that. */
16
+ export async function connectUpstream(decl, o) {
17
+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');
18
+ const client = new Client({ name: 'agentchannel', version: '1' });
19
+ const within = (p, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(`${what}: no answer within ${CONNECT_MS / 1000} s`)), CONNECT_MS).unref())]);
20
+ if (decl.command) {
21
+ const { StdioClientTransport } = await import('@modelcontextprotocol/sdk/client/stdio.js');
22
+ const t = new StdioClientTransport({
23
+ command: decl.command[0],
24
+ args: decl.command.slice(1),
25
+ env: capEnv(o.baseEnv ?? process.env, o.realHome, decl.env),
26
+ cwd: decl.cwd ?? o.home,
27
+ stderr: 'ignore',
28
+ });
29
+ await within(client.connect(t), `${decl.name} (${decl.command[0]})`);
30
+ return client;
31
+ }
32
+ const url = new URL(decl.url);
33
+ const requestInit = decl.headers ? { headers: decl.headers } : undefined;
34
+ let authProvider;
35
+ if (decl.oauth) {
36
+ const { FileOAuthProvider, hasLogin } = await import('./mcpauth.js');
37
+ if (!hasLogin(o.home, decl.name))
38
+ throw new Error(`${decl.name} needs a login: run \`ach caps login ${decl.name}\` on this machine`);
39
+ authProvider = new FileOAuthProvider(o.home, decl);
40
+ }
41
+ const { StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js');
42
+ try {
43
+ await within(client.connect(new StreamableHTTPClientTransport(url, { requestInit, authProvider })), decl.name);
44
+ return client;
45
+ }
46
+ catch (e) {
47
+ // an auth failure is not a transport mismatch: say it as it is
48
+ if (e?.code === 401 || e?.code === 403 || e?.name === 'UnauthorizedError' || /unauthori[sz]ed|login/i.test(String(e?.message ?? e)))
49
+ throw loginError(decl, e);
50
+ const { SSEClientTransport } = await import('@modelcontextprotocol/sdk/client/sse.js');
51
+ const sse = new Client({ name: 'agentchannel', version: '1' });
52
+ try {
53
+ await within(sse.connect(new SSEClientTransport(url, { requestInit, authProvider })), decl.name);
54
+ return sse;
55
+ }
56
+ catch {
57
+ throw e;
58
+ }
59
+ }
60
+ }
61
+ function loginError(decl, e) {
62
+ const msg = e?.code ? `HTTP ${e.code}` : String(e?.message ?? e);
63
+ if (decl.oauth)
64
+ return new Error(`${decl.name}: the login is no longer accepted (${msg}); run \`ach caps login ${decl.name}\` again`);
65
+ return new Error(`${decl.name}: the server refused the credentials in its headers (${msg})`);
66
+ }
67
+ /** Every tool the server offers (all pages). */
68
+ export async function upstreamTools(client) {
69
+ const out = [];
70
+ let cursor;
71
+ do {
72
+ const r = await client.listTools(cursor ? { cursor } : undefined);
73
+ out.push(...(r.tools ?? []));
74
+ cursor = r.nextCursor;
75
+ } while (cursor);
76
+ return out;
77
+ }
78
+ /** The declared tools the server really has, and the declared ones it does not. Pure. */
79
+ export function pickTools(decl, offered) {
80
+ const tools = decl.tools.map((n) => offered.find((t) => t.name === n)).filter((t) => !!t);
81
+ return { tools, missing: decl.tools.filter((n) => !offered.some((t) => t.name === n)) };
82
+ }
83
+ function kb(n) {
84
+ return n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : n >= 1024 ? `${Math.round(n / 1024)} KB` : `${n} B`;
85
+ }
86
+ /** A tool result with every text part above `max` characters saved to a file in `outDir` (named in its place). */
87
+ export function capResult(result, o) {
88
+ const max = o.max ?? MAX_TEXT;
89
+ if (!Array.isArray(result?.content))
90
+ return result;
91
+ let i = 0;
92
+ const content = result.content.map((part) => {
93
+ if (part?.type !== 'text' || typeof part.text !== 'string' || part.text.length <= max)
94
+ return part;
95
+ const bytes = Buffer.byteLength(part.text);
96
+ let file;
97
+ if (o.outDir) {
98
+ try {
99
+ mkdirSync(o.outDir, { recursive: true });
100
+ file = join(o.outDir, `mcp-${o.server}-${o.tool}-${o.now ?? Date.now()}-${i++}.txt`);
101
+ writeFileSync(file, part.text);
102
+ }
103
+ catch {
104
+ file = undefined;
105
+ }
106
+ }
107
+ const note = file ? `\n[output is ${kb(bytes)}: the first ${max} characters are above; the full output is in ${file}]` : `\n[output cut at ${max} characters of ${kb(bytes)}]`;
108
+ return { ...part, text: part.text.slice(0, max) + note };
109
+ });
110
+ return { ...result, content };
111
+ }
112
+ function logLine(file, entry) {
113
+ if (!file)
114
+ return;
115
+ try {
116
+ mkdirSync(dirname(file), { recursive: true });
117
+ appendFileSync(file, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
118
+ }
119
+ catch {
120
+ /* the log never stops a call */
121
+ }
122
+ }
123
+ /** The stdio MCP server of `ach caps-serve --mcp <name>`. */
124
+ export async function serveMcpProxy(argv) {
125
+ const opt = (n) => {
126
+ const i = argv.indexOf(n);
127
+ return i >= 0 ? argv[i + 1] : undefined;
128
+ };
129
+ const context = {};
130
+ argv.forEach((a, i) => {
131
+ if (a === '--context' && argv[i + 1]?.includes('=')) {
132
+ const [k, ...v] = argv[i + 1].split('=');
133
+ context[k] = v.join('=');
134
+ }
135
+ });
136
+ const file = opt('--file');
137
+ const home = opt('--home');
138
+ const name = opt('--mcp');
139
+ if (!file || !home || !name)
140
+ throw new Error('caps-serve --mcp needs --file, --home and --mcp');
141
+ const log = opt('--log');
142
+ const outDir = opt('--out');
143
+ const realHome = opt('--real-home');
144
+ const decl = loadCaps(file).mcp.find((m) => m.name === name);
145
+ const { Server } = await import('@modelcontextprotocol/sdk/server/index.js');
146
+ const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
147
+ const { ListToolsRequestSchema, CallToolRequestSchema } = await import('@modelcontextprotocol/sdk/types.js');
148
+ // connect before answering the runtime: its tool list is read once, at the start of the run
149
+ let client;
150
+ let tools = [];
151
+ let failure = decl ? '' : `${name} is not declared in ${file}`;
152
+ if (decl) {
153
+ try {
154
+ client = await connectUpstream(decl, { home, realHome });
155
+ const picked = pickTools(decl, await upstreamTools(client));
156
+ tools = picked.tools;
157
+ if (picked.missing.length)
158
+ logLine(log, { at: new Date().toISOString(), mcp: name, ...context, missing: picked.missing });
159
+ }
160
+ catch (e) {
161
+ failure = String(e?.message ?? e);
162
+ }
163
+ }
164
+ if (failure)
165
+ logLine(log, { at: new Date().toISOString(), mcp: name, ...context, unavailable: failure });
166
+ const server = new Server({ name, version: '1' }, { capabilities: { tools: {} }, ...(failure ? { instructions: `Not available in this run: ${failure}` } : {}) });
167
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
168
+ tools: tools.map((t) => ({ name: t.name, ...(t.description ? { description: t.description } : {}), inputSchema: t.inputSchema, ...(t.annotations ? { annotations: t.annotations } : {}) })),
169
+ }));
170
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
171
+ const started = Date.now();
172
+ const tool = req.params.name;
173
+ const args = (req.params.arguments ?? {});
174
+ const entry = { at: new Date(started).toISOString(), mcp: name, tool, args: Object.fromEntries(Object.entries(args).map(([k, v]) => [k, (typeof v === 'string' ? v : JSON.stringify(v)).slice(0, 500)])), ...context };
175
+ const fail = (text) => ({ content: [{ type: 'text', text }], isError: true });
176
+ if (!client || !tools.some((t) => t.name === tool)) {
177
+ const why = client ? `${tool} is not one of the tools your owner declared for ${name}` : `${name} is not available: ${failure}`;
178
+ logLine(log, { ...entry, refused: why });
179
+ return fail(why);
180
+ }
181
+ try {
182
+ const r = await client.callTool({ name: tool, arguments: args }, undefined, { timeout: (decl.timeout ?? DEFAULT_TIMEOUT) * 1000, resetTimeoutOnProgress: true });
183
+ logLine(log, { ...entry, ms: Date.now() - started, ...(r.isError ? { error: true } : {}) });
184
+ return capResult(r, { outDir, server: name, tool, now: started });
185
+ }
186
+ catch (e) {
187
+ const msg = String(e?.message ?? e);
188
+ logLine(log, { ...entry, ms: Date.now() - started, failed: msg.slice(0, 500) });
189
+ return fail(`${name}.${tool} failed: ${msg}`);
190
+ }
191
+ });
192
+ await server.connect(new StdioServerTransport());
193
+ }