@soft-boy/agentschema 0.4.0 → 0.5.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/README.md +8 -2
- package/dist/bin/agentschema.d.ts +2 -0
- package/dist/bin/agentschema.js +333 -0
- package/dist/lib/channels.d.ts +65 -0
- package/dist/lib/channels.js +339 -0
- package/dist/lib/check.d.ts +10 -0
- package/dist/lib/check.js +411 -0
- package/dist/lib/files.d.ts +7 -0
- package/{lib → dist/lib}/files.js +10 -14
- package/dist/lib/index.d.ts +24 -0
- package/{lib → dist/lib}/index.js +3 -12
- package/dist/lib/instance.d.ts +41 -0
- package/dist/lib/instance.js +74 -0
- package/dist/lib/markdown.d.ts +11 -0
- package/dist/lib/markdown.js +38 -0
- package/dist/lib/scaffold.d.ts +15 -0
- package/dist/lib/scaffold.js +46 -0
- package/dist/lib/scheduled.d.ts +56 -0
- package/dist/lib/scheduled.js +185 -0
- package/dist/lib/skills.d.ts +28 -0
- package/dist/lib/skills.js +55 -0
- package/dist/lib/stream.d.ts +30 -0
- package/dist/lib/stream.js +56 -0
- package/dist/lib/system-prompt.d.ts +16 -0
- package/{lib → dist/lib}/system-prompt.js +14 -15
- package/dist/lib/tools.d.ts +105 -0
- package/dist/lib/tools.js +353 -0
- package/dist/lib/vaults.d.ts +55 -0
- package/dist/lib/vaults.js +143 -0
- package/dist/src/chat.d.ts +15 -0
- package/dist/src/chat.js +159 -0
- package/dist/src/check.d.ts +2 -0
- package/dist/src/check.js +14 -0
- package/dist/src/cred-menu.d.ts +17 -0
- package/dist/src/cred-menu.js +193 -0
- package/dist/src/cred.d.ts +54 -0
- package/dist/src/cred.js +252 -0
- package/dist/src/custom-tools.d.ts +3 -0
- package/dist/src/custom-tools.js +18 -0
- package/dist/src/delete.d.ts +9 -0
- package/dist/src/delete.js +27 -0
- package/dist/src/deploy.d.ts +62 -0
- package/dist/src/deploy.js +442 -0
- package/dist/src/dotenv.d.ts +7 -0
- package/dist/src/dotenv.js +54 -0
- package/dist/src/folder.d.ts +5 -0
- package/{src → dist/src}/folder.js +30 -28
- package/dist/src/init.d.ts +11 -0
- package/dist/src/init.js +51 -0
- package/dist/src/list.d.ts +3 -0
- package/dist/src/list.js +46 -0
- package/dist/src/lock.d.ts +10 -0
- package/dist/src/lock.js +37 -0
- package/dist/src/mcp.d.ts +11 -0
- package/dist/src/mcp.js +79 -0
- package/dist/src/node.d.ts +14 -0
- package/dist/src/oauth.d.ts +64 -0
- package/dist/src/oauth.js +208 -0
- package/dist/src/prompts.d.ts +18 -0
- package/dist/src/prompts.js +166 -0
- package/dist/src/session.d.ts +58 -0
- package/dist/src/session.js +200 -0
- package/dist/src/tools-menu.d.ts +8 -0
- package/dist/src/tools-menu.js +173 -0
- package/package.json +21 -9
- package/bin/agentschema.js +0 -326
- package/lib/channels.js +0 -338
- package/lib/check.js +0 -387
- package/lib/instance.js +0 -75
- package/lib/markdown.js +0 -42
- package/lib/scaffold.js +0 -51
- package/lib/scheduled.js +0 -175
- package/lib/skills.js +0 -58
- package/lib/stream.js +0 -50
- package/lib/tools.js +0 -327
- package/lib/vaults.js +0 -142
- package/src/chat.js +0 -156
- package/src/check.js +0 -14
- package/src/cred-menu.js +0 -197
- package/src/cred.js +0 -263
- package/src/custom-tools.js +0 -17
- package/src/delete.js +0 -25
- package/src/deploy.js +0 -441
- package/src/dotenv.js +0 -50
- package/src/init.js +0 -54
- package/src/list.js +0 -49
- package/src/lock.js +0 -40
- package/src/mcp.js +0 -76
- package/src/oauth.js +0 -215
- package/src/prompts.js +0 -159
- package/src/session.js +0 -194
- package/src/tools-menu.js +0 -163
- /package/{src → dist/src}/node.js +0 -0
package/dist/src/chat.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
import { agentMessageText, textStream } from "../lib/stream.js";
|
|
3
|
+
import { loadTool } from "./custom-tools.js";
|
|
4
|
+
import { Conversation } from "./session.js";
|
|
5
|
+
const color = (code) => (text) => (process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text);
|
|
6
|
+
const dim = color(2);
|
|
7
|
+
const red = color(31);
|
|
8
|
+
const bold = color(1);
|
|
9
|
+
// Prints a session's events as a terminal transcript.
|
|
10
|
+
export function formatEvent(event) {
|
|
11
|
+
switch (event.type) {
|
|
12
|
+
case "agent.message":
|
|
13
|
+
return agentMessageText(event);
|
|
14
|
+
case "agent.tool_use":
|
|
15
|
+
case "agent.mcp_tool_use": {
|
|
16
|
+
const name = event.type === "agent.mcp_tool_use" ? `${event.mcp_server_name}.${event.name}` : event.name;
|
|
17
|
+
const denied = event.evaluated_permission === "deny" ? red(" (denied)") : "";
|
|
18
|
+
return dim(`· ${name} ${summarize(event.input)}`) + denied;
|
|
19
|
+
}
|
|
20
|
+
case "agent.custom_tool_use":
|
|
21
|
+
return dim(`· ${event.name} ${summarize(event.input)}`);
|
|
22
|
+
case "agent.tool_result":
|
|
23
|
+
case "agent.mcp_tool_result":
|
|
24
|
+
if (!event.is_error)
|
|
25
|
+
return null;
|
|
26
|
+
return red(` ↳ ${firstLine(event.content)}`);
|
|
27
|
+
case "session.error":
|
|
28
|
+
return red(`error: ${event.error?.message ?? event.error?.type ?? "unknown error"}`);
|
|
29
|
+
case "session.status_idle": {
|
|
30
|
+
const reason = event.stop_reason?.type;
|
|
31
|
+
if (reason === "retries_exhausted")
|
|
32
|
+
return red("The agent gave up after repeated errors.");
|
|
33
|
+
if (reason === "budget_reached")
|
|
34
|
+
return red("The session reached its budget and paused.");
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
case "session.status_terminated":
|
|
38
|
+
return dim("The session has ended.");
|
|
39
|
+
default:
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
// One line describing a tool call's input: the command, path or query when there is one.
|
|
44
|
+
function summarize(input = {}) {
|
|
45
|
+
for (const key of ["command", "file_path", "path", "pattern", "url", "query"]) {
|
|
46
|
+
if (typeof input[key] === "string")
|
|
47
|
+
return truncate(input[key]);
|
|
48
|
+
}
|
|
49
|
+
return truncate(JSON.stringify(input));
|
|
50
|
+
}
|
|
51
|
+
function firstLine(content = []) {
|
|
52
|
+
const text = content.find((b) => b.type === "text")?.text ?? "tool error";
|
|
53
|
+
return truncate(text.split("\n")[0]);
|
|
54
|
+
}
|
|
55
|
+
const truncate = (s, n = 100) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
56
|
+
// Runs a custom tool's code with the call's input. A thrown error is returned as an error
|
|
57
|
+
// result, so the agent sees what went wrong.
|
|
58
|
+
export async function runTool(tool, input) {
|
|
59
|
+
try {
|
|
60
|
+
const value = await loadTool(tool)(input);
|
|
61
|
+
return { text: typeof value === "string" ? value : (JSON.stringify(value) ?? "") };
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
return { text: `Error: ${err?.message ?? err}`, isError: true };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// Runs an interactive chat in the terminal until the user quits or the session ends.
|
|
68
|
+
// `tools` maps custom tool names to their tools/ files; their code runs here when called.
|
|
69
|
+
export async function chat(client, session, { agentName, tools = {}, input = process.stdin, output = process.stdout }) {
|
|
70
|
+
const rl = createInterface({ input, output, terminal: input.isTTY });
|
|
71
|
+
const lines = rl[Symbol.asyncIterator]();
|
|
72
|
+
let running = false;
|
|
73
|
+
let interrupted = false;
|
|
74
|
+
let quit = false;
|
|
75
|
+
const ask = async (prompt) => {
|
|
76
|
+
output.write(prompt);
|
|
77
|
+
const { value, done } = await lines.next();
|
|
78
|
+
if (done)
|
|
79
|
+
quit = true;
|
|
80
|
+
return done ? null : value;
|
|
81
|
+
};
|
|
82
|
+
const stream = textStream((text) => output.write(text));
|
|
83
|
+
const ui = {
|
|
84
|
+
event(event) {
|
|
85
|
+
if (stream.handle(event))
|
|
86
|
+
return;
|
|
87
|
+
const text = formatEvent(event);
|
|
88
|
+
if (text)
|
|
89
|
+
output.write(`${text}\n`);
|
|
90
|
+
},
|
|
91
|
+
async confirm(event) {
|
|
92
|
+
const answer = await ask(bold(`Allow ${event.name}? `) + dim("[y/N, or type why not] "));
|
|
93
|
+
if (answer && /^(y|yes)$/i.test(answer.trim()))
|
|
94
|
+
return { result: "allow" };
|
|
95
|
+
const reason = answer?.trim();
|
|
96
|
+
return { result: "deny", deny_message: reason && !/^(n|no)$/i.test(reason) ? reason : undefined };
|
|
97
|
+
},
|
|
98
|
+
async customToolResult(event) {
|
|
99
|
+
if (tools[event.name]) {
|
|
100
|
+
const result = await runTool(tools[event.name], event.input);
|
|
101
|
+
if (result.isError)
|
|
102
|
+
output.write(`${red(` ↳ ${truncate(result.text.split("\n")[0])}`)}\n`);
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
output.write(dim(`${event.name} is a custom tool, so you supply its result.\n`));
|
|
106
|
+
output.write(dim(`input: ${JSON.stringify(event.input)}\n`));
|
|
107
|
+
return (await ask(bold("result> "))) ?? "The user didn't provide a result.";
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
const conversation = new Conversation(client, session.id, ui);
|
|
111
|
+
let ended = false;
|
|
112
|
+
// Ctrl+C interrupts the agent while it works; a second Ctrl+C, or one at the prompt, quits.
|
|
113
|
+
rl.on("SIGINT", () => {
|
|
114
|
+
if (running && !interrupted) {
|
|
115
|
+
interrupted = true;
|
|
116
|
+
output.write(dim("\nInterrupting… (Ctrl+C again to quit)\n"));
|
|
117
|
+
conversation.interrupt().catch(() => { });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
quit = true;
|
|
121
|
+
conversation.close();
|
|
122
|
+
rl.close();
|
|
123
|
+
});
|
|
124
|
+
output.write(dim(`${agentName} · session ${session.id}\nCtrl+C interrupts the agent, Ctrl+D quits.\n\n`));
|
|
125
|
+
try {
|
|
126
|
+
while (!quit) {
|
|
127
|
+
const text = await ask(bold("> "));
|
|
128
|
+
if (text === null)
|
|
129
|
+
break;
|
|
130
|
+
if (text.trim() === "")
|
|
131
|
+
continue;
|
|
132
|
+
running = true;
|
|
133
|
+
interrupted = false;
|
|
134
|
+
let outcome;
|
|
135
|
+
try {
|
|
136
|
+
outcome = await conversation.send(text);
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
if (quit)
|
|
140
|
+
break;
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
running = false;
|
|
145
|
+
}
|
|
146
|
+
output.write("\n");
|
|
147
|
+
if (outcome === "terminated") {
|
|
148
|
+
ended = true;
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
conversation.close();
|
|
155
|
+
rl.close();
|
|
156
|
+
}
|
|
157
|
+
if (!ended)
|
|
158
|
+
output.write(dim(`Resume this conversation with: agentschema run --resume ${session.id}\n`));
|
|
159
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { checkFiles } from "../lib/check.js";
|
|
3
|
+
import { folderProblem, readFolder } from "./folder.js";
|
|
4
|
+
// Validates an agent folder without calling the API. See checkFiles for what it returns.
|
|
5
|
+
export function check(dir, options) {
|
|
6
|
+
const problem = folderProblem(dir);
|
|
7
|
+
if (problem)
|
|
8
|
+
return { errors: [problem], warnings: [], instance: null };
|
|
9
|
+
const result = checkFiles(readFolder(dir), options);
|
|
10
|
+
// Where each tool's code lives, so its require() calls can resolve from there.
|
|
11
|
+
for (const tool of result.instance?.tools ?? [])
|
|
12
|
+
tool.path = resolve(dir, tool.file);
|
|
13
|
+
return result;
|
|
14
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type Anthropic from "@anthropic-ai/sdk";
|
|
2
|
+
import type { BetaManagedAgentsCredential } from "@anthropic-ai/sdk/resources/beta/vaults/credentials";
|
|
3
|
+
import { type Log } from "./deploy.ts";
|
|
4
|
+
import type { Prompts } from "./prompts.ts";
|
|
5
|
+
type Fetch = typeof globalThis.fetch;
|
|
6
|
+
export interface CredMenuOptions {
|
|
7
|
+
io: Prompts;
|
|
8
|
+
client: Anthropic;
|
|
9
|
+
openBrowser: (url: string) => void;
|
|
10
|
+
port?: number | string;
|
|
11
|
+
fetch?: Fetch;
|
|
12
|
+
log?: Log;
|
|
13
|
+
}
|
|
14
|
+
export declare function credCreate(dir: string | undefined, options: CredMenuOptions): Promise<BetaManagedAgentsCredential | null>;
|
|
15
|
+
export declare function credDeploy(file: string, options: CredMenuOptions): Promise<BetaManagedAgentsCredential>;
|
|
16
|
+
export declare function serviceName(url: string): string;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,193 @@
|
|
|
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 "../lib/vaults.js";
|
|
9
|
+
const SIGN_IN = "Sign in with the browser";
|
|
10
|
+
const PASTE = "Paste the tokens";
|
|
11
|
+
const PASTE_VALUE = "Paste the value";
|
|
12
|
+
const LATER = "Just write the file";
|
|
13
|
+
const NEW_VAULT = "New vault…";
|
|
14
|
+
const OTHER_URL = "Another URL…";
|
|
15
|
+
const FOR_MCP = "An MCP server's sign-in (OAuth)";
|
|
16
|
+
const FOR_ENV_VAR = "An environment variable (an API key, say)";
|
|
17
|
+
const HEADERS_ONLY = "Request headers only";
|
|
18
|
+
const HEADERS_AND_BODY = "Headers and body";
|
|
19
|
+
// `cred create`: asks which vault the credential goes in and what it's for, writes its file,
|
|
20
|
+
// then gets its secrets and creates it, unless you'd rather do that later with `cred deploy`.
|
|
21
|
+
export async function credCreate(dir = ".", options) {
|
|
22
|
+
const { io, fetch = globalThis.fetch, log = () => { } } = options;
|
|
23
|
+
if (dir.endsWith(".md")) {
|
|
24
|
+
throw new DeployError(`cred create takes the agent folder; to create the credential ${dir} describes, run agentschema cred deploy ${dir}`);
|
|
25
|
+
}
|
|
26
|
+
const { file, method } = await writeCredentialFile(dir, { io, fetch, log });
|
|
27
|
+
if (method === LATER) {
|
|
28
|
+
log(`\nCreate the credential in Anthropic when you're ready with:\n agentschema cred deploy ${file}`);
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
return getTokens(file, method, options);
|
|
32
|
+
}
|
|
33
|
+
// `cred deploy`: creates the credential a file describes in Anthropic, asking whether to sign
|
|
34
|
+
// in for its tokens or paste them.
|
|
35
|
+
export async function credDeploy(file, options) {
|
|
36
|
+
if (!existsSync(file))
|
|
37
|
+
throw new DeployError(`${file}: no such file; to write a new credential file, run agentschema cred create`);
|
|
38
|
+
const { cred } = locate(file);
|
|
39
|
+
// An environment variable has no sign-in, so there's only its value to ask for.
|
|
40
|
+
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);
|
|
41
|
+
return getTokens(file, method, options);
|
|
42
|
+
}
|
|
43
|
+
// Tokens come from signing in (`cred login`) or from pasting them (`credPaste`).
|
|
44
|
+
function getTokens(file, method, { client, io, openBrowser, port = 0, fetch = globalThis.fetch, log = () => { } }) {
|
|
45
|
+
const ask = (question, { secret }) => (secret ? io.secret(question.trim()) : io.text(question.trim()));
|
|
46
|
+
return method === SIGN_IN
|
|
47
|
+
? credLogin(file, { client, ask, openBrowser, port, fetch, log })
|
|
48
|
+
: credPaste(file, { client, ask, log });
|
|
49
|
+
}
|
|
50
|
+
// Asks about the credential, and writes vaults/<vault>/<name>.md. Returns { file, method }.
|
|
51
|
+
async function writeCredentialFile(dir, { io, fetch, log }) {
|
|
52
|
+
const { errors, instance } = check(dir);
|
|
53
|
+
if (!instance)
|
|
54
|
+
throw new DeployError(`${dir} isn't an agent folder:\n ${errors.join("\n ")}`);
|
|
55
|
+
if (errors.length > 0)
|
|
56
|
+
throw new DeployError(`check failed:\n ${errors.join("\n ")}`);
|
|
57
|
+
// The vault: an existing one, or a new folder.
|
|
58
|
+
const names = instance.vaults.map((v) => v.name);
|
|
59
|
+
let vaultName = names.length > 0 ? await io.select("Which vault?", [...names, NEW_VAULT], names[0]) : NEW_VAULT;
|
|
60
|
+
if (vaultName === NEW_VAULT) {
|
|
61
|
+
vaultName = await io.text("New vault's name?", names.includes("Shared") ? "" : "Shared", {
|
|
62
|
+
validate: (name) => fileName(name, "vault") ?? (names.includes(name) ? `There's already a vault called ${name}` : null),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
const vault = instance.vaults.find((v) => v.name === vaultName);
|
|
66
|
+
const vaultDir = join(dir, VAULTS_DIR, vaultName);
|
|
67
|
+
const kind = await io.select("What is it for?", [FOR_MCP, FOR_ENV_VAR], FOR_MCP);
|
|
68
|
+
const { name, auth, method } = kind === FOR_ENV_VAR
|
|
69
|
+
? await envVarCredential({ io, vault, vaultName, vaultDir })
|
|
70
|
+
: await mcpCredential({ io, instance, vault, vaultName, vaultDir, fetch, log });
|
|
71
|
+
mkdirSync(vaultDir, { recursive: true });
|
|
72
|
+
const file = join(vaultDir, `${name}.md`);
|
|
73
|
+
writeFileSync(file, `---\n${stringify({ auth })}---\n`);
|
|
74
|
+
log(`Wrote ${file}`);
|
|
75
|
+
const rel = `${VAULTS_DIR}/${vaultName}/${name}.md`;
|
|
76
|
+
for (const warning of check(dir).warnings.filter((w) => w.startsWith(rel)))
|
|
77
|
+
log(`warning: ${warning}`);
|
|
78
|
+
return { file, method };
|
|
79
|
+
}
|
|
80
|
+
// An environment variable: its name, the hosts that may receive it, and where it can appear.
|
|
81
|
+
async function envVarCredential({ io, vault, vaultName, vaultDir }) {
|
|
82
|
+
const taken = new Set(vault?.credentials.map((c) => c.data.auth?.secret_name) ?? []);
|
|
83
|
+
const secretName = await io.text("Variable name? (like STRIPE_API_KEY)", "", {
|
|
84
|
+
validate: (n) => {
|
|
85
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))
|
|
86
|
+
return "Use letters, digits and _, not starting with a digit";
|
|
87
|
+
return taken.has(n) ? `${vaultName} already sets ${n}` : null;
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
const hosts = await io.text("Which hosts may it be sent to? (like api.stripe.com; separate several with spaces)", "", {
|
|
91
|
+
validate: (h) => {
|
|
92
|
+
const list = h.split(/[\s,]+/).filter(Boolean);
|
|
93
|
+
if (list.length === 0)
|
|
94
|
+
return "List at least one host";
|
|
95
|
+
return list.some((x) => x.includes("/")) ? "Enter host names, without https:// or a path" : null;
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
const where = await io.select("Where in a request can it appear?", [HEADERS_ONLY, HEADERS_AND_BODY], HEADERS_ONLY);
|
|
99
|
+
const name = await io.text("Credential name?", secretName, {
|
|
100
|
+
validate: (n) => fileName(n, "credential") ?? (existsSync(join(vaultDir, `${n}.md`)) ? `${vaultName}/${n}.md already exists` : null),
|
|
101
|
+
});
|
|
102
|
+
const method = await io.select("How do you want to set its value?", [PASTE_VALUE, LATER], PASTE_VALUE);
|
|
103
|
+
return {
|
|
104
|
+
name,
|
|
105
|
+
method: method === PASTE_VALUE ? PASTE : LATER,
|
|
106
|
+
auth: {
|
|
107
|
+
type: ENV_VAR,
|
|
108
|
+
secret_name: secretName,
|
|
109
|
+
networking: { type: "limited", allowed_hosts: hosts.split(/[\s,]+/).filter(Boolean) },
|
|
110
|
+
injection_location: { header: true, body: where === HEADERS_AND_BODY },
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
// An MCP server's sign-in: the server, a name, and how its tokens will be fetched.
|
|
115
|
+
async function mcpCredential({ io, instance, vault, vaultName, vaultDir, fetch, log, }) {
|
|
116
|
+
const taken = new Set(vault?.credentials.map((c) => c.data.auth?.mcp_server_url) ?? []);
|
|
117
|
+
// The MCP server: one agent.md declares, or any URL.
|
|
118
|
+
const declared = instance.agent.data.mcp_servers ?? [];
|
|
119
|
+
const servers = declared.filter((s) => typeof s?.url === "string" && !taken.has(s.url));
|
|
120
|
+
const label = (s) => `${s.name ?? s.url} (${s.url})`;
|
|
121
|
+
let url = OTHER_URL;
|
|
122
|
+
if (servers.length > 0) {
|
|
123
|
+
const picked = await io.select("Which MCP server is it for?", [...servers.map(label), OTHER_URL], label(servers[0]));
|
|
124
|
+
url = servers.find((s) => label(s) === picked)?.url ?? OTHER_URL;
|
|
125
|
+
}
|
|
126
|
+
if (url === OTHER_URL) {
|
|
127
|
+
url = await io.text("MCP server URL?", "", {
|
|
128
|
+
validate: (u) => (!/^https?:\/\/\S+$/.test(u) ? "Enter an http(s) URL" : taken.has(u) ? `${vaultName} already has a credential for ${u}` : null),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const suggested = servers.find((s) => s.url === url)?.name ?? serviceName(url);
|
|
132
|
+
const name = await io.text("Credential name?", suggested, {
|
|
133
|
+
validate: (n) => fileName(n, "credential") ?? (existsSync(join(vaultDir, `${n}.md`)) ? `${vaultName}/${n}.md already exists` : null),
|
|
134
|
+
});
|
|
135
|
+
// How its tokens will be fetched decides what the file needs.
|
|
136
|
+
log(`Looking up the sign-in for ${url}…`);
|
|
137
|
+
const server = await discover(url, { fetch }).catch(() => null);
|
|
138
|
+
if (!server)
|
|
139
|
+
log("It doesn't publish an OAuth sign-in, so you'll paste its tokens.");
|
|
140
|
+
const method = await io.select("How do you want to get its tokens?", server ? [SIGN_IN, PASTE, LATER] : [PASTE, LATER], server ? SIGN_IN : PASTE);
|
|
141
|
+
const auth = { type: "mcp_oauth", mcp_server_url: url };
|
|
142
|
+
if (server && method !== PASTE) {
|
|
143
|
+
// Signing in registers agentschema as a client where the server allows it; elsewhere, it
|
|
144
|
+
// needs your own OAuth client.
|
|
145
|
+
if (!server.registrationEndpoint) {
|
|
146
|
+
log(`${server.issuer} doesn't let apps register themselves, so sign-in needs your own OAuth client.`);
|
|
147
|
+
log("Create one with the provider, allowing the redirect URI http://127.0.0.1:<port>/callback.");
|
|
148
|
+
auth.refresh = await refreshBlock(io, server, { tokenEndpoint: server.tokenEndpoint });
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
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)))) {
|
|
152
|
+
auth.refresh = await refreshBlock(io, server, {});
|
|
153
|
+
}
|
|
154
|
+
return { name, auth, method };
|
|
155
|
+
}
|
|
156
|
+
// The client details for the file's auth.refresh block.
|
|
157
|
+
async function refreshBlock(io, server, { tokenEndpoint }) {
|
|
158
|
+
const refresh = {}; // filled in below, in the order the file lists them
|
|
159
|
+
refresh.token_endpoint = tokenEndpoint ?? (await io.text("Token endpoint?", server?.tokenEndpoint ?? "", {
|
|
160
|
+
validate: (u) => (/^https?:\/\/\S+$/.test(u) ? null : "Enter an http(s) URL"),
|
|
161
|
+
}));
|
|
162
|
+
refresh.client_id = await io.text("OAuth client ID?", "", { validate: (id) => (id ? null : "The client ID is required") });
|
|
163
|
+
const supported = server?.scopesSupported ?? [];
|
|
164
|
+
const hint = supported.length > 0 ? ` (supported: ${supported.slice(0, 6).join(" ")}${supported.length > 6 ? " …" : ""})` : "";
|
|
165
|
+
const scope = await io.text(`Scopes, separated by spaces${hint}?`, "");
|
|
166
|
+
if (scope)
|
|
167
|
+
refresh.scope = scope;
|
|
168
|
+
const type = await io.select("How does the client authenticate to the token endpoint?", TOKEN_ENDPOINT_AUTH, "client_secret_post");
|
|
169
|
+
refresh.token_endpoint_auth = { type };
|
|
170
|
+
return refresh;
|
|
171
|
+
}
|
|
172
|
+
// Why a vault or credential name can't be a file name, or nothing when it can.
|
|
173
|
+
function fileName(name, what) {
|
|
174
|
+
if (!name)
|
|
175
|
+
return `The ${what} needs a name`;
|
|
176
|
+
if (/[/\\]/.test(name) || name.startsWith("."))
|
|
177
|
+
return `A ${what} name can't contain / or start with .`;
|
|
178
|
+
if (what === "credential" && `${name}.md` === VAULT_FILE)
|
|
179
|
+
return "vault is reserved for vault.md";
|
|
180
|
+
if (name.length > 255)
|
|
181
|
+
return `A ${what} name can be at most 255 characters`;
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
// "Linear" for https://mcp.linear.app/mcp: the host's main label, capitalized.
|
|
185
|
+
export function serviceName(url) {
|
|
186
|
+
const labels = new URL(url).hostname.split(".").filter((l) => !["mcp", "api", "www"].includes(l));
|
|
187
|
+
let main = labels.length >= 2 ? labels[labels.length - 2] : (labels[0] ?? "credential");
|
|
188
|
+
// A cloud's shared domain names the cloud, not the service: calendarmcp.googleapis.com.
|
|
189
|
+
if (["googleapis", "amazonaws", "azure", "azurewebsites", "cloudflare", "workers"].includes(main) && labels.length > 2) {
|
|
190
|
+
main = labels[0].replace(/-?mcp$/, "") || main;
|
|
191
|
+
}
|
|
192
|
+
return main.replace(/^./, (c) => c.toUpperCase());
|
|
193
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
2
|
+
import type { BetaManagedAgentsCredential } from "@anthropic-ai/sdk/resources/beta/vaults/credentials";
|
|
3
|
+
import { type Log, type PreparedLock, type SaveLock } from "./deploy.ts";
|
|
4
|
+
import { type Credential, type CredentialSecrets, type Vault } from "../lib/vaults.ts";
|
|
5
|
+
export type Ask = (question: string, options: {
|
|
6
|
+
secret: boolean;
|
|
7
|
+
}) => Promise<string>;
|
|
8
|
+
export type Secrets = {
|
|
9
|
+
[K in keyof CredentialSecrets]?: CredentialSecrets[K] | null;
|
|
10
|
+
};
|
|
11
|
+
export interface Located {
|
|
12
|
+
dir: string;
|
|
13
|
+
vault: Vault;
|
|
14
|
+
cred: Credential;
|
|
15
|
+
}
|
|
16
|
+
export interface CredPasteOptions {
|
|
17
|
+
client: Anthropic;
|
|
18
|
+
ask: Ask;
|
|
19
|
+
log?: Log;
|
|
20
|
+
}
|
|
21
|
+
export interface CreateCredentialOptions {
|
|
22
|
+
lock: PreparedLock;
|
|
23
|
+
vault: Pick<Vault, "name" | "path" | "file">;
|
|
24
|
+
cred: Credential;
|
|
25
|
+
secrets: Secrets;
|
|
26
|
+
client: Anthropic;
|
|
27
|
+
saveLock?: SaveLock;
|
|
28
|
+
log?: Log;
|
|
29
|
+
}
|
|
30
|
+
export interface CredLoginOptions {
|
|
31
|
+
client: Anthropic;
|
|
32
|
+
ask: Ask;
|
|
33
|
+
openBrowser: (url: string) => void;
|
|
34
|
+
port?: number | string;
|
|
35
|
+
fetch?: typeof globalThis.fetch;
|
|
36
|
+
log?: Log;
|
|
37
|
+
}
|
|
38
|
+
export interface CredDeleteOptions {
|
|
39
|
+
client: Anthropic;
|
|
40
|
+
confirm: (question: string) => Promise<boolean>;
|
|
41
|
+
log?: Log;
|
|
42
|
+
}
|
|
43
|
+
export interface DeleteCredentialOptions {
|
|
44
|
+
lock: PreparedLock;
|
|
45
|
+
cred: Pick<Credential, "file">;
|
|
46
|
+
client: Anthropic;
|
|
47
|
+
saveLock?: SaveLock;
|
|
48
|
+
}
|
|
49
|
+
export declare function locate(path: string): Located;
|
|
50
|
+
export declare function credPaste(path: string, { client, ask, log }: CredPasteOptions): Promise<BetaManagedAgentsCredential>;
|
|
51
|
+
export declare function createCredential({ lock, vault, cred, secrets, client, saveLock, log, }: CreateCredentialOptions): Promise<BetaManagedAgentsCredential>;
|
|
52
|
+
export declare function credLogin(path: string, { client, ask, openBrowser, port, fetch, log }: CredLoginOptions): Promise<BetaManagedAgentsCredential>;
|
|
53
|
+
export declare function credDelete(path: string, { client, confirm, log }: CredDeleteOptions): Promise<void>;
|
|
54
|
+
export declare function deleteCredential({ lock, cred, client, saveLock }: DeleteCredentialOptions): Promise<void>;
|