|
| 1 | +#!/usr/bin/env bun |
| 2 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 3 | +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; |
| 4 | +import { resolve } from "node:path"; |
| 5 | +import { z } from "zod"; |
| 6 | +import { config } from "./config.ts"; |
| 7 | +import { delegate, formatOutcome } from "./delegate.ts"; |
| 8 | +import { listModels } from "./models.ts"; |
| 9 | +import { execText } from "./opencode.ts"; |
| 10 | +import { getTask, listTasks, startTask, waitTask, type Task } from "./tasks.ts"; |
| 11 | +import pkg from "../package.json" with { type: "json" }; |
| 12 | + |
| 13 | +const server = new McpServer({ name: "opencode-delegate", version: pkg.version }); |
| 14 | + |
| 15 | +const text = (t: string, isError = false) => ({ |
| 16 | + content: [{ type: "text" as const, text: t }], |
| 17 | + isError, |
| 18 | +}); |
| 19 | + |
| 20 | +const delegateShape = { |
| 21 | + prompt: z |
| 22 | + .string() |
| 23 | + .min(1) |
| 24 | + .describe( |
| 25 | + "Complete, self-contained task for the opencode model. It cannot see this conversation: include goal, relevant files/paths, constraints, and acceptance criteria.", |
| 26 | + ), |
| 27 | + model: z |
| 28 | + .string() |
| 29 | + .optional() |
| 30 | + .describe( |
| 31 | + `opencode model: exact 'provider/model' id (e.g. 'xai/grok-4.7') or a loose name ('grok 4.7', 'kimi k3'). Append '#variant' for a reasoning variant. Omit to use the default: ${config.defaultModel ?? "opencode's default"} for normal tasks, ${config.readModel ?? config.defaultModel ?? "opencode's default"} (free) when auto is false.`, |
| 32 | + ), |
| 33 | + cwd: z |
| 34 | + .string() |
| 35 | + .optional() |
| 36 | + .describe( |
| 37 | + "Working directory for the task (absolute, or relative to the server's cwd). Defaults to the current project.", |
| 38 | + ), |
| 39 | + agent: z |
| 40 | + .string() |
| 41 | + .optional() |
| 42 | + .describe("opencode agent to use (e.g. 'build', 'plan', or a custom agent)."), |
| 43 | + files: z.array(z.string()).optional().describe("Files to attach to the message."), |
| 44 | + session_id: z |
| 45 | + .string() |
| 46 | + .optional() |
| 47 | + .describe( |
| 48 | + "Continue an existing opencode session (returned by a previous call) for follow-ups.", |
| 49 | + ), |
| 50 | + continue: z.boolean().optional().describe("Continue the most recent opencode session in cwd."), |
| 51 | + fork: z |
| 52 | + .boolean() |
| 53 | + .optional() |
| 54 | + .describe("Fork the session given by session_id/continue instead of appending to it."), |
| 55 | + auto: z |
| 56 | + .boolean() |
| 57 | + .optional() |
| 58 | + .describe( |
| 59 | + `Auto-approve tool permissions (edits, shell) that are not explicitly denied. Default: ${config.auto}. Set false for read-only work (reading files, reviews, questions); without a model that also selects the free read model.`, |
| 60 | + ), |
| 61 | + thinking: z |
| 62 | + .boolean() |
| 63 | + .optional() |
| 64 | + .describe( |
| 65 | + `Show/enable the model's thinking (reasoning) output (opencode --thinking). Default: ${config.thinking} (env OPENCODE_DELEGATE_THINKING).`, |
| 66 | + ), |
| 67 | + title: z.string().optional().describe("Session title shown in opencode."), |
| 68 | + timeout_s: z |
| 69 | + .number() |
| 70 | + .int() |
| 71 | + .positive() |
| 72 | + .optional() |
| 73 | + .describe(`Kill the run after this many seconds. Default: ${config.timeoutSec}.`), |
| 74 | +}; |
| 75 | + |
| 76 | +server.registerTool( |
| 77 | + "list_models", |
| 78 | + { |
| 79 | + title: "List opencode models", |
| 80 | + description: |
| 81 | + "List the models available in the local opencode install, as 'provider/model' ids.", |
| 82 | + inputSchema: { |
| 83 | + filter: z |
| 84 | + .string() |
| 85 | + .optional() |
| 86 | + .describe("Case-insensitive substring filter, e.g. 'grok' or 'opencode-go/'."), |
| 87 | + refresh: z.boolean().optional().describe("Bypass the 5 minute cache."), |
| 88 | + }, |
| 89 | + annotations: { readOnlyHint: true }, |
| 90 | + }, |
| 91 | + async ({ filter, refresh }) => { |
| 92 | + try { |
| 93 | + let models = await listModels(refresh); |
| 94 | + if (filter) models = models.filter((m) => m.toLowerCase().includes(filter.toLowerCase())); |
| 95 | + return text(models.length ? models.join("\n") : "(no models match)"); |
| 96 | + } catch (e) { |
| 97 | + return text(String(e instanceof Error ? e.message : e), true); |
| 98 | + } |
| 99 | + }, |
| 100 | +); |
| 101 | + |
| 102 | +server.registerTool( |
| 103 | + "delegate", |
| 104 | + { |
| 105 | + title: "Delegate a task to an opencode model", |
| 106 | + description: |
| 107 | + "Run a task with another model through opencode (`opencode run`) and wait for it to finish. The model works in `cwd` with opencode's own tools (read/edit/shell), so it can implement code, not just answer. Returns its final response, session_id (for follow-ups), token usage and git changes. You remain the orchestrator: review its changes afterwards. For long tasks or running several models in parallel, use delegate_async.", |
| 108 | + inputSchema: delegateShape, |
| 109 | + }, |
| 110 | + async (input, extra) => { |
| 111 | + const progressToken = extra._meta?.progressToken; |
| 112 | + let tick = 0; |
| 113 | + // Keep-alive progress so clients that reset timeouts on progress don't give up on long runs. |
| 114 | + const heartbeat = progressToken |
| 115 | + ? setInterval(() => { |
| 116 | + tick++; |
| 117 | + extra |
| 118 | + .sendNotification({ |
| 119 | + method: "notifications/progress", |
| 120 | + params: { |
| 121 | + progressToken, |
| 122 | + progress: tick, |
| 123 | + message: `opencode running (${tick * 15}s)`, |
| 124 | + }, |
| 125 | + }) |
| 126 | + .catch(() => {}); |
| 127 | + }, 15000) |
| 128 | + : undefined; |
| 129 | + try { |
| 130 | + const outcome = await delegate(input, extra.signal); |
| 131 | + return text(formatOutcome(outcome), !outcome.result.ok); |
| 132 | + } catch (e) { |
| 133 | + return text(String(e instanceof Error ? e.message : e), true); |
| 134 | + } finally { |
| 135 | + if (heartbeat) clearInterval(heartbeat); |
| 136 | + } |
| 137 | + }, |
| 138 | +); |
| 139 | + |
| 140 | +function taskSummary(t: Task): string { |
| 141 | + const secs = (((t.finishedAt ?? Date.now()) - t.startedAt) / 1000).toFixed(0); |
| 142 | + const model = t.outcome?.model ?? t.input.model ?? "(default)"; |
| 143 | + return `${t.id} ${t.status.padEnd(9)} ${secs}s ${model} ${t.input.title ?? t.input.prompt.slice(0, 60).replace(/\s+/g, " ")}`; |
| 144 | +} |
| 145 | + |
| 146 | +server.registerTool( |
| 147 | + "delegate_async", |
| 148 | + { |
| 149 | + title: "Start an opencode task in the background", |
| 150 | + description: |
| 151 | + "Same as delegate, but returns a task_id immediately while the opencode model works in the background. Use for long tasks or to run several models in parallel; then call task_result to collect output. Parallel tasks editing the same directory can conflict — give each its own cwd/worktree or non-overlapping files.", |
| 152 | + inputSchema: delegateShape, |
| 153 | + }, |
| 154 | + async (input) => { |
| 155 | + const t = startTask(input); |
| 156 | + return text( |
| 157 | + `started ${t.id}\nCall task_result with task_id="${t.id}" (optionally wait_s) to get the output.`, |
| 158 | + ); |
| 159 | + }, |
| 160 | +); |
| 161 | + |
| 162 | +server.registerTool( |
| 163 | + "task_result", |
| 164 | + { |
| 165 | + title: "Get a background opencode task's result", |
| 166 | + description: |
| 167 | + "Return the status/result of a delegate_async task, optionally waiting up to wait_s seconds for it to finish.", |
| 168 | + inputSchema: { |
| 169 | + task_id: z.string(), |
| 170 | + wait_s: z |
| 171 | + .number() |
| 172 | + .int() |
| 173 | + .min(0) |
| 174 | + .max(3600) |
| 175 | + .optional() |
| 176 | + .describe("Seconds to wait for completion before returning (default 0)."), |
| 177 | + }, |
| 178 | + annotations: { readOnlyHint: true }, |
| 179 | + }, |
| 180 | + async ({ task_id, wait_s }) => { |
| 181 | + const t = getTask(task_id); |
| 182 | + if (!t) return text(`unknown task_id '${task_id}'`, true); |
| 183 | + await waitTask(t, wait_s ?? 0); |
| 184 | + if (t.status === "running") |
| 185 | + return text(`${taskSummary(t)}\nstill running — call again later or with a larger wait_s.`); |
| 186 | + if (t.outcome) |
| 187 | + return text(`task: ${t.id} (${t.status})\n${formatOutcome(t.outcome)}`, t.status !== "done"); |
| 188 | + return text(`task: ${t.id} (${t.status})\nerror: ${t.error}`, true); |
| 189 | + }, |
| 190 | +); |
| 191 | + |
| 192 | +server.registerTool( |
| 193 | + "task_list", |
| 194 | + { |
| 195 | + title: "List background opencode tasks", |
| 196 | + description: "List delegate_async tasks started by this server with their status.", |
| 197 | + inputSchema: {}, |
| 198 | + annotations: { readOnlyHint: true }, |
| 199 | + }, |
| 200 | + async () => { |
| 201 | + const all = listTasks(); |
| 202 | + return text(all.length ? all.map(taskSummary).join("\n") : "(no tasks)"); |
| 203 | + }, |
| 204 | +); |
| 205 | + |
| 206 | +server.registerTool( |
| 207 | + "task_cancel", |
| 208 | + { |
| 209 | + title: "Cancel a background opencode task", |
| 210 | + description: "Stop a running delegate_async task.", |
| 211 | + inputSchema: { task_id: z.string() }, |
| 212 | + }, |
| 213 | + async ({ task_id }) => { |
| 214 | + const t = getTask(task_id); |
| 215 | + if (!t) return text(`unknown task_id '${task_id}'`, true); |
| 216 | + if (t.status !== "running") return text(`${t.id} already ${t.status}`); |
| 217 | + t.controller.abort(); |
| 218 | + await waitTask(t, 5); |
| 219 | + return text(`${t.id} ${t.status === "running" ? "cancelling" : t.status}`); |
| 220 | + }, |
| 221 | +); |
| 222 | + |
| 223 | +server.registerTool( |
| 224 | + "list_sessions", |
| 225 | + { |
| 226 | + title: "List opencode sessions", |
| 227 | + description: |
| 228 | + "List recent opencode sessions for a project directory (to find a session_id to continue).", |
| 229 | + inputSchema: { |
| 230 | + cwd: z.string().optional().describe("Project directory. Defaults to the current project."), |
| 231 | + limit: z.number().int().positive().max(100).optional().describe("Max sessions (default 20)."), |
| 232 | + }, |
| 233 | + annotations: { readOnlyHint: true }, |
| 234 | + }, |
| 235 | + async ({ cwd, limit }) => { |
| 236 | + const dir = resolve(config.defaultCwd, cwd ?? "."); |
| 237 | + const r = await execText(["session", "list", "-n", String(limit ?? 20)], dir); |
| 238 | + if (r.code !== 0) return text(r.stderr.trim() || `exit ${r.code}`, true); |
| 239 | + return text(r.stdout.trim() || "(no sessions)"); |
| 240 | + }, |
| 241 | +); |
| 242 | + |
| 243 | +await server.connect(new StdioServerTransport()); |
0 commit comments