Skip to content

Commit 05dfc09

Browse files
author
Developer
committed
fix(mcp): tolerate invalid tool output schemas
Closes anomalyco#26529. When an MCP server returns a tool whose \`outputSchema\` contains a broken \`$ref\` (e.g. Google Stitch's \`#/$defs/ScreenInstance\`), the SDK's typed \`listTools()\` validator throws and opencode marks the ENTIRE server as failed — losing every other valid tool the server exposes. Catch the schema-reference errors and retry with a tolerant schema (\`looseObject\` + \`outputSchema: z.unknown().optional()\`) via the raw \`request\` path so the bad tool's schema is accepted as opaque while the others load normally. Equivalent fix shape to anomalyco#26530 (nicolascancino) — kept his approach since it's correct. Bundles our reproducer test from \`kit/issue-reproducers\` so the regression is locked in. Verified red → green → red → green: - pre-fix: server marked \`failed\` - post-fix: server stays \`connected\`, valid tool present
1 parent 89bfd9a commit 05dfc09

2 files changed

Lines changed: 50 additions & 2 deletions

File tree

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

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,24 @@ import { withStatics } from "@opencode-ai/core/schema"
3636
const log = Log.create({ service: "mcp" })
3737
const DEFAULT_TIMEOUT = 30_000
3838

39+
const TolerantToolSchema = z.looseObject({
40+
name: z.string(),
41+
description: z.string().optional(),
42+
inputSchema: z
43+
.object({
44+
type: z.literal("object"),
45+
properties: z.record(z.string(), z.unknown()).optional(),
46+
required: z.array(z.string()).optional(),
47+
})
48+
.catchall(z.unknown()),
49+
outputSchema: z.unknown().optional(),
50+
})
51+
52+
const TolerantListToolsResultSchema = z.looseObject({
53+
tools: z.array(TolerantToolSchema),
54+
nextCursor: z.string().optional(),
55+
})
56+
3957
export const Resource = Schema.Struct({
4058
name: Schema.String,
4159
uri: Schema.String,
@@ -119,6 +137,27 @@ function remoteURL(key: string, value: string) {
119137
log.warn("invalid remote mcp url", { key })
120138
}
121139

140+
function isSchemaReferenceError(err: Error) {
141+
return /can't resolve reference|schema.*reference|reference.*schema/i.test(err.message)
142+
}
143+
144+
async function listTools(key: string, client: MCPClient, timeout: number) {
145+
try {
146+
return (await client.listTools(undefined, { timeout })).tools
147+
} catch (err) {
148+
const error = err instanceof Error ? err : new Error(String(err))
149+
if (!isSchemaReferenceError(error)) throw error
150+
151+
log.warn("failed to validate MCP tool output schemas, retrying without output schema validation", {
152+
key,
153+
error,
154+
})
155+
156+
const result = await client.request({ method: "tools/list" }, TolerantListToolsResultSchema, { timeout })
157+
return result.tools as MCPToolDef[]
158+
}
159+
}
160+
122161
// Convert MCP tool definition to AI SDK Tool type
123162
function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Tool {
124163
const inputSchema = mcpTool.inputSchema
@@ -152,10 +191,10 @@ function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number
152191

153192
function defs(key: string, client: MCPClient, timeout?: number) {
154193
return Effect.tryPromise({
155-
try: () => withTimeout(client.listTools(), timeout ?? DEFAULT_TIMEOUT),
194+
try: () => listTools(key, client, timeout ?? DEFAULT_TIMEOUT),
156195
catch: (err) => (err instanceof Error ? err : new Error(String(err))),
157196
}).pipe(
158-
Effect.map((result) => result.tools),
197+
Effect.map((tools) => tools),
159198
Effect.catch((err) => {
160199
log.error("failed to get tools from client", { key, error: err })
161200
return Effect.succeed(undefined)

‎packages/opencode/test/mcp/output-schema-unresolved-refs.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,15 @@ void mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({
108108
}
109109
return { tools: this._state?.tools ?? [] }
110110
}
111+
async request(req: { method: string }) {
112+
// The fix retries via raw `request("tools/list", ...)` with a
113+
// tolerant schema after the typed listTools() rejects on a bad
114+
// outputSchema reference. The retry path bypasses the SDK's
115+
// strict validator, so the mock returns the same tools list
116+
// without the validation that originally threw.
117+
if (req.method === "tools/list") return { tools: this._state?.tools ?? [] }
118+
throw new Error(`unsupported request: ${req.method}`)
119+
}
111120
async listPrompts() {
112121
return { prompts: [] }
113122
}

0 commit comments

Comments
 (0)