opencode-acp-provider 1.1.0 → 1.1.1

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.
package/src/index.ts CHANGED
@@ -6,16 +6,17 @@ import { join } from "node:path"
6
6
  import {
7
7
  AcpServerManager,
8
8
  type AcpCompactResult,
9
+ type AcpModelInfo,
9
10
  type AcpServerConfig,
10
11
  type AcpServerState,
11
12
  type AcpSessionStore,
13
+ type AcpUnsolicitedTurnInfo,
12
14
  } from "./server-manager.ts"
13
15
  import { sharedAgentPool } from "./agent-pool.ts"
14
16
  import { createShim } from "./shim.ts"
15
- import { boundedMessages, historyLimits, recentConversation } from "./prompt.ts"
17
+ import { boundedMessages, historyLimits, recentConversation, textOf } from "./prompt.ts"
16
18
  import { createAcpLanguageModel } from "./language-model.ts"
17
19
  import { createMcpServer } from "./mcp-server.ts"
18
- import { createOpenCodeMcpSource } from "./mcp-config.ts"
19
20
  import { createSteering, type LocalService } from "./steering.ts"
20
21
  import { createSkillMirror } from "./skills.ts"
21
22
  import { createCommandBridge } from "./commands.ts"
@@ -88,6 +89,31 @@ function storedSessionKey(poolKey: string) {
88
89
  return `acp-session/${createHash("sha256").update(poolKey).digest("hex")}`
89
90
  }
90
91
 
92
+ /**
93
+ * Resolve an ACP continuation token when OpenCode is running a turn prompted by
94
+ * a background-completion synthetic message rather than a new user prompt.
95
+ */
96
+ function continuationTokenOf(
97
+ messages: ReadonlyArray<{
98
+ role: string
99
+ content?: string | ReadonlyArray<{ type?: string; text?: unknown }>
100
+ metadata?: Record<string, unknown>
101
+ }>,
102
+ sessionID: string,
103
+ manager: Pick<AcpServerManager, "findContinuationByText">,
104
+ ): string | undefined {
105
+ for (let i = messages.length - 1; i >= 0; i--) {
106
+ const message = messages[i]
107
+ if (!message) continue
108
+ if (message.role === "assistant") return undefined
109
+ if (message.role !== "user") continue
110
+ const token = message.metadata?.source === "acp-background" ? message.metadata.acpContinuation : undefined
111
+ if (typeof token === "string" && token) return token
112
+ return sessionID ? manager.findContinuationByText(sessionID, textOf(message)) : undefined
113
+ }
114
+ return undefined
115
+ }
116
+
91
117
 
92
118
  /**
93
119
  * A `serve --service` server records its address and password next to its
@@ -172,15 +198,6 @@ export default Plugin.define({
172
198
  }
173
199
  }
174
200
 
175
- // Forward the MCP servers OpenCode is configured with so a server is set up
176
- // once and reaches every ACP agent, alongside this plugin's own bridge.
177
- let openCodeMcp: Awaited<ReturnType<typeof createOpenCodeMcpSource>> | undefined
178
- try {
179
- openCodeMcp = await createOpenCodeMcpSource(ctx, log)
180
- } catch (error) {
181
- log("warn", `OpenCode MCP servers disabled: ${errorMessage(error)}`)
182
- }
183
-
184
201
  // A plugin reload or a crashed agent starts a new process with no in-memory
185
202
  // sessions. Persist which ACP session belongs to each OpenCode session so
186
203
  // the next process can resume it instead of losing the conversation.
@@ -202,35 +219,69 @@ export default Plugin.define({
202
219
  // Assigned once the agents are up and their skills are known, but the
203
220
  // manager reports command updates from the first `session/new` onward.
204
221
  let commandBridge: Awaited<ReturnType<typeof createCommandBridge>> | undefined
222
+ const continuations = new Map<string, string>()
223
+ let disposed = false
224
+ let manager: AcpServerManager
225
+ let serverForProvider = new Map<string, string>()
205
226
 
206
- const manager = new AcpServerManager({
227
+ const wakeSessionForUnsolicited = async (turn: AcpUnsolicitedTurnInfo) => {
228
+ if (disposed || typeof ctx.session?.synthetic !== "function") {
229
+ manager.dropContinuation(turn.sessionKey, turn.token)
230
+ return
231
+ }
232
+ try {
233
+ if (typeof ctx.session.get === "function") {
234
+ const session = await ctx.session.get({ sessionID: turn.sessionKey as any }).catch(() => undefined)
235
+ const providerID = session?.model?.providerID
236
+ if (providerID && serverForProvider.get(providerID) !== turn.server) {
237
+ log(
238
+ "debug",
239
+ `skipping ACP background wake for ${turn.sessionKey}: session switched to provider ${providerID}`,
240
+ )
241
+ manager.dropContinuation(turn.sessionKey, turn.token)
242
+ return
243
+ }
244
+ }
245
+ await ctx.session.synthetic({
246
+ sessionID: turn.sessionKey as any,
247
+ text: turn.text,
248
+ description: turn.description,
249
+ metadata: {
250
+ source: "acp-background",
251
+ server: turn.server,
252
+ acpContinuation: turn.token,
253
+ },
254
+ delivery: "queue",
255
+ resume: true,
256
+ })
257
+ } catch (error) {
258
+ log("warn", `could not wake OpenCode session ${turn.sessionKey} for ACP background task: ${errorMessage(error)}`)
259
+ manager.dropContinuation(turn.sessionKey, turn.token)
260
+ }
261
+ }
262
+
263
+ manager = new AcpServerManager({
207
264
  servers,
208
265
  defaultCwd: ctx.location.directory,
209
266
  log,
210
267
  sessions: sessionStore,
211
268
  agents: sharedAgentPool(),
269
+ discoverCommands: options.commands !== false,
212
270
  onCommands: (server) => void commandBridge?.sync(server),
213
- mcp:
214
- mcp || openCodeMcp
215
- ? {
216
- servers: async (sessionKey, agent) => {
217
- const lease = mcp?.issue(sessionKey)
218
- try {
219
- const configured = (await openCodeMcp?.servers(agent)) ?? []
220
- // Let the plugin's own bridge win a name collision with a
221
- // configured server, since that is the one agents rely on.
222
- const taken = new Set(lease?.servers.map((server) => server.name) ?? [])
223
- return {
224
- servers: [...(lease?.servers ?? []), ...configured.filter((server) => !taken.has(server.name))],
225
- release: () => lease?.release(),
226
- }
227
- } catch (error) {
228
- lease?.release()
229
- throw error
230
- }
231
- },
232
- }
233
- : undefined,
271
+ // A model's effort levels are learned when it is first selected; refresh its variants.
272
+ onModels: (server) => {
273
+ const state = manager.get(server)
274
+ if (!state || disposed || !registered.has(server)) return
275
+ void publishInventory(state).then(() => persistInventory(state))
276
+ },
277
+ onUnsolicited: (turn) => {
278
+ if (!disposed) void wakeSessionForUnsolicited(turn)
279
+ },
280
+ mcp: mcp
281
+ ? {
282
+ servers: async (sessionKey) => mcp.issue(sessionKey),
283
+ }
284
+ : undefined,
234
285
  additionalDirectories: skills ? [skills.root] : undefined,
235
286
  cmdSkillDir: skills?.agentsDir,
236
287
  cmdOrchestration: mcp !== undefined,
@@ -261,7 +312,6 @@ export default Plugin.define({
261
312
  const outputLimit = options.outputLimit ?? 32_000
262
313
  const shimToken = randomUUID()
263
314
 
264
- let disposed = false
265
315
  const retryTimers = new Set<ReturnType<typeof setTimeout>>()
266
316
  const registrations: Awaited<ReturnType<typeof ctx.provider.transform>>[] = []
267
317
  const registered = new Set<string>()
@@ -282,10 +332,12 @@ export default Plugin.define({
282
332
  }
283
333
 
284
334
  const providerModels = (state: AcpServerState, providerID: ReturnType<typeof Provider.ID.make>, inventory: AcpInventory) => {
285
- const variants = effortLevels(inventory.efforts).map((effort) => ({
286
- id: Model.VariantID.make(effort),
287
- settings: { reasoningEffort: effort },
288
- }))
335
+ // Efforts can differ per model, and a model may offer none at all.
336
+ const variantsFor = (model: AcpModelInfo) =>
337
+ effortLevels(model.efforts ?? inventory.efforts).map((effort) => ({
338
+ id: Model.VariantID.make(effort),
339
+ settings: { reasoningEffort: effort },
340
+ }))
289
341
  return inventory.models.map((model) => ({
290
342
  ...Model.Info.default(providerID, Model.ID.make(model.id)),
291
343
  modelID: Model.ID.make(`${state.config.id}::${model.id}`),
@@ -300,7 +352,7 @@ export default Plugin.define({
300
352
  output: ["text"],
301
353
  temperature: false,
302
354
  },
303
- variants,
355
+ variants: variantsFor(model),
304
356
  // The agent keeps the conversation in its reused ACP session and
305
357
  // compacts it itself. A known window would let OpenCode auto-compact,
306
358
  // which only spends a turn on a summary the agent never reads. OpenCode
@@ -351,7 +403,15 @@ export default Plugin.define({
351
403
  if (left.models.length !== right.models.length || left.efforts.length !== right.efforts.length) return false
352
404
  const modelsMatch = left.models.every((model, index) => {
353
405
  const other = right.models[index]
354
- return other !== undefined && model.id === other.id && model.name === other.name && model.description === other.description
406
+ return (
407
+ other !== undefined &&
408
+ model.id === other.id &&
409
+ model.name === other.name &&
410
+ model.description === other.description &&
411
+ model.defaultEffort === other.defaultEffort &&
412
+ (model.efforts ?? []).join("\u0000") === (other.efforts ?? []).join("\u0000") &&
413
+ (model.efforts === undefined) === (other.efforts === undefined)
414
+ )
355
415
  })
356
416
  return modelsMatch && left.efforts.every((effort, index) => effort === right.efforts[index])
357
417
  }
@@ -448,12 +508,12 @@ export default Plugin.define({
448
508
  await manager.stop().catch(() => {})
449
509
  await mcp?.close().catch(() => {})
450
510
  await skills?.close().catch(() => {})
451
- await openCodeMcp?.close().catch(() => {})
452
511
  throw error
453
512
  }
454
513
 
455
514
  const cleanup = async () => {
456
515
  disposed = true
516
+ continuations.clear()
457
517
  for (const timer of retryTimers) clearTimeout(timer)
458
518
  retryTimers.clear()
459
519
  for (const registration of registrations) await registration.dispose().catch(() => {})
@@ -467,7 +527,6 @@ export default Plugin.define({
467
527
  await manager.stop().catch(() => {})
468
528
  await skills?.close().catch(() => {})
469
529
  await mcp?.close().catch(() => {})
470
- await openCodeMcp?.close().catch(() => {})
471
530
  })()
472
531
  }
473
532
 
@@ -476,7 +535,7 @@ export default Plugin.define({
476
535
  // late cannot steal the id of one that already registered.
477
536
  for (const state of manager.list) providerIDForServer(state.config.id)
478
537
  // Every provider id is reserved above, so this reverse map is complete.
479
- const serverForProvider = new Map([...providerIDs].map(([server, providerID]) => [providerID, server]))
538
+ serverForProvider = new Map([...providerIDs].map(([server, providerID]) => [providerID, server]))
480
539
 
481
540
  // A server whose models were discovered before, in another location or an
482
541
  // earlier process, is registered now, so this location resolves them
@@ -523,9 +582,37 @@ export default Plugin.define({
523
582
  await ctx.session.hook("model.request", (event) => {
524
583
  if (!serverForProvider.has(event.model.providerID)) return
525
584
  event.headers["x-acp-request-kind"] = event.kind
585
+ if (event.kind === "primary" && event.sessionID) {
586
+ const token = continuations.get(event.sessionID)
587
+ if (token) {
588
+ continuations.delete(event.sessionID)
589
+ event.headers["x-acp-continuation"] = token
590
+ }
591
+ }
526
592
  }),
527
593
  )
528
594
  const limits = historyLimits(options)
595
+ // Detect background continuation turns on every route, and trim fallback
596
+ // HTTP requests when the server cannot register an AI SDK provider.
597
+ registrations.push(
598
+ await ctx.session.hook("context", (event) => {
599
+ if (!serverForProvider.has(event.model.providerID)) return
600
+ if (event.sessionID) {
601
+ const token = continuationTokenOf(event.messages, event.sessionID, manager)
602
+ if (token) continuations.set(event.sessionID, token)
603
+ else continuations.delete(event.sessionID)
604
+ }
605
+ if (!nativeToolParts) {
606
+ const includeSystem = options.includeSystem === true
607
+ if (!includeSystem) event.system = []
608
+ const messages: typeof event.messages = []
609
+ for (const { message, text } of boundedMessages(event.messages, limits, includeSystem)) {
610
+ if (message.role !== "tool") messages.push({ ...message, content: [{ type: "text", text }] })
611
+ }
612
+ event.messages = messages
613
+ }
614
+ }),
615
+ )
529
616
  if (nativeToolParts) {
530
617
  registrations.push(
531
618
  await ctx.aisdk.hook("sdk", (evt) => {
@@ -551,13 +638,11 @@ export default Plugin.define({
551
638
  } else {
552
639
  // The native HTTP provider serializes these messages itself. Trim
553
640
  // its model request before that happens, without changing the transcript.
554
- for (const kind of ["context", "generate", "title"] as const) {
641
+ for (const kind of ["generate", "title"] as const) {
555
642
  registrations.push(await ctx.session.hook(kind, (event) => {
556
643
  if (!serverForProvider.has(event.model.providerID)) return
557
- const includeSystem = kind !== "context" || options.includeSystem === true
558
- if (!includeSystem) event.system = []
559
644
  const messages: typeof event.messages = []
560
- for (const { message, text } of boundedMessages(event.messages, limits, includeSystem)) {
645
+ for (const { message, text } of boundedMessages(event.messages, limits, true)) {
561
646
  if (message.role !== "tool") messages.push({ ...message, content: [{ type: "text", text }] })
562
647
  }
563
648
  event.messages = messages
package/src/inventory.ts CHANGED
@@ -11,6 +11,14 @@ export interface AcpInventory {
11
11
  efforts: string[]
12
12
  }
13
13
 
14
+ /** Live discovery, shared by locations for the lifetime of the service. */
15
+ export interface AcpCatalog extends AcpInventory {
16
+ defaultModel?: string
17
+ modelConfigID?: string
18
+ effortConfigID?: string
19
+ onModels: Set<() => void>
20
+ }
21
+
14
22
  /** Bump when the payload shape changes; an older entry is treated as a miss. */
15
23
  const VERSION = 1
16
24
  const MAX_MODELS = 1_000
@@ -29,6 +37,8 @@ function cacheInput(config: AcpServerConfig) {
29
37
  return {
30
38
  command: Array.isArray(config.command) ? config.command : [config.command],
31
39
  env: Object.entries(config.env ?? {}).sort(([a], [b]) => a.localeCompare(b)),
40
+ ...(config.meta ? { meta: config.meta } : {}),
41
+ ...(config.setup?.trim() ? { setup: config.setup.trim() } : {}),
32
42
  models: config.models ?? null,
33
43
  }
34
44
  }
@@ -62,6 +72,10 @@ export function parseInventory(value: unknown): AcpInventory | undefined {
62
72
  if (typeof entry.name !== "string" || !entry.name) return undefined
63
73
  const model: AcpModelInfo = { id: entry.id, name: entry.name }
64
74
  if (typeof entry.description === "string" && entry.description) model.description = entry.description
75
+ if (Array.isArray(entry.efforts)) {
76
+ model.efforts = effortLevels(entry.efforts.filter((effort): effort is string => typeof effort === "string"))
77
+ }
78
+ if (typeof entry.defaultEffort === "string" && entry.defaultEffort) model.defaultEffort = entry.defaultEffort
65
79
  models.push(model)
66
80
  }
67
81
 
@@ -34,6 +34,7 @@ export function createAcpLanguageModel(options: AcpLanguageModelOptions) {
34
34
  async doStream(call: CallOptions) {
35
35
  const sessionID = header(call.headers, "x-opencode-session-id")
36
36
  const requestKind = header(call.headers, "x-acp-request-kind")
37
+ const continuation = header(call.headers, "x-acp-continuation")
37
38
  options.log?.(
38
39
  "debug",
39
40
  `acp language model ${options.server}/${options.model} session=${sessionID ?? "-"} kind=${requestKind ?? "primary"} messages=${call.prompt?.length ?? 0}`,
@@ -49,6 +50,7 @@ export function createAcpLanguageModel(options: AcpLanguageModelOptions) {
49
50
  ...(options.token ? { authorization: `Bearer ${options.token}` } : {}),
50
51
  ...(sessionID ? { "x-opencode-session-id": sessionID } : {}),
51
52
  ...(requestKind ? { "x-acp-request-kind": requestKind } : {}),
53
+ ...(continuation ? { "x-acp-continuation": continuation } : {}),
52
54
  },
53
55
  body: JSON.stringify({
54
56
  model: `${options.server}::${options.model}`,
@@ -270,26 +272,34 @@ function translate(body: ReadableStream<Uint8Array>, log?: LogFn) {
270
272
  const handleTool = (event: any) => {
271
273
  if (!event || typeof event.id !== "string") return
272
274
  const existing = tools.get(event.id)
273
- const name = existing?.name ?? (typeof event.name === "string" && event.name ? event.name : "tool")
275
+ if (existing?.settled) return
276
+ const incomingName = typeof event.name === "string" && event.name ? event.name : undefined
277
+ const name = existing?.called ? existing.name : (incomingName ?? existing?.name ?? "unknown")
274
278
  const current: ToolProgress = existing ?? { name, started: false, called: false, settled: false }
275
279
  if (!existing) tools.set(event.id, current)
280
+ if (!current.called) current.name = name
276
281
  if (typeof event.title === "string" && event.title) current.title = event.title
277
- if (typeof event.output === "string" && event.output) current.output = event.output
278
- closeText()
279
- closeReasoning()
280
- if (!current.started) {
281
- push({ type: "tool-input-start", id: event.id, toolName: name, providerExecuted: true })
282
- current.started = true
283
- }
282
+ if (typeof event.output === "string") current.output = event.output
284
283
  const input = event.input && typeof event.input === "object" && !Array.isArray(event.input) ? event.input : {}
285
284
  const done = event.done === true
286
285
  const keys = Object.keys(input)
287
- // Agents stream edit/write input in pieces. Wait for the actual change so
288
- // the card is created with its diff instead of a path-only placeholder.
286
+ // Agents stream edit/write/patch input in pieces. Wait for the actual
287
+ // change so the card is created with its diff instead of a path-only
288
+ // placeholder, and so tool-input-start commits the final tool name.
289
289
  const partial =
290
- (name === "edit" && (input.oldString === undefined || input.newString === undefined)) ||
291
- (name === "write" && input.content === undefined)
292
- if (!current.called && (done || (keys.length > 0 && !partial))) {
290
+ (current.name === "edit" && (input.oldString === undefined || input.newString === undefined)) ||
291
+ (current.name === "write" && input.content === undefined) ||
292
+ (current.name === "patch" && input.patchText === undefined)
293
+ const ready = done || (keys.length > 0 && !partial)
294
+ if (ready) {
295
+ closeText()
296
+ closeReasoning()
297
+ if (!current.started) {
298
+ push({ type: "tool-input-start", id: event.id, toolName: current.name, providerExecuted: true })
299
+ current.started = true
300
+ }
301
+ }
302
+ if (!current.called && ready) {
293
303
  callTool(event.id, current, input)
294
304
  current.called = true
295
305
  }
@@ -355,6 +365,10 @@ function translate(body: ReadableStream<Uint8Array>, log?: LogFn) {
355
365
  // failed turn cannot leave a card stuck in the streaming state.
356
366
  for (const [id, current] of tools) {
357
367
  if (current.settled) continue
368
+ if (!current.started) {
369
+ push({ type: "tool-input-start", id, toolName: current.name, providerExecuted: true })
370
+ current.started = true
371
+ }
358
372
  if (!current.called) {
359
373
  callTool(id, current, {})
360
374
  current.called = true
package/src/mcp-server.ts CHANGED
@@ -4,6 +4,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
4
4
  import { posix, win32 } from "node:path"
5
5
  import { fileURLToPath } from "node:url"
6
6
  import type { Plugin } from "@opencode/plugin"
7
+ import { Schema } from "effect"
7
8
  import packageJson from "../package.json" with { type: "json" }
8
9
  import type { AcpMcpServer } from "./acp-client.ts"
9
10
  import type { LogFn, McpLease } from "./server-manager.ts"
@@ -20,14 +21,6 @@ const MAX_CONTEXT_CHARS = 60_000
20
21
  /** Live tokens above this suggest leases are not being released. */
21
22
  const TOKEN_WARN_THRESHOLD = 256
22
23
 
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
24
  /**
32
25
  * Order used by the initialize instructions. Clients that defer MCP tools (Codex
33
26
  * shows only the server's `instructions` until a namespace is loaded, and appends
@@ -37,6 +30,7 @@ const SUBAGENT_DESCRIPTION = [
37
30
  const TOOL_ORDER = [
38
31
  "question",
39
32
  "subagent",
33
+ "subagent_list",
40
34
  "models",
41
35
  "todowrite",
42
36
  "session_create",
@@ -73,6 +67,7 @@ interface McpTool {
73
67
  name: string
74
68
  description: string
75
69
  inputSchema: Record<string, unknown>
70
+ nativeInput?: unknown
76
71
  call: (args: any, signal: AbortSignal) => Promise<any>
77
72
  }
78
73
 
@@ -96,6 +91,47 @@ const objectSchema = (properties: Record<string, unknown>, required: string[] =
96
91
 
97
92
  const stringSchema = (description?: string) => ({ type: "string", ...(description ? { description } : {}) })
98
93
 
94
+ function schemaRecord(value: unknown): Record<string, unknown> | undefined {
95
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined
96
+ }
97
+
98
+ function nativeSchema(input: unknown) {
99
+ try {
100
+ if (Schema.isSchema(input)) {
101
+ return Schema.toJsonSchemaDocument(input, {
102
+ referencePolicy: () => undefined,
103
+ generateDescriptions: false,
104
+ }).schema
105
+ }
106
+ const schema = schemaRecord(input)
107
+ const jsonSchema = schemaRecord(schemaRecord(schema?.["~standard"])?.jsonSchema)
108
+ if (typeof jsonSchema?.input === "function") return jsonSchema.input({ target: "draft-2020-12" }) as unknown
109
+ return schema
110
+ } catch {
111
+ // Not every registry schema supports JSON Schema export.
112
+ return undefined
113
+ }
114
+ }
115
+
116
+ // Only copy annotations at existing field paths; the bridge owns the wire shape and constraints.
117
+ function withNativeDescriptions(input: Record<string, unknown>, source: unknown): Record<string, unknown> {
118
+ const native = schemaRecord(source)
119
+ if (!native) return input
120
+ const result = { ...input }
121
+ if (typeof native.description === "string") result.description = native.description
122
+ const properties = schemaRecord(input.properties)
123
+ const nativeProperties = schemaRecord(native.properties)
124
+ if (properties && nativeProperties) {
125
+ result.properties = Object.fromEntries(Object.entries(properties).map(([key, value]) => {
126
+ const field = schemaRecord(value)
127
+ return [key, field ? withNativeDescriptions(field, nativeProperties[key]) : value]
128
+ }))
129
+ }
130
+ const items = schemaRecord(input.items)
131
+ if (items) result.items = withNativeDescriptions(items, native.items)
132
+ return result
133
+ }
134
+
99
135
  /**
100
136
  * How to launch the stdio bridge. An absolute runtime runs directly; a bare
101
137
  * name (default `node`) is looked up on PATH, through `/usr/bin/env` on POSIX
@@ -328,16 +364,14 @@ export async function createMcpServer(options: McpServerOptions): Promise<McpSer
328
364
  tools: tools.map((tool) => ({
329
365
  name: tool.name,
330
366
  description: tool.description,
331
- inputSchema: tool.inputSchema,
367
+ inputSchema: withNativeDescriptions(tool.inputSchema, nativeSchema(tool.nativeInput)),
332
368
  })),
333
369
  })
334
370
  }
335
371
  case "tools/call": {
336
372
  const name = String(message.params?.name ?? "")
337
373
  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 })
374
+ const tools = await buildTools(ctx, sessionKey, options.localService, log)
341
375
  const tool = tools.find((candidate) => candidate.name === name)
342
376
  if (!tool) return fail(-32602, `Unknown tool: ${name}`)
343
377
  const startedAt = Date.now()
@@ -488,7 +522,7 @@ async function buildInstructions(
488
522
  log?: LogFn,
489
523
  ) {
490
524
  // Only the names are used here.
491
- const tools = await buildTools(ctx, sessionKey, service, log, { describe: false })
525
+ const tools = await buildTools(ctx, sessionKey, service, log)
492
526
  if (!tools.length) return undefined
493
527
  const names = new Set(tools.map((tool) => tool.name))
494
528
  // Tools the model is most likely to need come first; some clients append this
@@ -511,7 +545,7 @@ async function buildInstructions(
511
545
  }
512
546
  if (names.has("subagent")) {
513
547
  lines.push(
514
- "Use `subagent` for delegation instead of a native subagent or task tool: call it with { agent, description, prompt }.",
548
+ "Use `subagent_list` to discover agent IDs and descriptions, then delegate with `subagent` ({ agent, description, prompt }).",
515
549
  "It returns at once and reports back with a <subagent> message when the child goes idle; do not poll it.",
516
550
  )
517
551
  }
@@ -526,7 +560,6 @@ async function buildTools(
526
560
  sessionKey: string,
527
561
  localService?: LocalServiceSource,
528
562
  log?: LogFn,
529
- { describe = true }: { describe?: boolean } = {},
530
563
  ): Promise<McpTool[]> {
531
564
  const tools: McpTool[] = []
532
565
  const available = await ctx.tool.list().catch(() => [])
@@ -563,7 +596,8 @@ async function buildTools(
563
596
  if (models) {
564
597
  tools.push({
565
598
  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.",
599
+ description: models.description,
600
+ nativeInput: models.input,
567
601
  inputSchema: objectSchema({
568
602
  query: stringSchema("Text to search for in model names and IDs."),
569
603
  provider: stringSchema("Provider ID or name to filter by. Try your own provider first."),
@@ -588,7 +622,8 @@ async function buildTools(
588
622
  if (subagent) {
589
623
  tools.push({
590
624
  name: "subagent",
591
- description: describe ? await subagentDescription(ctx) : SUBAGENT_DESCRIPTION,
625
+ description: subagent.description,
626
+ nativeInput: subagent.input,
592
627
  inputSchema: objectSchema(
593
628
  {
594
629
  agent: stringSchema(
@@ -610,28 +645,35 @@ async function buildTools(
610
645
  return toMcpResult(await invoke(subagent, input, signal))
611
646
  },
612
647
  })
648
+ tools.push({
649
+ name: "subagent_list",
650
+ description: "List available OpenCode subagents and their descriptions. Call before delegating with `subagent` to pick a valid `agent` ID.",
651
+ inputSchema: objectSchema({}),
652
+ call: async () => {
653
+ const { data } = await ctx.agent.list()
654
+ const agents = data
655
+ .filter((agent) => agent.mode !== "primary" && !agent.hidden)
656
+ .sort((left, right) => left.id.localeCompare(right.id))
657
+ .map(({ id, description }) => ({
658
+ id,
659
+ description,
660
+ }))
661
+ return toMcpResult({ agents })
662
+ },
663
+ })
613
664
  }
614
665
 
615
666
  const question = find("question")
616
667
  if (question) {
617
668
  tools.push({
618
669
  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"),
670
+ description: question.description,
671
+ nativeInput: question.input,
631
672
  inputSchema: objectSchema({
632
673
  questions: {
633
674
  type: "array",
634
675
  description: "Questions to ask",
676
+ minItems: 1,
635
677
  items: objectSchema(
636
678
  {
637
679
  header: stringSchema("Very short label (max 30 chars)"),
@@ -669,15 +711,8 @@ async function buildTools(
669
711
  if (todowrite) {
670
712
  tools.push({
671
713
  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"),
714
+ description: todowrite.description,
715
+ nativeInput: todowrite.input,
681
716
  inputSchema: objectSchema({
682
717
  todos: {
683
718
  type: "array",
@@ -876,22 +911,6 @@ async function buildTools(
876
911
  return tools
877
912
  }
878
913
 
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
914
  /**
896
915
  * Ask for a `session` or `worktree` permission on a target. Listing spans
897
916
  * targets, so it is asserted against `"*"` and needs an explicit permission of
@@ -998,4 +1017,3 @@ function boundContext(messages: any[]) {
998
1017
  }
999
1018
  return { messages: messages.slice(start), truncated: true, omittedMessages: start }
1000
1019
  }
1001
-