@soft-boy/agentschema 0.2.1 → 0.2.2

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/src/oauth.js ADDED
@@ -0,0 +1,192 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { DeployError } from "./deploy.js";
4
+
5
+ // OAuth for MCP servers, as the MCP authorization spec describes it: find the server's
6
+ // authorization server from its URL, then sign in through the browser with the authorization
7
+ // code flow and PKCE, receiving the code on a local port.
8
+
9
+ // A DeployError, so the CLI reports it like any other failure.
10
+ export class OAuthError extends DeployError {}
11
+
12
+ const GOOGLE = "accounts.google.com";
13
+
14
+ // Finds the OAuth endpoints for an MCP server from its URL alone.
15
+ // Returns { resource, scopesSupported, issuer, authorizationEndpoint, tokenEndpoint,
16
+ // registrationEndpoint, codeChallengeMethods }.
17
+ export async function discover(serverUrl, { fetch = globalThis.fetch } = {}) {
18
+ const url = new URL(serverUrl);
19
+ const path = url.pathname.replace(/\/$/, "");
20
+
21
+ // Protected resource metadata (RFC 9728): which authorization server the MCP server trusts.
22
+ const resourceMeta =
23
+ (path && (await getJSON(`${url.origin}/.well-known/oauth-protected-resource${path}`, fetch))) ||
24
+ (await getJSON(`${url.origin}/.well-known/oauth-protected-resource`, fetch));
25
+ const issuer = resourceMeta?.authorization_servers?.[0] ?? url.origin;
26
+
27
+ // Authorization server metadata (RFC 8414), or OpenID Connect discovery, which Google uses.
28
+ const as = new URL(issuer);
29
+ const asPath = as.pathname.replace(/\/$/, "");
30
+ const candidates = [
31
+ `${as.origin}/.well-known/oauth-authorization-server${asPath}`,
32
+ `${as.origin}/.well-known/openid-configuration${asPath}`,
33
+ ...(asPath ? [`${as.origin}${asPath}/.well-known/openid-configuration`] : []),
34
+ ];
35
+ let meta = null;
36
+ for (const candidate of candidates) {
37
+ meta = await getJSON(candidate, fetch);
38
+ if (meta?.authorization_endpoint && meta?.token_endpoint) break;
39
+ meta = null;
40
+ }
41
+ if (!meta) {
42
+ throw new OAuthError(`couldn't find the OAuth sign-in for ${serverUrl}: ${issuer} publishes no authorization server metadata`);
43
+ }
44
+
45
+ return {
46
+ resource: resourceMeta?.resource ?? null,
47
+ scopesSupported: resourceMeta?.scopes_supported ?? meta.scopes_supported ?? [],
48
+ issuer: meta.issuer ?? issuer,
49
+ authorizationEndpoint: meta.authorization_endpoint,
50
+ tokenEndpoint: meta.token_endpoint,
51
+ registrationEndpoint: meta.registration_endpoint ?? null,
52
+ codeChallengeMethods: meta.code_challenge_methods_supported ?? null,
53
+ };
54
+ }
55
+
56
+ async function getJSON(url, fetch) {
57
+ try {
58
+ const res = await fetch(url, { headers: { accept: "application/json" } });
59
+ if (!res.ok) return null;
60
+ return await res.json();
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ // Starts the local server the browser is sent back to after signing in.
67
+ // Returns { redirectUri, waitForCode(state, timeoutMs), close() }.
68
+ export async function startCallbackServer(port = 0) {
69
+ let deliver;
70
+ const received = new Promise((resolve) => (deliver = resolve));
71
+ const server = createServer((req, res) => {
72
+ const url = new URL(req.url, "http://127.0.0.1");
73
+ if (url.pathname !== "/callback") {
74
+ res.writeHead(404).end();
75
+ return;
76
+ }
77
+ const error = url.searchParams.get("error");
78
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
79
+ res.end(
80
+ `<!doctype html><title>agentschema</title><body style="font:16px system-ui;margin:4em auto;max-width:30em">` +
81
+ (error ? `<h1>Sign-in failed</h1><p>${escape(error)}. Check the terminal.</p>` : "<h1>Signed in</h1><p>You can close this tab and go back to the terminal.</p>") +
82
+ "</body>",
83
+ );
84
+ deliver(url.searchParams);
85
+ });
86
+ await new Promise((resolve, reject) => {
87
+ server.once("error", (err) => reject(new OAuthError(`couldn't listen on 127.0.0.1:${port}: ${err.message}`)));
88
+ server.listen(port, "127.0.0.1", resolve);
89
+ });
90
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
91
+
92
+ return {
93
+ redirectUri,
94
+ async waitForCode(state, timeoutMs = 5 * 60_000) {
95
+ let timer;
96
+ const timeout = new Promise((_, reject) => {
97
+ timer = setTimeout(() => reject(new OAuthError("timed out waiting for the browser sign-in")), timeoutMs);
98
+ });
99
+ try {
100
+ const params = await Promise.race([received, timeout]);
101
+ const error = params.get("error");
102
+ if (error) {
103
+ const detail = params.get("error_description");
104
+ throw new OAuthError(`sign-in failed: ${error}${detail ? ` (${detail})` : ""}`);
105
+ }
106
+ if (params.get("state") !== state) throw new OAuthError("sign-in failed: the response's state didn't match");
107
+ const code = params.get("code");
108
+ if (!code) throw new OAuthError("sign-in failed: no authorization code came back");
109
+ return code;
110
+ } finally {
111
+ clearTimeout(timer);
112
+ }
113
+ },
114
+ close: () => new Promise((resolve) => server.close(resolve)),
115
+ };
116
+ }
117
+
118
+ const escape = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
119
+
120
+ // Registers agentschema as an OAuth client (RFC 7591), for servers that allow it.
121
+ // Returns { clientId, clientSecret, authMethod }.
122
+ export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch } = {}) {
123
+ const res = await fetch(registrationEndpoint, {
124
+ method: "POST",
125
+ headers: { "content-type": "application/json", accept: "application/json" },
126
+ body: JSON.stringify({
127
+ client_name: "agentschema",
128
+ redirect_uris: [redirectUri],
129
+ grant_types: ["authorization_code", "refresh_token"],
130
+ response_types: ["code"],
131
+ token_endpoint_auth_method: "none",
132
+ }),
133
+ });
134
+ const body = await res.json().catch(() => ({}));
135
+ if (!res.ok || !body.client_id) {
136
+ throw new OAuthError(`couldn't register a client at ${registrationEndpoint} (${res.status}): ${body.error_description ?? body.error ?? "no client_id in the response"}`);
137
+ }
138
+ return {
139
+ clientId: body.client_id,
140
+ clientSecret: body.client_secret ?? null,
141
+ authMethod: body.token_endpoint_auth_method ?? (body.client_secret ? "client_secret_post" : "none"),
142
+ };
143
+ }
144
+
145
+ // The URL to send the browser to, and the PKCE verifier and state to finish with.
146
+ export function authorizationRequest({ authorizationEndpoint, issuer, clientId, redirectUri, scope, resource }) {
147
+ const verifier = base64url(randomBytes(32));
148
+ const state = base64url(randomBytes(16));
149
+ const url = new URL(authorizationEndpoint);
150
+ const params = {
151
+ response_type: "code",
152
+ client_id: clientId,
153
+ redirect_uri: redirectUri,
154
+ code_challenge: base64url(createHash("sha256").update(verifier).digest()),
155
+ code_challenge_method: "S256",
156
+ state,
157
+ };
158
+ if (scope) params.scope = scope;
159
+ if (resource) params.resource = resource;
160
+ // Google only issues a refresh token for offline access, and only on a fresh consent.
161
+ if (new URL(issuer).host === GOOGLE) Object.assign(params, { access_type: "offline", prompt: "consent" });
162
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
163
+ return { url: url.toString(), verifier, state };
164
+ }
165
+
166
+ // Trades the authorization code for tokens.
167
+ // Returns { accessToken, refreshToken, expiresAt, scope }.
168
+ export async function exchangeCode({ tokenEndpoint, code, verifier, redirectUri, clientId, clientSecret, authMethod, resource }, { fetch = globalThis.fetch } = {}) {
169
+ const form = new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirectUri, code_verifier: verifier });
170
+ if (resource) form.set("resource", resource);
171
+ const headers = { "content-type": "application/x-www-form-urlencoded", accept: "application/json" };
172
+ if (authMethod === "client_secret_basic") {
173
+ headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`).toString("base64")}`;
174
+ } else {
175
+ form.set("client_id", clientId);
176
+ if (authMethod === "client_secret_post") form.set("client_secret", clientSecret);
177
+ }
178
+
179
+ const res = await fetch(tokenEndpoint, { method: "POST", headers, body: form });
180
+ const body = await res.json().catch(() => ({}));
181
+ if (!res.ok || !body.access_token) {
182
+ throw new OAuthError(`the token endpoint refused the sign-in (${res.status}): ${body.error_description ?? body.error ?? "no access token in the response"}`);
183
+ }
184
+ return {
185
+ accessToken: body.access_token,
186
+ refreshToken: body.refresh_token ?? null,
187
+ expiresAt: body.expires_in ? new Date(Date.now() + Number(body.expires_in) * 1000).toISOString() : null,
188
+ scope: body.scope ?? null,
189
+ };
190
+ }
191
+
192
+ const base64url = (buf) => buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
package/src/prompts.js ADDED
@@ -0,0 +1,159 @@
1
+ import { createInterface, emitKeypressEvents } from "node:readline";
2
+
3
+ // Interactive questions, shared by `init` and `cred create`. In a terminal, choices are picked
4
+ // with the arrow keys and secrets aren't echoed; with piped input, each answer is a line.
5
+ //
6
+ // text(question, fallback, { validate }) an empty reply keeps the fallback; validate returns
7
+ // an error message, or nothing when the reply is fine
8
+ // select(question, choices, fallback) one of `choices` (strings)
9
+ // confirm(question, fallback) true or false
10
+ // secret(question) a reply that isn't shown
11
+ // close()
12
+ //
13
+ // Ctrl+C rejects with the error `cancelled()` returns.
14
+ export function prompts(input, output, { cancelled = () => new Error("cancelled") } = {}) {
15
+ const base = input.isTTY ? terminalPrompts(input, output, cancelled) : linePrompts(input, output, cancelled);
16
+
17
+ const text = async (question, fallback = "", { validate } = {}) => {
18
+ while (true) {
19
+ const reply = await base.text(question, fallback);
20
+ const problem = validate?.(reply);
21
+ if (!problem) return reply;
22
+ output.write(`${problem}\n`);
23
+ if (base.ended?.()) throw cancelled();
24
+ }
25
+ };
26
+ const confirm = async (question, fallback) => {
27
+ while (true) {
28
+ const reply = (await base.text(`${question} [y/n]`, fallback ? "y" : "n")).toLowerCase();
29
+ if (/^(y|yes)$/.test(reply)) return true;
30
+ if (/^(n|no)$/.test(reply)) return false;
31
+ output.write("Answer y or n\n");
32
+ }
33
+ };
34
+ return { ...base, text, confirm };
35
+ }
36
+
37
+ // Prompts for piped input: one answer per line, and choices picked by name or number.
38
+ function linePrompts(input, output, cancelled) {
39
+ const rl = createInterface({ input, output, terminal: false });
40
+ const lines = rl[Symbol.asyncIterator]();
41
+ let ended = false;
42
+
43
+ const line = async () => {
44
+ if (ended) return null;
45
+ const { value, done } = await lines.next();
46
+ if (done) {
47
+ ended = true;
48
+ output.write("\n");
49
+ return null;
50
+ }
51
+ return value.trim();
52
+ };
53
+ const text = async (question, fallback) => {
54
+ output.write(fallback ? `${question} (${fallback}) ` : `${question} `);
55
+ return (await line()) || fallback;
56
+ };
57
+ const select = async (question, choices, fallback) => {
58
+ const listed = choices.map((c, i) => `${i + 1}) ${c}`).join(" ");
59
+ while (true) {
60
+ const reply = await text(`${question} ${listed}`, String(choices.indexOf(fallback) + 1 || 1));
61
+ const picked = choices[Number(reply) - 1] ?? choices.find((c) => c === reply);
62
+ if (picked) return picked;
63
+ output.write(`Pick one of: ${choices.join(", ")}\n`);
64
+ if (ended) throw cancelled();
65
+ }
66
+ };
67
+ const secret = async (question) => {
68
+ output.write(`${question} `);
69
+ const reply = await line();
70
+ if (reply === null) throw cancelled();
71
+ return reply;
72
+ };
73
+ return { text, select, secret, ended: () => ended, close: () => rl.close() };
74
+ }
75
+
76
+ const ESC = "\x1b[";
77
+ const cyan = (s) => `${ESC}36m${s}${ESC}0m`;
78
+ const dim = (s) => `${ESC}2m${s}${ESC}0m`;
79
+
80
+ // Prompts for a terminal: choices are picked with the arrow keys and Enter.
81
+ function terminalPrompts(input, output, cancelled) {
82
+ // A fresh readline per question, so it doesn't fight the raw-mode select for the arrow keys.
83
+ const text = (question, fallback) =>
84
+ new Promise((resolve, reject) => {
85
+ const rl = createInterface({ input, output, terminal: true });
86
+ rl.on("SIGINT", () => {
87
+ rl.close();
88
+ output.write("\n");
89
+ reject(cancelled());
90
+ });
91
+ rl.question(fallback ? `${question} ${dim(`(${fallback})`)} ` : `${question} `, (reply) => {
92
+ rl.close();
93
+ resolve(reply.trim() || fallback);
94
+ });
95
+ });
96
+
97
+ const select = (question, choices, fallback) =>
98
+ new Promise((resolve, reject) => {
99
+ let index = Math.max(0, choices.indexOf(fallback));
100
+ const render = (first) => {
101
+ if (!first) output.write(`${ESC}${choices.length}A`);
102
+ for (const [i, choice] of choices.entries()) {
103
+ output.write(`${ESC}2K${i === index ? cyan(`❯ ${choice}`) : ` ${choice}`}\n`);
104
+ }
105
+ };
106
+ const finish = (err) => {
107
+ input.off("keypress", onKey);
108
+ input.setRawMode(false);
109
+ input.pause();
110
+ // Collapse the list to one line with the answer.
111
+ output.write(`${ESC}${choices.length + 1}A${ESC}J${ESC}?25h`);
112
+ output.write(`${question} ${err ? dim("cancelled") : cyan(choices[index])}\n`);
113
+ err ? reject(err) : resolve(choices[index]);
114
+ };
115
+ const onKey = (str, key = {}) => {
116
+ if (key.ctrl && key.name === "c") return finish(cancelled());
117
+ if (key.name === "return" || key.name === "enter") return finish();
118
+ if (key.name === "up" || key.name === "k") index = (index - 1 + choices.length) % choices.length;
119
+ else if (key.name === "down" || key.name === "j" || key.name === "tab") index = (index + 1) % choices.length;
120
+ else if (/^[1-9]$/.test(str ?? "") && Number(str) <= choices.length) index = Number(str) - 1;
121
+ else return;
122
+ render(false);
123
+ };
124
+
125
+ emitKeypressEvents(input);
126
+ input.setRawMode(true);
127
+ input.resume();
128
+ output.write(`${question} ${dim("(↑/↓, Enter)")}\n${ESC}?25l`);
129
+ render(true);
130
+ input.on("keypress", onKey);
131
+ });
132
+
133
+ // Not echoed, so the secret doesn't end up on screen or in the scrollback; pasting works.
134
+ const secret = (question) =>
135
+ new Promise((resolve, reject) => {
136
+ output.write(`${question} ${dim("(hidden)")} `);
137
+ input.setRawMode(true);
138
+ input.resume();
139
+ let answer = "";
140
+ const finish = (err) => {
141
+ input.off("data", onData);
142
+ input.setRawMode(false);
143
+ input.pause();
144
+ output.write("\n");
145
+ err ? reject(err) : resolve(answer.trim());
146
+ };
147
+ const onData = (chunk) => {
148
+ for (const ch of chunk.toString("utf8")) {
149
+ if (ch === "\r" || ch === "\n") return finish();
150
+ if (ch === "\u0003") return finish(cancelled());
151
+ if (ch === "\u007f" || ch === "\b") answer = answer.slice(0, -1);
152
+ else if (ch >= " ") answer += ch;
153
+ }
154
+ };
155
+ input.on("data", onData);
156
+ });
157
+
158
+ return { text, select, secret, close() {} };
159
+ }
package/src/session.js CHANGED
@@ -1,7 +1,9 @@
1
+ import { join } from "node:path";
1
2
  import { check } from "./check.js";
2
3
  import { AGENT_FILE, ENV_FILE, agentBody, envBody } from "./instance.js";
3
4
  import { LOCK_FILE, hashBody, readLock } from "./lock.js";
4
5
  import { TOOLS_DIR } from "./tools.js";
6
+ import { credentialKey, vaultKey } from "./vaults.js";
5
7
 
6
8
  export class SessionError extends Error {}
7
9
 
@@ -34,13 +36,32 @@ export async function openSession(dir, { client, sessionId }) {
34
36
  agent: { type: "agent", id: agent.id, version: Number(agent.version) },
35
37
  environment_id: env.id,
36
38
  };
39
+
40
+ // Every deployed vault in vaults/, in name order: when two hold a credential for the same
41
+ // server, the first one wins.
42
+ const vaultIds = [];
43
+ for (const vault of instance?.vaults ?? []) {
44
+ const entry = lock.resources[vaultKey(vault)];
45
+ if (!entry) {
46
+ notes.push(`vault ${vault.path} hasn't been deployed, so this session doesn't have it; run agentschema deploy`);
47
+ continue;
48
+ }
49
+ vaultIds.push(entry.id);
50
+ for (const cred of vault.credentials) {
51
+ const credEntry = lock.resources[credentialKey(cred)];
52
+ if (!credEntry || credEntry.vault_id !== entry.id) {
53
+ notes.push(`credential ${cred.file} hasn't been created; run agentschema cred deploy ${join(dir, cred.file)}`);
54
+ }
55
+ }
56
+ }
57
+ if (vaultIds.length > 0) params.vault_ids = vaultIds;
37
58
  const name = instance?.agent.data.name;
38
59
  params.title = name ? `${name} (agentschema run)` : "agentschema run";
39
60
  return { session: await client.beta.sessions.create(params), notes };
40
61
  }
41
62
 
42
63
  // Drives a session one turn at a time. `ui` answers what only a person can:
43
- // ui.event(event) show an event
64
+ // ui.event(event) show an event, including the stream-only event_start / event_delta previews
44
65
  // ui.confirm(event) -> { result: "allow" | "deny", deny_message? } for a paused tool call
45
66
  // ui.customToolResult(event) -> string, or { text, isError }: the result of a custom tool call
46
67
  export class Conversation {
@@ -65,7 +86,7 @@ export class Conversation {
65
86
 
66
87
  async #turn(events) {
67
88
  // Stream first: events emitted before the stream opens would never reach us.
68
- this.stream = await this.client.beta.sessions.events.stream(this.sessionId);
89
+ this.stream = await this.#openStream();
69
90
  await this.client.beta.sessions.events.send(this.sessionId, { events });
70
91
 
71
92
  for (let attempt = 0; ; attempt++) {
@@ -78,7 +99,7 @@ export class Conversation {
78
99
  } catch (err) {
79
100
  if (this.closed || attempt >= 3) throw err;
80
101
  // The stream has no replay: reopen it, then catch up from the event history.
81
- this.stream = await this.client.beta.sessions.events.stream(this.sessionId);
102
+ this.stream = await this.#openStream();
82
103
  for await (const event of this.client.beta.sessions.events.list(this.sessionId)) {
83
104
  const done = await this.#handle(event);
84
105
  if (done) return done;
@@ -87,6 +108,12 @@ export class Conversation {
87
108
  }
88
109
  }
89
110
 
111
+ // Opts in to live previews, so agent text arrives as event_start / event_delta events while
112
+ // the model is still writing, ahead of the complete agent.message.
113
+ #openStream() {
114
+ return this.client.beta.sessions.events.stream(this.sessionId, { event_deltas: ["agent.message"] });
115
+ }
116
+
90
117
  // Returns a value when the turn is over.
91
118
  async #handle(event) {
92
119
  // Events are deduped by ID: the history and the live stream overlap after a reconnect,
@@ -0,0 +1,171 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { stringify } from "yaml";
4
+ import { check } from "./check.js";
5
+ import { serviceName } from "./cred-menu.js";
6
+ import { DeployError } from "./deploy.js";
7
+ import { builtInFile } from "./init.js";
8
+ import { AGENT_FILE, ENV_FILE } from "./instance.js";
9
+ import { updateFrontmatter } from "./markdown.js";
10
+ import { listMcpTools } from "./mcp.js";
11
+ import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "./tools.js";
12
+
13
+ const PREBUILT = "Pre-built tools (bash, files, web search)";
14
+ const CUSTOM = "Custom tool (JavaScript that runs on your machine)";
15
+ const MCP = "MCP server";
16
+ const INPUT_TYPES = ["string", "number", "integer", "boolean", "object", "string[]", "number[]", "integer[]", "boolean[]", "object[]"];
17
+
18
+ // `tools create`: asks what kind of tool to add, then writes its file in tools/.
19
+ // Returns the path of the file written.
20
+ export async function toolsCreate(dir = ".", { io, fetch = globalThis.fetch, log = () => {} }) {
21
+ const { errors, instance } = check(dir);
22
+ if (!instance) throw new DeployError(`${dir} isn't an agent folder:\n ${errors.join("\n ")}`);
23
+
24
+ const kind = await io.select("What kind of tool?", [PREBUILT, CUSTOM, MCP], PREBUILT);
25
+ const write = kind === PREBUILT ? prebuilt : kind === CUSTOM ? custom : mcp;
26
+ const { path, text, addServer } = await write(dir, instance, io, { fetch, log });
27
+
28
+ const file = join(dir, path);
29
+ mkdirSync(dirname(file), { recursive: true });
30
+ writeFileSync(file, text);
31
+ log(`Wrote ${file}`);
32
+ if (addServer) {
33
+ updateFrontmatter(join(dir, AGENT_FILE), (doc) => {
34
+ if (doc.hasIn(["mcp_servers"])) doc.addIn(["mcp_servers"], doc.createNode(addServer));
35
+ else doc.setIn(["mcp_servers"], doc.createNode([addServer]));
36
+ });
37
+ log(`Added ${addServer.name} to mcp_servers in ${join(dir, AGENT_FILE)}`);
38
+ }
39
+
40
+ const after = check(dir);
41
+ const related = (m) => m.startsWith(path) || (kind === MCP && (m.startsWith(AGENT_FILE) || m.startsWith(ENV_FILE)));
42
+ for (const w of after.warnings.filter(related)) log(`warning: ${w}`);
43
+ for (const e of after.errors.filter(related)) log(`error: ${e}`);
44
+ if (kind === CUSTOM) log(`\nWrite the tool's code in its ## Code block, then deploy with:\n agentschema deploy ${dir}`);
45
+ else if (kind === MCP) log(`\nIf the server needs you to sign in, add a credential for it:\n agentschema cred create ${dir}\nThen deploy with:\n agentschema deploy ${dir}`);
46
+ else log(`\nDeploy with:\n agentschema deploy ${dir}`);
47
+ return file;
48
+ }
49
+
50
+ // The pre-built toolset: one file, with a row for each tool.
51
+ async function prebuilt(dir, { tools }, io) {
52
+ const existing = tools.find((t) => t.data.type === TOOLSET);
53
+ if (existing) throw new DeployError(`the agent already has its pre-built tools in ${existing.file}; edit that file's table to turn tools on or off`);
54
+
55
+ let enabled = PREBUILT_TOOLS;
56
+ if (!(await io.confirm(`Turn on all eight (${PREBUILT_TOOLS.join(", ")})?`, true))) {
57
+ enabled = [];
58
+ for (const name of PREBUILT_TOOLS) if (await io.confirm(` ${name}?`, true)) enabled.push(name);
59
+ }
60
+ return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled) };
61
+ }
62
+
63
+ // A custom tool: its name, description and inputs, with a code block to fill in.
64
+ async function custom(dir, { tools }, io) {
65
+ const taken = new Set(tools.filter((t) => t.data.type === "custom").map((t) => t.name));
66
+ const name = await io.text("Tool name? (letters, digits, _ and -)", "", {
67
+ validate: (n) => {
68
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(n)) return "Use letters, digits, _ and -, up to 64 characters";
69
+ if (PREBUILT_TOOLS.includes(n)) return `${n} is a pre-built tool's name`;
70
+ if (/^(mcp__|ant__)/.test(n)) return "A custom tool's name can't start with mcp__ or ant__";
71
+ if (taken.has(n) || existsSync(join(dir, TOOLS_DIR, `${n}.md`))) return `There's already a tool called ${n}`;
72
+ return null;
73
+ },
74
+ });
75
+ const description = await io.text("What does it do? (Claude reads this to decide when to call it)", "", {
76
+ validate: (d) => (d ? null : "The description is required"),
77
+ });
78
+
79
+ const inputs = [];
80
+ while (true) {
81
+ const input = await io.text(inputs.length === 0 ? "First input's name? (Enter for none)" : "Next input's name? (Enter when done)", "", {
82
+ validate: (n) => {
83
+ if (n && !/^[a-zA-Z_$][\w$]*$/.test(n)) return "Use a name like city or max_results";
84
+ if (inputs.some((i) => i.name === n)) return `${n} is already an input`;
85
+ return null;
86
+ },
87
+ });
88
+ if (!input) break;
89
+ const type = await io.select(` ${input}'s type?`, INPUT_TYPES, "string");
90
+ const about = await io.text(` ${input}'s description?`, "");
91
+ const required = await io.confirm(` Is ${input} required?`, true);
92
+ inputs.push({ name: input, type, about, required });
93
+ }
94
+
95
+ const cell = (s) => s.replace(/\|/g, "\\|");
96
+ const table = inputs.length === 0 ? "" : [
97
+ "## Input Schema", "",
98
+ "| Name | Type | Description | Required |",
99
+ "|---|---|---|---|",
100
+ ...inputs.map((i) => `| \`${i.name}\` | \`${i.type}\` | ${cell(i.about)} | \`${i.required}\` |`),
101
+ "", "",
102
+ ].join("\n");
103
+ const args = inputs.length === 0 ? "()" : `({ ${inputs.map((i) => i.name).join(", ")} })`;
104
+ const code = [
105
+ "## Code", "",
106
+ "```javascript",
107
+ `module.exports = async ${args} => {`,
108
+ ` throw new Error("${name} isn't implemented yet");`,
109
+ "};",
110
+ "```", "",
111
+ ].join("\n");
112
+
113
+ const front = stringify({ type: "custom", name, description });
114
+ return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${front}---\n\n${table}${code}` };
115
+ }
116
+
117
+ // An MCP server: its URL and name, how its tools are approved, and a table of those tools.
118
+ // The server itself is declared in agent.md; a server already declared there only needs its file.
119
+ async function mcp(dir, instance, io, { fetch, log }) {
120
+ const { tools, agent } = instance;
121
+ const declared = Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers : [];
122
+ const toolsets = new Set(tools.filter((t) => t.data.type === MCP_TOOLSET).map((t) => t.data.mcp_server_name));
123
+ const url = await io.text("MCP server URL?", "", {
124
+ validate: (u) => {
125
+ if (!/^https?:\/\/\S+$/.test(u)) return "Enter an http(s) URL";
126
+ const same = declared.find((s) => s?.url === u);
127
+ return same && toolsets.has(same.name) ? `${AGENT_FILE} already declares that server, as ${same.name}` : null;
128
+ },
129
+ });
130
+ const existing = declared.find((s) => s?.url === url);
131
+ const name = existing?.name ?? await io.text("Name for it?", serviceName(url).toLowerCase(), {
132
+ validate: (n) => {
133
+ if (!n || /[/\\]/.test(n) || n.startsWith(".")) return "Use a name without / that doesn't start with .";
134
+ if (declared.some((s) => s?.name === n)) return `${AGENT_FILE} already declares a server called ${n}`;
135
+ if (existsSync(join(dir, TOOLS_DIR, `${n}.md`))) return `There's already a tool file called ${n}.md`;
136
+ return null;
137
+ },
138
+ });
139
+ const addServer = existing ? null : { type: "url", name, url };
140
+
141
+ const policies = ["always_ask", ...POLICIES.filter((p) => p !== "always_ask")];
142
+ const policy = await io.select("Ask you before each call? (permission for its tools)", policies.map(describePolicy), describePolicy("always_ask"));
143
+ const permission = policies.find((p) => describePolicy(p) === policy);
144
+
145
+ // A table of the server's tools, all on, to edit. A tool the server adds later isn't in the
146
+ // table, so it gets the API's defaults: on, and asking before each call.
147
+ log(`Asking ${url} for its tools…`);
148
+ const names = await listMcpTools(url, { fetch });
149
+ const front = { type: MCP_TOOLSET, mcp_server_name: name };
150
+ if (names) {
151
+ log(`It has ${names.length} tool${names.length === 1 ? "" : "s"}.`);
152
+ const rows = names.map((t) => `| \`${t}\` | \`true\` | \`${permission}\` |`);
153
+ const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
154
+ return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${stringify(front)}---\n\n${body}`, addServer };
155
+ }
156
+
157
+ // It won't list them without signing in: every tool is on, with the permission chosen.
158
+ log("It won't list its tools without signing in, so the file has no table; every tool is on.");
159
+ if (permission !== "always_ask") front.default_config = { permission_policy: { type: permission } };
160
+ const body = "Every tool the server offers is on. To turn one off, or give it its own permission, add a table:\n\n" +
161
+ " ## Tools\n\n | Name | Enabled | Permission |\n |---|---|---|\n | `delete_event` | `false` | |\n";
162
+ return { path: `${TOOLS_DIR}/${name}.md`, text: `---\n${stringify(front)}---\n\n${body}`, addServer };
163
+ }
164
+
165
+ function describePolicy(policy) {
166
+ return {
167
+ always_ask: "always_ask: ask before every call (the API's default for MCP tools)",
168
+ always_allow: "always_allow: never ask",
169
+ auto: "auto: Anthropic decides per call, and asks when it can't",
170
+ }[policy];
171
+ }