@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.
package/src/index.ts ADDED
@@ -0,0 +1,392 @@
1
+ /**
2
+ * The bot plugin: a bot is a working directory, a default harness, skills, a
3
+ * speaker and an access profile; `bot:chat` opens a chat on one. The chat's own
4
+ * plugin is `chat`; this one only says where and under what rules it runs, and
5
+ * says it again at every reply.
6
+ *
7
+ * Hook for Telegram: a chat bound from a channel is made with
8
+ * {@link openChat} on {@link DEFAULT_BOT}; a rule that names another bot is not
9
+ * built yet, and this is the one place it goes.
10
+ */
11
+
12
+ import { mkdirSync } from "node:fs";
13
+ import { fileURLToPath } from "node:url";
14
+ import { CHAT_TYPE, agentConditionals, type AgentChoices, chatData, createChat, sendMessage, startingEffort, startingModel, titleFromMessage } from "@operad-io/chat";
15
+ import { definePlugin, isRecord, type ActionArgsSchema, type ActionTypeDefinition, type JsonValue, type ObjectRow, type ObjectStore, type ObjectViews, type PluginStepResult, type SectionContent, type StepContext, type StoredObject } from "@operad-io/engine";
16
+ import {
17
+ BOT_SETTINGS,
18
+ DEFAULT_BOT,
19
+ BOT_TYPE,
20
+ BotError,
21
+ readBots,
22
+ repositoryPaths,
23
+ resolveBot,
24
+ type ResolvedBot,
25
+ } from "./bot.ts";
26
+ import { ingestReports, runMcpCommand } from "./mcp-proposals.ts";
27
+ import {
28
+ PROPOSAL_TYPE,
29
+ proposalActions,
30
+ proposalItems,
31
+ proposalViews,
32
+ runSettingCommand,
33
+ runSkillCommand,
34
+ } from "./proposals.ts";
35
+
36
+ /** The step a chat calls at every reply to read its bot. */
37
+ export const SETTINGS_STEP = "bot/settings";
38
+
39
+ /** The bot as the row of a list shows it. */
40
+ function rowOf(bot: ResolvedBot): Record<string, JsonValue> {
41
+ return {
42
+ name: bot.name,
43
+ cwd: bot.cwd,
44
+ harness: bot.harness,
45
+ model: bot.model,
46
+ effort: bot.effort,
47
+ skills: [...bot.skills],
48
+ speaker: bot.speaker,
49
+ access: bot.access,
50
+ mcpServers: Object.keys(bot.mcpServers),
51
+ };
52
+ }
53
+
54
+ /** The harnesses that take MCP servers natively; any other does not mount a bot's servers. */
55
+ export const MCP_HARNESSES: readonly string[] = ["claude", "radian"];
56
+
57
+ const GUARD = fileURLToPath(new URL("./guard.ts", import.meta.url));
58
+
59
+ /** What a harness starts for one of a bot's servers: the guard, which starts the server itself. */
60
+ export function guardCommand(home: string, bot: string, server: string): { readonly command: string; readonly args: readonly string[] } {
61
+ return { command: process.execPath, args: [GUARD, "--home", home, "--bot", bot, "--server", server] };
62
+ }
63
+
64
+ /**
65
+ * Makes the bot objects match the settings: one per bot, the default always,
66
+ * and a bot taken out of the settings is marked removed (its chats stop
67
+ * answering). A bot that cannot be used is stored with its problem.
68
+ */
69
+ export async function syncBots(
70
+ store: ObjectStore,
71
+ home: string,
72
+ fallback: Readonly<Record<string, JsonValue>>,
73
+ ): Promise<void> {
74
+ const written = readBots(home, fallback);
75
+ const repositories = await repositoryPaths(store);
76
+ for (const [name, settings] of Object.entries(written)) {
77
+ let data: Record<string, JsonValue>;
78
+ try {
79
+ data = { ...rowOf(resolveBot(home, name, settings, repositories)), removed: false };
80
+ } catch (error) {
81
+ if (!(error instanceof BotError)) throw error;
82
+ data = { name, removed: false, problem: error.message };
83
+ }
84
+ const current = await store.get(BOT_TYPE, name);
85
+ if (current === undefined || JSON.stringify(current.data) !== JSON.stringify(data)) {
86
+ await store.put(BOT_TYPE, name, data, "bot");
87
+ }
88
+ }
89
+ let cursor: string | undefined;
90
+ do {
91
+ const page = await store.list(BOT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
92
+ for (const object of page.objects) {
93
+ if (written[object.id] === undefined && object.data.removed !== true) {
94
+ await store.put(BOT_TYPE, object.id, { ...object.data, removed: true }, "bot");
95
+ }
96
+ }
97
+ cursor = page.next;
98
+ } while (cursor !== undefined);
99
+ }
100
+
101
+ /** What opening a chat needs from the host. */
102
+ export interface OpenChat {
103
+ readonly store: ObjectStore;
104
+ readonly home: string;
105
+ readonly settings: Readonly<Record<string, JsonValue>>;
106
+ readonly harnesses: readonly string[];
107
+ readonly bot: string;
108
+ readonly models?: Readonly<Record<string, { readonly list: readonly string[]; readonly default: string | null }>> | undefined;
109
+ readonly efforts?: Readonly<Record<string, { readonly list: readonly string[]; readonly default: string | null }>> | undefined;
110
+ readonly harness?: string | undefined;
111
+ readonly model?: string | undefined;
112
+ readonly effort?: string | undefined;
113
+ readonly title?: string | undefined;
114
+ readonly cause: string;
115
+ }
116
+
117
+ /** Opens a chat on a bot and returns its id. Refuses with a plain message. */
118
+ export async function openChat(input: OpenChat): Promise<string> {
119
+ const written = readBots(input.home, input.settings)[input.bot];
120
+ if (written === undefined) throw new BotError(`there is no bot "${input.bot}"`);
121
+ const bot = resolveBot(input.home, input.bot, written, await repositoryPaths(input.store));
122
+ const harness = input.harness ?? bot.harness ?? input.harnesses[0];
123
+ if (harness === undefined) {
124
+ throw new BotError("no agent is loaded; load one to chat with the bot");
125
+ }
126
+ if (!input.harnesses.includes(harness)) {
127
+ throw new BotError(
128
+ `agent "${harness}" is not loaded; the loaded ones are: ${input.harnesses.join(", ") || "none"}`,
129
+ );
130
+ }
131
+ // The bot's configured model and effort must be ones the agent lists; an unlisted one is refused by name.
132
+ let model: string | undefined;
133
+ let effort: string | undefined;
134
+ try {
135
+ model = startingModel(harness, input.models?.[harness], input.model, bot.model ?? undefined);
136
+ effort = startingEffort(harness, input.efforts?.[harness], input.effort, bot.effort ?? undefined);
137
+ } catch (error) {
138
+ throw new BotError(error instanceof Error ? error.message : String(error));
139
+ }
140
+ const effortDefault = input.efforts?.[harness]?.default ?? undefined;
141
+ mkdirSync(bot.cwd, { recursive: true });
142
+ return createChat(
143
+ input.store,
144
+ {
145
+ parent: `${BOT_TYPE}:${bot.name}`,
146
+ harness,
147
+ ...(model === undefined ? {} : { model }),
148
+ ...(effort === undefined ? {} : { effort }),
149
+ ...(effort === undefined || effortDefault === undefined ? {} : { effortDefault }),
150
+ cwd: bot.cwd,
151
+ access: bot.access,
152
+ skills: bot.skills,
153
+ title: input.title ?? `Bot (${bot.name})`,
154
+ refresh: SETTINGS_STEP,
155
+ },
156
+ input.cause,
157
+ );
158
+ }
159
+
160
+ /** The `chat` arguments with the harness plugins loaded now as the choice. */
161
+ function chatArgs(
162
+ harnesses: readonly string[],
163
+ botHarness: unknown,
164
+ models: readonly string[] = [],
165
+ efforts: readonly string[] = [],
166
+ agents: readonly AgentChoices[] = [],
167
+ ): ActionArgsSchema {
168
+ const first = harnesses[0];
169
+ const fallback = typeof botHarness === "string" && harnesses.includes(botHarness) ? botHarness : first;
170
+ return {
171
+ type: "object",
172
+ description: "Opens a chat with the bot.",
173
+ properties: {
174
+ agent: {
175
+ type: "string",
176
+ ...(harnesses.length === 0 ? {} : { enum: [...harnesses] }),
177
+ ...(fallback === undefined ? {} : { default: fallback }),
178
+ description: "Which agent answers in this chat; it cannot change later.",
179
+ },
180
+ model: {
181
+ type: "string",
182
+ ...(models.length === 0 ? {} : { enum: [...models] }),
183
+ description:
184
+ "The model the agent uses; one from that agent's list. The bot's model, else the agent's default, when left out. It can be changed later.",
185
+ },
186
+ effort: {
187
+ type: "string",
188
+ ...(efforts.length === 0 ? {} : { enum: [...efforts] }),
189
+ description:
190
+ "The effort the agent uses; one from that agent's list. The bot's effort, else the agent's default, when left out. It can be changed later.",
191
+ },
192
+ title: { type: "string", minLength: 1, maxLength: 120, description: "What the chat is called." },
193
+ message: {
194
+ type: "string",
195
+ role: "note",
196
+ minLength: 1,
197
+ description:
198
+ "The first message; the chat is created and the message sent in one step. The title is taken from its start when none is given.",
199
+ },
200
+ },
201
+ ...(agents.length === 0 ? {} : { allOf: agentConditionals(agents) }),
202
+ additionalProperties: false,
203
+ };
204
+ }
205
+
206
+ const chatAction: ActionTypeDefinition = {
207
+ name: "chat",
208
+ on: BOT_TYPE,
209
+ creates: "chat",
210
+ args: chatArgs([], undefined),
211
+ argsFor: (object, env) =>
212
+ chatArgs(
213
+ env.harnesses ?? [],
214
+ object.data.harness,
215
+ [...new Set((env.harnesses ?? []).flatMap((name) => env.models?.[name]?.list ?? []))],
216
+ [...new Set((env.harnesses ?? []).flatMap((name) => env.efforts?.[name]?.list ?? []))],
217
+ (env.harnesses ?? []).map((name) => ({
218
+ name,
219
+ models: env.models?.[name],
220
+ efforts: env.efforts?.[name],
221
+ preferredModel: typeof object.data.model === "string" ? object.data.model : null,
222
+ preferredEffort: typeof object.data.effort === "string" ? object.data.effort : null,
223
+ })),
224
+ ),
225
+ when: (state, env) => state.removed !== true && typeof state.problem !== "string" && (env.harnesses ?? []).length > 0,
226
+ async why(object, env) {
227
+ if (object.data.removed === true) return `bot ${object.id} is no longer in the settings`;
228
+ if (typeof object.data.problem === "string") return `bot ${object.id}: ${object.data.problem}`;
229
+ if ((env.harnesses ?? []).length === 0) return `bot ${object.id}: no agent is loaded; load one to chat with it`;
230
+ return undefined;
231
+ },
232
+ async run(ctx, args) {
233
+ const input = args as {
234
+ readonly agent?: string;
235
+ readonly model?: string;
236
+ readonly effort?: string;
237
+ readonly title?: string;
238
+ readonly message?: string;
239
+ };
240
+ const id = await openChat({
241
+ store: ctx.store,
242
+ home: ctx.home,
243
+ settings: ctx.settings,
244
+ harnesses: ctx.harnesses,
245
+ models: ctx.models,
246
+ efforts: ctx.efforts,
247
+ bot: ctx.object.id,
248
+ harness: input.agent,
249
+ model: input.model,
250
+ effort: input.effort,
251
+ title: input.title ?? (input.message === undefined ? undefined : titleFromMessage(input.message)),
252
+ cause: "action:bot/chat",
253
+ });
254
+ const sent = input.message === undefined ? undefined : await sendMessage(ctx, id, input.message);
255
+ return { text: `opened chat ${id}${sent === undefined ? "" : `; ${sent}`}`, opens: `chat:${id}` };
256
+ },
257
+ };
258
+
259
+ /**
260
+ * Step `bot/settings`: the working directory, access profile and skills of a
261
+ * chat's bot as they are now. The `chat` reply calls it every time, so
262
+ * tightening access or adding a skill needs no new chat. A bot that is gone or
263
+ * cannot be used fails the reply; it is never answered from an older copy.
264
+ */
265
+ export async function runSettings(ctx: StepContext, params: unknown): Promise<PluginStepResult> {
266
+ const chatId = isRecord(params) && typeof params.chat === "string" ? params.chat : undefined;
267
+ const stored = chatId === undefined ? undefined : await ctx.store.get(CHAT_TYPE, chatId);
268
+ if (stored === undefined) return { result: "failed", data: { message: "there is no such chat" } };
269
+ const parent = chatData(stored.data).parent ?? "";
270
+ if (!parent.startsWith(`${BOT_TYPE}:`)) {
271
+ return { result: "failed", data: { message: `chat ${chatId} is not a chat of a bot` } };
272
+ }
273
+ const name = parent.slice(BOT_TYPE.length + 1);
274
+ try {
275
+ await ingestReports(ctx.store, ctx.home);
276
+ const written = readBots(ctx.home, ctx.settings)[name];
277
+ if (written === undefined) {
278
+ return { result: "failed", data: { message: `bot "${name}" is no longer in the settings` } };
279
+ }
280
+ const bot = resolveBot(ctx.home, name, written, await repositoryPaths(ctx.store));
281
+ mkdirSync(bot.cwd, { recursive: true });
282
+ // Only the servers the bot lists, and only on a harness that takes MCP servers natively.
283
+ const mounts = MCP_HARNESSES.includes(chatData(stored.data).harness);
284
+ const mcpServers: Record<string, JsonValue> = {};
285
+ for (const [server, entry] of Object.entries(bot.mcpServers)) {
286
+ if (mounts && entry.digest !== undefined) mcpServers[server] = { ...guardCommand(ctx.home, name, server) } as unknown as JsonValue;
287
+ }
288
+ return {
289
+ result: "done",
290
+ data: { cwd: bot.cwd, access: bot.access, skills: [...bot.skills], mcpServers },
291
+ };
292
+ } catch (error) {
293
+ return { result: "failed", data: { message: error instanceof Error ? error.message : String(error) } };
294
+ }
295
+ }
296
+
297
+ function botMarkdown(object: StoredObject): string {
298
+ const data = object.data;
299
+ const lines = [`**${object.id}**`];
300
+ if (typeof data.problem === "string") lines.push(`Cannot be used: ${data.problem}`);
301
+ if (typeof data.cwd === "string") lines.push(`Working directory: ${data.cwd}`);
302
+ if (typeof data.harness === "string") lines.push(`Default agent: ${data.harness}`);
303
+ if (typeof data.speaker === "string") lines.push(`Speaker: ${data.speaker}`);
304
+ const skills = Array.isArray(data.skills) ? data.skills : [];
305
+ lines.push(skills.length === 0 ? "No skills." : `Skills: ${skills.join(", ")}`);
306
+ const servers = Array.isArray(data.mcpServers) ? data.mcpServers : [];
307
+ if (servers.length > 0) {
308
+ lines.push(
309
+ `MCP servers: ${servers.join(", ")}`,
310
+ `They are mounted in chats on ${MCP_HARNESSES.join(" and ")}. A chat on pi does not mount them: pi takes no MCP servers yet, so it cannot use ${servers.join(", ")}.`,
311
+ );
312
+ }
313
+ return lines.join("\n\n");
314
+ }
315
+
316
+ /** How a bot shows in a list and on its page. */
317
+ export const botViews: ObjectViews = {
318
+ row: (object): ObjectRow => ({
319
+ id: object.id,
320
+ title: object.id,
321
+ state: object.data.removed === true ? "removed" : "open",
322
+ }),
323
+ sections: () => [{ id: "bot", title: "Bot" }],
324
+ load: (_ctx, object): SectionContent => ({ markdown: botMarkdown(object) }),
325
+ };
326
+
327
+ /** Builds the bot plugin. */
328
+ export function createBotPlugin() {
329
+ return definePlugin({
330
+ name: "bot",
331
+ kind: "domain",
332
+ version: "0.0.0",
333
+ requires: { plugins: { chat: "^0.0.0" } },
334
+ settings: BOT_SETTINGS,
335
+ // A bot page is that bot's settings page; bots live under settings, not in a tab.
336
+ objectsUnderSettings: true,
337
+ objects: [
338
+ {
339
+ name: BOT_TYPE,
340
+ filters: [
341
+ { name: "open", states: ["open"], default: true },
342
+ { name: "removed", states: ["removed"] },
343
+ ],
344
+ // Every list and get sees the bots the settings name.
345
+ prepare: ({ store, home, settings }) => syncBots(store, home, settings),
346
+ },
347
+ {
348
+ name: PROPOSAL_TYPE,
349
+ index: ["state", "bot"],
350
+ filters: [
351
+ { name: "pending", states: ["pending"], default: true },
352
+ { name: "applied", states: ["applied"] },
353
+ { name: "rejected", states: ["rejected"] },
354
+ ],
355
+ },
356
+ ],
357
+ steps: [{ name: "settings", results: ["done", "failed"], run: runSettings }],
358
+ actions: [chatAction, ...proposalActions],
359
+ commands: [
360
+ {
361
+ name: "skill",
362
+ args: "<bot> <name> [--from <dir>]",
363
+ run: runSkillCommand,
364
+ },
365
+ {
366
+ name: "mcp",
367
+ args: "<bot> <name> [<command> [args...]]",
368
+ run: runMcpCommand,
369
+ },
370
+ {
371
+ name: "setting",
372
+ args: "<bot>",
373
+ run: runSettingCommand,
374
+ },
375
+ ],
376
+ // A proposal waits for no run; each one is a pending item of its bot.
377
+ standing: async (ctx) => {
378
+ await ingestReports(ctx.store, ctx.home);
379
+ return proposalItems(ctx.store);
380
+ },
381
+ views: { [BOT_TYPE]: botViews, [PROPOSAL_TYPE]: proposalViews },
382
+ });
383
+ }
384
+
385
+ export default createBotPlugin();
386
+
387
+ export * from "./bot.ts";
388
+ export * from "./proposals.ts";
389
+ export * from "./mcp.ts";
390
+ export * from "./mcp-proposals.ts";
391
+ export { runGuard, markedResult, MATERIAL_NOTE, reportPath } from "./guard.ts";
392
+ export { probeServer, type McpTool } from "./mcp-client.ts";
@@ -0,0 +1,215 @@
1
+ /**
2
+ * A small MCP client over a child's stdio, for two jobs: reading the tool list
3
+ * of a server once (to register it), and the guard in front of a server a bot
4
+ * mounts. It speaks newline-delimited JSON-RPC and nothing else of MCP.
5
+ */
6
+
7
+ import { spawn, type ChildProcess } from "node:child_process";
8
+ import { createInterface } from "node:readline";
9
+ import { isRecord, messageOf } from "@operad-io/engine";
10
+ import { KILL_GRACE_MS, killProcessGroup } from "@operad-io/engine/platform";
11
+
12
+ /** The protocol version this client offers. */
13
+ export const MCP_PROTOCOL_VERSION = "2025-06-18";
14
+
15
+ /** One tool a server offers, as a person reads it. */
16
+ export interface McpTool {
17
+ readonly name: string;
18
+ readonly description: string;
19
+ }
20
+
21
+ /** A JSON-RPC message. */
22
+ export type RpcMessage = Record<string, unknown>;
23
+
24
+ /** What a request got back. */
25
+ export type RpcReply = { readonly result: unknown } | { readonly error: unknown };
26
+
27
+ export interface StdioOptions {
28
+ readonly command: string;
29
+ readonly args: readonly string[];
30
+ readonly cwd: string;
31
+ /** The whole environment of the server: nothing is inherited. */
32
+ readonly env: Readonly<Record<string, string>>;
33
+ /** How long one request may take. */
34
+ readonly timeoutMs?: number | undefined;
35
+ }
36
+
37
+ /** The environment a server gets before secrets: a path to find programs and a home. */
38
+ export function baseEnvironment(): Record<string, string> {
39
+ const env: Record<string, string> = {};
40
+ for (const name of ["PATH", "HOME", "TMPDIR", "LANG"]) {
41
+ const value = process.env[name];
42
+ if (value !== undefined) env[name] = value;
43
+ }
44
+ return env;
45
+ }
46
+
47
+ /** A started server and the requests made of it. */
48
+ export class StdioServer {
49
+ readonly #child: ChildProcess;
50
+ readonly #pending = new Map<string, (reply: RpcReply) => void>();
51
+ readonly #stderr: string[] = [];
52
+ readonly #timeoutMs: number;
53
+ #next = 0;
54
+ #ended = false;
55
+ #onMessage: (message: RpcMessage) => void = () => undefined;
56
+ readonly exited: Promise<void>;
57
+
58
+ constructor(options: StdioOptions) {
59
+ this.#timeoutMs = options.timeoutMs ?? 30_000;
60
+ // A new process group, so the server and what it starts can be stopped together.
61
+ this.#child = spawn(options.command, [...options.args], {
62
+ cwd: options.cwd,
63
+ env: { ...options.env },
64
+ stdio: ["pipe", "pipe", "pipe"],
65
+ detached: true,
66
+ });
67
+ this.exited = new Promise<void>((resolve) => {
68
+ const done = (): void => {
69
+ this.#ended = true;
70
+ for (const settle of this.#pending.values()) settle({ error: { message: `the server ended: ${this.stderrTail()}` } });
71
+ this.#pending.clear();
72
+ resolve();
73
+ };
74
+ this.#child.once("close", done);
75
+ this.#child.once("error", (error) => {
76
+ this.#stderr.push(messageOf(error));
77
+ done();
78
+ });
79
+ });
80
+ this.#child.stdin?.on("error", () => undefined);
81
+ this.#child.stderr?.on("data", (chunk: Buffer) => {
82
+ this.#stderr.push(chunk.toString("utf8"));
83
+ if (this.#stderr.length > 20) this.#stderr.splice(0, this.#stderr.length - 20);
84
+ });
85
+ if (this.#child.stdout !== null) {
86
+ createInterface({ input: this.#child.stdout }).on("line", (line) => this.#line(line));
87
+ }
88
+ }
89
+
90
+ #line(line: string): void {
91
+ if (line.trim().length === 0) return;
92
+ let parsed: unknown;
93
+ try {
94
+ parsed = JSON.parse(line);
95
+ } catch {
96
+ return;
97
+ }
98
+ if (!isRecord(parsed)) return;
99
+ const id = parsed.id;
100
+ if (typeof id === "string" && parsed.method === undefined) {
101
+ const settle = this.#pending.get(id);
102
+ if (settle !== undefined) {
103
+ this.#pending.delete(id);
104
+ settle("error" in parsed ? { error: parsed.error } : { result: parsed.result });
105
+ return;
106
+ }
107
+ }
108
+ this.#onMessage(parsed);
109
+ }
110
+
111
+ /** Receives what the server sent that was not the answer to one of this client's requests. */
112
+ onMessage(handler: (message: RpcMessage) => void): void {
113
+ this.#onMessage = handler;
114
+ }
115
+
116
+ /** The last lines the server wrote to its error output. */
117
+ stderrTail(): string {
118
+ return this.#stderr.join("").trim().split("\n").slice(-5).join("\n");
119
+ }
120
+
121
+ /** Writes one message. */
122
+ send(message: RpcMessage): void {
123
+ if (this.#ended) return;
124
+ this.#child.stdin?.write(`${JSON.stringify(message)}\n`);
125
+ }
126
+
127
+ /** One request. The id is this client's own (`g<n>`), so it never meets one of the server's. */
128
+ request(method: string, params?: unknown): Promise<RpcReply> {
129
+ if (this.#ended) return Promise.resolve({ error: { message: `the server ended: ${this.stderrTail()}` } });
130
+ this.#next += 1;
131
+ const id = `g${this.#next}`;
132
+ return new Promise<RpcReply>((resolve) => {
133
+ const timer = setTimeout(() => {
134
+ this.#pending.delete(id);
135
+ resolve({ error: { message: `the server did not answer "${method}" in ${Math.round(this.#timeoutMs / 1000)} s` } });
136
+ }, this.#timeoutMs);
137
+ this.#pending.set(id, (reply) => {
138
+ clearTimeout(timer);
139
+ resolve(reply);
140
+ });
141
+ this.send({ jsonrpc: "2.0", id, method, ...(params === undefined ? {} : { params }) });
142
+ });
143
+ }
144
+
145
+ /** The handshake: initialize and the `initialized` notice. Returns the server's answer. */
146
+ async initialize(client: string): Promise<RpcReply> {
147
+ const reply = await this.request("initialize", {
148
+ protocolVersion: MCP_PROTOCOL_VERSION,
149
+ capabilities: {},
150
+ clientInfo: { name: client, version: "0.0.0" },
151
+ });
152
+ if ("result" in reply) this.send({ jsonrpc: "2.0", method: "notifications/initialized" });
153
+ return reply;
154
+ }
155
+
156
+ /** Every tool the server offers, following its pages. */
157
+ async listTools(): Promise<readonly McpTool[]> {
158
+ const found: McpTool[] = [];
159
+ let cursor: string | undefined;
160
+ do {
161
+ const reply = await this.request("tools/list", cursor === undefined ? {} : { cursor });
162
+ if ("error" in reply) throw new Error(errorText(reply.error));
163
+ const page = toolsOf(reply.result);
164
+ found.push(...page.tools);
165
+ cursor = page.next;
166
+ } while (cursor !== undefined);
167
+ return found;
168
+ }
169
+
170
+ /** Ends the server and what it started. */
171
+ async close(): Promise<void> {
172
+ if (!this.#ended) {
173
+ this.#child.stdin?.end();
174
+ const pid = this.#child.pid;
175
+ if (pid !== undefined && !killProcessGroup(pid, "SIGTERM")) this.#child.kill("SIGTERM");
176
+ // A server that ignores the first signal is killed after a short grace.
177
+ const timer = setTimeout(() => {
178
+ if (pid !== undefined && !killProcessGroup(pid, "SIGKILL")) this.#child.kill("SIGKILL");
179
+ }, KILL_GRACE_MS);
180
+ await this.exited;
181
+ clearTimeout(timer);
182
+ return;
183
+ }
184
+ await this.exited;
185
+ }
186
+ }
187
+
188
+ /** A tool list as a person reads it: name and description, sorted by name. */
189
+ export function toolsOf(result: unknown): { readonly tools: readonly McpTool[]; readonly next: string | undefined } {
190
+ const list = isRecord(result) && Array.isArray(result.tools) ? result.tools : [];
191
+ const tools: McpTool[] = [];
192
+ for (const item of list) {
193
+ if (!isRecord(item) || typeof item.name !== "string") continue;
194
+ tools.push({ name: item.name, description: typeof item.description === "string" ? item.description : "" });
195
+ }
196
+ const next = isRecord(result) && typeof result.nextCursor === "string" && result.nextCursor.length > 0 ? result.nextCursor : undefined;
197
+ return { tools, next };
198
+ }
199
+
200
+ /** The message of a JSON-RPC error. */
201
+ export function errorText(error: unknown): string {
202
+ return isRecord(error) && typeof error.message === "string" ? error.message : "the server answered with an error";
203
+ }
204
+
205
+ /** Starts a server, reads its tool list once and ends it. */
206
+ export async function probeServer(options: StdioOptions): Promise<readonly McpTool[]> {
207
+ const server = new StdioServer(options);
208
+ try {
209
+ const hello = await server.initialize("operad-bot");
210
+ if ("error" in hello) throw new Error(errorText(hello.error));
211
+ return [...(await server.listTools())].sort((a, b) => a.name.localeCompare(b.name));
212
+ } finally {
213
+ await server.close();
214
+ }
215
+ }
@@ -0,0 +1,2 @@
1
+ /** Where the guard leaves a changed tool list for the bot plugin to find. Inside the home, outside `bot/`. */
2
+ export const MCP_REPORT_DIR = "bot-mcp";