Skip to content

Commit c3be6c4

Browse files
authored
fix(mcp): honor callback port in debug (#39259)
1 parent 172d08c commit c3be6c4

6 files changed

Lines changed: 84 additions & 55 deletions

File tree

‎packages/opencode/src/cli/cmd/mcp.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -737,6 +737,7 @@ export const McpDebugCommand = effectCmd({
737737
clientId: oauthConfig?.clientId,
738738
clientSecret: oauthConfig?.clientSecret,
739739
scope: oauthConfig?.scope,
740+
callbackPort: oauthConfig?.callbackPort,
740741
redirectUri: oauthConfig?.redirectUri,
741742
},
742743
{

‎packages/opencode/src/mcp/catalog.ts‎

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,57 @@
1-
import { Client, type Tool as MCPToolDef } from "@modelcontextprotocol/client"
1+
import { Client, type CallToolResult, type Tool as MCPToolDef } from "@modelcontextprotocol/client"
22
import { dynamicTool, jsonSchema, type JSONSchema7, type Tool } from "ai"
33
import { Effect } from "effect"
44

55
const DEFAULT_TIMEOUT = 30_000
6+
7+
export interface McpTool {
8+
readonly def: MCPToolDef
9+
readonly client: Client
10+
readonly timeout?: number
11+
}
12+
13+
export async function callTool(
14+
tool: McpTool,
15+
args: Record<string, unknown>,
16+
signal?: AbortSignal,
17+
): Promise<CallToolResult> {
18+
const result = await tool.client.callTool(
19+
{ name: tool.def.name, arguments: args },
20+
{
21+
resetTimeoutOnProgress: true,
22+
signal,
23+
timeout: tool.timeout,
24+
// The MCP SDK only sends a progress token when this hook is present, enabling timeout resets.
25+
onprogress: () => {},
26+
},
27+
)
28+
if (result.isError)
29+
throw new Error(
30+
result.content
31+
.flatMap((item) => (item.type === "text" ? [item.text] : []))
32+
.filter((text) => text.trim())
33+
.join("\n\n") || "MCP tool returned an error",
34+
)
35+
return result
36+
}
37+
638
export function defs(client: Client, timeout?: number) {
739
return listTools(client, timeout ?? DEFAULT_TIMEOUT).pipe(Effect.catch(() => Effect.void))
840
}
941

10-
export function convertTool(mcpTool: MCPToolDef, client: Client, timeout?: number): Tool {
42+
export function convertTool(tool: McpTool): Tool {
1143
const inputSchema: JSONSchema7 = {
12-
...(mcpTool.inputSchema as JSONSchema7),
44+
...(tool.def.inputSchema as JSONSchema7),
1345
type: "object",
14-
properties: (mcpTool.inputSchema.properties ?? {}) as JSONSchema7["properties"],
46+
properties: (tool.def.inputSchema.properties ?? {}) as JSONSchema7["properties"],
1547
additionalProperties: false,
1648
}
1749

1850
return dynamicTool({
19-
description: mcpTool.description ?? "",
51+
description: tool.def.description ?? "",
2052
inputSchema: jsonSchema(inputSchema),
2153
execute: async (args: unknown, options) => {
22-
const result = await client.callTool(
23-
{
24-
name: mcpTool.name,
25-
arguments: (args || {}) as Record<string, unknown>,
26-
},
27-
{
28-
resetTimeoutOnProgress: true,
29-
signal: options.abortSignal,
30-
timeout,
31-
// The MCP SDK only sends a progress token when this hook is present, enabling timeout resets.
32-
onprogress: () => {},
33-
},
34-
)
35-
if (result.isError)
36-
throw new Error(
37-
result.content
38-
.flatMap((item) => (item.type === "text" ? [item.text] : []))
39-
.filter((text) => text.trim())
40-
.join("\n\n") || "MCP tool returned an error",
41-
)
54+
const result = await callTool(tool, (args || {}) as Record<string, unknown>, options.abortSignal)
4255
if (result.content.length > 0 || result.structuredContent === undefined || result.structuredContent === null)
4356
return result
4457
return {

‎packages/opencode/src/mcp/index.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -162,12 +162,7 @@ export interface ServerInstructions {
162162
}
163163

164164
/** An MCP tool in its native shape; consumers adapt it to their own tool format. */
165-
export interface McpTool {
166-
/** Shared cached definition; consumers must copy rather than mutate it. */
167-
readonly def: MCPToolDef
168-
readonly client: MCPClient
169-
readonly timeout?: number
170-
}
165+
export type McpTool = McpCatalog.McpTool
171166

172167
export interface Interface {
173168
readonly status: () => Effect.Effect<Record<string, Status>>

‎packages/opencode/src/session/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ export const resolve = Effect.fn("SessionTools.resolve")(function* (input: {
388388
if (flags.experimentalCodeMode) return tools
389389

390390
for (const [key, entry] of Object.entries(yield* mcp.tools())) {
391-
const item = McpCatalog.convertTool(entry.def, entry.client, entry.timeout)
391+
const item = McpCatalog.convertTool(entry)
392392
const execute = item.execute
393393
if (!execute) continue
394394

‎packages/opencode/src/tool/code-mode.ts‎

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -145,27 +145,7 @@ const invokeChildTool = Effect.fn("CodeMode.invokeChildTool")(function* (input:
145145
)
146146
const result: CallToolResult = yield* Effect.gen(function* () {
147147
yield* input.ctx.ask({ permission: input.entry.key, metadata: {}, patterns: ["*"], always: ["*"] })
148-
// Deliberately mirrors McpCatalog.convertTool's transport call so the MCP service stays free of tool-loop concerns.
149-
return yield* Effect.promise(async () => {
150-
const raw = await input.entry.tool.client.callTool(
151-
{ name: input.entry.tool.def.name, arguments: input.args },
152-
{
153-
resetTimeoutOnProgress: true,
154-
signal: input.ctx.abort,
155-
timeout: input.entry.tool.timeout,
156-
// The MCP SDK only sends a progress token when this hook is present, enabling timeout resets.
157-
onprogress: () => {},
158-
},
159-
)
160-
if (raw.isError)
161-
throw new Error(
162-
raw.content
163-
.flatMap((item) => (item.type === "text" ? [item.text] : []))
164-
.filter((text) => text.trim())
165-
.join("\n\n") || "MCP tool returned an error",
166-
)
167-
return raw
168-
})
148+
return yield* Effect.promise(() => McpCatalog.callTool(input.entry.tool, input.args, input.ctx.abort))
169149
}).pipe(
170150
Effect.withSpan("Tool.execute", {
171151
attributes: {

‎packages/opencode/test/mcp/catalog.test.ts‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ describe("McpCatalog.convertTool", () => {
2828
test("preserves content when structuredContent is also present", async () => {
2929
const content = [{ type: "image" as const, mimeType: "image/png", data: "AAAA" }]
3030
const structuredContent = { image: { mimeType: "image/png", data: "AAAA" } }
31-
const converted = McpCatalog.convertTool(mcpTool(), clientReturning({ content, structuredContent }))
31+
const converted = McpCatalog.convertTool({
32+
def: mcpTool(),
33+
client: clientReturning({ content, structuredContent }),
34+
})
3235

3336
const output = await converted.execute?.({}, options)
3437

@@ -37,7 +40,10 @@ describe("McpCatalog.convertTool", () => {
3740

3841
test("falls back to structuredContent only when content is absent", async () => {
3942
const structuredContent = { results: [{ title: "one" }] }
40-
const converted = McpCatalog.convertTool(mcpTool(), clientReturning({ content: [], structuredContent }))
43+
const converted = McpCatalog.convertTool({
44+
def: mcpTool(),
45+
client: clientReturning({ content: [], structuredContent }),
46+
})
4147

4248
const output = await converted.execute?.({}, options)
4349

@@ -48,6 +54,40 @@ describe("McpCatalog.convertTool", () => {
4854
})
4955
})
5056

57+
describe("McpCatalog.callTool", () => {
58+
test("forwards the request options", async () => {
59+
const controller = new AbortController()
60+
let request: unknown
61+
let options: unknown
62+
const client = {
63+
callTool: async (input: unknown, config: unknown) => {
64+
request = input
65+
options = config
66+
return { content: [] }
67+
},
68+
} as unknown as Client
69+
70+
await McpCatalog.callTool({ def: mcpTool(), client, timeout: 123 }, { value: true }, controller.signal)
71+
72+
expect(request).toEqual({ name: "screenshot", arguments: { value: true } })
73+
expect(options).toMatchObject({ resetTimeoutOnProgress: true, signal: controller.signal, timeout: 123 })
74+
expect(typeof (options as { onprogress?: unknown }).onprogress).toBe("function")
75+
})
76+
77+
test("throws text returned by an MCP tool error", async () => {
78+
const client = clientReturning({
79+
isError: true,
80+
content: [
81+
{ type: "image", data: "AAAA", mimeType: "image/png" },
82+
{ type: "text", text: "first" },
83+
{ type: "text", text: "second" },
84+
],
85+
})
86+
87+
await expect(McpCatalog.callTool({ def: mcpTool(), client }, {})).rejects.toThrow("first\n\nsecond")
88+
})
89+
})
90+
5191
test("preserves output schema validation across paginated tool discovery", async () => {
5292
const server = new Server({ name: "pagination", version: "1.0.0" }, { capabilities: { tools: {} } })
5393
server.setRequestHandler("tools/list", ({ params }) =>

0 commit comments

Comments
 (0)