Skip to content

Commit f6b2e2d

Browse files
suryaiyer95claude
andcommitted
fix: [#791][#792] support bearer-auth remote MCP servers (Microsoft Fabric, etc.)
Three coupled fixes that together let altimate-code connect to MCP servers gated by short-lived bearer tokens — most prominently Microsoft Fabric Core MCP — without a local proxy or per-hour config edits. Issues addressed: - #791 (dynamic auth for remote MCP servers): static `headers` only. - #792 (external MCP servers not auto-activated at session start): mostly caused by OAuth dynamic-client-registration probes pre-empting valid bearer headers and ending the connect in a non-`connected` status. - A third defect surfaced during this work: the strict `ListToolsResultSchema` from `@modelcontextprotocol/sdk` rejects the `null` annotation hints that Fabric returns, causing `listTools()` to throw and the connection to be marked failed even after a successful initialize. None of these are altimate-specific — they all reproduce on upstream `opencode`. Changes: 1. `McpRemote.headersCommand: Record<string, string[]>` — header values produced by running an argv command (executed via `execFile`, not a shell, so values aren't subject to shell injection). Resolved on every connect so expiring tokens refresh automatically. Example: "headersCommand": { "Authorization": ["sh", "-c", "printf 'Bearer %s' \"$(az account get-access-token ... -o tsv)\""] } 2. OAuth provider is no longer attached when the user supplies an explicit `Authorization` header (statically or via `headersCommand`) and `oauth` is not specified. Prevents Entra ID's DCR rejection from short-circuiting a bearer-authenticated connection. Behavior is unchanged when `oauth` is explicitly configured. 3. `listTools()` is wrapped to retry with a permissive Zod schema on schema-validation errors. The fast path is unchanged for compliant servers; non-compliant servers (Fabric returns `null` for `annotations.{readOnlyHint,destructiveHint,idempotentHint,openWorldHint}`) no longer fail the connection. 4. `normalizeMcpConfig` was silently dropping `oauth` and (would have dropped) `headersCommand` when reconstructing remote entries. Both are now passed through. This was a pre-existing latent bug that made `oauth: false` configurations no-op at runtime. Tests: - 22 new tests across `test/mcp/mcp-bearer-auth.test.ts` (lenient schema, `headersCommand` resolution + execFile-not-shell semantics, Authorization detection, schema round-trip) and `test/mcp/headers.test.ts` (OAuth auto-disable on static bearer, on `headersCommand`, and explicit-OAuth override). All pass. - Zero regressions vs `origin/main` baseline on existing 185 MCP tests. - Live-verified end-to-end against `https://api.fabric.microsoft.com/v1/mcp/core` using `headersCommand` + `az account get-access-token`: server connected, 29 tools registered, no proxy required. Co-Authored-By: Claude Opus 4.7 <[email protected]>
1 parent 95b7b90 commit f6b2e2d

4 files changed

Lines changed: 537 additions & 16 deletions

File tree

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -649,11 +649,26 @@ 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`).
655+
headersCommand: z
656+
.record(z.string(), z.array(z.string()).nonempty())
657+
.optional()
658+
.describe(
659+
"Headers whose values are produced by running a command (argv form: [cmd, ...args]). " +
660+
"stdout is trimmed and used as the header value. Resolved on every connect so tokens " +
661+
"with short TTLs (e.g. Microsoft Entra ID bearer tokens for Fabric) refresh automatically. " +
662+
"Values from headersCommand override matching keys in `headers`.",
663+
),
664+
// altimate_change end
652665
oauth: z
653666
.union([McpOAuth, z.literal(false)])
654667
.optional()
655668
.describe(
656-
"OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.",
669+
"OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection. " +
670+
"When `headers.Authorization` or `headersCommand.Authorization` is set and `oauth` is not specified, " +
671+
"OAuth is disabled automatically so a static bearer token isn't overridden by a competing OAuth flow.",
657672
),
658673
timeout: z
659674
.number()
@@ -1440,6 +1455,15 @@ export namespace Config {
14401455
} else if (entry.url && typeof entry.url === "string") {
14411456
const transformed: Record<string, any> = { type: "remote", url: entry.url }
14421457
if (entry.headers && typeof entry.headers === "object") transformed.headers = entry.headers
1458+
// altimate_change start — preserve fields that the original normalizer dropped
1459+
// silently. Without these passes, a user-supplied `oauth: false` or
1460+
// `headersCommand` would be reconstructed-away, leaving the runtime
1461+
// believing the config was bare. See #791 / #792.
1462+
if (entry.headersCommand && typeof entry.headersCommand === "object") {
1463+
transformed.headersCommand = entry.headersCommand
1464+
}
1465+
if (entry.oauth !== undefined) transformed.oauth = entry.oauth
1466+
// altimate_change end
14431467
if (typeof entry.timeout === "number") transformed.timeout = entry.timeout
14441468
if (typeof entry.enabled === "boolean") transformed.enabled = entry.enabled
14451469
servers[name] = transformed

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

Lines changed: 162 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ import { Config } from "../config/config"
1313
import { Log } from "../util/log"
1414
import { NamedError } from "@opencode-ai/util/error"
1515
import z from "zod/v4"
16+
// altimate_change start — needed to resolve `headersCommand` for remote MCP
17+
// servers that require bearer tokens with short TTLs (Microsoft Fabric, etc.)
18+
import { execFile } from "node:child_process"
19+
import { promisify } from "node:util"
20+
const execFileAsync = promisify(execFile)
21+
// altimate_change end
1622
import { Instance } from "../project/instance"
1723
import { Installation } from "../installation"
1824
import { withTimeout } from "@/util/timeout"
@@ -121,6 +127,118 @@ export namespace MCP {
121127
const toolListCache = new Map<string, MCPToolDef[]>()
122128
// altimate_change end
123129

130+
// altimate_change start — Microsoft Fabric Core MCP returns `null` for
131+
// `tool.annotations.{readOnlyHint,destructiveHint,idempotentHint,openWorldHint}`,
132+
// which the SDK's `ListToolsResultSchema` (z.boolean().optional()) rejects via
133+
// Zod, blocking listTools() entirely. We accept `null` as "hint absent" by
134+
// calling `client.request()` with a permissive schema in place of the SDK's
135+
// 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()
165+
166+
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
171+
}
172+
173+
/**
174+
* Calls the SDK's strict `listTools()` first; on a Zod schema-validation
175+
* failure (e.g. server emits non-spec values like `null` annotation hints),
176+
* retries via `client.request()` with a permissive schema. This keeps the
177+
* fast path unchanged for compliant servers while letting non-compliant
178+
* ones (Microsoft Fabric, etc.) still register their tools.
179+
*/
180+
async function listToolsLenient(client: MCPClient): Promise<{ tools: MCPToolDef[] }> {
181+
try {
182+
return await client.listTools()
183+
} catch (err) {
184+
if (!isSchemaError(err)) throw err
185+
log.info("listTools strict schema rejected response, retrying with lenient schema", {
186+
error: err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200),
187+
})
188+
const result = await client.request(
189+
{ method: "tools/list", params: {} },
190+
LenientListToolsResultSchema as any,
191+
)
192+
return result as { tools: MCPToolDef[] }
193+
}
194+
}
195+
196+
/** @internal — exported only for unit tests. Prefer using `tools()` in production code. */
197+
export const _testing = {
198+
LenientListToolsResultSchema,
199+
isSchemaError,
200+
resolveHeadersCommand: (spec: Record<string, string[]> | undefined, key = "test") =>
201+
resolveHeadersCommand(spec, key),
202+
hasAuthorizationHeader,
203+
}
204+
// altimate_change end
205+
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.
210+
// See https://github.com/AltimateAI/altimate-code/issues/791.
211+
async function resolveHeadersCommand(
212+
spec: Record<string, string[]> | undefined,
213+
serverKey: string,
214+
): Promise<Record<string, string>> {
215+
if (!spec) return {}
216+
const out: Record<string, string> = {}
217+
for (const [name, argv] of Object.entries(spec)) {
218+
if (!Array.isArray(argv) || argv.length === 0) {
219+
throw new Error(`headersCommand[${name}] must be a non-empty argv array`)
220+
}
221+
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+
const value = stdout.trim()
228+
if (!value) {
229+
throw new Error(`headersCommand[${name}] produced empty output`)
230+
}
231+
log.info("resolved dynamic header", { server: serverKey, header: name })
232+
out[name] = value
233+
}
234+
return out
235+
}
236+
237+
function hasAuthorizationHeader(headers: Record<string, string>): boolean {
238+
return Object.keys(headers).some((k) => k.toLowerCase() === "authorization")
239+
}
240+
// altimate_change end
241+
124242
// Register notification handlers for MCP client
125243
function registerNotificationHandlers(client: MCPClient, serverName: string) {
126244
client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
@@ -364,8 +482,36 @@ export namespace MCP {
364482
let connectedTransport: "stdio" | "sse" | "streamable-http" | undefined = undefined
365483

366484
if (mcp.type === "remote") {
367-
// OAuth is enabled by default for remote servers unless explicitly disabled with oauth: false
368-
const oauthDisabled = mcp.oauth === false
485+
// altimate_change start — resolve dynamic headers (e.g. bearer tokens
486+
// 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.
490+
let dynamicHeaders: Record<string, string> = {}
491+
try {
492+
dynamicHeaders = await resolveHeadersCommand(mcp.headersCommand, key)
493+
} catch (err) {
494+
const message = err instanceof Error ? err.message : String(err)
495+
log.error("headersCommand resolution failed", { key, error: message })
496+
return {
497+
mcpClient: undefined,
498+
status: { status: "failed" as const, error: `headersCommand failed: ${message}` },
499+
}
500+
}
501+
const mergedHeaders: Record<string, string> = { ...(mcp.headers ?? {}), ...dynamicHeaders }
502+
// altimate_change end
503+
504+
// altimate_change start — OAuth is enabled by default for remote servers,
505+
// BUT if the user provided an explicit Authorization header (statically or
506+
// via headersCommand) and didn't ask for OAuth, skip OAuth so the bearer
507+
// header isn't pre-empted by an OAuth flow that fails (e.g. Microsoft
508+
// Entra ID rejects RFC 7591 dynamic client registration). See #792.
509+
const oauthExplicitlyDisabled = mcp.oauth === false
510+
const oauthExplicitlyConfigured = typeof mcp.oauth === "object"
511+
const oauthDisabled =
512+
oauthExplicitlyDisabled ||
513+
(!oauthExplicitlyConfigured && hasAuthorizationHeader(mergedHeaders))
514+
// altimate_change end
369515
const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
370516
let authProvider: McpOAuthProvider | undefined
371517

@@ -387,22 +533,25 @@ export namespace MCP {
387533
)
388534
}
389535

536+
// altimate_change start — pass merged (static + dynamic) headers to transports
537+
const requestInit = Object.keys(mergedHeaders).length > 0 ? { headers: mergedHeaders } : undefined
390538
const transports: Array<{ name: string; transport: TransportWithAuth }> = [
391539
{
392540
name: "StreamableHTTP",
393541
transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
394542
authProvider,
395-
requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
543+
requestInit,
396544
}),
397545
},
398546
{
399547
name: "SSE",
400548
transport: new SSEClientTransport(new URL(mcp.url), {
401549
authProvider,
402-
requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
550+
requestInit,
403551
}),
404552
},
405553
]
554+
// altimate_change end
406555

407556
let lastError: Error | undefined
408557
const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
@@ -429,8 +578,10 @@ export namespace MCP {
429578
duration_ms: Date.now() - connectStart,
430579
})
431580
// altimate_change start — bridge merge: prefetch tool list synchronously
432-
// for cache so MCP.tools() doesn't re-call listTools.
433-
const toolsList = await client.listTools().catch(() => undefined)
581+
// for cache so MCP.tools() doesn't re-call listTools. Use lenient
582+
// schema so servers that emit `null` annotation hints (e.g. Fabric)
583+
// don't trip Zod validation. See #792.
584+
const toolsList = await listToolsLenient(client).catch(() => undefined)
434585
if (toolsList) toolListCache.set(key, toolsList.tools)
435586
// altimate_change end
436587
// Census: collect resource counts (fire-and-forget, never block connect)
@@ -567,8 +718,9 @@ export namespace MCP {
567718
duration_ms: Date.now() - localConnectStart,
568719
})
569720
// altimate_change start — bridge merge: prefetch tool list synchronously
570-
// for cache so MCP.tools() doesn't re-call listTools.
571-
const toolsListSync = await client.listTools().catch(() => undefined)
721+
// for cache so MCP.tools() doesn't re-call listTools. Use lenient schema
722+
// so non-compliant annotation hints (`null`) don't fail validation.
723+
const toolsListSync = await listToolsLenient(client).catch(() => undefined)
572724
if (toolsListSync) toolListCache.set(key, toolsListSync.tools)
573725
// altimate_change end
574726
// Census: collect resource counts (fire-and-forget, never block connect)
@@ -635,7 +787,7 @@ export namespace MCP {
635787
const cachedTools = toolListCache.get(key)
636788
const result = cachedTools
637789
? { tools: cachedTools }
638-
: await withTimeout(mcpClient.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
790+
: await withTimeout(listToolsLenient(mcpClient), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
639791
log.error("failed to get tools from client", { key, error: err })
640792
return undefined
641793
})
@@ -784,7 +936,7 @@ export namespace MCP {
784936
if (cached) {
785937
return { clientName, client, toolsResult: { tools: cached } }
786938
}
787-
const toolsResult = await client.listTools().catch((e) => {
939+
const toolsResult = await listToolsLenient(client).catch((e) => {
788940
log.error("failed to get tools", { clientName, error: e.message })
789941
const failedStatus = {
790942
status: "failed" as const,

0 commit comments

Comments
 (0)