Skip to content

Commit 3157a5a

Browse files
suryaiyer95claude
andcommitted
fix: [#791][#792] address review feedback on bearer-auth remote MCP
Follow-up to f6b2e2d resolving all bot review comments: - `isSchemaError`: narrow to `name === ZodError|$ZodError` AND an `issues` array, so unrelated errors carrying an `issues` property no longer trigger the lenient retry (Copilot). - `resolveHeadersCommand`: wrap `execFile` failures with the header key (`headersCommand[<name>] failed: ...`) and append trimmed `stderr` so `mcp list` points to the exact failing command (Copilot). - Drop the now-redundant `headersCommand failed:` prefix at the call site since the thrown message already names the header. - Use Zod v4 `z.looseObject(...)` instead of deprecated `.loose()` for the lenient `tools/list` schemas (CodeRabbit). - `config.ts`: reword `headersCommand` comment to clarify it is argv via `execFile` (no shell interpolation); document why `normalizeMcpConfig` passes malformed array shapes through (schema rejects them with an actionable `invalid_type` rather than silently dropping) (Copilot). - Tests: remove unnecessary `as any` cast; assert against the production `LenientListToolsResultSchema` via `MCP._testing` instead of a duplicated copy; add an end-to-end `listToolsLenient` retry test using a real SDK `$ZodError`, and a test that array-shaped headers are rejected loudly. Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent 9396102 commit 3157a5a

4 files changed

Lines changed: 159 additions & 87 deletions

File tree

‎packages/opencode/src/config/config.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -652,9 +652,11 @@ export namespace Config {
652652
url: z.string().describe("URL of the remote MCP server"),
653653
enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
654654
headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
655-
// altimate_change start — dynamic header values produced by a shell command,
656-
// resolved on each (re)connect so callers can refresh expiring bearer tokens
657-
// without restarting the session (e.g. `az account get-access-token`).
655+
// altimate_change start — dynamic header values produced by an argv command
656+
// (run via execFile, not a shell — no shell interpolation unless the user
657+
// explicitly invokes one like `sh -c`), resolved on each (re)connect so
658+
// callers can refresh expiring bearer tokens without restarting the session
659+
// (e.g. `az account get-access-token`).
658660
headersCommand: z
659661
.record(z.string(), z.array(z.string()).nonempty())
660662
.optional()
@@ -1466,6 +1468,12 @@ export namespace Config {
14661468
servers[name] = transformed
14671469
} else if (entry.url && typeof entry.url === "string") {
14681470
const transformed: Record<string, any> = { type: "remote", url: entry.url }
1471+
// Copy `headers` / `headersCommand` through as-is — including malformed
1472+
// array shapes. The downstream `Info.safeParse` validates `mcp` against
1473+
// the McpRemote schema, and `z.record(...)` rejects an array with an
1474+
// actionable `invalid_type` error. Stripping arrays here would instead
1475+
// drop the field silently and connect a header-less server with no
1476+
// feedback to the user. See #791 / #792.
14691477
if (entry.headers && typeof entry.headers === "object") transformed.headers = entry.headers
14701478
// altimate_change start — preserve fields that the original normalizer dropped
14711479
// silently. Without these passes, a user-supplied `oauth: false` or

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

Lines changed: 66 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -137,41 +137,42 @@ export namespace MCP {
137137
// Zod, blocking listTools() entirely. We accept `null` as "hint absent" by
138138
// calling `client.request()` with a permissive schema in place of the SDK's
139139
// strict one. See https://github.com/AltimateAI/altimate-code/issues/792.
140-
const LenientToolAnnotationsSchema = z
141-
.object({
142-
title: z.string().optional(),
143-
readOnlyHint: z.boolean().nullable().optional(),
144-
destructiveHint: z.boolean().nullable().optional(),
145-
idempotentHint: z.boolean().nullable().optional(),
146-
openWorldHint: z.boolean().nullable().optional(),
147-
})
148-
.loose()
149-
150-
const LenientToolSchema = z
151-
.object({
152-
name: z.string(),
153-
title: z.string().optional(),
154-
description: z.string().optional(),
155-
inputSchema: z.any(),
156-
outputSchema: z.any().optional(),
157-
annotations: LenientToolAnnotationsSchema.optional(),
158-
_meta: z.record(z.string(), z.unknown()).optional(),
159-
})
160-
.loose()
161-
162-
const LenientListToolsResultSchema = z
163-
.object({
164-
tools: z.array(LenientToolSchema),
165-
nextCursor: z.string().optional(),
166-
_meta: z.record(z.string(), z.unknown()).optional(),
167-
})
168-
.loose()
140+
const LenientToolAnnotationsSchema = z.looseObject({
141+
title: z.string().optional(),
142+
readOnlyHint: z.boolean().nullable().optional(),
143+
destructiveHint: z.boolean().nullable().optional(),
144+
idempotentHint: z.boolean().nullable().optional(),
145+
openWorldHint: z.boolean().nullable().optional(),
146+
})
147+
148+
const LenientToolSchema = z.looseObject({
149+
name: z.string(),
150+
title: z.string().optional(),
151+
description: z.string().optional(),
152+
inputSchema: z.any(),
153+
outputSchema: z.any().optional(),
154+
annotations: LenientToolAnnotationsSchema.optional(),
155+
_meta: z.record(z.string(), z.unknown()).optional(),
156+
})
157+
158+
const LenientListToolsResultSchema = z.looseObject({
159+
tools: z.array(LenientToolSchema),
160+
nextCursor: z.string().optional(),
161+
_meta: z.record(z.string(), z.unknown()).optional(),
162+
})
169163

170164
function isSchemaError(err: unknown): boolean {
171-
if (!err) return false
172-
if (err instanceof Error && (err.name === "ZodError" || err.constructor?.name === "$ZodError")) return true
173-
if (typeof err === "object" && err !== null && "issues" in err) return true
174-
return false
165+
// Narrowly match Zod validation errors only. We key off the error *name*
166+
// (not `instanceof z.ZodError`) because the MCP SDK may throw a ZodError
167+
// from a different zod copy (it depends on `zod@^3.25 || ^4.0`), which
168+
// would fail a cross-realm `instanceof`. In practice the SDK's z4-mini path
169+
// names the error `$ZodError` (the primary case); the public ZodError
170+
// subclass names it `ZodError`. We require an `issues` *array* (rather than
171+
// `"issues" in err`) to avoid a throwing getter and to reject unrelated
172+
// errors that merely carry an `issues` property of some other type.
173+
if (typeof err !== "object" || err === null) return false
174+
const name = (err as { name?: string }).name ?? (err as { constructor?: { name?: string } }).constructor?.name
175+
return (name === "ZodError" || name === "$ZodError") && Array.isArray((err as { issues?: unknown }).issues)
175176
}
176177

177178
/**
@@ -201,16 +202,20 @@ export namespace MCP {
201202
export const _testing = {
202203
LenientListToolsResultSchema,
203204
isSchemaError,
205+
listToolsLenient: (client: {
206+
listTools: () => Promise<{ tools: MCPToolDef[] }>
207+
request: (...args: any[]) => Promise<unknown>
208+
}) => listToolsLenient(client as unknown as MCPClient),
204209
resolveHeadersCommand: (spec: Record<string, string[]> | undefined, key = "test") =>
205210
resolveHeadersCommand(spec, key),
206211
hasAuthorizationHeader,
207212
}
208213
// altimate_change end
209214

210-
// altimate_change start — resolve dynamic header values produced by shell
211-
// commands (e.g. `az account get-access-token`). Runs via execFile (not a
212-
// shell) so values aren't subject to shell injection. Re-runs on every
213-
// connect so expiring bearer tokens refresh without manual config edits.
215+
// altimate_change start — resolve dynamic header values from argv commands
216+
// (e.g. `az account get-access-token`). Each value is an argv array run via
217+
// execFile (no shell) so values aren't subject to shell injection. Re-runs on
218+
// every connect so expiring bearer tokens refresh without manual config edits.
214219
// See https://github.com/AltimateAI/altimate-code/issues/791.
215220
async function resolveHeadersCommand(
216221
spec: Record<string, string[]> | undefined,
@@ -223,11 +228,26 @@ export namespace MCP {
223228
throw new Error(`headersCommand[${name}] must be a non-empty argv array`)
224229
}
225230
const [cmd, ...args] = argv
226-
const { stdout } = await execFileAsync(cmd, args, {
227-
encoding: "utf-8",
228-
maxBuffer: 1024 * 1024,
229-
timeout: 30_000,
230-
})
231+
let stdout = ""
232+
try {
233+
stdout = (
234+
await execFileAsync(cmd, args, {
235+
encoding: "utf-8",
236+
maxBuffer: 1024 * 1024,
237+
timeout: 30_000,
238+
})
239+
).stdout
240+
} catch (err) {
241+
// Wrap with the header key so `mcp list` points to the exact failing
242+
// command (ENOENT, timeout, non-zero exit) rather than a bare error.
243+
// On a non-zero exit the actionable reason lives on `err.stderr` (e.g.
244+
// `az`'s "run 'az login'"), which `err.message` omits — append it.
245+
const e = err as { message?: string; stderr?: string }
246+
const stderr = typeof e.stderr === "string" ? e.stderr.trim().slice(0, 500) : ""
247+
const base = err instanceof Error ? err.message : String(err)
248+
const message = stderr ? `${base}: ${stderr}` : base
249+
throw new Error(`headersCommand[${name}] failed: ${message}`)
250+
}
231251
const value = stdout.trim()
232252
if (!value) {
233253
throw new Error(`headersCommand[${name}] produced empty output`)
@@ -488,9 +508,9 @@ export namespace MCP {
488508
if (mcp.type === "remote") {
489509
// altimate_change start — resolve dynamic headers (e.g. bearer tokens
490510
// produced by `az account get-access-token`) before constructing
491-
// transports. Failure to resolve aborts the connect attempt with a
492-
// clear error so the user sees `failed: headersCommand[...] failed`
493-
// in `mcp list` rather than a generic transport error.
511+
// transports. Failure to resolve aborts the connect attempt. The thrown
512+
// message already names the failing header (`headersCommand[<name>] failed:
513+
// ...`), so the user sees exactly which command broke in `mcp list`.
494514
let dynamicHeaders: Record<string, string> = {}
495515
try {
496516
dynamicHeaders = await resolveHeadersCommand(mcp.headersCommand, key)
@@ -499,7 +519,7 @@ export namespace MCP {
499519
log.error("headersCommand resolution failed", { key, error: message })
500520
return {
501521
mcpClient: undefined,
502-
status: { status: "failed" as const, error: `headersCommand failed: ${message}` },
522+
status: { status: "failed" as const, error: message },
503523
}
504524
}
505525
const mergedHeaders: Record<string, string> = { ...(mcp.headers ?? {}), ...dynamicHeaders }

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ test("OAuth is auto-disabled when Authorization is supplied via headersCommand",
143143
headersCommand: {
144144
Authorization: ["printf", "Bearer dynamic-token"],
145145
},
146-
} as any).catch(() => {})
146+
}).catch(() => {})
147147

148148
expect(transportCalls.length).toBeGreaterThanOrEqual(1)
149149
for (const call of transportCalls) {

‎packages/opencode/test/mcp/mcp-bearer-auth.test.ts‎

Lines changed: 81 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,12 @@
11
import { describe, test, expect } from "bun:test"
2-
import z from "zod/v4"
32
import { Config } from "../../src/config/config"
43

5-
// We replicate the lenient ListTools schema used in mcp/index.ts here so the
6-
// test does not depend on the MCP module's heavy import surface (Instance,
7-
// Telemetry, Bus, Plugin, etc.). The schema is byte-for-byte identical to
8-
// the one in mcp/index.ts; if it drifts, the integration test in mcp.test.ts
9-
// will catch it.
10-
const LenientToolAnnotationsSchema = z
11-
.object({
12-
title: z.string().optional(),
13-
readOnlyHint: z.boolean().nullable().optional(),
14-
destructiveHint: z.boolean().nullable().optional(),
15-
idempotentHint: z.boolean().nullable().optional(),
16-
openWorldHint: z.boolean().nullable().optional(),
17-
})
18-
.loose()
19-
20-
const LenientToolSchema = z
21-
.object({
22-
name: z.string(),
23-
title: z.string().optional(),
24-
description: z.string().optional(),
25-
inputSchema: z.any(),
26-
outputSchema: z.any().optional(),
27-
annotations: LenientToolAnnotationsSchema.optional(),
28-
_meta: z.record(z.string(), z.unknown()).optional(),
29-
})
30-
.loose()
31-
32-
const LenientListToolsResultSchema = z
33-
.object({
34-
tools: z.array(LenientToolSchema),
35-
nextCursor: z.string().optional(),
36-
_meta: z.record(z.string(), z.unknown()).optional(),
37-
})
38-
.loose()
4+
// Assert against the *production* lenient schema directly (exported via
5+
// MCP._testing) so this test can never pass against a stale duplicate. The MCP
6+
// module is already imported dynamically by the resolveHeadersCommand tests
7+
// below, so pulling it in here adds no new import surface.
8+
const { MCP } = await import("../../src/mcp")
9+
const { LenientListToolsResultSchema } = MCP._testing
3910

4011
// ---------------------------------------------------------------------------
4112
// 1. Lenient tools/list schema accepts what real-world servers emit.
@@ -108,6 +79,67 @@ describe("lenient tools/list schema", () => {
10879
})
10980
})
11081

82+
// ---------------------------------------------------------------------------
83+
// 1b. End-to-end listToolsLenient retry (#792). Locks in the load-bearing
84+
// contract: when the SDK's strict listTools() rejects a Fabric-style payload,
85+
// the rejected error is named `$ZodError` (zod v4-mini), isSchemaError catches
86+
// it, and the lenient client.request() retry returns the tools. A future
87+
// re-narrowing of isSchemaError would break this without tripping the
88+
// schema-only tests above.
89+
// ---------------------------------------------------------------------------
90+
describe("listToolsLenient retry against SDK $ZodError (#792)", () => {
91+
test("retries with lenient schema when strict listTools() rejects Fabric-style nulls", async () => {
92+
const { ListToolsResultSchema } = await import("@modelcontextprotocol/sdk/types.js")
93+
const { safeParse } = await import("@modelcontextprotocol/sdk/server/zod-compat.js")
94+
// Real payload shape from Microsoft Fabric Core MCP: null annotation hints.
95+
const fabricPayload = {
96+
tools: [
97+
{
98+
name: "list_workspaces",
99+
inputSchema: { type: "object", properties: {} },
100+
annotations: { readOnlyHint: true, destructiveHint: null, idempotentHint: null, openWorldHint: null },
101+
},
102+
],
103+
}
104+
// Produce the exact error the SDK would reject with (a `$ZodError`).
105+
const strict: any = safeParse(ListToolsResultSchema as any, fabricPayload)
106+
expect(strict.success).toBe(false)
107+
expect(strict.error?.name).toBe("$ZodError")
108+
109+
let requestCalled = false
110+
const fakeClient = {
111+
listTools: async () => {
112+
throw strict.error
113+
},
114+
request: async () => {
115+
requestCalled = true
116+
return fabricPayload
117+
},
118+
}
119+
120+
const result = await MCP._testing.listToolsLenient(fakeClient)
121+
expect(requestCalled).toBe(true)
122+
expect(result.tools).toHaveLength(1)
123+
expect(result.tools[0].name).toBe("list_workspaces")
124+
})
125+
126+
test("does NOT retry (rethrows) when the error is not a schema error", async () => {
127+
const transportError = new Error("ECONNREFUSED")
128+
let requestCalled = false
129+
const fakeClient = {
130+
listTools: async () => {
131+
throw transportError
132+
},
133+
request: async () => {
134+
requestCalled = true
135+
return { tools: [] }
136+
},
137+
}
138+
await expect(MCP._testing.listToolsLenient(fakeClient)).rejects.toThrow(/ECONNREFUSED/)
139+
expect(requestCalled).toBe(false)
140+
})
141+
})
142+
111143
// ---------------------------------------------------------------------------
112144
// 2. McpRemote schema accepts new headersCommand field (issue #791).
113145
// ---------------------------------------------------------------------------
@@ -133,6 +165,16 @@ describe("McpRemote.headersCommand schema (#791)", () => {
133165
expect(result.success).toBe(false)
134166
})
135167

168+
test("rejects array-shaped headers/headersCommand with an actionable invalid_type error", () => {
169+
// normalizeMcpConfig passes these malformed shapes through unchanged so the
170+
// schema rejects them loudly instead of the normalizer silently dropping
171+
// them (which would connect a header-less server with no feedback).
172+
const headersArr = Config.McpRemote.safeParse({ type: "remote", url: "https://x/mcp", headers: ["a", "b"] })
173+
expect(headersArr.success).toBe(false)
174+
const cmdArr = Config.McpRemote.safeParse({ type: "remote", url: "https://x/mcp", headersCommand: [["x"]] })
175+
expect(cmdArr.success).toBe(false)
176+
})
177+
136178
test("allows static headers and headersCommand to coexist", () => {
137179
const config = {
138180
type: "remote" as const,
@@ -182,11 +224,13 @@ describe("resolveHeadersCommand helper", () => {
182224
)
183225
})
184226

185-
test("throws when command does not exist", async () => {
227+
test("throws when command does not exist, naming the failing header", async () => {
186228
const { MCP } = await import("../../src/mcp")
229+
// The error must name the specific header so `mcp list` points to the
230+
// exact failing command rather than a bare ENOENT.
187231
await expect(
188232
MCP._testing.resolveHeadersCommand({ Authorization: ["this-binary-does-not-exist-xyz"] }),
189-
).rejects.toThrow()
233+
).rejects.toThrow(/headersCommand\[Authorization\] failed:/)
190234
})
191235

192236
test("does not invoke a shell (argv is passed directly to execFile)", async () => {

0 commit comments

Comments
 (0)