codex-supervisor-mcp 0.0.0-stage → 0.4.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.
@@ -0,0 +1,599 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { z } from "zod";
5
+ import {
6
+ cancelCodexWorker,
7
+ createCodexWorker,
8
+ createFollowupWorker,
9
+ resumeCodexWorker
10
+ } from "./codex-runner.js";
11
+ import {
12
+ getTask,
13
+ getTasks,
14
+ listTaskEventKinds,
15
+ readTaskEvents,
16
+ readTasks,
17
+ readTasksBySession,
18
+ reconcileDetachedActiveTasks,
19
+ searchTasks,
20
+ upsertTask
21
+ } from "./task-store.js";
22
+ import { readNativeGoal } from "./goal-store.js";
23
+ import { mergeChangedFiles, readWorktreeChanges } from "./worktree.js";
24
+ import { ACTIVE_STATUSES, TERMINAL_STATUSES, TASK_STATUSES, isGoalNeedingAttention } from "./status.js";
25
+ import { approxTokenCount, truncateEventStrings } from "./truncate.js";
26
+
27
+ const server = new McpServer({
28
+ name: "codex-supervisor",
29
+ version: "0.4.0"
30
+ });
31
+
32
+ const OVERVIEW_BYTE_BUDGET = 7000;
33
+ const OVERVIEW_CAP_LEVELS = [
34
+ { title: 40, goal: 60, action: 60, path: 60 },
35
+ { title: 28, goal: 40, action: 40, path: 40 },
36
+ { title: 18, goal: 24, action: 24, path: 24 },
37
+ { title: 12, goal: 16, action: 16, path: 16 }
38
+ ];
39
+
40
+ function textResult(value) {
41
+ return {
42
+ content: [
43
+ {
44
+ type: "text",
45
+ text: typeof value === "string" ? value : JSON.stringify(value, null, 2)
46
+ }
47
+ ]
48
+ };
49
+ }
50
+
51
+ function clip(value, maxChars) {
52
+ if (value === null || value === undefined) return null;
53
+ const text = String(value);
54
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;
55
+ }
56
+
57
+ function sleep(ms) {
58
+ return new Promise((resolve) => setTimeout(resolve, ms));
59
+ }
60
+
61
+ function summarizeTask(task) {
62
+ return {
63
+ id: task.id,
64
+ title: task.title,
65
+ worker: task.worker,
66
+ status: task.status,
67
+ phase: task.phase ?? null,
68
+ cwd: task.cwd,
69
+ project_root: task.project_root,
70
+ sandbox: task.sandbox,
71
+ model: task.model,
72
+ reasoning_effort: task.reasoning_effort ?? "high",
73
+ thread_id: task.thread_id,
74
+ followup_of: task.followup_of,
75
+ resumed_from: task.resumed_from,
76
+ depends_on: task.depends_on ?? [],
77
+ owned_paths: task.owned_paths ?? [],
78
+ worktree_path: task.worktree_path,
79
+ goal_objective: task.goal_objective,
80
+ goal_token_budget: task.goal_token_budget,
81
+ goal_status: task.goal_status,
82
+ changed_file_count: (task.changed_files ?? []).length,
83
+ command_count: (task.commands ?? []).length,
84
+ run_count: task.run_count ?? 0,
85
+ current_action: task.current_action,
86
+ last_event_type: task.last_event_type,
87
+ last_message: clip(task.last_message, 400),
88
+ notices: clip(task.notices, 400),
89
+ error: task.error,
90
+ created_at: task.created_at,
91
+ updated_at: task.updated_at,
92
+ started_at: task.started_at,
93
+ completed_at: task.completed_at,
94
+ exit_code: task.exit_code
95
+ };
96
+ }
97
+
98
+ function overviewRow(task, caps) {
99
+ return {
100
+ id: task.id,
101
+ title: clip(task.title, caps.title),
102
+ status: task.status,
103
+ phase: task.phase ?? null,
104
+ goal: clip(task.goal_objective, caps.goal),
105
+ goal_status: task.goal_status ?? null,
106
+ last_action: clip(task.current_action, caps.action),
107
+ changed_files: (task.changed_files ?? []).length,
108
+ depends_on: task.depends_on ?? [],
109
+ owned_paths: (task.owned_paths ?? []).map((entry) => clip(entry, caps.path))
110
+ };
111
+ }
112
+
113
+ // One line per work for the listing tools. Kept deliberately small: the caller
114
+ // is usually a main thread that will drill into at most one of these.
115
+ function workRow(task) {
116
+ return {
117
+ id: task.id,
118
+ title: task.title,
119
+ status: task.status,
120
+ phase: task.phase ?? null,
121
+ goal: task.goal_objective ?? null,
122
+ session_id: task.session_id ?? null,
123
+ thread_id: task.thread_id ?? null,
124
+ created_at: task.created_at,
125
+ updated_at: task.updated_at
126
+ };
127
+ }
128
+
129
+ // The overview is the tool the orchestrator calls by default, so it has to fit
130
+ // a fixed budget no matter how long titles and goals are. Field caps are
131
+ // lowered until the payload fits, and the payload reports what it cost.
132
+ function settleTokenCount(payload) {
133
+ // The reported cost has to include the field that reports it, so iterate to
134
+ // a fixed point instead of measuring a payload that lacks the number.
135
+ let tokens = 0;
136
+ for (let attempt = 0; attempt < 6; attempt += 1) {
137
+ payload.approx_tokens = tokens;
138
+ const next = approxTokenCount(JSON.stringify(payload));
139
+ if (next === tokens) break;
140
+ tokens = next;
141
+ }
142
+ payload.approx_tokens = tokens;
143
+ return Buffer.byteLength(JSON.stringify(payload), "utf8");
144
+ }
145
+
146
+ function buildOverview(tasks) {
147
+ let payload;
148
+ for (const [index, caps] of OVERVIEW_CAP_LEVELS.entries()) {
149
+ payload = {
150
+ generated_at: new Date().toISOString(),
151
+ total: tasks.length,
152
+ active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
153
+ needs_attention: tasks
154
+ .filter((task) => task.status === "running" && isGoalNeedingAttention(task.goal_status))
155
+ .map((task) => task.id),
156
+ workers: tasks.map((task) => overviewRow(task, caps))
157
+ };
158
+ const bytes = settleTokenCount(payload);
159
+ if (bytes <= OVERVIEW_BYTE_BUDGET) return payload;
160
+ if (index === OVERVIEW_CAP_LEVELS.length - 1) {
161
+ payload.budget_exceeded = true;
162
+ payload.truncated_fields = true;
163
+ settleTokenCount(payload);
164
+ return payload;
165
+ }
166
+ delete payload.approx_tokens;
167
+ }
168
+ return payload;
169
+ }
170
+
171
+ function buildWorkerSummary(task, nativeGoal) {
172
+ // Read the worktree too: a worker that edits via shell commands emits no
173
+ // file_change events, so the checkout is the authoritative diff.
174
+ const changed = mergeChangedFiles(task.changed_files, readWorktreeChanges(task.worktree_path));
175
+ const commands = task.commands ?? [];
176
+ const lines = [
177
+ `${task.title ?? task.id} — status=${task.status}${task.phase ? `, phase=${task.phase}` : ""}`,
178
+ `goal: ${task.goal_objective ?? "-"}${task.goal_token_budget ? ` (budget ${task.goal_token_budget} tokens)` : ""}`,
179
+ nativeGoal
180
+ ? `codex goal: ${nativeGoal.status}, ${nativeGoal.tokens_used} tokens used, ${nativeGoal.time_used_seconds}s elapsed`
181
+ : "codex goal: none recorded for this thread",
182
+ `changed files (${changed.length}): ${changed.slice(0, 10).join(", ") || "-"}`,
183
+ `last command: ${commands.at(-1)?.command ?? "-"}`,
184
+ `last action: ${task.current_action ?? "-"}`,
185
+ `runs: ${task.run_count ?? 0}${task.resumed_from ? `, resumed from ${task.resumed_from}` : ""}`,
186
+ task.error ? `error: ${task.error}` : null
187
+ ].filter(Boolean);
188
+
189
+ return {
190
+ id: task.id,
191
+ title: task.title,
192
+ status: task.status,
193
+ phase: task.phase ?? null,
194
+ thread_id: task.thread_id,
195
+ goal_objective: task.goal_objective,
196
+ goal_token_budget: task.goal_token_budget,
197
+ goal_status: task.goal_status,
198
+ native_goal: nativeGoal,
199
+ owned_paths: task.owned_paths ?? [],
200
+ depends_on: task.depends_on ?? [],
201
+ run_count: task.run_count ?? 0,
202
+ changed_files: changed,
203
+ command_count: commands.length,
204
+ last_command: commands.at(-1)?.command ?? null,
205
+ last_message: task.last_message ?? null,
206
+ notices: task.notices ?? null,
207
+ error: task.error ?? null,
208
+ created_at: task.created_at,
209
+ updated_at: task.updated_at,
210
+ completed_at: task.completed_at,
211
+ summary: lines.join("\n")
212
+ };
213
+ }
214
+
215
+ function errorResult(error) {
216
+ return textResult({
217
+ error: error.code ?? "error",
218
+ message: error.message,
219
+ ...(error.conflicts ? { conflicts: error.conflicts } : {})
220
+ });
221
+ }
222
+
223
+ server.registerTool(
224
+ "create_codex_worker",
225
+ {
226
+ title: "Create Codex worker",
227
+ description:
228
+ "Launch a Codex CLI worker with codex exec --json and track its events. ownedPaths and goal are required: ownedPaths reserves the files this worker may write, goal records what the worker is for.",
229
+ inputSchema: {
230
+ title: z.string().optional(),
231
+ task: z.string().min(1),
232
+ cwd: z.string().min(1),
233
+ session_id: z.string().min(1).optional(),
234
+ sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).default("workspace-write"),
235
+ model: z.string().optional(),
236
+ reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
237
+ skipGitRepoCheck: z.boolean().default(true),
238
+ ownedPaths: z.array(z.string().min(1)).min(1),
239
+ goal: z.object({
240
+ objective: z.string().min(1),
241
+ tokenBudget: z.number().int().positive().optional()
242
+ }),
243
+ dependsOn: z.array(z.string().min(1)).optional()
244
+ }
245
+ },
246
+ async (input) => {
247
+ try {
248
+ return textResult(await createCodexWorker({ ...input, sessionId: input.session_id ?? null }));
249
+ } catch (error) {
250
+ return errorResult(error);
251
+ }
252
+ }
253
+ );
254
+
255
+ server.registerTool(
256
+ "create_codex_followup_worker",
257
+ {
258
+ title: "Create Codex follow-up worker",
259
+ description:
260
+ "Start a NEW Codex session seeded with the previous worker's prompt, status, and recent events. To continue the same session instead, use resume_codex_worker.",
261
+ inputSchema: {
262
+ task_id: z.string().min(1),
263
+ followup_prompt: z.string().min(1),
264
+ session_id: z.string().min(1).optional(),
265
+ title: z.string().optional(),
266
+ cwd: z.string().optional(),
267
+ sandbox: z.enum(["read-only", "workspace-write", "danger-full-access"]).optional(),
268
+ model: z.string().optional(),
269
+ reasoningEffort: z.enum(["minimal", "low", "medium", "high"]).default("high"),
270
+ ownedPaths: z.array(z.string().min(1)).optional(),
271
+ goal: z
272
+ .object({
273
+ objective: z.string().min(1),
274
+ tokenBudget: z.number().int().positive().optional()
275
+ })
276
+ .optional()
277
+ }
278
+ },
279
+ async ({ task_id, followup_prompt, session_id, ...options }) => {
280
+ try {
281
+ return textResult(
282
+ await createFollowupWorker({
283
+ taskId: task_id,
284
+ followupPrompt: followup_prompt,
285
+ sessionId: session_id ?? null,
286
+ ...options
287
+ })
288
+ );
289
+ } catch (error) {
290
+ return errorResult(error);
291
+ }
292
+ }
293
+ );
294
+
295
+ server.registerTool(
296
+ "resume_codex_worker",
297
+ {
298
+ title: "Resume Codex worker",
299
+ description:
300
+ "Continue the SAME Codex session for an existing worker via `codex exec resume <thread_id>`. Works from a different MCP process or a fresh client session as long as the task recorded a thread_id.",
301
+ inputSchema: {
302
+ task_id: z.string().min(1),
303
+ prompt: z.string().min(1)
304
+ }
305
+ },
306
+ async ({ task_id, prompt }) => {
307
+ try {
308
+ return textResult(await resumeCodexWorker({ taskId: task_id, prompt }));
309
+ } catch (error) {
310
+ return errorResult(error);
311
+ }
312
+ }
313
+ );
314
+
315
+ server.registerTool(
316
+ "list_codex_workers",
317
+ {
318
+ title: "List Codex workers",
319
+ description: "List tracked Codex workers. Defaults to active workers only.",
320
+ inputSchema: {
321
+ status: z.enum(TASK_STATUSES).optional(),
322
+ includeHistory: z.boolean().default(false),
323
+ includeDetails: z.boolean().default(false)
324
+ }
325
+ },
326
+ async ({ status, includeHistory, includeDetails } = {}) => {
327
+ await reconcileDetachedActiveTasks();
328
+ const tasks = await readTasks();
329
+ const filtered = status
330
+ ? tasks.filter((task) => task.status === status)
331
+ : includeHistory
332
+ ? tasks
333
+ : tasks.filter((task) => ACTIVE_STATUSES.has(task.status));
334
+ return textResult(includeDetails ? filtered : filtered.map(summarizeTask));
335
+ }
336
+ );
337
+
338
+ server.registerTool(
339
+ "get_orchestration_overview",
340
+ {
341
+ title: "Get orchestration overview",
342
+ description:
343
+ "Compact status table for every worker, budgeted to stay under ~2k tokens. This is the default read for an orchestrating main thread; fetch details per worker only when needed.",
344
+ inputSchema: {
345
+ status: z.enum(TASK_STATUSES).optional(),
346
+ limit: z.number().int().min(1).max(200).default(50)
347
+ }
348
+ },
349
+ async ({ status, limit } = {}) => {
350
+ await reconcileDetachedActiveTasks();
351
+ const tasks = await readTasks();
352
+ const filtered = (status ? tasks.filter((task) => task.status === status) : tasks).slice(-limit);
353
+ return textResult(buildOverview(filtered));
354
+ }
355
+ );
356
+
357
+ server.registerTool(
358
+ "wait_codex_workers",
359
+ {
360
+ title: "Wait for Codex workers",
361
+ description: "Block until selected Codex workers reach a terminal status, then return summaries.",
362
+ inputSchema: {
363
+ task_ids: z.array(z.string().min(1)).min(1),
364
+ mode: z.enum(["any", "all"]).default("all"),
365
+ timeoutMinutes: z.number().int().min(1).max(360).default(30),
366
+ timeoutMs: z.number().int().min(1000).max(21600000).optional(),
367
+ pollMs: z.number().int().min(250).max(10000).default(1000),
368
+ includeEvents: z.boolean().default(true),
369
+ eventLimit: z.number().int().min(1).max(50).default(10),
370
+ eventMaxChars: z.number().int().min(0).max(1000000).optional(),
371
+ eventKinds: z.array(z.string().min(1)).optional()
372
+ }
373
+ },
374
+ async ({
375
+ task_ids,
376
+ mode,
377
+ timeoutMinutes,
378
+ timeoutMs,
379
+ pollMs,
380
+ includeEvents,
381
+ eventLimit,
382
+ eventMaxChars,
383
+ eventKinds
384
+ }) => {
385
+ const startedAt = Date.now();
386
+ const effectiveTimeoutMs = timeoutMs ?? timeoutMinutes * 60 * 1000;
387
+ let tasks = [];
388
+
389
+ while (Date.now() - startedAt < effectiveTimeoutMs) {
390
+ await reconcileDetachedActiveTasks();
391
+ tasks = (await getTasks(task_ids)).filter(Boolean);
392
+ const terminalCount = tasks.filter((task) => TERMINAL_STATUSES.has(task.status)).length;
393
+ const isDone = mode === "any" ? terminalCount > 0 : terminalCount === task_ids.length;
394
+ if (isDone) break;
395
+ await sleep(pollMs);
396
+ }
397
+
398
+ await reconcileDetachedActiveTasks();
399
+ tasks = (await getTasks(task_ids)).filter(Boolean);
400
+ const missingIds = task_ids.filter((taskId) => !tasks.some((task) => task.id === taskId));
401
+ const terminalTasks = tasks.filter((task) => TERMINAL_STATUSES.has(task.status));
402
+ const timedOut =
403
+ mode === "any" ? terminalTasks.length === 0 : terminalTasks.length !== task_ids.length;
404
+
405
+ const summaries = await Promise.all(
406
+ tasks.map(async (task) => ({
407
+ ...summarizeTask(task),
408
+ recent_events: includeEvents
409
+ ? await readTaskEvents(task.id, eventLimit, eventKinds ?? null).then((events) =>
410
+ eventMaxChars === undefined ? events : events.map((event) => truncateEventStrings(event, eventMaxChars))
411
+ )
412
+ : undefined
413
+ }))
414
+ );
415
+
416
+ return textResult({
417
+ mode,
418
+ timed_out: timedOut,
419
+ waited_ms: Date.now() - startedAt,
420
+ timeout_ms: effectiveTimeoutMs,
421
+ timeout_minutes: Math.round(effectiveTimeoutMs / 60000),
422
+ missing_ids: missingIds,
423
+ completed_count: tasks.filter((task) => task.status === "completed").length,
424
+ failed_count: tasks.filter((task) => task.status === "failed").length,
425
+ cancelled_count: tasks.filter((task) => task.status === "cancelled").length,
426
+ lost_count: tasks.filter((task) => task.status === "lost").length,
427
+ active_count: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
428
+ workers: summaries
429
+ });
430
+ }
431
+ );
432
+
433
+ server.registerTool(
434
+ "get_session_works",
435
+ {
436
+ title: "Get session works",
437
+ description:
438
+ "Every worker dispatched under one session_id, oldest first. This is the reconnect path: a main-thread session that died can list the whole batch it started without holding any of it in context.",
439
+ inputSchema: {
440
+ session_id: z.string().min(1)
441
+ }
442
+ },
443
+ async ({ session_id }) => {
444
+ const tasks = await readTasksBySession(session_id);
445
+ return textResult({
446
+ session_id,
447
+ count: tasks.length,
448
+ active: tasks.filter((task) => ACTIVE_STATUSES.has(task.status)).length,
449
+ works: tasks.map(workRow)
450
+ });
451
+ }
452
+ );
453
+
454
+ server.registerTool(
455
+ "search_works",
456
+ {
457
+ title: "Search works",
458
+ description:
459
+ "Substring search over title, goal, prompt and last message of every tracked worker, newest first. Use it to find an earlier work by keyword instead of paging through history.",
460
+ inputSchema: {
461
+ query: z.string().min(1),
462
+ limit: z.number().int().positive().max(100).default(20)
463
+ }
464
+ },
465
+ async ({ query, limit }) => {
466
+ const tasks = await searchTasks(query, limit);
467
+ return textResult({
468
+ query,
469
+ count: tasks.length,
470
+ works: tasks.map(workRow)
471
+ });
472
+ }
473
+ );
474
+
475
+ server.registerTool(
476
+ "get_codex_worker_status",
477
+ {
478
+ title: "Get Codex worker status",
479
+ description: "Read the latest normalized status for one Codex worker.",
480
+ inputSchema: {
481
+ task_id: z.string().min(1)
482
+ }
483
+ },
484
+ async ({ task_id }) => {
485
+ const task = await getTask(task_id);
486
+ if (!task) return textResult({ error: "task_not_found", task_id });
487
+ return textResult(task);
488
+ }
489
+ );
490
+
491
+ server.registerTool(
492
+ "get_codex_worker_events",
493
+ {
494
+ title: "Get Codex worker events",
495
+ description:
496
+ "Read recent raw Codex JSONL events for one worker. limit, maxChars and kinds keep the read inside a context budget; maxChars truncates the middle of oversized strings the same way Codex truncates its own output.",
497
+ inputSchema: {
498
+ task_id: z.string().min(1),
499
+ limit: z.number().int().min(1).max(1000).default(100),
500
+ maxChars: z.number().int().min(0).max(1000000).optional(),
501
+ kinds: z.array(z.string().min(1)).optional()
502
+ }
503
+ },
504
+ async ({ task_id, limit, maxChars, kinds }) => {
505
+ const task = await getTask(task_id);
506
+ if (!task) return textResult({ error: "task_not_found", task_id });
507
+ const events = await readTaskEvents(task_id, limit, kinds ?? null);
508
+ const trimmed = maxChars === undefined ? events : events.map((event) => truncateEventStrings(event, maxChars));
509
+ return textResult({
510
+ task_id,
511
+ count: trimmed.length,
512
+ available_kinds: await listTaskEventKinds(task_id),
513
+ events: trimmed
514
+ });
515
+ }
516
+ );
517
+
518
+ server.registerTool(
519
+ "get_worker_goal",
520
+ {
521
+ title: "Get worker goal",
522
+ description:
523
+ "Read the goal recorded for a worker, plus the native Codex thread goal when the thread has one (status, tokens used, time used).",
524
+ inputSchema: {
525
+ task_id: z.string().min(1)
526
+ }
527
+ },
528
+ async ({ task_id }) => {
529
+ const task = await getTask(task_id);
530
+ if (!task) return textResult({ error: "task_not_found", task_id });
531
+ return textResult({
532
+ task_id,
533
+ thread_id: task.thread_id,
534
+ status: task.status,
535
+ objective: task.goal_objective,
536
+ token_budget: task.goal_token_budget,
537
+ goal_status: task.goal_status,
538
+ needs_attention: isGoalNeedingAttention(task.goal_status),
539
+ native_goal: readNativeGoal(task.thread_id)
540
+ });
541
+ }
542
+ );
543
+
544
+ server.registerTool(
545
+ "get_worker_summary",
546
+ {
547
+ title: "Get worker summary",
548
+ description:
549
+ "One compact summary per worker: goal, status, changed files, last command, last message. Cheap enough for a main thread to read every worker at the end of a run.",
550
+ inputSchema: {
551
+ task_id: z.string().min(1)
552
+ }
553
+ },
554
+ async ({ task_id }) => {
555
+ const task = await getTask(task_id);
556
+ if (!task) return textResult({ error: "task_not_found", task_id });
557
+ const summary = buildWorkerSummary(task, readNativeGoal(task.thread_id));
558
+ if (summary.changed_files.length !== (task.changed_files ?? []).length) {
559
+ await upsertTask({ ...task, changed_files: summary.changed_files, updated_at: new Date().toISOString() });
560
+ }
561
+ return textResult(summary);
562
+ }
563
+ );
564
+
565
+ server.registerTool(
566
+ "cancel_codex_worker",
567
+ {
568
+ title: "Cancel Codex worker",
569
+ description:
570
+ "Terminate a running Codex worker. Uses the in-process handle when available, otherwise the pid recorded on disk so a different MCP session can still cancel it.",
571
+ inputSchema: {
572
+ task_id: z.string().min(1)
573
+ }
574
+ },
575
+ async ({ task_id }) => {
576
+ const now = new Date().toISOString();
577
+ const task = await getTask(task_id);
578
+ // The marker is persisted before the signal is sent so the process that
579
+ // owns the worker reports "cancelled" instead of "lost" when it exits.
580
+ if (task && ACTIVE_STATUSES.has(task.status)) {
581
+ await upsertTask({ ...task, cancel_requested_at: now, updated_at: now });
582
+ }
583
+ const result = await cancelCodexWorker(task_id);
584
+ if (result.cancelled && task) {
585
+ await upsertTask({
586
+ ...task,
587
+ status: "cancelled",
588
+ phase: null,
589
+ cancel_requested_at: now,
590
+ updated_at: now,
591
+ completed_at: task.completed_at ?? now
592
+ });
593
+ }
594
+ return textResult(result);
595
+ }
596
+ );
597
+
598
+ const transport = new StdioServerTransport();
599
+ await server.connect(transport);