@soft-boy/agentschema 0.3.2 → 0.3.4

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/lib/index.js CHANGED
@@ -9,7 +9,7 @@ export { MAX_UPLOAD_BYTES, SKILLS_DIR, SKILL_FILE, readSkills, skillKey, skillRe
9
9
  export { agentMessageText, textStream } from "./stream.js";
10
10
  export {
11
11
  AGENTBOOK, MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR,
12
- agentbookTools, compileTools, readTools,
12
+ agentbookTools, compileTools, mcpToolsetFile, readTools,
13
13
  } from "./tools.js";
14
14
  export {
15
15
  CREDENTIAL_TYPES, ENV_VAR, MCP_OAUTH, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE,
package/lib/scaffold.js CHANGED
@@ -13,6 +13,7 @@ export function defaultAnswers(name) {
13
13
  model: MODELS[0],
14
14
  system: "You are a helpful assistant.",
15
15
  tools: true,
16
+ permission: "auto",
16
17
  environment: slug,
17
18
  networking: "limited",
18
19
  packageManagers: true,
@@ -36,14 +37,15 @@ export function scaffold(answers) {
36
37
  [ENV_FILE]: `---\n${stringify(env)}---\nCloud container with ${access}.\n`,
37
38
  };
38
39
  if (answers.tools) {
39
- files[`${TOOLS_DIR}/${TOOLSET_FILE}`] = builtInFile(PREBUILT_TOOLS);
40
+ files[`${TOOLS_DIR}/${TOOLSET_FILE}`] = builtInFile(PREBUILT_TOOLS, PREBUILT_TOOLS, answers.permission);
40
41
  }
41
42
  return files;
42
43
  }
43
44
 
44
- // The pre-built toolset file, with a row for each of `names`: on if it's in `enabled`, with the
45
- // API's default permission policy.
46
- export function builtInFile(names, enabled = names) {
47
- const rows = names.map((name) => `| \`${name}\` | \`${enabled.includes(name)}\` | |`).join("\n");
45
+ // The pre-built toolset file, with a row for each of `names`: on if it's in `enabled`, each with
46
+ // `permission`, so what's chosen is there to read and change. `auto` is what the API recommends for
47
+ // these tools: Anthropic judges each call, and asks when it can't tell.
48
+ export function builtInFile(names, enabled = names, permission = "auto") {
49
+ const rows = names.map((name) => `| \`${name}\` | \`${enabled.includes(name)}\` | \`${permission}\` |`).join("\n");
48
50
  return `---\ntype: ${TOOLSET}\n---\n\nThe tools Claude runs in the agent's container. Set Enabled to false to turn a tool off.\n\n## Tools\n\n| Name | Enabled | Permission |\n|---|---|---|\n${rows}\n`;
49
51
  }
package/lib/tools.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { stringify } from "yaml";
1
2
  import { pathsUnder, textOf } from "./files.js";
2
3
  import { FileError, parseMarkdown } from "./markdown.js";
3
4
 
@@ -246,6 +247,21 @@ function checkCustom(tool, err) {
246
247
  }
247
248
  }
248
249
 
250
+ // An MCP server's tool file. With the server's tools, it's a table of them, all on, each with
251
+ // `permission`. A tool the server adds later isn't in the table, so it gets the API's defaults: on, and
252
+ // asking before each call. Many servers won't list their tools until you've signed in, so with no tools
253
+ // it keeps `permission` for all of them, ready for the table: see listedMcpToolset.
254
+ export function mcpToolsetFile({ name, tools = [], permission = "always_ask" }) {
255
+ const front = { type: MCP_TOOLSET, mcp_server_name: name };
256
+ if (tools.length > 0) {
257
+ const rows = tools.map((tool) => `| \`${tool}\` | \`true\` | \`${permission}\` |`);
258
+ const body = ["Set Enabled to false to turn a tool off.", "", "## Tools", "", "| Name | Enabled | Permission |", "|---|---|---|", ...rows, ""].join("\n");
259
+ return `---\n${stringify(front)}---\n\n${body}`;
260
+ }
261
+ if (permission !== "always_ask") front.default_config = { permission_policy: { type: permission } };
262
+ return `---\n${stringify(front)}---\n\nEvery tool the server offers is on. Its tools get listed here once it's been signed in to.\n`;
263
+ }
264
+
249
265
  // The agentbook tools a folder turns on, as { file, toolset, name, description, input_schema,
250
266
  // permission }. `toolsets` is the catalog, { [toolset]: { tools: [{ name, description, input_schema }] } }.
251
267
  // A blank permission means `always_ask`, the safe choice for a tool with no policy of its own.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soft-boy/agentschema",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Markdown based AI agent schema",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cred.js CHANGED
@@ -1,9 +1,11 @@
1
- import { basename, dirname, relative, resolve, sep } from "node:path";
1
+ import { writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
2
3
  import Anthropic from "@anthropic-ai/sdk";
3
4
  import { check } from "./check.js";
4
5
  import { DeployError, call, openLock, retrieve } from "./deploy.js";
5
6
  import { LOCK_FILE, hashBody, writeLock } from "./lock.js";
6
- import { updateFrontmatter } from "./folder.js";
7
+ import { readFolder, updateFrontmatter } from "./folder.js";
8
+ import { listedMcpToolset } from "./mcp.js";
7
9
  import { authorizationRequest, discover, exchangeCode, registerClient, startCallbackServer } from "./oauth.js";
8
10
  import {
9
11
  ENV_VAR, VAULTS_DIR, VAULT_FILE, changedImmutableFields, credentialCreateBody, credentialKey, credentialSettings,
@@ -51,7 +53,7 @@ export async function credPaste(path, { client, ask, log = () => {} }) {
51
53
  };
52
54
  if (cred.data.auth.type === ENV_VAR) {
53
55
  const secretValue = await required(`Value of ${cred.data.auth.secret_name}: `);
54
- return createCredential({ dir, lock, vault, cred }, { secretValue }, { client, log });
56
+ return createCredential({ lock, vault, cred, secrets: { secretValue }, client, saveLock: (next) => writeLock(dir, next), log });
55
57
  }
56
58
  const secrets = { accessToken: await required("Access token: ") };
57
59
  const expiresAt = (await ask("Access token expires at (ISO 8601, e.g. 2026-12-31T23:59:59Z; blank if unknown): ", { secret: false })).trim();
@@ -62,19 +64,20 @@ export async function credPaste(path, { client, ask, log = () => {} }) {
62
64
  if (needs.refreshToken) secrets.refreshToken = await required("Refresh token: ");
63
65
  if (needs.clientSecret) secrets.clientSecret = await required("Client secret: ");
64
66
 
65
- return createCredential({ dir, lock, vault, cred }, secrets, { client, log });
67
+ return createCredential({ lock, vault, cred, secrets, client, saveLock: (next) => writeLock(dir, next), log });
66
68
  }
67
69
 
68
70
  // Creates a credential with its secrets, creating its vault first if needed, records it in the
69
- // lock, and asks the API to try it.
70
- async function createCredential({ dir, lock, vault, cred }, secrets, { client, log }) {
71
+ // lock, and asks the API to try it. `secrets` are what credentialCreateBody takes. Works on a lock
72
+ // object, so a host can keep it wherever it likes, and `saveLock` may be async.
73
+ export async function createCredential({ lock, vault, cred, secrets, client, saveLock = () => {}, log = () => {} }) {
71
74
  let vaultId = lock.resources[vaultKey(vault)]?.id;
72
75
  if (!vaultId) {
73
76
  const body = vaultBody(vault);
74
77
  const created = await call({ file: vault.path, kind: "vault" }, () => client.beta.vaults.create(body));
75
78
  vaultId = created.id;
76
79
  lock.resources[vaultKey(vault)] = { kind: "vault", id: vaultId, hash: hashBody(body) };
77
- writeLock(dir, lock);
80
+ await saveLock(lock);
78
81
  log(`created vault ${vaultId}`);
79
82
  }
80
83
 
@@ -82,7 +85,7 @@ async function createCredential({ dir, lock, vault, cred }, secrets, { client, l
82
85
  client.beta.vaults.credentials.create(vaultId, credentialCreateBody(cred, secrets)),
83
86
  );
84
87
  lock.resources[credentialKey(cred)] = { kind: "credential", id: created.id, vault_id: vaultId, hash: hashBody(credentialSettings(cred)) };
85
- writeLock(dir, lock);
88
+ await saveLock(lock);
86
89
  log(`created credential ${created.id}`);
87
90
 
88
91
  if (cred.data.auth.type === ENV_VAR) return created;
@@ -167,17 +170,26 @@ export async function credLogin(path, { client, ask, openBrowser, port = 0, fetc
167
170
 
168
171
  const secrets = { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, refreshToken: tokens.refreshToken, clientSecret };
169
172
  const { dir, vault, cred } = located;
173
+ await listToolsInFile(dir, auth.mcp_server_url, tokens.accessToken, { fetch, log });
170
174
  const lock = openLock(dir, client);
171
175
  const existing = lock.resources[credentialKey(cred)];
172
176
  if (existing && existing.vault_id === lock.resources[vaultKey(vault)]?.id) {
173
177
  return replaceTokens({ dir, lock, cred, entry: existing }, secrets, { client, log });
174
178
  }
175
- return createCredential({ dir, lock, vault, cred }, secrets, { client, log });
179
+ return createCredential({ lock, vault, cred, secrets, client, saveLock: (next) => writeLock(dir, next), log });
176
180
  } finally {
177
181
  await callback.close();
178
182
  }
179
183
  }
180
184
 
185
+ // Now that the server will say what it offers, lists its tools in their file.
186
+ async function listToolsInFile(dir, url, token, { fetch, log }) {
187
+ const listed = await listedMcpToolset(readFolder(dir), url, { fetch, token });
188
+ if (!listed) return;
189
+ writeFileSync(join(dir, listed.path), listed.text);
190
+ log(`Listed the server's tools in ${listed.path}.`);
191
+ }
192
+
181
193
  async function required(ask, question) {
182
194
  const answer = (await ask(question, { secret: true })).trim();
183
195
  if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
@@ -230,6 +242,15 @@ export async function credDelete(path, { client, confirm, log = () => {} }) {
230
242
  log("Cancelled.");
231
243
  return;
232
244
  }
245
+ await deleteCredential({ lock, cred, client, saveLock: (next) => writeLock(dir, next) });
246
+ log(`deleted credential ${entry.id}`);
247
+ }
248
+
249
+ // Permanently deletes a credential, if it has one, and removes it from the lock. One that's already
250
+ // gone counts as deleted. Works on a lock object, like createCredential.
251
+ export async function deleteCredential({ lock, cred, client, saveLock = () => {} }) {
252
+ const entry = lock.resources[credentialKey(cred)];
253
+ if (!entry) return;
233
254
  try {
234
255
  await client.beta.vaults.credentials.delete(entry.id, { vault_id: entry.vault_id });
235
256
  } catch (err) {
@@ -238,6 +259,5 @@ export async function credDelete(path, { client, confirm, log = () => {} }) {
238
259
  }
239
260
  }
240
261
  delete lock.resources[credentialKey(cred)];
241
- writeLock(dir, lock);
242
- log(`deleted credential ${entry.id}`);
262
+ await saveLock(lock);
243
263
  }
package/src/init.js CHANGED
@@ -3,6 +3,7 @@ import { basename, dirname, resolve } from "node:path";
3
3
  import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
4
4
  import { MODELS, NETWORKING, defaultAnswers, scaffold } from "../lib/scaffold.js";
5
5
  import { TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
6
+ import { choosePermission } from "./tools-menu.js";
6
7
  import { prompts } from "./prompts.js";
7
8
 
8
9
  export class InitError extends Error {}
@@ -41,6 +42,7 @@ async function ask(answers, input, output) {
41
42
  answers.model = await io.select("Model?", MODELS, answers.model);
42
43
  answers.system = await io.text("System prompt?", answers.system);
43
44
  answers.tools = await confirm("Give it the built-in tools (bash, files, web)?", answers.tools);
45
+ if (answers.tools) answers.permission = await choosePermission(io, answers.permission);
44
46
  answers.environment = await io.text("Environment name?", answers.environment);
45
47
  answers.networking = await io.select("Networking?", NETWORKING, answers.networking);
46
48
  if (answers.networking === "limited") {
package/src/mcp.js CHANGED
@@ -1,16 +1,20 @@
1
+ import { readTools, MCP_TOOLSET, mcpToolsetFile } from "../lib/tools.js";
2
+ import { readInstance } from "../lib/instance.js";
3
+
1
4
  // Just enough of the MCP client protocol (Streamable HTTP) to ask a server for its tools.
2
5
 
3
6
  const PROTOCOL_VERSION = "2025-06-18";
4
7
  const TIMEOUT_MS = 10_000;
5
8
 
6
- // The names of the tools an MCP server offers, sorted. Returns null when the server won't say
7
- // without signing in, or can't be reached. Sends no credentials.
8
- export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
9
+ // The names of the tools an MCP server offers, sorted. Returns null when the server won't say, or
10
+ // can't be reached. Many only say once you've signed in, so `token` is sent if it's given.
11
+ export async function listMcpTools(url, { fetch = globalThis.fetch, token, clientName = "agentschema" } = {}) {
9
12
  try {
10
13
  let sessionId = null;
11
14
  const send = async (message) => {
12
15
  const headers = { "content-type": "application/json", accept: "application/json, text/event-stream" };
13
16
  if (sessionId) headers["mcp-session-id"] = sessionId;
17
+ if (token) headers.authorization = `Bearer ${token}`;
14
18
  const res = await fetch(url, { method: "POST", headers, body: JSON.stringify(message), signal: AbortSignal.timeout(TIMEOUT_MS) });
15
19
  sessionId = res.headers.get("mcp-session-id") ?? sessionId;
16
20
  if (!res.ok) throw new Error(`status ${res.status}`);
@@ -21,7 +25,7 @@ export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
21
25
  jsonrpc: "2.0",
22
26
  id: 1,
23
27
  method: "initialize",
24
- params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "agentschema", version: "0" } },
28
+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: clientName, version: "0" } },
25
29
  });
26
30
  await send({ jsonrpc: "2.0", method: "notifications/initialized" });
27
31
 
@@ -39,6 +43,21 @@ export async function listMcpTools(url, { fetch = globalThis.fetch } = {}) {
39
43
  }
40
44
  }
41
45
 
46
+ // The tool file for the server at `url`, now listing its tools, once there's a way to ask. Returns
47
+ // { path, text }, or null if there's nothing to change: the file has a table already, so it may hold
48
+ // choices worth keeping, or the agent has no file for that server, or it won't say what it offers.
49
+ export async function listedMcpToolset(files, url, options = {}) {
50
+ const servers = readInstance(files).agent?.data.mcp_servers;
51
+ const server = Array.isArray(servers) ? servers.find((candidate) => candidate?.url === url) : null;
52
+ if (!server) return null;
53
+ const tool = readTools(files).tools.find((candidate) => candidate.data.type === MCP_TOOLSET && candidate.data.mcp_server_name === server.name);
54
+ if (!tool || tool.rows?.length) return null;
55
+
56
+ const names = await listMcpTools(url, options);
57
+ if (!names?.length) return null;
58
+ return { path: tool.file, text: mcpToolsetFile({ name: server.name, tools: names, permission: tool.data.default_config?.permission_policy?.type ?? "always_ask" }) };
59
+ }
60
+
42
61
  // A response is either plain JSON, or a stream of events with the JSON in a `data:` line.
43
62
  function parseResponse(text, id) {
44
63
  const trimmed = text.trim();
package/src/node.js CHANGED
@@ -1,7 +1,10 @@
1
1
  // What agentschema does on a server: anything that needs the API client, hashing or the disk. It
2
2
  // works on file maps and lock objects, so a host can keep both in a database.
3
3
  export { check } from "./check.js";
4
+ export { createCredential, deleteCredential } from "./cred.js";
4
5
  export { DeployError, deploy, deployFiles, prepareLock } from "./deploy.js";
5
6
  export { readFolder, updateFrontmatter } from "./folder.js";
6
7
  export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
+ export { listMcpTools, listedMcpToolset } from "./mcp.js";
9
+ export { OAuthError, authorizationRequest, discover, exchangeCode, registerClient } from "./oauth.js";
7
10
  export { Conversation, SessionError, openSession, startSession } from "./session.js";
package/src/oauth.js CHANGED
@@ -117,14 +117,14 @@ export async function startCallbackServer(port = 0) {
117
117
 
118
118
  const escape = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
119
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 } = {}) {
120
+ // Registers as an OAuth client (RFC 7591), for servers that allow it. `clientName` is what the
121
+ // provider shows on its sign-in page. Returns { clientId, clientSecret, authMethod }.
122
+ export async function registerClient(registrationEndpoint, redirectUri, { fetch = globalThis.fetch, clientName = "agentschema" } = {}) {
123
123
  const res = await fetch(registrationEndpoint, {
124
124
  method: "POST",
125
125
  headers: { "content-type": "application/json", accept: "application/json" },
126
126
  body: JSON.stringify({
127
- client_name: "agentschema",
127
+ client_name: clientName,
128
128
  redirect_uris: [redirectUri],
129
129
  grant_types: ["authorization_code", "refresh_token"],
130
130
  response_types: ["code"],
package/src/tools-menu.js CHANGED
@@ -8,7 +8,7 @@ import { AGENT_FILE, ENV_FILE } from "../lib/instance.js";
8
8
  import { builtInFile } from "../lib/scaffold.js";
9
9
  import { updateFrontmatter } from "./folder.js";
10
10
  import { listMcpTools } from "./mcp.js";
11
- import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR } from "../lib/tools.js";
11
+ import { MCP_TOOLSET, POLICIES, PREBUILT_TOOLS, TOOLSET, TOOLSET_FILE, TOOLS_DIR, mcpToolsetFile } from "../lib/tools.js";
12
12
 
13
13
  const PREBUILT = "Pre-built tools (bash, files, web search)";
14
14
  const CUSTOM = "Custom tool (JavaScript that runs on your machine)";
@@ -57,7 +57,7 @@ async function prebuilt(dir, { tools }, io) {
57
57
  enabled = [];
58
58
  for (const name of PREBUILT_TOOLS) if (await io.confirm(` ${name}?`, true)) enabled.push(name);
59
59
  }
60
- return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled) };
60
+ return { path: `${TOOLS_DIR}/${TOOLSET_FILE}`, text: builtInFile(PREBUILT_TOOLS, enabled, await choosePermission(io, "auto")) };
61
61
  }
62
62
 
63
63
  // A custom tool: its name, description and inputs, with a code block to fill in.
@@ -138,28 +138,20 @@ async function mcp(dir, instance, io, { fetch, log }) {
138
138
  });
139
139
  const addServer = existing ? null : { type: "url", name, url };
140
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);
141
+ const permission = await choosePermission(io, "always_ask");
144
142
 
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
143
  log(`Asking ${url} for its tools…`);
148
144
  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
- }
145
+ if (names) log(`It has ${names.length} tool${names.length === 1 ? "" : "s"}.`);
146
+ else log("It won't list its tools without signing in, so they'll be listed once you have; until then, every tool is on.");
147
+ return { path: `${TOOLS_DIR}/${name}.md`, text: mcpToolsetFile({ name, tools: names ?? [], permission }), addServer };
148
+ }
156
149
 
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 };
150
+ // Asks how a set of tools should be approved, offering `recommended` first.
151
+ export async function choosePermission(io, recommended) {
152
+ const policies = [recommended, ...POLICIES.filter((p) => p !== recommended)];
153
+ const answer = await io.select("Ask you before each call? (permission for its tools)", policies.map(describePolicy), describePolicy(recommended));
154
+ return policies.find((p) => describePolicy(p) === answer);
163
155
  }
164
156
 
165
157
  function describePolicy(policy) {