@operad-io/mcp 0.0.0-stage → 0.1.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/tools.ts ADDED
@@ -0,0 +1,627 @@
1
+ /** The MCP tool table: names, input schemas and the one-line descriptions. */
2
+
3
+ import type {
4
+ Kernel,
5
+ LogBackend,
6
+ McpConfig,
7
+ PendingItem,
8
+ PluginRegistry,
9
+ RunningItem,
10
+ ViewListPage,
11
+ ViewObject,
12
+ ViewSectionContent,
13
+ Views,
14
+ } from "@operad-io/engine";
15
+ import {
16
+ fileProperties,
17
+ HISTORY_SECTION,
18
+ listPending,
19
+ listRunning,
20
+ listTypes,
21
+ messageOf,
22
+ ViewError,
23
+ type Actor,
24
+ type ViewTypeInfo,
25
+ } from "@operad-io/engine";
26
+ import { machineLoad, type MachineLoad } from "@operad-io/engine/platform";
27
+ import { InvalidToolArguments, validateArguments } from "./arguments.ts";
28
+ import {
29
+ historyMarkdown,
30
+ listMarkdown,
31
+ pendingMarkdown,
32
+ runningMarkdown,
33
+ sectionMarkdown,
34
+ showMarkdown,
35
+ typesMarkdown,
36
+ valueText,
37
+ } from "./format.ts";
38
+ import {
39
+ actionInfoNamed,
40
+ actionMayRun,
41
+ mcpPolicy,
42
+ ownerRefusal,
43
+ splitActions,
44
+ splitPendingActions,
45
+ } from "./policy.ts";
46
+
47
+ /** The JSON Schema subset a tool input uses. */
48
+ export interface InputPropertySchema {
49
+ readonly type?: "string" | "boolean" | "integer" | "array" | "object";
50
+ readonly description?: string;
51
+ readonly minLength?: number;
52
+ readonly items?: InputPropertySchema;
53
+ }
54
+
55
+ /** A tool's input: an object with known properties only. */
56
+ export interface InputSchema {
57
+ readonly type: "object";
58
+ readonly required?: readonly string[];
59
+ readonly additionalProperties: false;
60
+ readonly properties: Readonly<Record<string, InputPropertySchema>>;
61
+ }
62
+
63
+ /** One tool as `tools/list` serves it. */
64
+ export interface ToolDefinition {
65
+ readonly name: string;
66
+ readonly description: string;
67
+ readonly inputSchema: InputSchema;
68
+ }
69
+
70
+ /** Kernel command names; a plugin verb is never reachable through MCP. */
71
+ const KERNEL_VERBS = new Set([
72
+ "init",
73
+ "serve",
74
+ "pending",
75
+ "history",
76
+ "running",
77
+ "flows",
78
+ "trigger",
79
+ "list",
80
+ "show",
81
+ "plugin",
82
+ "secret",
83
+ "http",
84
+ "pair",
85
+ "run-internal",
86
+ "mcp",
87
+ ]);
88
+
89
+ /** The tools this server offers, in the order it lists them. */
90
+ export const TOOLS = [
91
+ {
92
+ name: "types",
93
+ description:
94
+ "List the object types with views, their plugin, and whether they belong under settings rather than a tab.",
95
+ inputSchema: {
96
+ type: "object",
97
+ additionalProperties: false,
98
+ properties: {},
99
+ },
100
+ },
101
+ {
102
+ name: "list",
103
+ description: "List one object type, with the kernel's waiting and running flags.",
104
+ inputSchema: {
105
+ type: "object",
106
+ additionalProperties: false,
107
+ properties: {
108
+ type: {
109
+ type: "string",
110
+ minLength: 1,
111
+ description:
112
+ "An object type, such as task. Optional with root or parent: then every type is listed.",
113
+ },
114
+ root: {
115
+ type: "boolean",
116
+ description: "Only rows with no parent.",
117
+ },
118
+ parent: {
119
+ type: "string",
120
+ minLength: 1,
121
+ description: "Only rows whose parent is this object id.",
122
+ },
123
+ cursor: {
124
+ type: "string",
125
+ description: "The next cursor from an earlier list.",
126
+ },
127
+ },
128
+ },
129
+ },
130
+ {
131
+ name: "show",
132
+ description: "Show one object's row, sections and available actions.",
133
+ inputSchema: {
134
+ type: "object",
135
+ required: ["id"],
136
+ additionalProperties: false,
137
+ properties: {
138
+ id: {
139
+ type: "string",
140
+ minLength: 1,
141
+ description: "A bare id or type:id.",
142
+ },
143
+ },
144
+ },
145
+ },
146
+ {
147
+ name: "section",
148
+ description: "Read one section of an object as Markdown.",
149
+ inputSchema: {
150
+ type: "object",
151
+ required: ["id", "section"],
152
+ additionalProperties: false,
153
+ properties: {
154
+ id: {
155
+ type: "string",
156
+ minLength: 1,
157
+ description: "A bare id or type:id.",
158
+ },
159
+ section: {
160
+ type: "string",
161
+ minLength: 1,
162
+ description: "A section id from show.",
163
+ },
164
+ cursor: {
165
+ type: "string",
166
+ description: "The next cursor from an earlier read.",
167
+ },
168
+ after: {
169
+ type: "string",
170
+ description:
171
+ "A mark from an earlier read: return only the finished content after it. The answer says in `delta` whether it is that part alone or a whole page.",
172
+ },
173
+ full: {
174
+ type: "boolean",
175
+ description: "Return the whole section without the size cap.",
176
+ },
177
+ },
178
+ },
179
+ },
180
+ {
181
+ name: "pending",
182
+ description: "List the items waiting for a person, with their actions.",
183
+ inputSchema: {
184
+ type: "object",
185
+ additionalProperties: false,
186
+ properties: {},
187
+ },
188
+ },
189
+ {
190
+ name: "answer",
191
+ description: "Answer one open question of a pending item by its wait id.",
192
+ inputSchema: {
193
+ type: "object",
194
+ required: ["runId", "waitId", "choice"],
195
+ additionalProperties: false,
196
+ properties: {
197
+ runId: {
198
+ type: "string",
199
+ minLength: 1,
200
+ description: "The pending item's runId.",
201
+ },
202
+ waitId: {
203
+ type: "string",
204
+ minLength: 1,
205
+ description: "The pending item's waitId.",
206
+ },
207
+ choice: {
208
+ type: "string",
209
+ minLength: 1,
210
+ description: "One of the item's choices.",
211
+ },
212
+ note: {
213
+ type: "string",
214
+ description: "The note, when the question asks for one.",
215
+ },
216
+ confirmed: {
217
+ type: "boolean",
218
+ description:
219
+ "Set when the answer is a choice whose action asks to confirm.",
220
+ },
221
+ },
222
+ },
223
+ },
224
+ {
225
+ name: "running",
226
+ description:
227
+ "List the runs in progress, with the machine's 1-minute load average and core count.",
228
+ inputSchema: {
229
+ type: "object",
230
+ additionalProperties: false,
231
+ properties: {},
232
+ },
233
+ },
234
+ {
235
+ name: "history",
236
+ description: "Read the history section of one object.",
237
+ inputSchema: {
238
+ type: "object",
239
+ required: ["id"],
240
+ additionalProperties: false,
241
+ properties: {
242
+ id: {
243
+ type: "string",
244
+ minLength: 1,
245
+ description: "A bare id or type:id.",
246
+ },
247
+ },
248
+ },
249
+ },
250
+ {
251
+ name: "command",
252
+ description: "Run a plugin verb the way the CLI does.",
253
+ inputSchema: {
254
+ type: "object",
255
+ required: ["plugin", "verb"],
256
+ additionalProperties: false,
257
+ properties: {
258
+ plugin: {
259
+ type: "string",
260
+ minLength: 1,
261
+ description: "A loaded plugin name, such as dev.",
262
+ },
263
+ verb: {
264
+ type: "string",
265
+ minLength: 1,
266
+ description: "A verb the plugin declares, such as plan.",
267
+ },
268
+ args: {
269
+ type: "array",
270
+ items: { type: "string" },
271
+ description: "The command-line arguments after the verb.",
272
+ },
273
+ input: {
274
+ type: "string",
275
+ description: "The text the CLI reads from stdin, such as a brief.",
276
+ },
277
+ },
278
+ },
279
+ },
280
+ {
281
+ name: "act",
282
+ description:
283
+ "Run an action the MCP server is allowed to run for a lead. An action's file arguments cannot be passed here: a client uploads files.",
284
+ inputSchema: {
285
+ type: "object",
286
+ required: ["action"],
287
+ additionalProperties: false,
288
+ properties: {
289
+ action: {
290
+ type: "string",
291
+ minLength: 1,
292
+ description: "A <plugin>:<action> name from show.",
293
+ },
294
+ id: {
295
+ type: "string",
296
+ description: "The object id when the action targets one.",
297
+ },
298
+ args: {
299
+ type: "object",
300
+ description: "The action's arguments, as its schema names them.",
301
+ },
302
+ note: {
303
+ type: "string",
304
+ description: "The note for an action whose schema declares one.",
305
+ },
306
+ },
307
+ },
308
+ },
309
+ ] as const satisfies readonly ToolDefinition[];
310
+
311
+ /** One text block of a tool result. */
312
+ export interface ToolTextContent {
313
+ readonly type: "text";
314
+ readonly text: string;
315
+ }
316
+
317
+ /** A successful tool result, or a view refusal with `isError`. */
318
+ export interface ToolResult {
319
+ readonly content: readonly ToolTextContent[];
320
+ /** MCP requires an object here, never a list: a list is wrapped as `{ items }`. */
321
+ readonly structuredContent?: object;
322
+ readonly isError?: true;
323
+ }
324
+
325
+ /** What a tool call reads; all of it is the presentation kernel's own view. */
326
+ export interface ToolContext {
327
+ readonly views: Views;
328
+ readonly log: LogBackend;
329
+ readonly registry: PluginRegistry;
330
+ readonly kernel: Kernel;
331
+ readonly clock: () => number;
332
+ readonly cwd?: string | undefined;
333
+ readonly mcp?: McpConfig | undefined;
334
+ /** Reads the machine load; tests inject it. */
335
+ readonly load?: (() => MachineLoad) | undefined;
336
+ }
337
+
338
+ function text(value: string): ToolTextContent {
339
+ return { type: "text", text: value };
340
+ }
341
+
342
+ /** The error result a view refusal becomes: the view's message, and no stack. */
343
+ export function toolError(message: string): ToolResult {
344
+ return {
345
+ content: [text(message)],
346
+ isError: true,
347
+ };
348
+ }
349
+
350
+ /**
351
+ * A plugin verb's value as MCP structured content: a plain object as it is,
352
+ * anything else (a list, a string, a number) wrapped as `{ value }`.
353
+ */
354
+ function structuredValue(value: unknown): object {
355
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
356
+ return value;
357
+ }
358
+ return { value };
359
+ }
360
+
361
+ /**
362
+ * Runs one read tool. The arguments are already checked against the table's
363
+ * input schema by the caller.
364
+ */
365
+ export async function runTool(
366
+ name: string,
367
+ args: Readonly<Record<string, unknown>>,
368
+ context: ToolContext,
369
+ ): Promise<ToolResult> {
370
+ switch (name) {
371
+ case "types": {
372
+ const types: readonly ViewTypeInfo[] = listTypes(context.registry);
373
+ return {
374
+ content: [text(typesMarkdown(types))],
375
+ structuredContent: { types },
376
+ };
377
+ }
378
+ case "list": {
379
+ const type = args.type === undefined ? undefined : String(args.type);
380
+ const root = args.root === true;
381
+ const parent = args.parent === undefined ? undefined : String(args.parent);
382
+ if (type === undefined && !root && parent === undefined) {
383
+ throw new ViewError("args", "list needs a type, root or parent");
384
+ }
385
+ const level = {
386
+ ...(root ? { root } : {}),
387
+ ...(parent === undefined ? {} : { parent }),
388
+ ...(args.cursor === undefined ? {} : { cursor: String(args.cursor) }),
389
+ };
390
+ const page: ViewListPage =
391
+ root || parent !== undefined
392
+ ? await context.views.listTree(type, level)
393
+ : await context.views.list(String(type), level);
394
+ return {
395
+ content: [text(listMarkdown(page))],
396
+ structuredContent: page,
397
+ };
398
+ }
399
+ case "show": {
400
+ const object: ViewObject = await context.views.get(String(args.id));
401
+ const shown = splitActions(object, mcpPolicy(context.mcp));
402
+ return {
403
+ content: [text(showMarkdown(shown))],
404
+ structuredContent: shown,
405
+ };
406
+ }
407
+ case "section": {
408
+ const content: ViewSectionContent = await context.views.section(
409
+ String(args.id),
410
+ String(args.section),
411
+ args.cursor === undefined ? undefined : String(args.cursor),
412
+ {
413
+ full: args.full === true,
414
+ ...(args.after === undefined ? {} : { after: String(args.after) }),
415
+ },
416
+ );
417
+ return {
418
+ content: [text(sectionMarkdown(content))],
419
+ structuredContent: content,
420
+ };
421
+ }
422
+ case "pending": {
423
+ const pending: readonly PendingItem[] = await listPending(
424
+ context.log,
425
+ context.registry,
426
+ context.kernel,
427
+ context.views,
428
+ );
429
+ const shown = splitPendingActions(
430
+ pending,
431
+ context.registry.actions(),
432
+ mcpPolicy(context.mcp),
433
+ );
434
+ return {
435
+ content: [text(pendingMarkdown(shown))],
436
+ structuredContent: { items: shown },
437
+ };
438
+ }
439
+ case "answer": {
440
+ const runId = String(args.runId);
441
+ const waitId = String(args.waitId);
442
+ const choice = String(args.choice);
443
+ const note = args.note === undefined ? undefined : String(args.note);
444
+ const actor: Actor = { via: "mcp", id: "lead" };
445
+ const pending = await listPending(
446
+ context.log,
447
+ context.registry,
448
+ context.kernel,
449
+ context.views,
450
+ );
451
+ const item = pending.find(
452
+ (candidate) => candidate.runId === runId && candidate.waitId === waitId,
453
+ );
454
+ // A wait whose choices are the object's actions answers through that
455
+ // action, so its confirmation and the owner's allow list still apply.
456
+ const throughAction =
457
+ item !== undefined &&
458
+ item.choices.every((name) =>
459
+ item.actions.some((action) => action.action === name),
460
+ )
461
+ ? item.actions.find((action) => action.action === choice)
462
+ : undefined;
463
+ if (item !== undefined && throughAction !== undefined) {
464
+ const info = actionInfoNamed(
465
+ context.registry.actions(),
466
+ `${throughAction.plugin}:${throughAction.action}`,
467
+ );
468
+ if (info === undefined) {
469
+ return toolError(`there is no action "${throughAction.action}"`);
470
+ }
471
+ if (!actionMayRun(mcpPolicy(context.mcp), info)) {
472
+ return toolError(ownerRefusal(info.name));
473
+ }
474
+ if (item.object === undefined) {
475
+ return toolError(`the pending item "${waitId}" names no object`);
476
+ }
477
+ try {
478
+ const run = await context.views.act(info.name, item.object, {
479
+ args: {},
480
+ ...(note === undefined ? {} : { note }),
481
+ yes: args.confirmed === true,
482
+ actor,
483
+ });
484
+ return {
485
+ content: [text(valueText(run.value) || `ran "${run.name}"\n`)],
486
+ structuredContent: run,
487
+ };
488
+ } catch (error) {
489
+ return toolError(messageOf(error));
490
+ }
491
+ }
492
+ const result = {
493
+ runId,
494
+ waitId,
495
+ choice,
496
+ ...(note === undefined ? {} : { note }),
497
+ };
498
+ try {
499
+ await context.views.answer({
500
+ runId,
501
+ waitId,
502
+ choice,
503
+ ...(note === undefined ? {} : { note }),
504
+ ...(args.confirmed === true ? { confirmed: true } : {}),
505
+ actor,
506
+ });
507
+ return {
508
+ content: [text(`answered ${waitId}\n`)],
509
+ structuredContent: result,
510
+ };
511
+ } catch (error) {
512
+ return toolError(messageOf(error));
513
+ }
514
+ }
515
+ case "running": {
516
+ const running: readonly RunningItem[] = await listRunning(
517
+ context.log,
518
+ context.clock,
519
+ context.views,
520
+ );
521
+ const load = (context.load ?? machineLoad)();
522
+ return {
523
+ content: [text(runningMarkdown(running, load))],
524
+ structuredContent: { items: running, load },
525
+ };
526
+ }
527
+ case "history": {
528
+ const id = String(args.id);
529
+ const content = await context.views.section(id, HISTORY_SECTION);
530
+ const result = { id, ...content };
531
+ return {
532
+ content: [text(historyMarkdown(result))],
533
+ structuredContent: result,
534
+ };
535
+ }
536
+ case "command": {
537
+ const plugin = String(args.plugin);
538
+ const verb = String(args.verb);
539
+ if (KERNEL_VERBS.has(plugin)) {
540
+ return toolError(
541
+ `"${plugin}" is a kernel verb; it is not reachable through MCP`,
542
+ );
543
+ }
544
+ const commandArgs = Array.isArray(args.args)
545
+ ? args.args.map((item) => String(item))
546
+ : [];
547
+ const argv = [plugin, verb, ...commandArgs];
548
+ const resolved = context.registry.resolveCommand(argv);
549
+ if (
550
+ resolved === undefined ||
551
+ resolved.plugin !== plugin ||
552
+ resolved.command !== verb
553
+ ) {
554
+ if (KERNEL_VERBS.has(verb)) {
555
+ return toolError(
556
+ `"${verb}" is a kernel verb; it is not reachable through MCP`,
557
+ );
558
+ }
559
+ return toolError(
560
+ `no loaded plugin "${plugin}" declares the verb "${verb}"`,
561
+ );
562
+ }
563
+ try {
564
+ const run = await context.registry.runCommand(
565
+ argv,
566
+ {
567
+ ...(context.cwd === undefined ? {} : { cwd: context.cwd }),
568
+ input: args.input === undefined ? "" : String(args.input),
569
+ },
570
+ );
571
+ if (run === undefined) {
572
+ return toolError(
573
+ `no loaded plugin "${plugin}" declares the verb "${verb}"`,
574
+ );
575
+ }
576
+ return {
577
+ content: [text(valueText(run.value))],
578
+ structuredContent: structuredValue(run.value),
579
+ };
580
+ } catch (error) {
581
+ return toolError(messageOf(error));
582
+ }
583
+ }
584
+ case "act": {
585
+ const policy = mcpPolicy(context.mcp);
586
+ const action = String(args.action);
587
+ const info = actionInfoNamed(context.registry.actions(), action);
588
+ if (info === undefined) {
589
+ return toolError(`there is no action "${action}"`);
590
+ }
591
+ if (!actionMayRun(policy, info)) {
592
+ return toolError(ownerRefusal(info.name));
593
+ }
594
+ const actionArgs =
595
+ args.args !== undefined && typeof args.args === "object" && args.args !== null
596
+ ? (args.args as Readonly<Record<string, unknown>>)
597
+ : {};
598
+ // A file argument is a file a client uploaded. This server has no upload,
599
+ // and a path the agent names is not a file the person chose to send.
600
+ const given = fileProperties(info.args).filter((file) => actionArgs[file.name] !== undefined);
601
+ if (given.length > 0) {
602
+ return toolError(
603
+ `action "${info.name}" takes a file (${given.map((file) => file.name).join(", ")}); a file is sent by a client that uploads it, not through these tools`,
604
+ );
605
+ }
606
+ const actor: Actor = { via: "mcp", id: "lead" };
607
+ try {
608
+ const run = await context.views.act(info.name, args.id === undefined ? undefined : String(args.id), {
609
+ args: actionArgs,
610
+ ...(args.note === undefined ? {} : { note: String(args.note) }),
611
+ yes: info.confirm,
612
+ actor,
613
+ });
614
+ return {
615
+ content: [text(valueText(run.value) || `ran "${run.name}"\n`)],
616
+ structuredContent: run,
617
+ };
618
+ } catch (error) {
619
+ return toolError(messageOf(error));
620
+ }
621
+ }
622
+ default:
623
+ throw new InvalidToolArguments(`unknown tool "${name}"`);
624
+ }
625
+ }
626
+
627
+ export { validateArguments };