Skip to content

Commit df38da6

Browse files
committed
feat(mcp): restore opencode MCP server
1 parent 9f4722f commit df38da6

5 files changed

Lines changed: 319 additions & 4 deletions

File tree

‎.prettierignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
.atl/
33
openspec/
44
odd/
5+
dist/

‎package-lock.json‎

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"delegate"
1818
],
1919
"files": [
20+
"dist",
2021
"src",
2122
"skills",
2223
"agents",
@@ -29,14 +30,19 @@
2930
"bun": ">=1.1"
3031
},
3132
"scripts": {
33+
"start": "bun src/index.ts",
34+
"build": "bun build src/index.ts --target=bun --outfile=dist/index.js",
3235
"typecheck": "tsc --noEmit",
3336
"test": "bun test",
3437
"lint": "eslint . --max-warnings 0",
3538
"fmt": "prettier --check \"**/*.{ts,js,json,md,yml,yaml}\"",
3639
"fmt:fix": "prettier --write \"**/*.{ts,js,json,md,yml,yaml}\"",
3740
"verify": "bun run typecheck && bun test && bun run lint && bun run fmt"
3841
},
39-
"dependencies": {},
42+
"dependencies": {
43+
"@modelcontextprotocol/sdk": "^1.30.0",
44+
"zod": "^4.6.5"
45+
},
4046
"devDependencies": {
4147
"@eslint/js": "^10.0.1",
4248
"@types/bun": "^1.4.2",

‎src/index.ts‎

Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
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());

‎test/mcp-server.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { join } from "node:path";
3+
4+
const root = join(import.meta.dir, "..");
5+
const EXPECTED = [
6+
"delegate",
7+
"delegate_async",
8+
"list_models",
9+
"list_sessions",
10+
"task_cancel",
11+
"task_list",
12+
"task_result",
13+
];
14+
15+
interface Tool {
16+
name: string;
17+
inputSchema: { required?: string[] };
18+
}
19+
20+
async function listTools(entry: string): Promise<Tool[]> {
21+
const proc = Bun.spawn(["bun", join(root, entry)], {
22+
stdin: "pipe",
23+
stdout: "pipe",
24+
stderr: "pipe",
25+
env: { ...process.env, OPENCODE_BIN: "/bin/true" },
26+
});
27+
const send = (msg: object) => proc.stdin.write(JSON.stringify(msg) + "\n");
28+
send({
29+
jsonrpc: "2.0",
30+
id: 1,
31+
method: "initialize",
32+
params: {
33+
protocolVersion: "2024-11-05",
34+
capabilities: {},
35+
clientInfo: { name: "test", version: "0" },
36+
},
37+
});
38+
send({ jsonrpc: "2.0", method: "notifications/initialized" });
39+
send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
40+
proc.stdin.flush();
41+
42+
const reader = proc.stdout.getReader();
43+
const dec = new TextDecoder();
44+
let buf = "";
45+
try {
46+
while (true) {
47+
const { value, done } = await reader.read();
48+
if (done) throw new Error(`server exited early: ${await new Response(proc.stderr).text()}`);
49+
buf += dec.decode(value);
50+
for (const line of buf.split("\n")) {
51+
if (!line.trim()) continue;
52+
const msg = JSON.parse(line);
53+
if (msg.id === 2) return msg.result.tools as Tool[];
54+
}
55+
}
56+
} finally {
57+
proc.kill();
58+
}
59+
}
60+
61+
describe.each(["src/index.ts"])("MCP server (%s)", (entry) => {
62+
test("tools/list exposes the 7 tools and delegate requires prompt", async () => {
63+
const tools = await listTools(entry);
64+
expect(tools.map((t) => t.name).sort()).toEqual(EXPECTED);
65+
const d = tools.find((t) => t.name === "delegate");
66+
expect(d?.inputSchema.required).toContain("prompt");
67+
}, 15000);
68+
});

0 commit comments

Comments
 (0)