Skip to content

Commit 477baab

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 f6b2e2d commit 477baab

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
@@ -649,9 +649,11 @@ export namespace Config {
649649
url: z.string().describe("URL of the remote MCP server"),
650650
enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
651651
headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
652-
// altimate_change start — dynamic header values produced by a shell command,
653-
// resolved on each (re)connect so callers can refresh expiring bearer tokens
654-
// without restarting the session (e.g. `az account get-access-token`).
652+
// altimate_change start — dynamic header values produced by an argv command
653+
// (run via execFile, not a shell — no shell interpolation unless the user
654+
// explicitly invokes one like `sh -c`), resolved on each (re)connect so
655+
// callers can refresh expiring bearer tokens without restarting the session
656+
// (e.g. `az account get-access-token`).
655657
headersCommand: z
656658
.record(z.string(), z.array(z.string()).nonempty())
657659
.optional()
@@ -1454,6 +1456,12 @@ export namespace Config {
14541456
servers[name] = transformed
14551457
} else if (entry.url && typeof entry.url === "string") {
14561458
const transformed: Record<string, any> = { type: "remote", url: entry.url }
1459+
// Copy `headers` / `headersCommand` through as-is — including malformed
1460+
// array shapes. The downstream `Info.safeParse` validates `mcp` against
1461+
// the McpRemote schema, and `z.record(...)` rejects an array with an
1462+
// actionable `invalid_type` error. Stripping arrays here would instead
1463+
// drop the field silently and connect a header-less server with no
1464+
// feedback to the user. See #791 / #792.
14571465
if (entry.headers && typeof entry.headers === "object") transformed.headers = entry.headers
14581466
// altimate_change start — preserve fields that the original normalizer dropped
14591467
// 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
@@ -133,41 +133,42 @@ export namespace MCP {
133133
// Zod, blocking listTools() entirely. We accept `null` as "hint absent" by
134134
// calling `client.request()` with a permissive schema in place of the SDK's
135135
// strict one. See https://github.com/AltimateAI/altimate-code/issues/792.
136-
const LenientToolAnnotationsSchema = z
137-
.object({
138-
title: z.string().optional(),
139-
readOnlyHint: z.boolean().nullable().optional(),
140-
destructiveHint: z.boolean().nullable().optional(),
141-
idempotentHint: z.boolean().nullable().optional(),
142-
openWorldHint: z.boolean().nullable().optional(),
143-
})
144-
.loose()
145-
146-
const LenientToolSchema = z
147-
.object({
148-
name: z.string(),
149-
title: z.string().optional(),
150-
description: z.string().optional(),
151-
inputSchema: z.any(),
152-
outputSchema: z.any().optional(),
153-
annotations: LenientToolAnnotationsSchema.optional(),
154-
_meta: z.record(z.string(), z.unknown()).optional(),
155-
})
156-
.loose()
157-
158-
const LenientListToolsResultSchema = z
159-
.object({
160-
tools: z.array(LenientToolSchema),
161-
nextCursor: z.string().optional(),
162-
_meta: z.record(z.string(), z.unknown()).optional(),
163-
})
164-
.loose()
136+
const LenientToolAnnotationsSchema = z.looseObject({
137+
title: z.string().optional(),
138+
readOnlyHint: z.boolean().nullable().optional(),
139+
destructiveHint: z.boolean().nullable().optional(),
140+
idempotentHint: z.boolean().nullable().optional(),
141+
openWorldHint: z.boolean().nullable().optional(),
142+
})
143+
144+
const LenientToolSchema = z.looseObject({
145+
name: z.string(),
146+
title: z.string().optional(),
147+
description: z.string().optional(),
148+
inputSchema: z.any(),
149+
outputSchema: z.any().optional(),
150+
annotations: LenientToolAnnotationsSchema.optional(),
151+
_meta: z.record(z.string(), z.unknown()).optional(),
152+
})
153+
154+
const LenientListToolsResultSchema = z.looseObject({
155+
tools: z.array(LenientToolSchema),
156+
nextCursor: z.string().optional(),
157+
_meta: z.record(z.string(), z.unknown()).optional(),
158+
})
165159

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

173174
/**
@@ -197,16 +198,20 @@ export namespace MCP {
197198
export const _testing = {
198199
LenientListToolsResultSchema,
199200
isSchemaError,
201+
listToolsLenient: (client: {
202+
listTools: () => Promise<{ tools: MCPToolDef[] }>
203+
request: (...args: any[]) => Promise<unknown>
204+
}) => listToolsLenient(client as unknown as MCPClient),
200205
resolveHeadersCommand: (spec: Record<string, string[]> | undefined, key = "test") =>
201206
resolveHeadersCommand(spec, key),
202207
hasAuthorizationHeader,
203208
}
204209
// altimate_change end
205210

206-
// altimate_change start — resolve dynamic header values produced by shell
207-
// commands (e.g. `az account get-access-token`). Runs via execFile (not a
208-
// shell) so values aren't subject to shell injection. Re-runs on every
209-
// connect so expiring bearer tokens refresh without manual config edits.
211+
// altimate_change start — resolve dynamic header values from argv commands
212+
// (e.g. `az account get-access-token`). Each value is an argv array run via
213+
// execFile (no shell) so values aren't subject to shell injection. Re-runs on
214+
// every connect so expiring bearer tokens refresh without manual config edits.
210215
// See https://github.com/AltimateAI/altimate-code/issues/791.
211216
async function resolveHeadersCommand(
212217
spec: Record<string, string[]> | undefined,
@@ -219,11 +224,26 @@ export namespace MCP {
219224
throw new Error(`headersCommand[${name}] must be a non-empty argv array`)
220225
}
221226
const [cmd, ...args] = argv
222-
const { stdout } = await execFileAsync(cmd, args, {
223-
encoding: "utf-8",
224-
maxBuffer: 1024 * 1024,
225-
timeout: 30_000,
226-
})
227+
let stdout = ""
228+
try {
229+
stdout = (
230+
await execFileAsync(cmd, args, {
231+
encoding: "utf-8",
232+
maxBuffer: 1024 * 1024,
233+
timeout: 30_000,
234+
})
235+
).stdout
236+
} catch (err) {
237+
// Wrap with the header key so `mcp list` points to the exact failing
238+
// command (ENOENT, timeout, non-zero exit) rather than a bare error.
239+
// On a non-zero exit the actionable reason lives on `err.stderr` (e.g.
240+
// `az`'s "run 'az login'"), which `err.message` omits — append it.
241+
const e = err as { message?: string; stderr?: string }
242+
const stderr = typeof e.stderr === "string" ? e.stderr.trim().slice(0, 500) : ""
243+
const base = err instanceof Error ? err.message : String(err)
244+
const message = stderr ? `${base}: ${stderr}` : base
245+
throw new Error(`headersCommand[${name}] failed: ${message}`)
246+
}
227247
const value = stdout.trim()
228248
if (!value) {
229249
throw new Error(`headersCommand[${name}] produced empty output`)
@@ -484,9 +504,9 @@ export namespace MCP {
484504
if (mcp.type === "remote") {
485505
// altimate_change start — resolve dynamic headers (e.g. bearer tokens
486506
// produced by `az account get-access-token`) before constructing
487-
// transports. Failure to resolve aborts the connect attempt with a
488-
// clear error so the user sees `failed: headersCommand[...] failed`
489-
// in `mcp list` rather than a generic transport error.
507+
// transports. Failure to resolve aborts the connect attempt. The thrown
508+
// message already names the failing header (`headersCommand[<name>] failed:
509+
// ...`), so the user sees exactly which command broke in `mcp list`.
490510
let dynamicHeaders: Record<string, string> = {}
491511
try {
492512
dynamicHeaders = await resolveHeadersCommand(mcp.headersCommand, key)
@@ -495,7 +515,7 @@ export namespace MCP {
495515
log.error("headersCommand resolution failed", { key, error: message })
496516
return {
497517
mcpClient: undefined,
498-
status: { status: "failed" as const, error: `headersCommand failed: ${message}` },
518+
status: { status: "failed" as const, error: message },
499519
}
500520
}
501521
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)