@soft-boy/agentschema 0.3.3 → 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.3",
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,
@@ -168,6 +170,7 @@ export async function credLogin(path, { client, ask, openBrowser, port = 0, fetc
168
170
 
169
171
  const secrets = { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt, refreshToken: tokens.refreshToken, clientSecret };
170
172
  const { dir, vault, cred } = located;
173
+ await listToolsInFile(dir, auth.mcp_server_url, tokens.accessToken, { fetch, log });
171
174
  const lock = openLock(dir, client);
172
175
  const existing = lock.resources[credentialKey(cred)];
173
176
  if (existing && existing.vault_id === lock.resources[vaultKey(vault)]?.id) {
@@ -179,6 +182,14 @@ export async function credLogin(path, { client, ask, openBrowser, port = 0, fetc
179
182
  }
180
183
  }
181
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
+
182
193
  async function required(ask, question) {
183
194
  const answer = (await ask(question, { secret: true })).trim();
184
195
  if (!answer) throw new DeployError(`${question.replace(/:\s*$/, "")} is required`);
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
@@ -5,5 +5,6 @@ export { createCredential, deleteCredential } from "./cred.js";
5
5
  export { DeployError, deploy, deployFiles, prepareLock } from "./deploy.js";
6
6
  export { readFolder, updateFrontmatter } from "./folder.js";
7
7
  export { LOCK_FILE, hashBody, readLock, skillFingerprint, writeLock } from "./lock.js";
8
+ export { listMcpTools, listedMcpToolset } from "./mcp.js";
8
9
  export { OAuthError, authorizationRequest, discover, exchangeCode, registerClient } from "./oauth.js";
9
10
  export { Conversation, SessionError, openSession, startSession } from "./session.js";
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) {