Skip to content

Commit 9396102

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 f376fef commit 9396102

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
@@ -652,11 +652,26 @@ 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`).
658+
headersCommand: z
659+
.record(z.string(), z.array(z.string()).nonempty())
660+
.optional()
661+
.describe(
662+
"Headers whose values are produced by running a command (argv form: [cmd, ...args]). " +
663+
"stdout is trimmed and used as the header value. Resolved on every connect so tokens " +
664+
"with short TTLs (e.g. Microsoft Entra ID bearer tokens for Fabric) refresh automatically. " +
665+
"Values from headersCommand override matching keys in `headers`.",
666+
),
667+
// altimate_change end
655668
oauth: z
656669
.union([McpOAuth, z.literal(false)])
657670
.optional()
658671
.describe(
659-
"OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection.",
672+
"OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection. " +
673+
"When `headers.Authorization` or `headersCommand.Authorization` is set and `oauth` is not specified, " +
674+
"OAuth is disabled automatically so a static bearer token isn't overridden by a competing OAuth flow.",
660675
),
661676
timeout: z
662677
.number()
@@ -1452,6 +1467,15 @@ export namespace Config {
14521467
} else if (entry.url && typeof entry.url === "string") {
14531468
const transformed: Record<string, any> = { type: "remote", url: entry.url }
14541469
if (entry.headers && typeof entry.headers === "object") transformed.headers = entry.headers
1470+
// altimate_change start — preserve fields that the original normalizer dropped
1471+
// silently. Without these passes, a user-supplied `oauth: false` or
1472+
// `headersCommand` would be reconstructed-away, leaving the runtime
1473+
// believing the config was bare. See #791 / #792.
1474+
if (entry.headersCommand && typeof entry.headersCommand === "object") {
1475+
transformed.headersCommand = entry.headersCommand
1476+
}
1477+
if (entry.oauth !== undefined) transformed.oauth = entry.oauth
1478+
// altimate_change end
14551479
if (typeof entry.timeout === "number") transformed.timeout = entry.timeout
14561480
if (typeof entry.enabled === "boolean") transformed.enabled = entry.enabled
14571481
if (typeof entry.updatedAt === "string") transformed.updatedAt = entry.updatedAt

‎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
// altimate_change start — persist enabled flag
@@ -125,6 +131,118 @@ export namespace MCP {
125131
const toolListCache = new Map<string, MCPToolDef[]>()
126132
// altimate_change end
127133

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

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

@@ -391,22 +537,25 @@ export namespace MCP {
391537
)
392538
}
393539

540+
// altimate_change start — pass merged (static + dynamic) headers to transports
541+
const requestInit = Object.keys(mergedHeaders).length > 0 ? { headers: mergedHeaders } : undefined
394542
const transports: Array<{ name: string; transport: TransportWithAuth }> = [
395543
{
396544
name: "StreamableHTTP",
397545
transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
398546
authProvider,
399-
requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
547+
requestInit,
400548
}),
401549
},
402550
{
403551
name: "SSE",
404552
transport: new SSEClientTransport(new URL(mcp.url), {
405553
authProvider,
406-
requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
554+
requestInit,
407555
}),
408556
},
409557
]
558+
// altimate_change end
410559

411560
let lastError: Error | undefined
412561
const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
@@ -433,8 +582,10 @@ export namespace MCP {
433582
duration_ms: Date.now() - connectStart,
434583
})
435584
// altimate_change start — bridge merge: prefetch tool list synchronously
436-
// for cache so MCP.tools() doesn't re-call listTools.
437-
const toolsList = await client.listTools().catch(() => undefined)
585+
// for cache so MCP.tools() doesn't re-call listTools. Use lenient
586+
// schema so servers that emit `null` annotation hints (e.g. Fabric)
587+
// don't trip Zod validation. See #792.
588+
const toolsList = await listToolsLenient(client).catch(() => undefined)
438589
if (toolsList) toolListCache.set(key, toolsList.tools)
439590
// altimate_change end
440591
// Census: collect resource counts (fire-and-forget, never block connect)
@@ -571,8 +722,9 @@ export namespace MCP {
571722
duration_ms: Date.now() - localConnectStart,
572723
})
573724
// altimate_change start — bridge merge: prefetch tool list synchronously
574-
// for cache so MCP.tools() doesn't re-call listTools.
575-
const toolsListSync = await client.listTools().catch(() => undefined)
725+
// for cache so MCP.tools() doesn't re-call listTools. Use lenient schema
726+
// so non-compliant annotation hints (`null`) don't fail validation.
727+
const toolsListSync = await listToolsLenient(client).catch(() => undefined)
576728
if (toolsListSync) toolListCache.set(key, toolsListSync.tools)
577729
// altimate_change end
578730
// Census: collect resource counts (fire-and-forget, never block connect)
@@ -639,7 +791,7 @@ export namespace MCP {
639791
const cachedTools = toolListCache.get(key)
640792
const result = cachedTools
641793
? { tools: cachedTools }
642-
: await withTimeout(mcpClient.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
794+
: await withTimeout(listToolsLenient(mcpClient), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
643795
log.error("failed to get tools from client", { key, error: err })
644796
return undefined
645797
})
@@ -836,7 +988,7 @@ export namespace MCP {
836988
if (cached) {
837989
return { clientName, client, toolsResult: { tools: cached } }
838990
}
839-
const toolsResult = await client.listTools().catch((e) => {
991+
const toolsResult = await listToolsLenient(client).catch((e) => {
840992
log.error("failed to get tools", { clientName, error: e.message })
841993
const failedStatus = {
842994
status: "failed" as const,

0 commit comments

Comments
 (0)