@soft-boy/agentschema 0.2.1 → 0.3.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/src/check.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { AGENT_FILE, ENV_FILE, readInstance } from "./instance.js";
2
- import { TOOLS_DIR, checkTools, readTools } from "./tools.js";
2
+ import { MAX_UPLOAD_BYTES, SKILLS_DIR, readSkills } from "./skills.js";
3
+ import { MCP_TOOLSET, TOOLS_DIR, checkTools, readTools } from "./tools.js";
4
+ import { CREDENTIAL_TYPES, ENV_VAR, SECRET_FIELDS, TOKEN_ENDPOINT_AUTH, VAULT_FILE, get, readVaults } from "./vaults.js";
3
5
 
4
6
  const AGENT_FIELDS = new Set([
5
7
  "name", "model", "description", "mcp_servers", "skills",
@@ -22,20 +24,32 @@ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v)
22
24
  export function check(dir) {
23
25
  const { agent, env, errors } = readInstance(dir);
24
26
  const { tools, errors: toolErrors } = readTools(dir);
25
- errors.push(...toolErrors);
27
+ const { vaults, errors: vaultErrors } = readVaults(dir);
28
+ const { skills, errors: skillErrors } = readSkills(dir);
29
+ errors.push(...toolErrors, ...vaultErrors, ...skillErrors);
26
30
  const warnings = [];
27
31
 
28
32
  if (agent) checkAgent(agent, errors, warnings);
29
33
  if (env) checkEnv(env, errors, warnings);
30
34
  checkTools(tools, errors);
31
- for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t])]) {
35
+ if (agent) checkMcpServers(agent, tools, errors);
36
+ if (agent && env) checkMcpNetworking(agent, env, warnings);
37
+ for (const skill of skills) checkSkill(skill, errors);
38
+ const declaredSkills = Array.isArray(agent?.data.skills) ? agent.data.skills.length : 0;
39
+ if (declaredSkills + skills.length > 500) errors.push(`${declaredSkills + skills.length} skills; the limit is 500`);
40
+ for (const vault of vaults) checkVault(vault, errors, warnings);
41
+ checkEnvVarCredentials(vaults, env, warnings);
42
+
43
+ const vaultFiles = vaults.flatMap((v) => [...(v.file ? [[`${v.path}/${VAULT_FILE}`, v.file]] : []), ...v.credentials.map((c) => [c.file, c])]);
44
+ const skillTexts = skills.flatMap((s) => s.files.map((f) => [`${s.path}/${f.rel}`, { raw: f.bytes.toString("utf8") }]));
45
+ for (const [file, parsed] of [[AGENT_FILE, agent], [ENV_FILE, env], ...tools.map((t) => [t.file, t]), ...vaultFiles, ...skillTexts]) {
32
46
  if (!parsed) continue;
33
47
  for (const [pattern, what] of SECRET_PATTERNS) {
34
48
  if (pattern.test(parsed.raw)) errors.push(`${file}: looks like it contains ${what}; keep secrets out of these files`);
35
49
  }
36
50
  }
37
51
 
38
- return { errors, warnings, instance: agent && env ? { agent, env, tools } : null };
52
+ return { errors, warnings, instance: agent && env ? { agent, env, tools, vaults, skills } : null };
39
53
  }
40
54
 
41
55
  function checkAgent({ data, body }, errors, warnings) {
@@ -65,6 +79,10 @@ function checkAgent({ data, body }, errors, warnings) {
65
79
  else if (data[field].length > max) err(`\`${field}\` has ${data[field].length} entries; the limit is ${max}`);
66
80
  }
67
81
 
82
+ if (Array.isArray(data.skills)) {
83
+ for (const [index, skill] of data.skills.entries()) checkSkillRef(skill, (msg) => err(`\`skills[${index}]\`: ${msg}`));
84
+ }
85
+
68
86
  checkMetadata(data.metadata, 16, err);
69
87
 
70
88
  for (const key of Object.keys(data)) {
@@ -102,6 +120,238 @@ function checkEnv({ data }, errors, warnings) {
102
120
  }
103
121
  }
104
122
 
123
+ // An entry in agent.md's `skills` list, in the API's shape.
124
+ function checkSkillRef(skill, err) {
125
+ if (typeof skill === "string") {
126
+ return err(`write this as a mapping with \`type\` and \`skill_id\`; a skill in ${SKILLS_DIR}/ is attached without being listed`);
127
+ }
128
+ if (!isObject(skill)) return err("must be a mapping with `type` and `skill_id`");
129
+ if (!["anthropic", "custom"].includes(skill.type)) err("`type` must be `anthropic` or `custom`");
130
+ if (typeof skill.skill_id !== "string" || skill.skill_id === "") err("`skill_id` is required");
131
+ else if (skill.type === "custom" && !skill.skill_id.startsWith("skill_")) err("a custom skill's `skill_id` starts with skill_");
132
+ if (skill.version !== undefined && skill.version !== null && typeof skill.version !== "string") {
133
+ err("`version` must be a string (quote numbers)");
134
+ }
135
+ }
136
+
137
+ function checkSkill(skill, errors) {
138
+ const err = (msg) => errors.push(`${skill.file}: ${msg}`);
139
+ const { name, description } = skill.data;
140
+ if (typeof name !== "string" || name === "") err("`name` is required");
141
+ else {
142
+ if (name !== skill.name) err(`\`name\` must match the folder's name (${skill.name})`);
143
+ if (!/^[a-z0-9-]{1,64}$/.test(name)) err("`name` may only use lowercase letters, digits and hyphens, up to 64 characters");
144
+ if (/anthropic|claude/.test(name)) err("`name` can't contain the reserved words `anthropic` or `claude`");
145
+ }
146
+ if (typeof description !== "string" || description.trim() === "") err("`description` is required");
147
+ else {
148
+ if (description.length > 1024) err(`\`description\` is ${description.length} characters; the limit is 1,024`);
149
+ if (/<[^>]+>/.test(description)) err("`description` can't contain XML tags");
150
+ }
151
+ const size = skill.files.reduce((total, f) => total + f.bytes.length, 0);
152
+ if (size > MAX_UPLOAD_BYTES) errors.push(`${skill.path}: its files add up to ${Math.ceil(size / 1024 / 1024)} MB; the limit is 30 MB`);
153
+ }
154
+
155
+ const mcpServers = (agent) => (Array.isArray(agent.data.mcp_servers) ? agent.data.mcp_servers.filter(isObject) : []);
156
+
157
+ // Each server agent.md declares needs a toolset file, and each toolset file a declared server;
158
+ // the API rejects an agent otherwise.
159
+ function checkMcpServers(agent, tools, errors) {
160
+ const err = (msg) => errors.push(`${AGENT_FILE}: ${msg}`);
161
+ const names = new Set();
162
+ for (const server of mcpServers(agent)) {
163
+ const label = typeof server.name === "string" && server.name ? `\`${server.name}\`` : "an entry";
164
+ if (server.type !== "url") err(`\`mcp_servers\`: ${label} must have \`type: url\``);
165
+ if (typeof server.name !== "string" || server.name === "" || server.name.length > 255) {
166
+ err("`mcp_servers`: each server needs a `name` of 1 to 255 characters");
167
+ } else if (names.has(server.name)) {
168
+ err(`\`mcp_servers\`: \`${server.name}\` is declared twice`);
169
+ }
170
+ if (typeof server.url !== "string" || !/^https?:\/\/\S+$/.test(server.url) || server.url.length > 2048) {
171
+ err(`\`mcp_servers\`: ${label} needs a \`url\`, an http(s) URL of at most 2048 characters`);
172
+ }
173
+ names.add(server.name);
174
+ }
175
+
176
+ const toolsets = tools.filter((t) => t.data.type === MCP_TOOLSET);
177
+ const covered = new Set(toolsets.map((t) => t.data.mcp_server_name));
178
+ for (const name of names) {
179
+ if (typeof name === "string" && name && !covered.has(name)) {
180
+ err(`\`mcp_servers\`: \`${name}\` has no toolset; add ${TOOLS_DIR}/${name}.md with \`type: mcp_toolset\`, or the API rejects the agent`);
181
+ }
182
+ }
183
+ for (const toolset of toolsets) {
184
+ const name = toolset.data.mcp_server_name;
185
+ if (typeof name === "string" && name && !names.has(name)) {
186
+ errors.push(`${toolset.file}: \`${name}\` isn't in ${AGENT_FILE}'s \`mcp_servers\``);
187
+ }
188
+ }
189
+ }
190
+
191
+ // A limited network blocks MCP servers that aren't allowed, and the API then refuses to start sessions.
192
+ function checkMcpNetworking(agent, env, warnings) {
193
+ const net = env.data.config?.networking;
194
+ if (net?.type !== "limited" || net.allow_mcp_servers === true) return;
195
+ const allowed = net.allowed_hosts ?? [];
196
+ for (const server of mcpServers(agent)) {
197
+ let host;
198
+ try {
199
+ host = new URL(server.url).host;
200
+ } catch {
201
+ continue;
202
+ }
203
+ if (!allowed.includes(host)) {
204
+ warnings.push(
205
+ `${ENV_FILE}: its limited networking doesn't allow MCP server \`${server.name}\` (${host}), so sessions won't start; ` +
206
+ `set config.networking.allow_mcp_servers to true, or add ${host} to allowed_hosts`,
207
+ );
208
+ }
209
+ }
210
+ }
211
+
212
+ function checkVault(vault, errors, warnings) {
213
+ if (vault.name.length > 255) errors.push(`${vault.path}: a vault's name (its folder name) must be at most 255 characters`);
214
+
215
+ if (vault.file) {
216
+ const file = `${vault.path}/${VAULT_FILE}`;
217
+ const err = (msg) => errors.push(`${file}: ${msg}`);
218
+ const { data } = vault.file;
219
+ if ("display_name" in data) err("`display_name` is not allowed; the folder name is the vault's name");
220
+ checkMetadata(data.metadata, 16, err);
221
+ for (const key of Object.keys(data)) {
222
+ if (key !== "metadata" && key !== "display_name") warnings.push(`${file}: unknown field \`${key}\` will be sent to the API as written`);
223
+ }
224
+ }
225
+
226
+ if (vault.credentials.length > 20) errors.push(`${vault.path}: ${vault.credentials.length} credentials; a vault holds at most 20`);
227
+ const urls = new Map();
228
+ const secretNames = new Map();
229
+ for (const cred of vault.credentials) {
230
+ checkCredential(cred, errors, warnings);
231
+ const url = cred.data.auth?.mcp_server_url;
232
+ if (typeof url === "string") {
233
+ if (urls.has(url)) errors.push(`${cred.file}: ${urls.get(url)} is already a credential for ${url}; a vault holds one per server`);
234
+ else urls.set(url, cred.file);
235
+ }
236
+ const secretName = cred.data.auth?.secret_name;
237
+ if (typeof secretName === "string") {
238
+ if (secretNames.has(secretName)) errors.push(`${cred.file}: ${secretNames.get(secretName)} already sets ${secretName}; a vault holds one per variable`);
239
+ else secretNames.set(secretName, cred.file);
240
+ }
241
+ }
242
+ }
243
+
244
+ // What an environment variable credential depends on outside its own file.
245
+ function checkEnvVarCredentials(vaults, env, warnings) {
246
+ const creds = vaults.flatMap((v) => v.credentials).filter((c) => c.data.auth?.type === ENV_VAR);
247
+ const net = env?.data.config?.networking;
248
+ const seen = new Map();
249
+ for (const cred of creds) {
250
+ const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
251
+ const { secret_name: name, networking } = cred.data.auth;
252
+
253
+ // Two vaults can both set a variable, but the docs don't say which one wins.
254
+ if (typeof name === "string") {
255
+ if (seen.has(name) && seen.get(name).vault !== cred.vault) warn(`${seen.get(name).file} also sets ${name}, and the API doesn't document which vault wins`);
256
+ else seen.set(name, cred);
257
+ }
258
+
259
+ if (env?.data.config?.type === "self_hosted") warn("environment variable credentials aren't supported on self-hosted environments yet");
260
+
261
+ // allowed_hosts only decides where the secret is substituted; the environment decides what's reachable.
262
+ if (net?.type === "limited" && networking?.type === "limited" && Array.isArray(networking.allowed_hosts)) {
263
+ for (const host of networking.allowed_hosts) {
264
+ if (!(net.allowed_hosts ?? []).includes(host)) {
265
+ warn(`${ENV_FILE}'s limited networking doesn't allow ${host}, so requests to it will be blocked; add it to allowed_hosts in ${ENV_FILE}`);
266
+ }
267
+ }
268
+ }
269
+ }
270
+ }
271
+
272
+ function checkCredential(cred, errors, warnings) {
273
+ const err = (msg) => errors.push(`${cred.file}: ${msg}`);
274
+ const warn = (msg) => warnings.push(`${cred.file}: ${msg}`);
275
+ const { data } = cred;
276
+ if (cred.name.length > 255) err("a credential's name (its file name) must be at most 255 characters");
277
+ if ("display_name" in data) err("`display_name` is not allowed; the file name is the credential's name");
278
+ checkMetadata(data.metadata, 16, err);
279
+ for (const key of Object.keys(data)) {
280
+ if (!["auth", "metadata", "display_name"].includes(key)) warn(`unknown field \`${key}\` will be sent to the API as written`);
281
+ }
282
+
283
+ const { auth } = data;
284
+ if (!isObject(auth)) return err("`auth` is required");
285
+ if (!CREDENTIAL_TYPES.includes(auth.type)) return err(`\`auth.type\` must be ${CREDENTIAL_TYPES.map((t) => `\`${t}\``).join(" or ")}; other credential types aren't supported yet`);
286
+
287
+ for (const path of SECRET_FIELDS[auth.type]) {
288
+ if (get(auth, path) !== undefined) {
289
+ err(`\`auth.${path.join(".")}\` doesn't go in the file; \`agentschema cred deploy\` asks for it and sends it straight to the vault`);
290
+ }
291
+ }
292
+
293
+ if (auth.type === ENV_VAR) return checkEnvVarAuth(auth, err, warn);
294
+
295
+ const url = (value, field) => {
296
+ if (typeof value !== "string" || value === "") return err(`\`${field}\` is required`);
297
+ if (!/^https?:\/\/\S+$/.test(value)) err(`\`${field}\` must be an http(s) URL`);
298
+ };
299
+ url(auth.mcp_server_url, "auth.mcp_server_url");
300
+ for (const key of Object.keys(auth)) {
301
+ if (!["type", "mcp_server_url", "refresh", "access_token", "expires_at"].includes(key)) {
302
+ warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
303
+ }
304
+ }
305
+
306
+ if (auth.refresh === undefined || auth.refresh === null) return;
307
+ const { refresh } = auth;
308
+ if (!isObject(refresh)) return err("`auth.refresh` must be a mapping");
309
+ url(refresh.token_endpoint, "auth.refresh.token_endpoint");
310
+ if (typeof refresh.client_id !== "string" || refresh.client_id === "") err("`auth.refresh.client_id` is required, as a string (quote it if it looks like a number)");
311
+ for (const field of ["scope", "resource"]) {
312
+ if (refresh[field] !== undefined && typeof refresh[field] !== "string") err(`\`auth.refresh.${field}\` must be a string`);
313
+ }
314
+ if (!isObject(refresh.token_endpoint_auth) || !TOKEN_ENDPOINT_AUTH.includes(refresh.token_endpoint_auth.type)) {
315
+ err(`\`auth.refresh.token_endpoint_auth.type\` must be ${TOKEN_ENDPOINT_AUTH.map((t) => `\`${t}\``).join(", ")}`);
316
+ }
317
+ for (const key of Object.keys(refresh)) {
318
+ if (!["token_endpoint", "client_id", "scope", "resource", "token_endpoint_auth", "refresh_token"].includes(key)) {
319
+ warn(`unknown field \`auth.refresh.${key}\` will be sent to the API as written`);
320
+ }
321
+ }
322
+ }
323
+
324
+ function checkEnvVarAuth(auth, err, warn) {
325
+ if (typeof auth.secret_name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(auth.secret_name)) {
326
+ err("`auth.secret_name` is required, and must be a variable name like STRIPE_API_KEY");
327
+ }
328
+
329
+ const { networking: net, injection_location: where } = auth;
330
+ if (!isObject(net) || !["limited", "unrestricted"].includes(net.type)) {
331
+ err("`auth.networking.type` is required, and must be `limited` or `unrestricted`");
332
+ } else if (net.type === "unrestricted") {
333
+ warn("`auth.networking` is `unrestricted`, so the secret is substituted on requests to any host; a prompt-injected agent could send it anywhere");
334
+ } else if (!Array.isArray(net.allowed_hosts) || net.allowed_hosts.length === 0 || net.allowed_hosts.some((h) => typeof h !== "string" || h === "")) {
335
+ err("`auth.networking.allowed_hosts` must list the hosts the secret may be sent to");
336
+ }
337
+
338
+ if (where !== undefined && where !== null) {
339
+ if (!isObject(where)) err("`auth.injection_location` must be a mapping");
340
+ else {
341
+ for (const field of ["header", "body"]) {
342
+ if (where[field] !== undefined && typeof where[field] !== "boolean") err(`\`auth.injection_location.${field}\` must be true or false`);
343
+ }
344
+ if (where.header !== true && where.body !== true) err("`auth.injection_location` must enable `header` or `body`; a field you leave out is false");
345
+ }
346
+ }
347
+
348
+ for (const key of Object.keys(auth)) {
349
+ if (!["type", "secret_name", "secret_value", "networking", "injection_location"].includes(key)) {
350
+ warn(`unknown field \`auth.${key}\` will be sent to the API as written`);
351
+ }
352
+ }
353
+ }
354
+
105
355
  function checkMetadata(metadata, maxKeys, err) {
106
356
  if (metadata === undefined) return;
107
357
  if (!isObject(metadata)) return err("`metadata` must be a mapping");
@@ -0,0 +1,197 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { stringify } from "yaml";
4
+ import { check } from "./check.js";
5
+ import { credLogin, credPaste, locate } from "./cred.js";
6
+ import { DeployError } from "./deploy.js";
7
+ import { discover } from "./oauth.js";
8
+ import { ENV_VAR, TOKEN_ENDPOINT_AUTH, VAULTS_DIR, VAULT_FILE } from "./vaults.js";
9
+
10
+ const SIGN_IN = "Sign in with the browser";
11
+ const PASTE = "Paste the tokens";
12
+ const PASTE_VALUE = "Paste the value";
13
+ const LATER = "Just write the file";
14
+ const NEW_VAULT = "New vault…";
15
+ const OTHER_URL = "Another URL…";
16
+ const FOR_MCP = "An MCP server's sign-in (OAuth)";
17
+ const FOR_ENV_VAR = "An environment variable (an API key, say)";
18
+ const HEADERS_ONLY = "Request headers only";
19
+ const HEADERS_AND_BODY = "Headers and body";
20
+
21
+ // `cred create`: asks which vault the credential goes in and what it's for, writes its file,
22
+ // then gets its secrets and creates it, unless you'd rather do that later with `cred deploy`.
23
+ export async function credCreate(dir = ".", options) {
24
+ const { io, fetch = globalThis.fetch, log = () => {} } = options;
25
+ if (dir.endsWith(".md")) {
26
+ throw new DeployError(`cred create takes the agent folder; to create the credential ${dir} describes, run agentschema cred deploy ${dir}`);
27
+ }
28
+ const { file, method } = await writeCredentialFile(dir, { io, fetch, log });
29
+ if (method === LATER) {
30
+ log(`\nCreate the credential in Anthropic when you're ready with:\n agentschema cred deploy ${file}`);
31
+ return null;
32
+ }
33
+ return getTokens(file, method, options);
34
+ }
35
+
36
+ // `cred deploy`: creates the credential a file describes in Anthropic, asking whether to sign
37
+ // in for its tokens or paste them.
38
+ export async function credDeploy(file, options) {
39
+ if (!existsSync(file)) throw new DeployError(`${file}: no such file; to write a new credential file, run agentschema cred create`);
40
+ const { cred } = locate(file);
41
+ // An environment variable has no sign-in, so there's only its value to ask for.
42
+ const method = cred.data.auth.type === ENV_VAR ? PASTE : await options.io.select("How do you want to get its tokens?", [SIGN_IN, PASTE], SIGN_IN);
43
+ return getTokens(file, method, options);
44
+ }
45
+
46
+ // Tokens come from signing in (`cred login`) or from pasting them (`credPaste`).
47
+ function getTokens(file, method, { client, io, openBrowser, port = 0, fetch = globalThis.fetch, log = () => {} }) {
48
+ const ask = (question, { secret }) => (secret ? io.secret(question.trim()) : io.text(question.trim()));
49
+ return method === SIGN_IN
50
+ ? credLogin(file, { client, ask, openBrowser, port, fetch, log })
51
+ : credPaste(file, { client, ask, log });
52
+ }
53
+
54
+ // Asks about the credential, and writes vaults/<vault>/<name>.md. Returns { file, method }.
55
+ async function writeCredentialFile(dir, { io, fetch, log }) {
56
+ const { errors, instance } = check(dir);
57
+ if (!instance) throw new DeployError(`${dir} isn't an agent folder:\n ${errors.join("\n ")}`);
58
+ if (errors.length > 0) throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
59
+
60
+ // The vault: an existing one, or a new folder.
61
+ const names = instance.vaults.map((v) => v.name);
62
+ let vaultName = names.length > 0 ? await io.select("Which vault?", [...names, NEW_VAULT], names[0]) : NEW_VAULT;
63
+ if (vaultName === NEW_VAULT) {
64
+ vaultName = await io.text("New vault's name?", names.includes("Shared") ? "" : "Shared", {
65
+ validate: (name) => fileName(name, "vault") ?? (names.includes(name) ? `There's already a vault called ${name}` : null),
66
+ });
67
+ }
68
+ const vault = instance.vaults.find((v) => v.name === vaultName);
69
+ const vaultDir = join(dir, VAULTS_DIR, vaultName);
70
+ const kind = await io.select("What is it for?", [FOR_MCP, FOR_ENV_VAR], FOR_MCP);
71
+ const { name, auth, method } = kind === FOR_ENV_VAR
72
+ ? await envVarCredential({ io, vault, vaultName, vaultDir })
73
+ : await mcpCredential({ io, instance, vault, vaultName, vaultDir, fetch, log });
74
+
75
+ mkdirSync(vaultDir, { recursive: true });
76
+ const file = join(vaultDir, `${name}.md`);
77
+ writeFileSync(file, `---\n${stringify({ auth })}---\n`);
78
+ log(`Wrote ${file}`);
79
+
80
+ const rel = `${VAULTS_DIR}/${vaultName}/${name}.md`;
81
+ for (const warning of check(dir).warnings.filter((w) => w.startsWith(rel))) log(`warning: ${warning}`);
82
+ return { file, method };
83
+ }
84
+
85
+ // An environment variable: its name, the hosts that may receive it, and where it can appear.
86
+ async function envVarCredential({ io, vault, vaultName, vaultDir }) {
87
+ const taken = new Set(vault?.credentials.map((c) => c.data.auth?.secret_name) ?? []);
88
+ const secretName = await io.text("Variable name? (like STRIPE_API_KEY)", "", {
89
+ validate: (n) => {
90
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)) return "Use letters, digits and _, not starting with a digit";
91
+ return taken.has(n) ? `${vaultName} already sets ${n}` : null;
92
+ },
93
+ });
94
+ const hosts = await io.text("Which hosts may it be sent to? (like api.stripe.com; separate several with spaces)", "", {
95
+ validate: (h) => {
96
+ const list = h.split(/[\s,]+/).filter(Boolean);
97
+ if (list.length === 0) return "List at least one host";
98
+ return list.some((x) => x.includes("/")) ? "Enter host names, without https:// or a path" : null;
99
+ },
100
+ });
101
+ const where = await io.select("Where in a request can it appear?", [HEADERS_ONLY, HEADERS_AND_BODY], HEADERS_ONLY);
102
+ const name = await io.text("Credential name?", secretName, {
103
+ validate: (n) => fileName(n, "credential") ?? (existsSync(join(vaultDir, `${n}.md`)) ? `${vaultName}/${n}.md already exists` : null),
104
+ });
105
+ const method = await io.select("How do you want to set its value?", [PASTE_VALUE, LATER], PASTE_VALUE);
106
+ return {
107
+ name,
108
+ method: method === PASTE_VALUE ? PASTE : LATER,
109
+ auth: {
110
+ type: ENV_VAR,
111
+ secret_name: secretName,
112
+ networking: { type: "limited", allowed_hosts: hosts.split(/[\s,]+/).filter(Boolean) },
113
+ injection_location: { header: true, body: where === HEADERS_AND_BODY },
114
+ },
115
+ };
116
+ }
117
+
118
+ // An MCP server's sign-in: the server, a name, and how its tokens will be fetched.
119
+ async function mcpCredential({ io, instance, vault, vaultName, vaultDir, fetch, log }) {
120
+ const taken = new Set(vault?.credentials.map((c) => c.data.auth?.mcp_server_url) ?? []);
121
+
122
+ // The MCP server: one agent.md declares, or any URL.
123
+ const servers = (instance.agent.data.mcp_servers ?? []).filter((s) => typeof s?.url === "string" && !taken.has(s.url));
124
+ const label = (s) => `${s.name ?? s.url} (${s.url})`;
125
+ let url = OTHER_URL;
126
+ if (servers.length > 0) {
127
+ const picked = await io.select("Which MCP server is it for?", [...servers.map(label), OTHER_URL], label(servers[0]));
128
+ url = servers.find((s) => label(s) === picked)?.url ?? OTHER_URL;
129
+ }
130
+ if (url === OTHER_URL) {
131
+ url = await io.text("MCP server URL?", "", {
132
+ validate: (u) => (!/^https?:\/\/\S+$/.test(u) ? "Enter an http(s) URL" : taken.has(u) ? `${vaultName} already has a credential for ${u}` : null),
133
+ });
134
+ }
135
+
136
+ const suggested = servers.find((s) => s.url === url)?.name ?? serviceName(url);
137
+ const name = await io.text("Credential name?", suggested, {
138
+ validate: (n) => fileName(n, "credential") ?? (existsSync(join(vaultDir, `${n}.md`)) ? `${vaultName}/${n}.md already exists` : null),
139
+ });
140
+
141
+ // How its tokens will be fetched decides what the file needs.
142
+ log(`Looking up the sign-in for ${url}…`);
143
+ const server = await discover(url, { fetch }).catch(() => null);
144
+ if (!server) log("It doesn't publish an OAuth sign-in, so you'll paste its tokens.");
145
+ const method = await io.select("How do you want to get its tokens?", server ? [SIGN_IN, PASTE, LATER] : [PASTE, LATER], server ? SIGN_IN : PASTE);
146
+
147
+ const auth = { type: "mcp_oauth", mcp_server_url: url };
148
+ if (server && method !== PASTE) {
149
+ // Signing in registers agentschema as a client where the server allows it; elsewhere, it
150
+ // needs your own OAuth client.
151
+ if (!server.registrationEndpoint) {
152
+ log(`${server.issuer} doesn't let apps register themselves, so sign-in needs your own OAuth client.`);
153
+ log("Create one with the provider, allowing the redirect URI http://127.0.0.1:<port>/callback.");
154
+ auth.refresh = await refreshBlock(io, server, { tokenEndpoint: server.tokenEndpoint });
155
+ }
156
+ } else if (method === PASTE && (await io.confirm("Can the access token be refreshed? (needs a refresh token and the OAuth client's details)", Boolean(server)))) {
157
+ auth.refresh = await refreshBlock(io, server, {});
158
+ }
159
+
160
+ return { name, auth, method };
161
+ }
162
+
163
+ // The client details for the file's auth.refresh block.
164
+ async function refreshBlock(io, server, { tokenEndpoint }) {
165
+ const refresh = {};
166
+ refresh.token_endpoint = tokenEndpoint ?? (await io.text("Token endpoint?", server?.tokenEndpoint ?? "", {
167
+ validate: (u) => (/^https?:\/\/\S+$/.test(u) ? null : "Enter an http(s) URL"),
168
+ }));
169
+ refresh.client_id = await io.text("OAuth client ID?", "", { validate: (id) => (id ? null : "The client ID is required") });
170
+ const supported = server?.scopesSupported ?? [];
171
+ const hint = supported.length > 0 ? ` (supported: ${supported.slice(0, 6).join(" ")}${supported.length > 6 ? " …" : ""})` : "";
172
+ const scope = await io.text(`Scopes, separated by spaces${hint}?`, "");
173
+ if (scope) refresh.scope = scope;
174
+ const type = await io.select("How does the client authenticate to the token endpoint?", TOKEN_ENDPOINT_AUTH, "client_secret_post");
175
+ refresh.token_endpoint_auth = { type };
176
+ return refresh;
177
+ }
178
+
179
+ // Why a vault or credential name can't be a file name, or nothing when it can.
180
+ function fileName(name, what) {
181
+ if (!name) return `The ${what} needs a name`;
182
+ if (/[/\\]/.test(name) || name.startsWith(".")) return `A ${what} name can't contain / or start with .`;
183
+ if (what === "credential" && `${name}.md` === VAULT_FILE) return "vault is reserved for vault.md";
184
+ if (name.length > 255) return `A ${what} name can be at most 255 characters`;
185
+ return null;
186
+ }
187
+
188
+ // "Linear" for https://mcp.linear.app/mcp: the host's main label, capitalized.
189
+ export function serviceName(url) {
190
+ const labels = new URL(url).hostname.split(".").filter((l) => !["mcp", "api", "www"].includes(l));
191
+ let main = labels.length >= 2 ? labels[labels.length - 2] : (labels[0] ?? "credential");
192
+ // A cloud's shared domain names the cloud, not the service: calendarmcp.googleapis.com.
193
+ if (["googleapis", "amazonaws", "azure", "azurewebsites", "cloudflare", "workers"].includes(main) && labels.length > 2) {
194
+ main = labels[0].replace(/-?mcp$/, "") || main;
195
+ }
196
+ return main.replace(/^./, (c) => c.toUpperCase());
197
+ }