opencode-acp-provider 0.0.0-stage → 1.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.
@@ -0,0 +1,1001 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { statSync } from "node:fs"
3
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"
4
+ import { posix, win32 } from "node:path"
5
+ import { fileURLToPath } from "node:url"
6
+ import type { Plugin } from "@opencode/plugin"
7
+ import packageJson from "../package.json" with { type: "json" }
8
+ import type { AcpMcpServer } from "./acp-client.ts"
9
+ import type { LogFn, McpLease } from "./server-manager.ts"
10
+ import type { LocalService } from "./steering.ts"
11
+ import { basicAuth, BodyTooLargeError, endFailedResponse, errorMessage, listenLocal, readBody, sleep } from "./util.ts"
12
+
13
+ type Ctx = Plugin.Context
14
+
15
+ const MCP_PROTOCOL_VERSION = "2025-06-18"
16
+ /** ACP server name of this plugin's bridge. */
17
+ const MCP_SERVER_NAME = "opencode"
18
+ const MAX_BODY_BYTES = 4 * 1024 * 1024
19
+ const MAX_CONTEXT_CHARS = 60_000
20
+ /** Live tokens above this suggest leases are not being released. */
21
+ const TOKEN_WARN_THRESHOLD = 256
22
+
23
+ const SUBAGENT_DESCRIPTION = [
24
+ "Spawns an agent in a child session to work on the specified task.",
25
+ "Subagents always run in the background: the call returns immediately with a sessionID, and you receive a `<subagent>` message each time the child goes idle, including after later work.",
26
+ "Keep working on non-overlapping tasks, or briefly tell the user what you launched and end your response. Do not sleep, poll, or proactively check on the child's progress.",
27
+ "New child sessions start with fresh context, so include all relevant context and instructions when you don't pass a sessionID.",
28
+ "Pass the returned sessionID to continue that specific child conversation. A follow-up to a running child joins its current run.",
29
+ ].join("\n")
30
+
31
+ /**
32
+ * Order used by the initialize instructions. Clients that defer MCP tools (Codex
33
+ * shows only the server's `instructions` until a namespace is loaded, and appends
34
+ * them to every tool description) never see the per-tool descriptions first, so
35
+ * the namespace text has to name each tool itself.
36
+ */
37
+ const TOOL_ORDER = [
38
+ "question",
39
+ "subagent",
40
+ "models",
41
+ "todowrite",
42
+ "session_create",
43
+ "session_list",
44
+ "session_get",
45
+ "session_context",
46
+ "session_prompt",
47
+ "session_wait",
48
+ "session_interrupt",
49
+ "worktree_create",
50
+ "worktree_remove",
51
+ ]
52
+
53
+ export interface McpServerOptions {
54
+ ctx: Ctx
55
+ log?: LogFn
56
+ /** Local OpenCode service that can create forms with a location. Resolved per question. */
57
+ localService?: LocalServiceSource
58
+ transport?: "stdio" | "http"
59
+ /** Runtime that can execute a JavaScript file, e.g. "node" or "bun". */
60
+ runtime?: string
61
+ version?: string
62
+ }
63
+
64
+ export interface McpServerHandle {
65
+ url: string
66
+ issue: (sessionKey: string) => McpLease
67
+ close: () => Promise<void>
68
+ }
69
+
70
+ type LocalServiceSource = LocalService | (() => Promise<LocalService | undefined>)
71
+
72
+ interface McpTool {
73
+ name: string
74
+ description: string
75
+ inputSchema: Record<string, unknown>
76
+ call: (args: any, signal: AbortSignal) => Promise<any>
77
+ }
78
+
79
+ interface JsonRpcRequest {
80
+ jsonrpc?: string
81
+ id?: number | string | null
82
+ method?: string
83
+ params?: any
84
+ }
85
+
86
+ interface TokenEntry {
87
+ sessionKey: string
88
+ }
89
+
90
+ const objectSchema = (properties: Record<string, unknown>, required: string[] = []) => ({
91
+ type: "object",
92
+ properties,
93
+ ...(required.length ? { required } : {}),
94
+ additionalProperties: false,
95
+ })
96
+
97
+ const stringSchema = (description?: string) => ({ type: "string", ...(description ? { description } : {}) })
98
+
99
+ /**
100
+ * How to launch the stdio bridge. An absolute runtime runs directly; a bare
101
+ * name (default `node`) is looked up on PATH, through `/usr/bin/env` on POSIX
102
+ * and by the spawner itself on Windows, which has no `/usr/bin/env`.
103
+ */
104
+ export function bridgeCommand(
105
+ runtime: string | undefined,
106
+ bridgePath: string,
107
+ platform: NodeJS.Platform = process.platform,
108
+ ): { command: string; args: string[] } {
109
+ const name = runtime?.trim() || "node"
110
+ const absolute = platform === "win32" ? win32.isAbsolute(name) : posix.isAbsolute(name)
111
+ if (absolute || platform === "win32") return { command: name, args: [bridgePath] }
112
+ return { command: "/usr/bin/env", args: [name, bridgePath] }
113
+ }
114
+
115
+ export async function createMcpServer(options: McpServerOptions): Promise<McpServerHandle> {
116
+ const { ctx, log = () => {} } = options
117
+ const transport = options.transport ?? "stdio"
118
+ const version = options.version ?? packageJson.version
119
+ const tokens = new Map<string, TokenEntry>()
120
+ /** In-flight tool calls, so `notifications/cancelled` can abort them. */
121
+ const inFlight = new Map<number | string, AbortController>()
122
+ const bridgePath = fileURLToPath(new URL("./mcp-bridge.mjs", import.meta.url))
123
+ let loggedTools = false
124
+
125
+ if (transport === "stdio") {
126
+ try {
127
+ statSync(bridgePath)
128
+ } catch {
129
+ throw new Error(`MCP stdio bridge not found at ${bridgePath}`)
130
+ }
131
+ }
132
+
133
+ const server = createServer((req, res) => {
134
+ void handleRequest(req, res).catch((error) => {
135
+ log("error", `MCP request failed: ${errorMessage(error)}`)
136
+ endFailedResponse(res)
137
+ })
138
+ })
139
+ server.requestTimeout = 0
140
+ server.timeout = 0
141
+
142
+ const url = `http://127.0.0.1:${await listenLocal(server)}/mcp`
143
+ log("info", `OpenCode MCP bridge listening on ${url} (${transport})`)
144
+
145
+ function buildServers(token: string): AcpMcpServer[] {
146
+ if (transport === "http") {
147
+ return [
148
+ {
149
+ type: "http",
150
+ name: MCP_SERVER_NAME,
151
+ url,
152
+ headers: [{ name: "Authorization", value: `Bearer ${token}` }],
153
+ },
154
+ ]
155
+ }
156
+ const { command, args } = bridgeCommand(options.runtime ?? process.env.OPENCODE_MCP_NODE, bridgePath)
157
+ return [
158
+ {
159
+ type: "stdio",
160
+ name: MCP_SERVER_NAME,
161
+ command,
162
+ args,
163
+ env: [
164
+ { name: "OPENCODE_MCP_URL", value: url },
165
+ { name: "OPENCODE_MCP_TOKEN", value: token },
166
+ ],
167
+ },
168
+ ]
169
+ }
170
+
171
+ function issue(sessionKey: string): McpLease {
172
+ // A token lives exactly as long as its lease: the pooled ACP session keeps
173
+ // sending it until the session closes and releases it. Expiring it on idle
174
+ // time or a size cap would turn a quiet but live session's MCP calls into
175
+ // 401s, since the session never gets a new token.
176
+ if (tokens.size === TOKEN_WARN_THRESHOLD) {
177
+ log("warn", `${TOKEN_WARN_THRESHOLD} MCP tokens are live; ACP sessions may not be releasing them`)
178
+ }
179
+ const token = randomUUID()
180
+ tokens.set(token, { sessionKey })
181
+ return {
182
+ servers: buildServers(token),
183
+ release: () => {
184
+ tokens.delete(token)
185
+ },
186
+ }
187
+ }
188
+
189
+ function resolveToken(req: IncomingMessage) {
190
+ const header = req.headers.authorization
191
+ if (typeof header !== "string" || !header.toLowerCase().startsWith("bearer ")) return undefined
192
+ const token = header.slice(7).trim()
193
+ const entry = tokens.get(token)
194
+ if (!entry) return undefined
195
+ return { token, sessionKey: entry.sessionKey }
196
+ }
197
+
198
+ async function handleRequest(req: IncomingMessage, res: ServerResponse) {
199
+ res.on("error", () => {})
200
+ const urlPath = (req.url ?? "").split("?")[0]
201
+ if (urlPath !== "/mcp") {
202
+ res.writeHead(404, { "content-type": "application/json" })
203
+ res.end(JSON.stringify({ error: "Not found" }))
204
+ return
205
+ }
206
+ if (req.method === "OPTIONS") {
207
+ res.writeHead(204, { allow: "POST, DELETE, OPTIONS" })
208
+ res.end()
209
+ return
210
+ }
211
+ if (req.method === "GET") {
212
+ res.writeHead(405, { allow: "POST, DELETE, OPTIONS" })
213
+ res.end()
214
+ return
215
+ }
216
+
217
+ const auth = resolveToken(req)
218
+ if (req.method === "DELETE") {
219
+ // Ending an MCP session does not revoke the token: it belongs to the ACP
220
+ // session's lease, and the agent may reconnect with it.
221
+ res.writeHead(204)
222
+ res.end()
223
+ return
224
+ }
225
+ if (!auth) {
226
+ res.writeHead(401, { "content-type": "application/json", "www-authenticate": "Bearer" })
227
+ res.end(JSON.stringify({ error: "Unauthorized" }))
228
+ return
229
+ }
230
+
231
+ if (req.method !== "POST") {
232
+ res.writeHead(405, { allow: "POST, DELETE, OPTIONS" })
233
+ res.end()
234
+ return
235
+ }
236
+
237
+ const controller = new AbortController()
238
+ res.on("close", () => {
239
+ if (!res.writableEnded) controller.abort()
240
+ })
241
+
242
+ let raw: string
243
+ try {
244
+ raw = await readBody(req, MAX_BODY_BYTES)
245
+ } catch (error) {
246
+ const tooLarge = error instanceof BodyTooLargeError
247
+ res.writeHead(tooLarge ? 413 : 400, { "content-type": "application/json" })
248
+ res.end(JSON.stringify({ error: tooLarge ? "Request body too large" : "Could not read request body" }))
249
+ if (tooLarge) req.destroy()
250
+ return
251
+ }
252
+
253
+ let payload: JsonRpcRequest | JsonRpcRequest[]
254
+ try {
255
+ payload = JSON.parse(raw)
256
+ } catch {
257
+ res.writeHead(400, { "content-type": "application/json" })
258
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }))
259
+ return
260
+ }
261
+
262
+ const messages = Array.isArray(payload) ? payload : [payload]
263
+ const responses: unknown[] = []
264
+ const scope = auth.token
265
+ for (const message of messages) {
266
+ if (!message || typeof message !== "object") continue
267
+ if (message.id === undefined || message.id === null) {
268
+ if (message.method === "notifications/cancelled") {
269
+ const requestId = message.params?.requestId
270
+ if (requestId !== undefined && requestId !== null) inFlight.get(`${scope}:${requestId}`)?.abort()
271
+ continue
272
+ }
273
+ await dispatch(message, auth.sessionKey, controller.signal).catch(() => undefined)
274
+ continue
275
+ }
276
+ const requestController = new AbortController()
277
+ const requestKey = `${scope}:${message.id}`
278
+ inFlight.set(requestKey, requestController)
279
+ try {
280
+ responses.push(
281
+ await dispatch(message, auth.sessionKey, AbortSignal.any([controller.signal, requestController.signal])),
282
+ )
283
+ } finally {
284
+ inFlight.delete(requestKey)
285
+ }
286
+ }
287
+
288
+ if (!responses.length) {
289
+ res.writeHead(202)
290
+ res.end()
291
+ return
292
+ }
293
+ if (res.headersSent || res.writableEnded) return
294
+ res.writeHead(200, { "content-type": "application/json" })
295
+ res.end(JSON.stringify(Array.isArray(payload) ? responses : responses[0]))
296
+ }
297
+
298
+ async function dispatch(message: JsonRpcRequest, sessionKey: string, signal: AbortSignal) {
299
+ const id = message.id ?? null
300
+ const reply = (result: unknown) => ({ jsonrpc: "2.0", id, result })
301
+ const fail = (code: number, text: string) => ({ jsonrpc: "2.0", id, error: { code, message: text } })
302
+
303
+ if (message.method === "notifications/initialized" || message.method === "notifications/cancelled") return undefined
304
+
305
+ try {
306
+ switch (message.method) {
307
+ case "initialize": {
308
+ // Only claim the version we actually implement.
309
+ const requested =
310
+ typeof message.params?.protocolVersion === "string" ? message.params.protocolVersion : undefined
311
+ const instructions = await buildInstructions(ctx, sessionKey, options.localService, log).catch(() => undefined)
312
+ return reply({
313
+ protocolVersion: requested === MCP_PROTOCOL_VERSION ? requested : MCP_PROTOCOL_VERSION,
314
+ capabilities: { tools: { listChanged: false } },
315
+ serverInfo: { name: "opencode", version },
316
+ ...(instructions ? { instructions } : {}),
317
+ })
318
+ }
319
+ case "ping":
320
+ return reply({})
321
+ case "tools/list": {
322
+ const tools = await buildTools(ctx, sessionKey, options.localService, log)
323
+ if (!loggedTools) {
324
+ loggedTools = true
325
+ log("info", `OpenCode MCP tools exposed: ${tools.map((tool) => tool.name).join(", ")}`)
326
+ }
327
+ return reply({
328
+ tools: tools.map((tool) => ({
329
+ name: tool.name,
330
+ description: tool.description,
331
+ inputSchema: tool.inputSchema,
332
+ })),
333
+ })
334
+ }
335
+ case "tools/call": {
336
+ const name = String(message.params?.name ?? "")
337
+ const args = message.params?.arguments ?? {}
338
+ // A call needs the handler, not the descriptions, so skip the agent
339
+ // lookup that only feeds the subagent description.
340
+ const tools = await buildTools(ctx, sessionKey, options.localService, log, { describe: false })
341
+ const tool = tools.find((candidate) => candidate.name === name)
342
+ if (!tool) return fail(-32602, `Unknown tool: ${name}`)
343
+ const startedAt = Date.now()
344
+ log("debug", `MCP tool ${name} started for ${sessionKey.slice(0, 12)}`)
345
+ try {
346
+ const result = await tool.call(args, signal)
347
+ log("debug", `MCP tool ${name} finished in ${Date.now() - startedAt}ms`)
348
+ return reply(result)
349
+ } catch (error) {
350
+ const text = errorMessage(error)
351
+ log("debug", `MCP tool ${name} failed in ${Date.now() - startedAt}ms: ${text}`)
352
+ return reply({ content: [{ type: "text", text }], isError: true })
353
+ }
354
+ }
355
+ case "resources/list":
356
+ return reply({ resources: [] })
357
+ case "prompts/list":
358
+ return reply({ prompts: [] })
359
+ case "logging/setLevel":
360
+ return reply({})
361
+ default:
362
+ return fail(-32601, `Method not found: ${message.method}`)
363
+ }
364
+ } catch (error) {
365
+ return fail(-32603, errorMessage(error))
366
+ }
367
+ }
368
+
369
+ return {
370
+ url,
371
+ issue,
372
+ async close() {
373
+ tokens.clear()
374
+ for (const controller of inFlight.values()) controller.abort()
375
+ inFlight.clear()
376
+ await new Promise<void>((resolve) => {
377
+ server.close(() => resolve())
378
+ server.closeAllConnections?.()
379
+ })
380
+ },
381
+ }
382
+ }
383
+
384
+ class QuestionFormError extends Error {}
385
+
386
+ function questionFields(questions: any[]) {
387
+ return questions.map((question, index) => ({
388
+ key: `q${index}`,
389
+ title: typeof question?.header === "string" ? question.header : `Question ${index + 1}`,
390
+ description: typeof question?.question === "string" ? question.question : "",
391
+ type: question?.multiple === true ? "multiselect" : "string",
392
+ options: (Array.isArray(question?.options) ? question.options : []).map((option: any) => ({
393
+ value: String(option?.label ?? ""),
394
+ label: String(option?.label ?? ""),
395
+ ...(typeof option?.description === "string" ? { description: option.description } : {}),
396
+ })),
397
+ custom: true,
398
+ }))
399
+ }
400
+
401
+ function answeredQuestions(questions: any[], answer: Record<string, unknown>) {
402
+ const answers = questions.map((_, index) => {
403
+ const value = answer[`q${index}`]
404
+ if (value === undefined || value === null) return []
405
+ if (Array.isArray(value)) return value.map(String)
406
+ return [String(value)]
407
+ })
408
+ const text = `User has answered your questions: ${questions
409
+ .map((question, index) => `"${question?.question ?? ""}"="${answers[index].length ? answers[index].join(", ") : "Unanswered"}"`)
410
+ .join(", ")}. You can now continue with the user's answers in mind.`
411
+ return { output: { answers }, content: [{ type: "text" as const, text }], metadata: { answers } }
412
+ }
413
+
414
+ /**
415
+ * Ask through the local server's form API instead of the builtin question tool.
416
+ * A form created outside the HTTP location middleware has no `location` on its
417
+ * event, and the desktop client ignores `form.created` events without one. The
418
+ * HTTP route runs inside that middleware, so the desktop renders the question.
419
+ */
420
+ async function askViaForm(
421
+ ctx: Ctx,
422
+ service: LocalService,
423
+ sessionKey: string,
424
+ args: any,
425
+ signal: AbortSignal,
426
+ log?: LogFn,
427
+ ): Promise<any> {
428
+ const questions = Array.isArray(args?.questions) ? args.questions : []
429
+ if (!questions.length) throw new QuestionFormError("No questions were provided")
430
+
431
+ const session = await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)
432
+ const directory = (session as any)?.location?.directory ?? ctx.location.directory
433
+ const base = service.url.replace(/\/+$/, "")
434
+ const headers = {
435
+ "content-type": "application/json",
436
+ authorization: basicAuth(service.password),
437
+ "x-opencode-directory": encodeURIComponent(directory),
438
+ }
439
+ const endpoint = `${base}/api/session/${encodeURIComponent(sessionKey)}/form`
440
+
441
+ const created = await fetch(endpoint, {
442
+ method: "POST",
443
+ headers,
444
+ body: JSON.stringify({ title: "Questions", metadata: { kind: "question" }, fields: questionFields(questions) }),
445
+ signal,
446
+ }).catch((error) => {
447
+ throw new QuestionFormError(errorMessage(error))
448
+ })
449
+ if (!created.ok) {
450
+ const detail = await created.text().catch(() => "")
451
+ throw new QuestionFormError(`form API returned ${created.status}${detail ? `: ${detail.slice(0, 200)}` : ""}`)
452
+ }
453
+ const form = ((await created.json().catch(() => undefined)) as any)?.data
454
+ if (!form?.id) throw new QuestionFormError("form API did not return a form id")
455
+
456
+ const formEndpoint = `${endpoint}/${encodeURIComponent(form.id)}`
457
+ try {
458
+ while (true) {
459
+ if (signal.aborted) throw signal.reason ?? new Error("aborted")
460
+ const response = await fetch(formEndpoint, { headers, signal })
461
+ if (response.ok) {
462
+ const detail = ((await response.json().catch(() => undefined)) as any)?.data
463
+ const state = detail?.state
464
+ if (state?.status === "answered") return answeredQuestions(questions, state.answer ?? {})
465
+ if (state?.status === "cancelled") throw new Error(state.message || "The user dismissed this question")
466
+ } else if (response.status === 404) {
467
+ throw new Error("The question form was closed")
468
+ } else {
469
+ log?.("warn", `question form poll returned ${response.status}`)
470
+ }
471
+ await sleep(300, signal)
472
+ }
473
+ } catch (error) {
474
+ await fetch(formEndpoint, {
475
+ method: "DELETE",
476
+ headers,
477
+ body: JSON.stringify({ message: "The question was cancelled because the request was interrupted." }),
478
+ signal: AbortSignal.timeout(2_000),
479
+ }).catch(() => {})
480
+ throw error
481
+ }
482
+ }
483
+
484
+ async function buildInstructions(
485
+ ctx: Ctx,
486
+ sessionKey: string,
487
+ service?: LocalServiceSource,
488
+ log?: LogFn,
489
+ ) {
490
+ // Only the names are used here.
491
+ const tools = await buildTools(ctx, sessionKey, service, log, { describe: false })
492
+ if (!tools.length) return undefined
493
+ const names = new Set(tools.map((tool) => tool.name))
494
+ // Tools the model is most likely to need come first; some clients append this
495
+ // text to every tool description, so keep it tight.
496
+ const order = new Map(TOOL_ORDER.map((name, index) => [name, index]))
497
+ const listed = [...tools]
498
+ .sort((left, right) => (order.get(left.name) ?? 99) - (order.get(right.name) ?? 99))
499
+ .map((tool) => `\`${tool.name}\``)
500
+ .join(", ")
501
+ const lines = [
502
+ "You are running as an ACP agent inside OpenCode: the user works in OpenCode's interface, so OpenCode's commands and settings are the ones available to them, not your client's.",
503
+ "OpenCode MCP server `opencode`. Tool names are plain (`question`, `subagent`, `session_get`, …) but every client adds its own MCP prefix, for example `mcp__opencode__question`, `opencode.question`, or `mcp.opencode.question`. Match the form your own tool list shows.",
504
+ `Available tools: ${listed}.`,
505
+ ]
506
+ if (names.has("question")) {
507
+ lines.push(
508
+ "Use `question` to ask the user for a decision, preference, or clarification instead of asking in plain text.",
509
+ "It exists even when the agent's native ask-user tool is disabled, so never report that there is no question tool.",
510
+ )
511
+ }
512
+ if (names.has("subagent")) {
513
+ lines.push(
514
+ "Use `subagent` for delegation instead of a native subagent or task tool: call it with { agent, description, prompt }.",
515
+ "It returns at once and reports back with a <subagent> message when the child goes idle; do not poll it.",
516
+ )
517
+ }
518
+ lines.push(
519
+ "If a tool above seems missing it may just be deferred: look it up under the `opencode` MCP namespace using your client's tool search before concluding it is unavailable.",
520
+ )
521
+ return lines.join("\n")
522
+ }
523
+
524
+ async function buildTools(
525
+ ctx: Ctx,
526
+ sessionKey: string,
527
+ localService?: LocalServiceSource,
528
+ log?: LogFn,
529
+ { describe = true }: { describe?: boolean } = {},
530
+ ): Promise<McpTool[]> {
531
+ const tools: McpTool[] = []
532
+ const available = await ctx.tool.list().catch(() => [])
533
+
534
+ const find = (...names: string[]) => {
535
+ for (const name of names) {
536
+ const match =
537
+ available.find((tool) => tool.name === name) ??
538
+ available.find((tool) => tool.name === `opencode.${name}`) ??
539
+ available.find((tool) => tool.id === `opencode.tool.${name}`) ??
540
+ available.find((tool) => tool.id?.endsWith(`.${name}`))
541
+ if (match) return match
542
+ }
543
+ return undefined
544
+ }
545
+
546
+ const invoke = async (tool: any, args: any, signal: AbortSignal) => {
547
+ const session = await ctx.session.get({ sessionID: sessionKey }).catch(() => undefined)
548
+ // The public plugin API exposes tool.execute, not the session's tool
549
+ // pipeline, so `execute.before`/`after` hooks do not run for MCP-originated
550
+ // calls. The wrapped builtins assert their own permissions.
551
+ const context = {
552
+ sessionID: sessionKey,
553
+ agent: session?.agent ?? "build",
554
+ messageID: randomUUID(),
555
+ id: randomUUID(),
556
+ signal,
557
+ progress: async () => {},
558
+ }
559
+ return tool.execute(args, context)
560
+ }
561
+
562
+ const models = find("models")
563
+ if (models) {
564
+ tools.push({
565
+ name: "models",
566
+ description: "Search the models available to use. Use this to turn a model name the user mentions into an exact reference for a tool that takes a model. Check your own provider first.",
567
+ inputSchema: objectSchema({
568
+ query: stringSchema("Text to search for in model names and IDs."),
569
+ provider: stringSchema("Provider ID or name to filter by. Try your own provider first."),
570
+ type: {
571
+ type: "string",
572
+ enum: ["chat", "image"],
573
+ description: [
574
+ "Which kind of model to list. Defaults to \"chat\".",
575
+ "\"chat\": a language model (LLM). Powers sessions, agents and subagents, and can call tools.",
576
+ "\"image\": generates or edits images from a prompt. It can't chat or call tools.",
577
+ ].join("\n"),
578
+ },
579
+ all: { type: "boolean", description: "Include older versions of each model family. By default only the newest version is listed." },
580
+ limit: { type: "integer", minimum: 1, maximum: 100, description: "Maximum number of models to return. Defaults to 20." },
581
+ offset: { type: "integer", minimum: 0, description: "Number of models to skip, for paging through results." },
582
+ }),
583
+ call: async (args, signal) => toMcpResult(await invoke(models, args ?? {}, signal)),
584
+ })
585
+ }
586
+
587
+ const subagent = find("subagent")
588
+ if (subagent) {
589
+ tools.push({
590
+ name: "subagent",
591
+ description: describe ? await subagentDescription(ctx) : SUBAGENT_DESCRIPTION,
592
+ inputSchema: objectSchema(
593
+ {
594
+ agent: stringSchema(
595
+ "The type of specialized agent to use for this task. If the user asks for a subagent by a name that is not one of the available subagents, they most likely mean a model: pick a suitable agent and pass the name through the model parameter instead.",
596
+ ),
597
+ description: stringSchema("A short 3-5 word label for the task, displayed to the user"),
598
+ prompt: stringSchema("The task for the subagent to perform"),
599
+ model: stringSchema(
600
+ "NEVER set this unless the user explicitly asks for a particular model or variant. It must be a chat model; image and decision models can't run subagents. The value is written as \"providerID/modelID\", or \"providerID/modelID#variant\" to include a variant. Do not guess the ID: look the model up with the models tool, filtering to your own provider first.",
601
+ ),
602
+ sessionID: stringSchema("Send a follow-up to an existing subagent, running or finished. Omit to start a new one."),
603
+ },
604
+ ["agent", "description", "prompt"],
605
+ ),
606
+ call: async (args, signal) => {
607
+ const input = { ...(args ?? {}) }
608
+ if (!input.model) delete input.model
609
+ if (!input.sessionID) delete input.sessionID
610
+ return toMcpResult(await invoke(subagent, input, signal))
611
+ },
612
+ })
613
+ }
614
+
615
+ const question = find("question")
616
+ if (question) {
617
+ tools.push({
618
+ name: "question",
619
+ description: [
620
+ "Use this tool when you need to ask the user questions during execution. This allows you to:",
621
+ "1. Gather user preferences or requirements",
622
+ "2. Clarify ambiguous instructions",
623
+ "3. Get decisions on implementation choices as you work",
624
+ "4. Offer choices to the user about what direction to take.",
625
+ "",
626
+ "Usage notes:",
627
+ "- A \"Type your own answer\" option is added automatically; don't include a separate option for free form answers",
628
+ "- Set `multiple: true` to allow selecting more than one option",
629
+ "- If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end of the label",
630
+ ].join("\n"),
631
+ inputSchema: objectSchema({
632
+ questions: {
633
+ type: "array",
634
+ description: "Questions to ask",
635
+ items: objectSchema(
636
+ {
637
+ header: stringSchema("Very short label (max 30 chars)"),
638
+ question: stringSchema("Complete question"),
639
+ options: {
640
+ type: "array",
641
+ description: "Available choices",
642
+ items: objectSchema(
643
+ { label: stringSchema("Display text (1-5 words, concise)"), description: stringSchema("Explanation of choice") },
644
+ ["label", "description"],
645
+ ),
646
+ },
647
+ multiple: { type: "boolean", description: "Allow selecting multiple choices" },
648
+ },
649
+ ["header", "question", "options"],
650
+ ),
651
+ },
652
+ }, ["questions"]),
653
+ call: async (args, signal) => {
654
+ const service = typeof localService === "function" ? await localService() : localService
655
+ if (service) {
656
+ try {
657
+ return toMcpResult(await askViaForm(ctx, service, sessionKey, args ?? {}, signal, log))
658
+ } catch (error) {
659
+ if (!(error instanceof QuestionFormError)) throw error
660
+ log?.("warn", `question form API unavailable (${error.message}); using the builtin question tool`)
661
+ }
662
+ }
663
+ return toMcpResult(await invoke(question, args ?? {}, signal))
664
+ },
665
+ })
666
+ }
667
+
668
+ const todowrite = find("todowrite", "todo")
669
+ if (todowrite) {
670
+ tools.push({
671
+ name: "todowrite",
672
+ description: [
673
+ "Create and update a todo list for the current session. The user sees it as your working plan.",
674
+ "",
675
+ "Use it proactively when a task has 3 or more distinct steps, or when the user gives several tasks or asks for a todo list. Skip it for a single simple task or a purely conversational request. When in doubt, use it.",
676
+ "",
677
+ "- Send the full list on every call; it replaces the previous one.",
678
+ "- Mark items `in_progress` when you start them and `completed` as soon as they're actually done.",
679
+ "- Only call it when the list changes.",
680
+ ].join("\n"),
681
+ inputSchema: objectSchema({
682
+ todos: {
683
+ type: "array",
684
+ description: "The updated todo list",
685
+ items: objectSchema(
686
+ {
687
+ content: stringSchema("Brief description of the task"),
688
+ status: {
689
+ type: "string",
690
+ enum: ["pending", "in_progress", "completed", "cancelled"],
691
+ description: "Current status of the task: pending, in_progress, completed, cancelled",
692
+ },
693
+ },
694
+ ["content", "status"],
695
+ ),
696
+ },
697
+ }, ["todos"]),
698
+ call: async (args, signal) => toMcpResult(await invoke(todowrite, args ?? {}, signal)),
699
+ })
700
+ }
701
+
702
+ tools.push(
703
+ {
704
+ name: "session_list",
705
+ description: "List sessions in this location, newest first. Mirrors session.list.",
706
+ inputSchema: objectSchema({
707
+ limit: { type: "integer", minimum: 1 },
708
+ order: { type: "string", enum: ["asc", "desc"] },
709
+ search: stringSchema("Filter by title or content."),
710
+ parentID: { type: ["string", "null"], description: "Only children of this session." },
711
+ archived: { type: "boolean" },
712
+ directory: stringSchema("Filter by directory."),
713
+ project: stringSchema("Filter by project."),
714
+ subpath: stringSchema("Filter by subpath."),
715
+ cursor: stringSchema("Paging cursor."),
716
+ }),
717
+ call: async (args, signal) => {
718
+ await assertPermission(ctx, sessionKey, "session", "*", "list", signal)
719
+ return toMcpResult(await ctx.session.list(args ?? {}))
720
+ },
721
+ },
722
+ {
723
+ name: "session_create",
724
+ description: "Start an independent top-level session that never reports back. For work that should report back, use `subagent`.",
725
+ inputSchema: objectSchema({
726
+ prompt: stringSchema("First message."),
727
+ title: stringSchema(),
728
+ agent: stringSchema("Primary agent."),
729
+ model: stringSchema("Only when the user names one: \"providerID/modelID#variant\", from the models tool."),
730
+ directory: stringSchema("Defaults to your session's directory."),
731
+ }),
732
+ call: async (args, signal) => {
733
+ await assertPermission(ctx, sessionKey, "session", "*", "create", signal)
734
+ const input = args ?? {}
735
+ const caller = await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)
736
+ const directory = nonEmpty(input.directory) ?? (caller as any)?.location?.directory ?? ctx.location.directory
737
+ const model = nonEmpty(input.model)
738
+ const session = await ctx.session.create({
739
+ ...(nonEmpty(input.title) ? { title: input.title } : {}),
740
+ ...(nonEmpty(input.agent) ? { agent: input.agent } : {}),
741
+ ...(model ? { model: parseModelRef(model) } : {}),
742
+ location: { directory },
743
+ } as any)
744
+ const prompt = nonEmpty(input.prompt)
745
+ if (prompt) await ctx.session.prompt({ sessionID: session.id, text: prompt } as any)
746
+ return toMcpResult({ sessionID: session.id, session, prompted: Boolean(prompt) })
747
+ },
748
+ },
749
+ {
750
+ name: "session_get",
751
+ description: "Read one session's status and metadata. Defaults to the calling session.",
752
+ inputSchema: objectSchema({ sessionID: stringSchema("Session ID. Omit for the calling session.") }),
753
+ call: async (args, signal) => {
754
+ const sessionID = await readTarget(ctx, sessionKey, args?.sessionID, "get", signal)
755
+ return toMcpResult(await ctx.session.get({ sessionID }))
756
+ },
757
+ },
758
+ {
759
+ name: "session_prompt",
760
+ description: "Send a message to a session. delivery=steer joins a running turn; delivery=queue starts a follow-up run. Mirrors session.prompt.",
761
+ inputSchema: objectSchema(
762
+ {
763
+ sessionID: stringSchema("Target session ID."),
764
+ text: stringSchema("Message text."),
765
+ id: stringSchema("Stable message id for idempotent retries."),
766
+ files: { type: "array", items: { type: "object", additionalProperties: true } },
767
+ agents: { type: "array", items: { type: "object", additionalProperties: true } },
768
+ skills: { type: "array", items: { type: "object", additionalProperties: true } },
769
+ metadata: { type: "object", additionalProperties: true },
770
+ delivery: { type: "string", enum: ["steer", "queue"], description: "Default follows the session's current state." },
771
+ resume: { type: "boolean" },
772
+ },
773
+ ["sessionID", "text"],
774
+ ),
775
+ call: async (args, signal) => {
776
+ await assertPermission(ctx, sessionKey, "session", args.sessionID, "prompt", signal)
777
+ return toMcpResult(await ctx.session.prompt(args))
778
+ },
779
+ },
780
+ {
781
+ name: "session_context",
782
+ description: "Read a session's messages. Defaults to the calling session. Large timelines are truncated to the most recent items.",
783
+ inputSchema: objectSchema({ sessionID: stringSchema("Session ID. Omit for the calling session.") }),
784
+ call: async (args, signal) => {
785
+ const sessionID = await readTarget(ctx, sessionKey, args?.sessionID, "context", signal)
786
+ const messages = await ctx.session.context({ sessionID })
787
+ return toMcpResult(boundContext(messages))
788
+ },
789
+ },
790
+ {
791
+ name: "session_wait",
792
+ description: "Wait for a session to become idle. The timeout does not cancel the session.",
793
+ inputSchema: objectSchema(
794
+ {
795
+ sessionID: stringSchema("Target session ID."),
796
+ timeoutMs: { type: "integer", minimum: 0, description: "Maximum wait in milliseconds. Defaults to 45000 and is capped at 120000." },
797
+ },
798
+ ["sessionID"],
799
+ ),
800
+ call: async (args, signal) => {
801
+ const sessionID = await readTarget(ctx, sessionKey, args.sessionID, "wait", signal)
802
+ const requested = Number(args.timeoutMs ?? 45_000)
803
+ const timeout = requested > 0 ? Math.min(requested, 120_000) : 45_000
804
+ const wait = ctx.session.wait({ sessionID })
805
+ let timer: ReturnType<typeof setTimeout> | undefined
806
+ const outcome = await Promise.race([
807
+ wait.then(() => "done" as const),
808
+ new Promise<"timeout">((resolve) => {
809
+ timer = setTimeout(() => resolve("timeout"), timeout)
810
+ timer.unref?.()
811
+ }),
812
+ waitForAbort(signal),
813
+ ]).finally(() => {
814
+ if (timer) clearTimeout(timer)
815
+ })
816
+ if (outcome === "cancelled") throw new Error("session wait cancelled")
817
+ const timedOut = outcome === "timeout"
818
+ const info = await ctx.session.get({ sessionID }).catch(() => undefined)
819
+ return toMcpResult({ sessionID, session: info, waitTimedOut: timedOut })
820
+ },
821
+ },
822
+ {
823
+ name: "session_interrupt",
824
+ description: "Interrupt a session's active run. Mirrors session.interrupt.",
825
+ inputSchema: objectSchema({ sessionID: stringSchema("Target session ID."), resume: { type: "boolean" } }, ["sessionID"]),
826
+
827
+ call: async (args, signal) => {
828
+ await assertPermission(ctx, sessionKey, "session", args.sessionID, "interrupt", signal)
829
+ return toMcpResult(await ctx.session.interrupt(args))
830
+ },
831
+ },
832
+ {
833
+ name: "worktree_create",
834
+ description: "Create a git worktree for the calling session's project and return its directory. Pass `from` to start it at a specific commit or ref. Mirrors worktree.create.",
835
+ inputSchema: objectSchema({
836
+ from: stringSchema("Commit, branch, or tag to start from. Defaults to the project's current HEAD."),
837
+ branch: stringSchema("Branch for the worktree."),
838
+ name: stringSchema("Name for the worktree; used to pick its directory."),
839
+ directory: stringSchema("Requested directory. The worktree strategy may choose another; use the returned directory."),
840
+ }),
841
+ call: async (args, signal) => {
842
+ await assertPermission(ctx, sessionKey, "worktree", "*", "create", signal)
843
+ const input: Record<string, string> = { projectID: await callerProjectID(ctx, sessionKey) }
844
+ for (const field of ["from", "branch", "name", "directory"]) {
845
+ const value = nonEmpty(args?.[field])
846
+ if (value) input[field] = value
847
+ }
848
+ const created = await ctx.worktree.create(input as any)
849
+ return toMcpResult({ directory: created.directory })
850
+ },
851
+ },
852
+ {
853
+ name: "worktree_remove",
854
+ description: "Remove a worktree of the calling session's project by its directory. Mirrors worktree.remove.",
855
+ inputSchema: objectSchema(
856
+ {
857
+ directory: stringSchema("Worktree directory, as returned by worktree_create."),
858
+ force: { type: "boolean", description: "Remove even with uncommitted changes. Defaults to false." },
859
+ },
860
+ ["directory"],
861
+ ),
862
+ call: async (args, signal) => {
863
+ const directory = nonEmpty(args?.directory)
864
+ if (!directory) throw new Error("worktree remove requires a directory")
865
+ await assertPermission(ctx, sessionKey, "worktree", directory, "remove", signal)
866
+ await ctx.worktree.remove({
867
+ projectID: await callerProjectID(ctx, sessionKey),
868
+ directory,
869
+ force: args?.force === true,
870
+ } as any)
871
+ return toMcpResult({ directory, removed: true })
872
+ },
873
+ },
874
+ )
875
+
876
+ return tools
877
+ }
878
+
879
+ async function subagentDescription(ctx: Ctx) {
880
+ const parts = [SUBAGENT_DESCRIPTION]
881
+ try {
882
+ const agents = (await ctx.agent.list()).data
883
+ const available = agents
884
+ .filter((agent) => agent.mode !== "primary" && !agent.hidden)
885
+ .sort((left, right) => left.id.localeCompare(right.id))
886
+ if (available.length) {
887
+ parts.push("", "Available subagents:", ...available.map((agent) => `- ${agent.id}: ${agent.description ?? "This subagent should only be called when explicitly requested."}`))
888
+ }
889
+ } catch {
890
+ // agent discovery is best effort
891
+ }
892
+ return parts.join("\n")
893
+ }
894
+
895
+ /**
896
+ * Ask for a `session` or `worktree` permission on a target. Listing spans
897
+ * targets, so it is asserted against `"*"` and needs an explicit permission of
898
+ * its own.
899
+ */
900
+ async function assertPermission(
901
+ ctx: Ctx,
902
+ caller: string,
903
+ action: "session" | "worktree",
904
+ target: any,
905
+ operation: string,
906
+ signal: AbortSignal,
907
+ ) {
908
+ if (!target) throw new Error(`${action} ${operation} requires a ${action === "session" ? "sessionID" : "target"}`)
909
+ try {
910
+ await ctx.permission.assert({
911
+ sessionID: caller as any,
912
+ action,
913
+ resources: [String(target)],
914
+ metadata: { operation },
915
+ } as any)
916
+ } catch (error) {
917
+ if (signal.aborted) throw error
918
+ const message = error instanceof Error && error.message ? `: ${error.message}` : ""
919
+ const scope = target === "*" ? "" : ` on ${target}`
920
+ throw new Error(`Permission denied: ${action} ${operation}${scope}${message}`)
921
+ }
922
+ }
923
+
924
+ /** Reads default to the calling session; another session needs a permission check. */
925
+ async function readTarget(
926
+ ctx: Ctx,
927
+ caller: string,
928
+ requested: unknown,
929
+ operation: string,
930
+ signal: AbortSignal,
931
+ ) {
932
+ const target = typeof requested === "string" && requested ? requested : caller
933
+ if (target !== caller) await assertPermission(ctx, caller, "session", target, operation, signal)
934
+ return target
935
+ }
936
+
937
+ /** The calling session's project, falling back to the plugin's own project. */
938
+ async function callerProjectID(ctx: Ctx, sessionKey: string) {
939
+ const caller = (await ctx.session.get({ sessionID: sessionKey as any }).catch(() => undefined)) as any
940
+ return caller?.projectID ?? ctx.location.project.id
941
+ }
942
+
943
+ function nonEmpty(value: unknown): string | undefined {
944
+ return typeof value === "string" && value.trim() ? value.trim() : undefined
945
+ }
946
+
947
+ /** Parse "providerID/modelID#variant"; the model id itself may contain slashes. */
948
+ export function parseModelRef(value: string): { providerID: string; id: string; variant?: string } {
949
+ const hash = value.lastIndexOf("#")
950
+ const ref = hash === -1 ? value : value.slice(0, hash)
951
+ const variant = hash === -1 ? undefined : value.slice(hash + 1)
952
+ const slash = ref.indexOf("/")
953
+ if (slash <= 0 || slash === ref.length - 1 || variant === "") {
954
+ throw new Error(`Invalid model "${value}": expected "providerID/modelID" or "providerID/modelID#variant"`)
955
+ }
956
+ return { providerID: ref.slice(0, slash), id: ref.slice(slash + 1), ...(variant ? { variant } : {}) }
957
+ }
958
+
959
+ function waitForAbort(signal: AbortSignal): Promise<"cancelled"> {
960
+ return new Promise((resolve) => {
961
+ if (signal.aborted) {
962
+ resolve("cancelled")
963
+ return
964
+ }
965
+ signal.addEventListener("abort", () => resolve("cancelled"), { once: true })
966
+ })
967
+ }
968
+
969
+
970
+ function toMcpResult(value: any) {
971
+ const output = value && typeof value === "object" && "output" in value ? value.output : value
972
+ let content = value && typeof value === "object" && Array.isArray(value.content) ? value.content : undefined
973
+ if (!content) {
974
+ const text =
975
+ value && typeof value === "object" && typeof value.content === "string"
976
+ ? value.content
977
+ : typeof output === "string"
978
+ ? output
979
+ : JSON.stringify(output ?? null)
980
+ content = [{ type: "text", text }]
981
+ }
982
+ return {
983
+ content,
984
+ ...(output === undefined ? {} : { structuredContent: output }),
985
+ }
986
+ }
987
+
988
+ function boundContext(messages: any[]) {
989
+ const serialized = JSON.stringify(messages)
990
+ if (serialized.length <= MAX_CONTEXT_CHARS) return { messages, truncated: false, omittedMessages: 0 }
991
+ let size = 0
992
+ let start = messages.length
993
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
994
+ const length = JSON.stringify(messages[index]).length
995
+ if (size + length > MAX_CONTEXT_CHARS) break
996
+ size += length
997
+ start = index
998
+ }
999
+ return { messages: messages.slice(start), truncated: true, omittedMessages: start }
1000
+ }
1001
+