@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/format.ts ADDED
@@ -0,0 +1,211 @@
1
+ /** One Markdown rendering per read tool, carrying the same data as its result. */
2
+
3
+ import type {
4
+ PendingItem,
5
+ RunningItem,
6
+ ViewListPage,
7
+ ViewObject,
8
+ ViewRow,
9
+ ViewSectionContent,
10
+ ViewTypeInfo,
11
+ } from "@operad-io/engine";
12
+ import type { MachineLoad } from "@operad-io/engine/platform";
13
+ import type { McpViewObject } from "./policy.ts";
14
+
15
+ function cell(value: string): string {
16
+ return value.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
17
+ }
18
+
19
+ function flags(row: ViewRow): string {
20
+ const names: string[] = [];
21
+ if (row.waiting) names.push("waiting");
22
+ if (row.running) names.push("running");
23
+ return names.length === 0 ? "-" : names.join(", ");
24
+ }
25
+
26
+ function rowName(row: ViewRow): string {
27
+ return row.scope === undefined ? row.id : `${row.scope}/${row.id}`;
28
+ }
29
+
30
+ /** A list page as a Markdown table with a trailing cursor line. */
31
+ export function listMarkdown(page: ViewListPage): string {
32
+ const lines: string[] = [];
33
+ if (page.rows.length === 0) {
34
+ lines.push("No objects.");
35
+ } else {
36
+ lines.push("| id | state | mark | badge | title | note | wait | flags |");
37
+ lines.push("| --- | --- | --- | --- | --- | --- | --- | --- |");
38
+ for (const row of page.rows) {
39
+ lines.push(
40
+ `| ${cell(rowName(row))} | ${cell(row.state)} | ${cell(row.mark ?? "")} | ${cell(row.badge ?? "")} | ${cell(row.title)} | ${cell(row.note ?? "")} | ${cell(row.wait ?? "")} | ${flags(row)} |`,
41
+ );
42
+ }
43
+ }
44
+ if (page.next !== undefined) {
45
+ lines.push("", `Next cursor: \`${page.next}\``);
46
+ }
47
+ return `${lines.join("\n")}\n`;
48
+ }
49
+
50
+ /** Every object type with views, its plugin and where a client puts it. */
51
+ export function typesMarkdown(types: readonly ViewTypeInfo[]): string {
52
+ if (types.length === 0) return "No object types.\n";
53
+ const lines = [
54
+ "| type | title | plugin | settings | filters | parents |",
55
+ "| --- | --- | --- | --- | --- | --- |",
56
+ ];
57
+ for (const info of types) {
58
+ const filters = (info.filters ?? []).map((filter) => filter.name).join(", ");
59
+ lines.push(
60
+ `| ${cell(info.type)} | ${cell(info.title)} | ${cell(info.plugin)} | ${info.settings === true ? "yes" : "no"} | ${cell(filters)} | ${cell((info.parents ?? []).join(", "))} |`,
61
+ );
62
+ }
63
+ return `${lines.join("\n")}\n`;
64
+ }
65
+
66
+ function actionMarkdown(action: ViewObject["actions"][number]): string[] {
67
+ const key = action.key === undefined ? "" : ` (${action.key})`;
68
+ const lines = [`- \`${action.name}\`${key}`];
69
+ lines.push(` - on: \`${action.on}\``);
70
+ lines.push(
71
+ ` - note: ${action.note === undefined ? "none" : `\`${action.note}\`${action.noteRequired ? " (required)" : ""}`}`,
72
+ );
73
+ lines.push(` - confirm: ${action.confirm ? "yes" : "no"}`);
74
+ if (action.creates !== undefined) lines.push(` - creates: \`${action.creates}\``);
75
+ if (action.args === undefined) {
76
+ lines.push(" - args: none");
77
+ } else {
78
+ lines.push(" - args:");
79
+ lines.push(" ```json");
80
+ for (const line of JSON.stringify(action.args, null, 2).split("\n")) {
81
+ lines.push(` ${line}`);
82
+ }
83
+ lines.push(" ```");
84
+ }
85
+ return lines;
86
+ }
87
+
88
+ /** One object as its row, section directory, actions and link. */
89
+ export function showMarkdown(object: ViewObject | McpViewObject): string {
90
+ const row = object.row;
91
+ const lines = [`# ${row.title}`, ""];
92
+ lines.push(`- id: \`${rowName(row)}\``);
93
+ lines.push(`- type: \`${object.type}\``);
94
+ lines.push(`- state: ${row.state}`);
95
+ if (row.mark !== undefined) lines.push(`- mark: ${row.mark}`);
96
+ if (row.badge !== undefined) lines.push(`- badge: ${row.badge}`);
97
+ if (row.parent !== undefined) lines.push(`- parent: ${row.parent}`);
98
+ if (object.dependents !== undefined) {
99
+ lines.push(`- after this one: ${object.dependents.join(", ")}`);
100
+ }
101
+ lines.push(`- flags: ${flags(row)}`);
102
+ if (row.note !== undefined) lines.push(`- note: ${row.note}`);
103
+ if (row.wait !== undefined) lines.push(`- wait: ${row.wait}`);
104
+ if (row.error !== undefined) lines.push(`- error: ${row.error}`);
105
+ lines.push(`- link: ${object.link}`);
106
+ if (object.unavailable !== undefined) {
107
+ lines.push(`- unavailable: ${object.unavailable}`);
108
+ }
109
+
110
+ lines.push("", "## Sections");
111
+ if (object.sections.length === 0) {
112
+ lines.push("No sections.");
113
+ } else {
114
+ for (const section of object.sections) {
115
+ lines.push(
116
+ `- \`${section.id}\`: ${section.title}${section.live === true ? " (live)" : ""}`,
117
+ );
118
+ }
119
+ }
120
+
121
+ lines.push("", "## Actions");
122
+ if (object.actions.length === 0) {
123
+ lines.push("No actions are available now.");
124
+ } else {
125
+ for (const action of object.actions) lines.push(...actionMarkdown(action));
126
+ }
127
+
128
+ const ownerActions = "ownerActions" in object ? object.ownerActions : [];
129
+ if (ownerActions.length > 0) {
130
+ lines.push("", "## Owner actions");
131
+ for (const name of ownerActions) {
132
+ lines.push(`- \`${name}\`: the owner runs it`);
133
+ }
134
+ }
135
+ return `${lines.join("\n")}\n`;
136
+ }
137
+
138
+ /** A plugin verb's or action's value as the CLI prints it. */
139
+ export function valueText(value: unknown): string {
140
+ if (value === undefined) return "";
141
+ if (typeof value === "string") return `${value}\n`;
142
+ return `${JSON.stringify(value, null, 2)}\n`;
143
+ }
144
+
145
+ /** A section's Markdown, with the cursor named when another page follows. */
146
+ export function sectionMarkdown(content: ViewSectionContent): string {
147
+ if (content.next === undefined) return content.markdown;
148
+ const separator = content.markdown.endsWith("\n") ? "\n" : "\n\n";
149
+ return `${content.markdown}${separator}Next cursor: \`${content.next}\`\n`;
150
+ }
151
+
152
+ /** The history tool's Markdown is the history section's Markdown. */
153
+ export function historyMarkdown(content: ViewSectionContent): string {
154
+ return sectionMarkdown(content);
155
+ }
156
+
157
+ function pendingItemMarkdown(item: PendingItem): string[] {
158
+ const lines = [`## ${item.runId} (${item.flow})`];
159
+ lines.push(`- step: ${item.step ?? "-"}`);
160
+ lines.push(`- waiting: ${item.prompt}`);
161
+ if (item.choices.length > 0) {
162
+ lines.push(`- choices: ${item.choices.join(", ")}`);
163
+ }
164
+ if (item.actions.length > 0) {
165
+ lines.push(
166
+ `- actions: ${item.actions.map((action) => `${action.plugin}:${action.action}`).join(", ")}`,
167
+ );
168
+ }
169
+ if (item.object !== undefined) lines.push(`- object: \`${item.object}\``);
170
+ if (item.link !== undefined) lines.push(`- link: ${item.link}`);
171
+ return lines;
172
+ }
173
+
174
+ /** Everything waiting for a person, one section per item. */
175
+ export function pendingMarkdown(pending: readonly PendingItem[]): string {
176
+ if (pending.length === 0) return "Nothing is waiting.\n";
177
+ const lines = ["# Pending", ""];
178
+ for (const [index, item] of pending.entries()) {
179
+ if (index > 0) lines.push("");
180
+ lines.push(...pendingItemMarkdown(item));
181
+ }
182
+ return `${lines.join("\n")}\n`;
183
+ }
184
+
185
+ function elapsed(ms: number): string {
186
+ if (ms < 1000) return `${ms}ms`;
187
+ const whole = Math.floor(ms / 1000);
188
+ if (whole < 60) return `${(ms / 1000).toFixed(1)}s`;
189
+ const minutes = Math.floor(whole / 60);
190
+ const rest = whole % 60;
191
+ return `${minutes}m ${rest}s`;
192
+ }
193
+
194
+ /** Every active run as a Markdown table. */
195
+ export function runningMarkdown(
196
+ running: readonly RunningItem[],
197
+ load: MachineLoad,
198
+ ): string {
199
+ const loadLine = `Load: ${load.load1} (1 minute), ${load.cores} cores\n`;
200
+ if (running.length === 0) return `Nothing is running.\n\n${loadLine}`;
201
+ const lines = [
202
+ "| object | title | flow | step | step time | run |",
203
+ "| --- | --- | --- | --- | --- | --- |",
204
+ ];
205
+ for (const item of running) {
206
+ lines.push(
207
+ `| ${cell(item.object ?? item.runId)} | ${cell(item.title ?? "")} | ${cell(item.flow)} | ${cell(item.stepLabel ?? "-")} | ${item.stepElapsedMs === null ? "-" : elapsed(item.stepElapsedMs)}${item.queuedMs === undefined || item.queuedMs <= 0 ? "" : ` (queued ${elapsed(item.queuedMs)})`} | ${elapsed(item.elapsedMs)} |`,
208
+ );
209
+ }
210
+ return `${lines.join("\n")}\n\n${loadLine}`;
211
+ }
package/src/index.ts ADDED
@@ -0,0 +1,39 @@
1
+ export {
2
+ INSTRUCTIONS,
3
+ instructionsFor,
4
+ MCP_VERSION,
5
+ PROTOCOL_VERSION,
6
+ RPC_ERRORS,
7
+ openMcpTools,
8
+ runMcpServer,
9
+ type McpInput,
10
+ type McpTools,
11
+ type OpenMcpToolsOptions,
12
+ type McpServerOptions,
13
+ } from "./server.ts";
14
+ export {
15
+ CHANNEL_CAPABILITY,
16
+ CHANNEL_INSTRUCTIONS,
17
+ CHANNEL_METHOD,
18
+ CHANNEL_PERMISSION_CAPABILITY,
19
+ ChannelNotifyError,
20
+ ChannelTypeError,
21
+ type ChannelReason,
22
+ startClaudeChannel,
23
+ type ChannelHandle,
24
+ type ChannelNotification,
25
+ type ChannelOptions,
26
+ } from "./channel.ts";
27
+ export {
28
+ TOOLS,
29
+ runTool,
30
+ toolError,
31
+ validateArguments,
32
+ type InputPropertySchema,
33
+ type InputSchema,
34
+ type ToolContext,
35
+ type ToolDefinition,
36
+ type ToolResult,
37
+ type ToolTextContent,
38
+ } from "./tools.ts";
39
+ export { InvalidToolArguments } from "./arguments.ts";
package/src/policy.ts ADDED
@@ -0,0 +1,93 @@
1
+ /** Which actions a lead may run through MCP, and which stay with the owner. */
2
+
3
+ import {
4
+ DEFAULT_MCP,
5
+ splitActionName,
6
+ type ActionInfo,
7
+ type McpConfig,
8
+ type PendingItem,
9
+ type ViewAction,
10
+ type ViewObject,
11
+ } from "@operad-io/engine";
12
+
13
+ /** The configured allow lists, prepared for lookups. */
14
+ export interface McpPolicy {
15
+ readonly actions: ReadonlySet<string>;
16
+ readonly confirmActions: ReadonlySet<string>;
17
+ }
18
+
19
+ /** Reads a config's `mcp` section, or the defaults when it has none. */
20
+ export function mcpPolicy(config: McpConfig | undefined): McpPolicy {
21
+ const value = config ?? DEFAULT_MCP;
22
+ return {
23
+ actions: new Set(value.actions),
24
+ confirmActions: new Set(value.confirmActions),
25
+ };
26
+ }
27
+
28
+ /** Whether the lead may run this action with the configured allow lists. */
29
+ export function actionMayRun(
30
+ policy: McpPolicy,
31
+ action: Pick<ActionInfo, "name" | "confirm">,
32
+ ): boolean {
33
+ return (
34
+ policy.actions.has(action.name) &&
35
+ (action.confirm !== true || policy.confirmActions.has(action.name))
36
+ );
37
+ }
38
+
39
+ /** The one refusal message for an action the owner keeps. */
40
+ export function ownerRefusal(name: string): string {
41
+ return `action "${name}" is not allowed through MCP; the owner runs it`;
42
+ }
43
+
44
+ /** Finds an action by `<plugin>:<action>` or a unique plain action name. */
45
+ export function actionInfoNamed(
46
+ actions: readonly ActionInfo[],
47
+ name: string,
48
+ ): ActionInfo | undefined {
49
+ const split = splitActionName(name);
50
+ if (split !== undefined) {
51
+ return actions.find(
52
+ (info) => info.plugin === split.plugin && info.action === split.action,
53
+ );
54
+ }
55
+ const matches = actions.filter((info) => info.action === name);
56
+ return matches.length === 1 ? matches[0] : undefined;
57
+ }
58
+
59
+ /** A shown object with the lead's actions separated from the owner's. */
60
+ export interface McpViewObject extends ViewObject {
61
+ /** The names of the available actions the lead may not run. */
62
+ readonly ownerActions: readonly string[];
63
+ }
64
+
65
+ /** Splits the available actions into the lead's and the owner's. */
66
+ export function splitActions(
67
+ object: ViewObject,
68
+ policy: McpPolicy,
69
+ ): McpViewObject {
70
+ const actions: ViewAction[] = [];
71
+ const ownerActions: string[] = [];
72
+ for (const action of object.actions) {
73
+ if (actionMayRun(policy, action)) actions.push(action);
74
+ else ownerActions.push(action.name);
75
+ }
76
+ return { ...object, actions, ownerActions };
77
+ }
78
+
79
+ /** Keeps only the pending actions the lead may run. */
80
+ export function splitPendingActions(
81
+ pending: readonly PendingItem[],
82
+ actions: readonly ActionInfo[],
83
+ policy: McpPolicy,
84
+ ): readonly PendingItem[] {
85
+ const byName = new Map(actions.map((info) => [info.name, info]));
86
+ return pending.map((item) => ({
87
+ ...item,
88
+ actions: item.actions.filter((action) => {
89
+ const info = byName.get(`${action.plugin}:${action.action}`);
90
+ return info !== undefined && actionMayRun(policy, info);
91
+ }),
92
+ }));
93
+ }