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