@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/LICENSE +21 -0
- package/README.md +11 -2
- package/package.json +21 -4
- package/src/arguments.ts +91 -0
- package/src/channel.ts +658 -0
- package/src/format.ts +211 -0
- package/src/index.ts +39 -0
- package/src/policy.ts +93 -0
- package/src/server.ts +558 -0
- package/src/stdio.ts +22 -0
- package/src/tools.ts +627 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
/** The MCP stdio server: JSON-RPC framing, method dispatch and read tools. */
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { Kernel, ViewError, cancelRun, createViews, defaultOperadHome, isRecord, listPending, loadPluginRegistry, messageOf, openConfigLog, openPluginStore, readConfig, recordAnswer, storeRootOf, type ActionInfo, type LogBackend, type OperadConfig, type PluginRegistry, type Views } from "@operad-io/engine";
|
|
7
|
+
import { InvalidToolArguments } from "./arguments.ts";
|
|
8
|
+
import { actionInfoNamed, actionMayRun, mcpPolicy } from "./policy.ts";
|
|
9
|
+
import {
|
|
10
|
+
CHANNEL_CAPABILITY,
|
|
11
|
+
CHANNEL_INSTRUCTIONS,
|
|
12
|
+
CHANNEL_METHOD,
|
|
13
|
+
startClaudeChannel,
|
|
14
|
+
type ChannelHandle,
|
|
15
|
+
} from "./channel.ts";
|
|
16
|
+
import {
|
|
17
|
+
TOOLS,
|
|
18
|
+
runTool,
|
|
19
|
+
toolError,
|
|
20
|
+
validateArguments,
|
|
21
|
+
type ToolContext,
|
|
22
|
+
type ToolResult,
|
|
23
|
+
} from "./tools.ts";
|
|
24
|
+
import type { ToolDefinition } from "./tools.ts";
|
|
25
|
+
|
|
26
|
+
/** The mcp package's own version, which the server reports to a client. */
|
|
27
|
+
export const MCP_VERSION = (() => {
|
|
28
|
+
const manifest: unknown = JSON.parse(
|
|
29
|
+
readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"),
|
|
30
|
+
);
|
|
31
|
+
return isRecord(manifest) && typeof manifest.version === "string" ? manifest.version : "unknown";
|
|
32
|
+
})();
|
|
33
|
+
|
|
34
|
+
/** The MCP protocol version this server implements. */
|
|
35
|
+
export const PROTOCOL_VERSION = "2025-06-18";
|
|
36
|
+
|
|
37
|
+
/** What `initialize` tells a client when the owner allows no action. */
|
|
38
|
+
export const INSTRUCTIONS =
|
|
39
|
+
"The operad MCP server reads objects, pending items and history, and writes the commands and lead actions it is allowed to. Owner decisions are not offered here.";
|
|
40
|
+
|
|
41
|
+
/** What `initialize` tells a client, following the configured allow lists. */
|
|
42
|
+
export function instructionsFor(
|
|
43
|
+
mcp: OperadConfig["mcp"] | undefined,
|
|
44
|
+
actions: readonly ActionInfo[] = [],
|
|
45
|
+
): string {
|
|
46
|
+
const policy = mcpPolicy(mcp);
|
|
47
|
+
// An action that asks for confirmation and is not in `confirmActions` is
|
|
48
|
+
// refused when run, so it is not promised here.
|
|
49
|
+
const runnable = (name: string): boolean => {
|
|
50
|
+
const info = actionInfoNamed(actions, name);
|
|
51
|
+
return info === undefined || actionMayRun(policy, info);
|
|
52
|
+
};
|
|
53
|
+
const allowed = [...policy.actions].filter(
|
|
54
|
+
(name) => !policy.confirmActions.has(name) && runnable(name),
|
|
55
|
+
);
|
|
56
|
+
const confirmed = [...policy.confirmActions].filter(
|
|
57
|
+
(name) => policy.actions.has(name) && runnable(name),
|
|
58
|
+
);
|
|
59
|
+
if (allowed.length === 0 && confirmed.length === 0) return INSTRUCTIONS;
|
|
60
|
+
const names = [...allowed, ...confirmed].join(", ");
|
|
61
|
+
return `The operad MCP server reads objects, pending items and history, and writes the commands it is allowed to. The owner's configuration lets the lead run these actions: ${names}. Every other action stays with the owner; show lists the ones it does not offer.`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** JSON-RPC error codes used by this server. */
|
|
65
|
+
export const RPC_ERRORS = {
|
|
66
|
+
parse: -32700,
|
|
67
|
+
request: -32600,
|
|
68
|
+
method: -32601,
|
|
69
|
+
params: -32602,
|
|
70
|
+
internal: -32603,
|
|
71
|
+
} as const;
|
|
72
|
+
|
|
73
|
+
type JsonRpcId = string | number | null;
|
|
74
|
+
|
|
75
|
+
interface JsonRpcSuccess {
|
|
76
|
+
readonly jsonrpc: "2.0";
|
|
77
|
+
readonly id: JsonRpcId;
|
|
78
|
+
readonly result: unknown;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface JsonRpcFailure {
|
|
82
|
+
readonly jsonrpc: "2.0";
|
|
83
|
+
readonly id: JsonRpcId;
|
|
84
|
+
readonly error: {
|
|
85
|
+
readonly code: number;
|
|
86
|
+
readonly message: string;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type JsonRpcResponse = JsonRpcSuccess | JsonRpcFailure;
|
|
91
|
+
|
|
92
|
+
/** A stream-shaped input: a byte stream or text chunks. */
|
|
93
|
+
export interface McpInput extends AsyncIterable<Uint8Array | string> {}
|
|
94
|
+
|
|
95
|
+
/** Where the server reads and writes. Tests inject all three. */
|
|
96
|
+
export interface McpServerOptions {
|
|
97
|
+
readonly home?: string | undefined;
|
|
98
|
+
readonly cwd?: string | undefined;
|
|
99
|
+
readonly input?: McpInput | undefined;
|
|
100
|
+
readonly write?: ((text: string) => void | Promise<void>) | undefined;
|
|
101
|
+
readonly error?: ((text: string) => void | Promise<void>) | undefined;
|
|
102
|
+
readonly clock?: (() => number) | undefined;
|
|
103
|
+
/** Declare Claude Code's channel capability and push object changes. */
|
|
104
|
+
readonly claudeChannel?: boolean | undefined;
|
|
105
|
+
/** The object types the channel reports; the default is every type with views. */
|
|
106
|
+
readonly types?: readonly string[] | undefined;
|
|
107
|
+
/** Plugins whose missing package is reported as "not installed; run `operad plugin enable`". */
|
|
108
|
+
readonly installOnEnable?: readonly string[] | undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface OpenContext {
|
|
112
|
+
readonly views: Views;
|
|
113
|
+
readonly log: LogBackend;
|
|
114
|
+
readonly registry: PluginRegistry;
|
|
115
|
+
readonly kernel: Kernel;
|
|
116
|
+
readonly mcp: OperadConfig["mcp"];
|
|
117
|
+
readonly cwd: string;
|
|
118
|
+
readonly storeRoot: string;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
class RpcError extends Error {
|
|
122
|
+
readonly code: number;
|
|
123
|
+
|
|
124
|
+
constructor(code: number, message: string) {
|
|
125
|
+
super(message);
|
|
126
|
+
this.name = "RpcError";
|
|
127
|
+
this.code = code;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function validId(value: unknown): JsonRpcId | undefined {
|
|
132
|
+
return typeof value === "string" ||
|
|
133
|
+
typeof value === "number" ||
|
|
134
|
+
value === null
|
|
135
|
+
? value
|
|
136
|
+
: undefined;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function success(id: JsonRpcId, result: unknown): JsonRpcSuccess {
|
|
140
|
+
return { jsonrpc: "2.0", id, result };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function failure(id: JsonRpcId, code: number, message: string): JsonRpcFailure {
|
|
144
|
+
return { jsonrpc: "2.0", id, error: { code, message } };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function lineWriter(
|
|
148
|
+
write: (text: string) => void | Promise<void>,
|
|
149
|
+
): (response: JsonRpcResponse) => Promise<void> {
|
|
150
|
+
return async (response) => {
|
|
151
|
+
await write(`${JSON.stringify(response)}\n`);
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** One writer, so a channel notification and a response never interleave. */
|
|
156
|
+
function serializedWrite(
|
|
157
|
+
write: (text: string) => void | Promise<void>,
|
|
158
|
+
): (text: string) => Promise<void> {
|
|
159
|
+
let tail: Promise<void> = Promise.resolve();
|
|
160
|
+
return (text) => {
|
|
161
|
+
const next = tail.then(async () => {
|
|
162
|
+
await write(text);
|
|
163
|
+
});
|
|
164
|
+
tail = next.catch(() => undefined);
|
|
165
|
+
return next;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function logWriter(
|
|
170
|
+
error: (text: string) => void | Promise<void>,
|
|
171
|
+
): (message: string) => Promise<void> {
|
|
172
|
+
return async (message) => {
|
|
173
|
+
await error(`${message.replace(/\n?$/, "\n")}`);
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function openContext(
|
|
178
|
+
home: string,
|
|
179
|
+
cwd: string,
|
|
180
|
+
clock: () => number,
|
|
181
|
+
onLog: (message: string) => void | Promise<void>,
|
|
182
|
+
installOnEnable: readonly string[] | undefined,
|
|
183
|
+
): Promise<OpenContext> {
|
|
184
|
+
const config: OperadConfig = await readConfig(home);
|
|
185
|
+
const storeRoot = storeRootOf(config);
|
|
186
|
+
const store = openPluginStore({
|
|
187
|
+
backend: config.store.backend,
|
|
188
|
+
root: storeRoot,
|
|
189
|
+
});
|
|
190
|
+
const log = openConfigLog(config);
|
|
191
|
+
let loaded: PluginRegistry | undefined;
|
|
192
|
+
const registry = await loadPluginRegistry({
|
|
193
|
+
home,
|
|
194
|
+
cwd,
|
|
195
|
+
store,
|
|
196
|
+
...(installOnEnable === undefined ? {} : { installOnEnable }),
|
|
197
|
+
onCancelRun: (runId, graph) =>
|
|
198
|
+
cancelRun({
|
|
199
|
+
log,
|
|
200
|
+
flow: (name) => loaded?.flow(name)?.flow,
|
|
201
|
+
runId,
|
|
202
|
+
graph,
|
|
203
|
+
clock,
|
|
204
|
+
source: "mcp",
|
|
205
|
+
}),
|
|
206
|
+
onAnswer: async (runId, choice, note, actor) => {
|
|
207
|
+
await recordAnswer({
|
|
208
|
+
log,
|
|
209
|
+
runId,
|
|
210
|
+
choice,
|
|
211
|
+
...(note === undefined ? {} : { note }),
|
|
212
|
+
actor,
|
|
213
|
+
});
|
|
214
|
+
},
|
|
215
|
+
onLog: (message) => {
|
|
216
|
+
void onLog(message);
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
loaded = registry;
|
|
220
|
+
const views = createViews({
|
|
221
|
+
registry,
|
|
222
|
+
store,
|
|
223
|
+
log,
|
|
224
|
+
cwd,
|
|
225
|
+
clock,
|
|
226
|
+
onLog: (message) => {
|
|
227
|
+
void onLog(message);
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
const kernel = new Kernel({
|
|
231
|
+
log,
|
|
232
|
+
registry,
|
|
233
|
+
home,
|
|
234
|
+
storeRoot,
|
|
235
|
+
clock,
|
|
236
|
+
onLog: (message) => {
|
|
237
|
+
void onLog(message);
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
return { views, log, registry, kernel, mcp: config.mcp, cwd, storeRoot };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function toolContext(
|
|
244
|
+
context: OpenContext,
|
|
245
|
+
clock: () => number,
|
|
246
|
+
): ToolContext {
|
|
247
|
+
return {
|
|
248
|
+
views: context.views,
|
|
249
|
+
log: context.log,
|
|
250
|
+
registry: context.registry,
|
|
251
|
+
kernel: context.kernel,
|
|
252
|
+
clock,
|
|
253
|
+
cwd: context.cwd,
|
|
254
|
+
mcp: context.mcp,
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function requireEmptyParams(params: unknown): void {
|
|
259
|
+
if (params === undefined || params === null) return;
|
|
260
|
+
if (!isRecord(params) || Object.keys(params).length > 0) {
|
|
261
|
+
throw new RpcError(RPC_ERRORS.params, "this method takes no parameters");
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function toolByName(name: string): ToolDefinition | undefined {
|
|
266
|
+
return TOOLS.find((tool) => tool.name === name);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function callTool(
|
|
270
|
+
params: unknown,
|
|
271
|
+
context: ToolContext,
|
|
272
|
+
): Promise<unknown> {
|
|
273
|
+
if (!isRecord(params)) {
|
|
274
|
+
throw new RpcError(RPC_ERRORS.params, "tools/call needs an object of parameters");
|
|
275
|
+
}
|
|
276
|
+
const name = params.name;
|
|
277
|
+
if (typeof name !== "string" || name.length === 0) {
|
|
278
|
+
throw new RpcError(RPC_ERRORS.params, "tools/call needs a tool name");
|
|
279
|
+
}
|
|
280
|
+
const tool = toolByName(name);
|
|
281
|
+
if (tool === undefined) {
|
|
282
|
+
throw new RpcError(RPC_ERRORS.params, `unknown tool "${name}"`);
|
|
283
|
+
}
|
|
284
|
+
let args: Record<string, unknown>;
|
|
285
|
+
try {
|
|
286
|
+
args = validateArguments(
|
|
287
|
+
tool.inputSchema,
|
|
288
|
+
params.arguments === undefined ? {} : params.arguments,
|
|
289
|
+
);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
if (error instanceof InvalidToolArguments) {
|
|
292
|
+
throw new RpcError(RPC_ERRORS.params, error.message);
|
|
293
|
+
}
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
return await runTool(name, args, context);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (error instanceof ViewError) {
|
|
300
|
+
return {
|
|
301
|
+
content: [{ type: "text", text: error.message }],
|
|
302
|
+
isError: true,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function dispatch(
|
|
310
|
+
method: string,
|
|
311
|
+
params: unknown,
|
|
312
|
+
context: ToolContext,
|
|
313
|
+
claudeChannel: boolean,
|
|
314
|
+
): Promise<unknown> {
|
|
315
|
+
switch (method) {
|
|
316
|
+
case "initialize":
|
|
317
|
+
if (params !== undefined && params !== null && !isRecord(params)) {
|
|
318
|
+
throw new RpcError(RPC_ERRORS.params, "initialize needs an object of parameters");
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
322
|
+
capabilities: claudeChannel
|
|
323
|
+
? {
|
|
324
|
+
tools: {},
|
|
325
|
+
experimental: { [CHANNEL_CAPABILITY]: {} },
|
|
326
|
+
}
|
|
327
|
+
: { tools: {} },
|
|
328
|
+
serverInfo: { name: "operad", version: MCP_VERSION },
|
|
329
|
+
instructions: claudeChannel
|
|
330
|
+
? `${instructionsFor(context.mcp, context.registry.actions())}\n\n${CHANNEL_INSTRUCTIONS}`
|
|
331
|
+
: instructionsFor(context.mcp, context.registry.actions()),
|
|
332
|
+
};
|
|
333
|
+
case "ping":
|
|
334
|
+
requireEmptyParams(params);
|
|
335
|
+
return {};
|
|
336
|
+
case "tools/list":
|
|
337
|
+
requireEmptyParams(params);
|
|
338
|
+
return { tools: TOOLS };
|
|
339
|
+
case "tools/call":
|
|
340
|
+
return callTool(params, context);
|
|
341
|
+
default:
|
|
342
|
+
throw new RpcError(RPC_ERRORS.method, `no method "${method}"`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function handleLine(
|
|
347
|
+
line: string,
|
|
348
|
+
context: ToolContext,
|
|
349
|
+
send: (response: JsonRpcResponse) => Promise<void>,
|
|
350
|
+
log: (message: string) => Promise<void>,
|
|
351
|
+
claudeChannel: boolean,
|
|
352
|
+
onInitialized: () => void,
|
|
353
|
+
): Promise<void> {
|
|
354
|
+
let message: unknown;
|
|
355
|
+
try {
|
|
356
|
+
message = JSON.parse(line);
|
|
357
|
+
} catch {
|
|
358
|
+
await send(failure(null, RPC_ERRORS.parse, "the line is not JSON"));
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (!isRecord(message)) {
|
|
362
|
+
await send(failure(null, RPC_ERRORS.request, "the message must be an object"));
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const givenId = message.id;
|
|
367
|
+
const id = validId(givenId);
|
|
368
|
+
const hasId = Object.prototype.hasOwnProperty.call(message, "id");
|
|
369
|
+
if (
|
|
370
|
+
message.jsonrpc !== "2.0" ||
|
|
371
|
+
typeof message.method !== "string" ||
|
|
372
|
+
(hasId && id === undefined)
|
|
373
|
+
) {
|
|
374
|
+
await send(
|
|
375
|
+
failure(id ?? null, RPC_ERRORS.request, "the message is not a JSON-RPC 2.0 request"),
|
|
376
|
+
);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// A notification has no id and never gets a response, including an unknown
|
|
381
|
+
// one. `notifications/initialized` is the only one MCP defines here, and it
|
|
382
|
+
// lets the channel send what it held.
|
|
383
|
+
if (!hasId) {
|
|
384
|
+
if (message.method === "notifications/initialized") onInitialized();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (id === undefined) return;
|
|
388
|
+
|
|
389
|
+
try {
|
|
390
|
+
const result = await dispatch(
|
|
391
|
+
message.method,
|
|
392
|
+
message.params,
|
|
393
|
+
context,
|
|
394
|
+
claudeChannel,
|
|
395
|
+
);
|
|
396
|
+
await send(success(id, result));
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (error instanceof RpcError) {
|
|
399
|
+
await send(failure(id, error.code, error.message));
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
await log(`operad mcp: ${messageOf(error)}`);
|
|
403
|
+
await send(
|
|
404
|
+
failure(id, RPC_ERRORS.internal, "the request failed"),
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
async function* decodeLines(
|
|
410
|
+
input: AsyncIterable<Uint8Array | string>,
|
|
411
|
+
): AsyncGenerator<string> {
|
|
412
|
+
const decoder = new TextDecoder();
|
|
413
|
+
let buffer = "";
|
|
414
|
+
for await (const chunk of input) {
|
|
415
|
+
buffer +=
|
|
416
|
+
typeof chunk === "string"
|
|
417
|
+
? chunk
|
|
418
|
+
: decoder.decode(chunk, { stream: true });
|
|
419
|
+
for (;;) {
|
|
420
|
+
const at = buffer.indexOf("\n");
|
|
421
|
+
if (at < 0) break;
|
|
422
|
+
const line = buffer.slice(0, at).replace(/\r$/, "");
|
|
423
|
+
buffer = buffer.slice(at + 1);
|
|
424
|
+
if (line.trim().length === 0) continue;
|
|
425
|
+
yield line;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
buffer += decoder.decode();
|
|
429
|
+
const last = buffer.replace(/\r$/, "");
|
|
430
|
+
if (last.trim().length > 0) yield last;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Runs the MCP server until stdin ends. It opens the configured home like a
|
|
435
|
+
* command does, serves the presentation views and the allowed writes, and
|
|
436
|
+
* never runs a step.
|
|
437
|
+
*/
|
|
438
|
+
export async function runMcpServer(
|
|
439
|
+
options: McpServerOptions = {},
|
|
440
|
+
): Promise<void> {
|
|
441
|
+
const home = options.home ?? defaultOperadHome();
|
|
442
|
+
const cwd = options.cwd ?? process.cwd();
|
|
443
|
+
const clock = options.clock ?? (() => Date.now());
|
|
444
|
+
const write = serializedWrite(
|
|
445
|
+
options.write ?? ((text: string) => void process.stdout.write(text)),
|
|
446
|
+
);
|
|
447
|
+
const error = options.error ?? ((text: string) => void process.stderr.write(text));
|
|
448
|
+
const log = logWriter(error);
|
|
449
|
+
const send = lineWriter(write);
|
|
450
|
+
const input = options.input ?? Bun.stdin.stream();
|
|
451
|
+
|
|
452
|
+
const opened = await openContext(home, cwd, clock, log, options.installOnEnable);
|
|
453
|
+
let channel: ChannelHandle | undefined;
|
|
454
|
+
try {
|
|
455
|
+
if (options.claudeChannel === true) {
|
|
456
|
+
channel = await startClaudeChannel({
|
|
457
|
+
views: opened.views,
|
|
458
|
+
registry: opened.registry,
|
|
459
|
+
log: opened.log,
|
|
460
|
+
hold: true,
|
|
461
|
+
notify: opened.mcp.channel.notify,
|
|
462
|
+
loopAfter: opened.mcp.channel.loopAfter,
|
|
463
|
+
pending: () =>
|
|
464
|
+
listPending(
|
|
465
|
+
opened.log,
|
|
466
|
+
opened.registry,
|
|
467
|
+
opened.kernel,
|
|
468
|
+
opened.views,
|
|
469
|
+
{ withAuto: true },
|
|
470
|
+
),
|
|
471
|
+
sentFile: join(
|
|
472
|
+
home,
|
|
473
|
+
`mcp-channel-${new Bun.CryptoHasher("sha1").update(opened.storeRoot).digest("hex").slice(0, 12)}.json`,
|
|
474
|
+
),
|
|
475
|
+
...(options.types === undefined ? {} : { types: options.types }),
|
|
476
|
+
send: async (notification) => {
|
|
477
|
+
await write(
|
|
478
|
+
`${JSON.stringify({
|
|
479
|
+
jsonrpc: "2.0",
|
|
480
|
+
method: CHANNEL_METHOD,
|
|
481
|
+
params: notification,
|
|
482
|
+
})}\n`,
|
|
483
|
+
);
|
|
484
|
+
},
|
|
485
|
+
onLog: (message) => {
|
|
486
|
+
void log(message);
|
|
487
|
+
},
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
const context = toolContext(opened, clock);
|
|
491
|
+
for await (const line of decodeLines(input)) {
|
|
492
|
+
await handleLine(line, context, send, log, channel !== undefined, () => {
|
|
493
|
+
void channel?.release();
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
} finally {
|
|
497
|
+
await channel?.close();
|
|
498
|
+
opened.views.close();
|
|
499
|
+
await opened.log.close();
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** The tools of the server, opened in this process for a harness that takes tools in-process. */
|
|
504
|
+
export interface McpTools {
|
|
505
|
+
readonly tools: readonly ToolDefinition[];
|
|
506
|
+
/** Runs one tool; a refusal of a view or a bad argument is an error result, never a throw. */
|
|
507
|
+
call(name: string, args: unknown): Promise<ToolResult>;
|
|
508
|
+
close(): Promise<void>;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** What `openMcpTools` reads. */
|
|
512
|
+
export interface OpenMcpToolsOptions {
|
|
513
|
+
readonly home?: string | undefined;
|
|
514
|
+
readonly cwd?: string | undefined;
|
|
515
|
+
readonly clock?: (() => number) | undefined;
|
|
516
|
+
readonly onLog?: ((message: string) => void) | undefined;
|
|
517
|
+
/** Plugins whose missing package is reported as "not installed; run `operad plugin enable`". */
|
|
518
|
+
readonly installOnEnable?: readonly string[] | undefined;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* Opens the home and offers the same tools `runMcpServer` serves, without the
|
|
523
|
+
* protocol: the caller is a harness that registers them as its own tools.
|
|
524
|
+
*/
|
|
525
|
+
export async function openMcpTools(options: OpenMcpToolsOptions = {}): Promise<McpTools> {
|
|
526
|
+
const home = options.home ?? defaultOperadHome();
|
|
527
|
+
const clock = options.clock ?? (() => Date.now());
|
|
528
|
+
const opened = await openContext(
|
|
529
|
+
home,
|
|
530
|
+
options.cwd ?? process.cwd(),
|
|
531
|
+
clock,
|
|
532
|
+
(message) => {
|
|
533
|
+
options.onLog?.(message);
|
|
534
|
+
},
|
|
535
|
+
options.installOnEnable,
|
|
536
|
+
);
|
|
537
|
+
const context = toolContext(opened, clock);
|
|
538
|
+
return {
|
|
539
|
+
tools: TOOLS,
|
|
540
|
+
async call(name, args) {
|
|
541
|
+
const tool = toolByName(name);
|
|
542
|
+
if (tool === undefined) return toolError(`unknown tool "${name}"`);
|
|
543
|
+
try {
|
|
544
|
+
const checked = validateArguments(tool.inputSchema, args === undefined ? {} : args);
|
|
545
|
+
return await runTool(name, checked, context);
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (error instanceof ViewError || error instanceof InvalidToolArguments) {
|
|
548
|
+
return toolError(error.message);
|
|
549
|
+
}
|
|
550
|
+
throw error;
|
|
551
|
+
}
|
|
552
|
+
},
|
|
553
|
+
async close() {
|
|
554
|
+
opened.views.close();
|
|
555
|
+
await opened.log.close();
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
}
|
package/src/stdio.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MCP server as a program a harness starts: `bun stdio.ts [--home <dir>]`.
|
|
3
|
+
* It is `operad mcp` without the `operad` command, for a harness that is given
|
|
4
|
+
* the tools as a server to start (the home is `OPERAD_HOME` when no `--home`).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { defaultOperadHome } from "@operad-io/engine";
|
|
8
|
+
import { runMcpServer } from "./server.ts";
|
|
9
|
+
|
|
10
|
+
/** The home `--home` names, or the configured default. */
|
|
11
|
+
export function homeFromArgs(args: readonly string[]): string {
|
|
12
|
+
const at = args.indexOf("--home");
|
|
13
|
+
if (at < 0) return defaultOperadHome();
|
|
14
|
+
return args[at + 1] ?? defaultOperadHome();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (import.meta.main) {
|
|
18
|
+
await runMcpServer({
|
|
19
|
+
home: homeFromArgs(process.argv.slice(2)),
|
|
20
|
+
cwd: process.cwd(),
|
|
21
|
+
});
|
|
22
|
+
}
|