@operad-io/bot 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Registering a local MCP server of a bot is a proposal a person approves; so
3
+ * is an upgrade, and so is letting a server through after its tools changed.
4
+ * Nothing is written to the bot's settings until then.
5
+ */
6
+
7
+ import { randomUUID } from "node:crypto";
8
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { match } from "@operad-io/access-match";
11
+ import {
12
+ FileSecretStore,
13
+ messageOf,
14
+ type CommandContext,
15
+ type JsonValue,
16
+ type ObjectStore,
17
+ } from "@operad-io/engine";
18
+ import { BotError, accessFor, readBots, resolveBot, type McpServerSettings } from "./bot.ts";
19
+ import { baseEnvironment, probeServer } from "./mcp-client.ts";
20
+ import {
21
+ commandLine,
22
+ packageOfCommand,
23
+ parsePasted,
24
+ readReport,
25
+ reportDirectory,
26
+ secretName,
27
+ toolDigest,
28
+ validateServerName,
29
+ type McpRegistration,
30
+ } from "./mcp.ts";
31
+ import { PROPOSAL_TYPE, mcpChangeOf, type McpChange, type ProposalData } from "./proposals.ts";
32
+
33
+ async function allProposals(store: ObjectStore): Promise<Array<{ readonly id: string; readonly data: Readonly<Record<string, unknown>> }>> {
34
+ const found: Array<{ readonly id: string; readonly data: Readonly<Record<string, unknown>> }> = [];
35
+ let cursor: string | undefined;
36
+ do {
37
+ const page = await store.list(PROPOSAL_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
38
+ for (const object of page.objects) found.push({ id: object.id, data: object.data });
39
+ cursor = page.next;
40
+ } while (cursor !== undefined);
41
+ return found;
42
+ }
43
+
44
+ async function put(store: ObjectStore, data: ProposalData, cause: string): Promise<string> {
45
+ const id = `p-${randomUUID()}`;
46
+ await store.put(PROPOSAL_TYPE, id, data as unknown as Record<string, JsonValue>, cause);
47
+ return id;
48
+ }
49
+
50
+ /** How long reading the tool list of a server may take, in milliseconds. */
51
+ export const PROBE_TIMEOUT_MS = 60_000;
52
+
53
+ export interface ProposeMcpOptions {
54
+ /** How long the server may take to answer; the default is `PROBE_TIMEOUT_MS`. */
55
+ readonly timeoutMs?: number | undefined;
56
+ }
57
+
58
+ /**
59
+ * Proposes a local MCP server for a bot: a new one, or an upgrade of one it
60
+ * lists. The command is checked first (a floating version is refused and the
61
+ * server is not started); then the server is started once, in the bot's
62
+ * working directory with a bare environment and its own secrets, to read its
63
+ * tool list.
64
+ */
65
+ export async function proposeMcp(
66
+ store: ObjectStore,
67
+ home: string,
68
+ bot: string,
69
+ name: string,
70
+ registration: McpRegistration,
71
+ options: ProposeMcpOptions = {},
72
+ ): Promise<string> {
73
+ validateServerName(name);
74
+ const written = readBots(home)[bot];
75
+ if (written === undefined) throw new BotError(`there is no bot "${bot}"`);
76
+ const pinned = packageOfCommand(registration.command, registration.args);
77
+ const resolved = resolveBot(home, bot, written);
78
+ // The bot's access profile applies to starting the server, as it does to any command of the bot.
79
+ const verdict = match(accessFor(home, written), {
80
+ tool: "bash",
81
+ input: { command: commandLine(registration.command, registration.args) },
82
+ cwd: resolved.cwd,
83
+ });
84
+ // The server is started before any person has approved it, so a command the
85
+ // profile asks about cannot be run here either.
86
+ if (!verdict.allow) {
87
+ throw new BotError(
88
+ verdict.ask === true
89
+ ? `the access profile of bot ${bot} asks before running this command, and nobody can be asked before the server is proposed: ${verdict.reason}`
90
+ : `the access profile of bot ${bot} refuses this command: ${verdict.reason}`,
91
+ );
92
+ }
93
+
94
+ const before = written.mcpServers?.[name] ?? null;
95
+ const variables = [...new Set([...(before?.secrets ?? []), ...registration.variables])];
96
+ const env = baseEnvironment();
97
+ const secrets = new FileSecretStore({ home, plugin: "bot" });
98
+ for (const variable of variables) {
99
+ const stored = await secrets.get(secretName(name, variable));
100
+ if (stored !== undefined) env[variable] = stored.reveal();
101
+ }
102
+ // Values pasted with the registration only serve this one start; they are not kept.
103
+ Object.assign(env, registration.given);
104
+
105
+ mkdirSync(resolved.cwd, { recursive: true });
106
+ let tools;
107
+ try {
108
+ tools = await probeServer({
109
+ command: registration.command,
110
+ args: registration.args,
111
+ cwd: resolved.cwd,
112
+ env,
113
+ timeoutMs: options.timeoutMs ?? PROBE_TIMEOUT_MS,
114
+ });
115
+ } catch (error) {
116
+ throw new BotError(
117
+ `could not read the tools of "${name}" by starting it: ${messageOf(error)}${
118
+ variables.length === 0 ? "" : `. It may need its secrets first: ${variables.map((v) => secretName(name, v)).join(", ")} (operad secret set bot <name>)`
119
+ }`,
120
+ );
121
+ }
122
+ const after: McpServerSettings = {
123
+ command: registration.command,
124
+ ...(registration.args.length === 0 ? {} : { args: [...registration.args] }),
125
+ ...(pinned === null ? {} : { package: pinned.package, version: pinned.version }),
126
+ ...(variables.length === 0 ? {} : { secrets: variables }),
127
+ tools: [...tools],
128
+ digest: toolDigest(tools),
129
+ };
130
+ const change: McpChange = { server: name, reason: before === null ? "new" : "upgrade", before, after };
131
+ const data: ProposalData = {
132
+ bot,
133
+ kind: "mcp",
134
+ title: before === null ? `MCP server ${name}` : `MCP server ${name} upgrade`,
135
+ state: "pending",
136
+ createdAt: Date.now(),
137
+ mcp: change,
138
+ };
139
+ await put(store, data, "command:bot/mcp");
140
+ const dropped = Object.keys(registration.given).length;
141
+ return `proposed MCP server "${name}" for bot ${bot} (${tools.length} tools); review it in pending${
142
+ dropped === 0 ? "" : `. The ${dropped} value(s) given in env were used once to start it and are not kept; store them as secrets`
143
+ }`;
144
+ }
145
+
146
+ /**
147
+ * Turns what guards left (a server whose tools differ from the approved ones)
148
+ * into pending items, and removes the reports. A report for a list that already
149
+ * has a proposal, pending or answered, makes no second one: a rejected change
150
+ * keeps the server off without asking again.
151
+ */
152
+ export async function ingestReports(store: ObjectStore, home: string): Promise<void> {
153
+ const directory = reportDirectory(home);
154
+ if (!existsSync(directory)) return;
155
+ const known = (await allProposals(store)).flatMap(({ data }) => {
156
+ const change = mcpChangeOf(data.mcp);
157
+ return typeof data.bot === "string" && change !== undefined ? [`${data.bot}\0${change.server}\0${change.after.digest ?? ""}`] : [];
158
+ });
159
+ for (const file of readdirSync(directory)) {
160
+ if (!file.endsWith(".json")) continue;
161
+ const path = join(directory, file);
162
+ let report;
163
+ try {
164
+ report = readReport(JSON.parse(readFileSync(path, "utf8")));
165
+ } catch {
166
+ report = undefined;
167
+ }
168
+ rmSync(path, { force: true });
169
+ if (report === undefined) continue;
170
+ const entry = readBots(home)[report.bot]?.mcpServers?.[report.server];
171
+ // Our own digest, not the report's: the file is only a list of tools.
172
+ const digest = toolDigest(report.tools);
173
+ if (entry === undefined || entry.digest === digest) continue;
174
+ const key = `${report.bot}\0${report.server}\0${digest}`;
175
+ if (known.includes(key)) continue;
176
+ known.push(key);
177
+ const after: McpServerSettings = { ...entry, tools: [...report.tools], digest };
178
+ await put(
179
+ store,
180
+ {
181
+ bot: report.bot,
182
+ kind: "mcp",
183
+ title: `MCP server ${report.server} changed its tools`,
184
+ state: "pending",
185
+ createdAt: Date.now(),
186
+ mcp: { server: report.server, reason: "changed", before: entry, after },
187
+ },
188
+ "guard:bot/mcp",
189
+ );
190
+ }
191
+ }
192
+
193
+ /** The pasted entry: the text the caller supplied, else what is piped to the command. */
194
+ async function pastedText(input: string | undefined): Promise<string> {
195
+ if (input !== undefined) return input;
196
+ if (process.stdin.isTTY === true) return "";
197
+ const chunks: Buffer[] = [];
198
+ for await (const chunk of process.stdin as AsyncIterable<Buffer | string>) {
199
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk);
200
+ }
201
+ return Buffer.concat(chunks).toString("utf8");
202
+ }
203
+
204
+ /**
205
+ * Parses `<bot> <name> [<command> [args...]]` for the `bot mcp` command. With no
206
+ * command, stdin is a pasted `mcpServers` entry.
207
+ */
208
+ export async function runMcpCommand(ctx: CommandContext, argv: readonly string[]): Promise<string> {
209
+ const bot = argv[0];
210
+ const name = argv[1];
211
+ if (bot === undefined || name === undefined) {
212
+ throw new BotError("usage: operad bot mcp <bot> <name> <command> [args...] or operad bot mcp <bot> <name> < pasted-entry.json");
213
+ }
214
+ const words = argv.slice(2);
215
+ let registration: McpRegistration;
216
+ if (words.length > 0) {
217
+ const command = words[0] ?? "";
218
+ registration = { command, args: words.slice(1), variables: [], given: {} };
219
+ } else {
220
+ const text = (await pastedText(ctx.input)).trim();
221
+ if (text.length === 0) throw new BotError("give the server as a command with arguments, or paste its mcpServers entry on stdin");
222
+ registration = parsePasted(text, name);
223
+ }
224
+ return proposeMcp(ctx.store, ctx.home, bot, name, registration);
225
+ }
package/src/mcp.ts ADDED
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Local MCP servers of a bot: what registering one takes (a command with
3
+ * arguments, or a pasted `mcpServers` entry of that form), the version pin, the
4
+ * digest of a tool list and the difference between two lists. A server is
5
+ * registered through a proposal a person approves (`proposals.ts`); the guard
6
+ * (`guard.ts`) stands in front of it when a chat starts it.
7
+ */
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { basename, join } from "node:path";
11
+ import { isRecord } from "@operad-io/engine";
12
+ import { MCP_REPORT_DIR } from "./mcp-constants.ts";
13
+ import { BotError, type McpServerSettings } from "./bot.ts";
14
+ import type { McpTool } from "./mcp-client.ts";
15
+
16
+ export { MCP_REPORT_DIR };
17
+
18
+ /** The directory of the reports of a home. */
19
+ export function reportDirectory(home: string): string {
20
+ return join(home, MCP_REPORT_DIR);
21
+ }
22
+
23
+ /** The name of a secret a server needs: the plugin's own secret store keeps it. */
24
+ export function secretName(server: string, variable: string): string {
25
+ return `${server}.${variable}`;
26
+ }
27
+
28
+ const SERVER_NAME = /^[a-z0-9][a-z0-9-]*(?:_[a-z0-9-]+)*$/;
29
+
30
+ /** Checks the name a server goes by in a chat: its tools are `mcp__<name>__<tool>`. */
31
+ export function validateServerName(name: string): void {
32
+ if (!SERVER_NAME.test(name) || name.includes("__")) {
33
+ throw new BotError(
34
+ `MCP server "${name}": a name is lowercase letters, digits and "-", with single "_" between parts`,
35
+ );
36
+ }
37
+ if (name === "operad") throw new BotError('MCP server "operad" is operad\'s own; use another name');
38
+ }
39
+
40
+ /** The digest of a tool list: names and descriptions only, in name order. */
41
+ export function toolDigest(tools: readonly McpTool[]): string {
42
+ const sorted = [...tools]
43
+ .map((tool) => ({ name: tool.name, description: tool.description }))
44
+ .sort((a, b) => a.name.localeCompare(b.name));
45
+ return `sha256:${createHash("sha256").update(JSON.stringify(sorted)).digest("hex")}`;
46
+ }
47
+
48
+ /** What was registered: the command as the person wrote it, and the variables the server needs. */
49
+ export interface McpRegistration {
50
+ readonly command: string;
51
+ readonly args: readonly string[];
52
+ /** Names of the environment variables the server needs; the values are never kept. */
53
+ readonly variables: readonly string[];
54
+ /** Values given with the registration (a pasted `env`); used to read the tool list once, then dropped. */
55
+ readonly given: Readonly<Record<string, string>>;
56
+ }
57
+
58
+ /** Reads the pasted text of a registration: an `mcpServers` map or one entry of the command form. */
59
+ export function parsePasted(text: string, name: string): McpRegistration {
60
+ let parsed: unknown;
61
+ try {
62
+ parsed = JSON.parse(text);
63
+ } catch {
64
+ throw new BotError("the pasted server is not JSON; paste an mcpServers entry such as {\"command\": \"npx\", \"args\": [\"-y\", \"pkg@1.2.3\"]}");
65
+ }
66
+ if (!isRecord(parsed)) throw new BotError("the pasted server must be a JSON object");
67
+ let entry: unknown = parsed;
68
+ if (isRecord(parsed.mcpServers)) {
69
+ const entries = Object.entries(parsed.mcpServers);
70
+ const named = parsed.mcpServers[name];
71
+ if (named !== undefined) entry = named;
72
+ else if (entries.length === 1) entry = entries[0]?.[1];
73
+ else throw new BotError(`the pasted mcpServers holds ${entries.length} servers and none is called "${name}"`);
74
+ }
75
+ if (!isRecord(entry)) throw new BotError("the pasted server must be a JSON object");
76
+ if (entry.url !== undefined || entry.type === "http" || entry.type === "sse" || entry.headers !== undefined) {
77
+ throw new BotError("a remote server (an address) cannot be registered yet; only a local one, a command with arguments");
78
+ }
79
+ if (typeof entry.command !== "string" || entry.command.trim().length === 0) {
80
+ throw new BotError("the pasted server needs a command");
81
+ }
82
+ const args = entry.args === undefined ? [] : entry.args;
83
+ if (!Array.isArray(args) || !args.every((item): item is string => typeof item === "string")) {
84
+ throw new BotError("the pasted server's args must be a list of text");
85
+ }
86
+ const given: Record<string, string> = {};
87
+ if (entry.env !== undefined) {
88
+ if (!isRecord(entry.env)) throw new BotError("the pasted server's env must be an object");
89
+ for (const [key, value] of Object.entries(entry.env)) {
90
+ if (typeof value !== "string") throw new BotError(`the pasted server's env "${key}" must be text`);
91
+ given[key] = value;
92
+ }
93
+ }
94
+ return { command: entry.command, args, variables: Object.keys(given), given };
95
+ }
96
+
97
+ /** What a command says about its package. */
98
+ export interface PackageRef {
99
+ readonly package: string;
100
+ readonly version: string;
101
+ }
102
+
103
+ const EXACT = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/;
104
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
105
+ const NPM_RUNNERS = new Set(["npx", "bunx", "pnpx"]);
106
+ const PYTHON_RUNNERS = new Set(["uvx", "pipx"]);
107
+ /** Flags of the runners that take a value: the package would then be named in a form not read here. */
108
+ const FLAGS_WITH_PACKAGE = new Set(["-p", "--package", "-c", "--call", "--from", "--with"]);
109
+
110
+ function floating(spec: string, why: string, name: string): BotError {
111
+ return new BotError(
112
+ `"${spec}" is not pinned (${why}). Pin an exact version so what runs cannot change under you, for example ${name}@1.2.3`,
113
+ );
114
+ }
115
+
116
+ function packageOf(spec: string, python: boolean): PackageRef {
117
+ let name: string;
118
+ let version: string;
119
+ const equals = python ? spec.indexOf("==") : -1;
120
+ if (equals > 0) {
121
+ name = spec.slice(0, equals);
122
+ version = spec.slice(equals + 2);
123
+ } else {
124
+ const at = spec.startsWith("@") ? spec.indexOf("@", 1) : spec.indexOf("@");
125
+ name = at < 0 ? spec : spec.slice(0, at);
126
+ version = at < 0 ? "" : spec.slice(at + 1);
127
+ }
128
+ if (python && /[<>=!~]/.test(name)) {
129
+ throw floating(spec, "a range", name.replace(/[<>=!~].*$/, ""));
130
+ }
131
+ if (!PACKAGE_NAME.test(name)) {
132
+ throw new BotError(
133
+ `"${spec}" is not a package name and version; write the package from a registry as name@1.2.3`,
134
+ );
135
+ }
136
+ if (version.length === 0) throw floating(spec, "no version", name);
137
+ if (version === "latest" || version === "next" || /^[a-z]+$/i.test(version)) {
138
+ throw floating(spec, `"${version}" is a tag that moves`, name);
139
+ }
140
+ if (!EXACT.test(version)) throw floating(spec, `"${version}" is a range or not an exact version`, name);
141
+ return { package: name, version };
142
+ }
143
+
144
+ /**
145
+ * The package a command runs, with its pinned version, or null when the command
146
+ * is not a package runner (a program or script the person already has). A
147
+ * runner with no version, a tag or a range is refused.
148
+ */
149
+ export function packageOfCommand(command: string, args: readonly string[]): PackageRef | null {
150
+ const runner = basename(command).toLowerCase().replace(/\.(?:cmd|exe)$/, "");
151
+ let rest: readonly string[];
152
+ let python = false;
153
+ if (NPM_RUNNERS.has(runner)) rest = args;
154
+ else if (PYTHON_RUNNERS.has(runner)) {
155
+ rest = runner === "pipx" ? (args[0] === "run" ? args.slice(1) : []) : args;
156
+ python = true;
157
+ if (rest.length === 0) return null;
158
+ } else if (["npm", "pnpm", "yarn", "bun"].includes(runner) && ["exec", "dlx", "x"].includes(args[0] ?? "")) {
159
+ rest = args.slice(1);
160
+ } else if (runner === "uv" && args[0] === "tool" && args[1] === "run") {
161
+ rest = args.slice(2);
162
+ python = true;
163
+ } else return null;
164
+ for (const word of rest) {
165
+ if (FLAGS_WITH_PACKAGE.has(word) || /^--(?:package|from|with)=/.test(word)) {
166
+ throw new BotError(`"${word}" names a package in a form that is not read here; give the package as the first argument, as name@1.2.3`);
167
+ }
168
+ if (word.startsWith("-")) continue;
169
+ return packageOf(word, python);
170
+ }
171
+ throw new BotError(`"${command}" is given no package; give it as name@1.2.3`);
172
+ }
173
+
174
+ /** The registration as a person reads the command. */
175
+ export function commandLine(command: string, args: readonly string[]): string {
176
+ return [command, ...args].map((word) => (/^[\w@%+=:,./-]+$/.test(word) ? word : JSON.stringify(word))).join(" ");
177
+ }
178
+
179
+ /** One tool that changed between two lists. */
180
+ export interface ToolChange {
181
+ readonly name: string;
182
+ readonly before: string;
183
+ readonly after: string;
184
+ }
185
+
186
+ /** What differs between the tool lists of a server before and after. */
187
+ export interface ToolDifference {
188
+ readonly added: readonly McpTool[];
189
+ readonly removed: readonly McpTool[];
190
+ readonly changed: readonly ToolChange[];
191
+ }
192
+
193
+ /** Compares two tool lists by name and description. */
194
+ export function compareTools(before: readonly McpTool[], after: readonly McpTool[]): ToolDifference {
195
+ const was = new Map(before.map((tool) => [tool.name, tool]));
196
+ const now = new Map(after.map((tool) => [tool.name, tool]));
197
+ return {
198
+ added: after.filter((tool) => !was.has(tool.name)),
199
+ removed: before.filter((tool) => !now.has(tool.name)),
200
+ changed: after.flatMap((tool) => {
201
+ const old = was.get(tool.name);
202
+ return old !== undefined && old.description !== tool.description
203
+ ? [{ name: tool.name, before: old.description, after: tool.description }]
204
+ : [];
205
+ }),
206
+ };
207
+ }
208
+
209
+ /** The difference as lines a person reads. */
210
+ export function differenceLines(diff: ToolDifference): string[] {
211
+ const out: string[] = [];
212
+ for (const tool of diff.added) out.push(`+ ${tool.name}: ${tool.description}`);
213
+ for (const tool of diff.removed) out.push(`- ${tool.name}: ${tool.description}`);
214
+ for (const change of diff.changed) {
215
+ out.push(`~ ${change.name}`, ` before: ${change.before}`, ` after: ${change.after}`);
216
+ }
217
+ return out.length === 0 ? ["The tools are the same."] : out;
218
+ }
219
+
220
+ /** The stored tools of a settings entry, read defensively. */
221
+ export function storedTools(entry: McpServerSettings): readonly McpTool[] {
222
+ return entry.tools ?? [];
223
+ }
224
+
225
+ /** What the guard writes when a server's tools are not the ones a person approved. */
226
+ export interface ChangeReport {
227
+ readonly bot: string;
228
+ readonly server: string;
229
+ readonly digest: string;
230
+ readonly tools: readonly McpTool[];
231
+ }
232
+
233
+ /** A report read from a file, or undefined when it is not one. */
234
+ export function readReport(value: unknown): ChangeReport | undefined {
235
+ if (!isRecord(value) || typeof value.bot !== "string" || typeof value.server !== "string" || typeof value.digest !== "string") {
236
+ return undefined;
237
+ }
238
+ if (!Array.isArray(value.tools)) return undefined;
239
+ const tools: McpTool[] = [];
240
+ for (const item of value.tools) {
241
+ if (!isRecord(item) || typeof item.name !== "string") return undefined;
242
+ tools.push({ name: item.name, description: typeof item.description === "string" ? item.description : "" });
243
+ }
244
+ return { bot: value.bot, server: value.server, digest: value.digest, tools };
245
+ }