Skip to content

Commit 4a6a711

Browse files
sdbrother0claude
andcommitted
[Feat] Support custom MCP OAuth callback paths and WWW-Authenticate discovery
Some authorization servers register static clients with a callback path other than /callback. The redirectUri option now accepts any path except the root path. The local callback server listens on that path. Some MCP servers host the protected resource metadata outside the RFC 9728 well-known URLs. When the well-known lookup fails, discovery now reads the resource_metadata URL from the 401 WWW-Authenticate header. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3f51e9d commit 4a6a711

6 files changed

Lines changed: 151 additions & 14 deletions

File tree

‎src/services/mcp/McpOAuthClientProvider.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -243,11 +243,12 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
243243

244244
private async _doStartCallbackServer(): Promise<void> {
245245
this._closed = false
246-
const { port: configuredPort, host } = getCallbackAddress(this._configuredRedirectUri)
246+
const { port: configuredPort, host, path } = getCallbackAddress(this._configuredRedirectUri)
247247
const { server, port, result, cancel } = await startCallbackServer(
248248
configuredPort ?? this._port,
249249
this._state,
250250
host,
251+
path,
251252
)
252253
this._server = server
253254
this._port = port
@@ -670,17 +671,22 @@ function resolveResourceIndicator(configured: McpOAuthResource | undefined, disc
670671
return discovered ?? null
671672
}
672673

673-
function getCallbackAddress(redirectUri?: string): { port?: number; host: "localhost" | "127.0.0.1" } {
674-
if (!redirectUri) return { host: "127.0.0.1" }
674+
function getCallbackAddress(redirectUri?: string): {
675+
port?: number
676+
host: "localhost" | "127.0.0.1"
677+
path: string
678+
} {
679+
if (!redirectUri) return { host: "127.0.0.1", path: "/callback" }
675680
const url = new URL(redirectUri)
676681
if (url.hostname !== "localhost" && url.hostname !== "127.0.0.1") {
677682
throw new Error("MCP OAuth redirectUri must use a loopback host")
678683
}
679684
if (url.protocol !== "http:") {
680685
throw new Error("MCP OAuth redirectUri must use HTTP on a loopback host")
681686
}
682-
if (url.pathname !== "/callback") {
683-
throw new Error("MCP OAuth redirectUri path must be /callback")
687+
// Authorization servers with pre-registered clients may require a specific path.
688+
if (url.pathname === "/") {
689+
throw new Error("MCP OAuth redirectUri must specify a callback path")
684690
}
685691
if (url.username || url.password || url.search || url.hash) {
686692
throw new Error("MCP OAuth redirectUri must not contain credentials, a query, or a fragment")
@@ -689,5 +695,5 @@ function getCallbackAddress(redirectUri?: string): { port?: number; host: "local
689695
if (!Number.isInteger(port) || port < 1 || port > 65535) {
690696
throw new Error("MCP OAuth redirectUri must specify a valid port")
691697
}
692-
return { port, host: url.hostname }
698+
return { port, host: url.hostname, path: url.pathname }
693699
}

‎src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -231,16 +231,39 @@ describe("McpOAuthClientProvider", () => {
231231
await provider.openBrowser()
232232
const openedUri = vi.mocked(vscode.env.openExternal).mock.calls[0][0].toString()
233233
expect(new URL(openedUri).searchParams.get("scope")).toBe("openid profile offline_access")
234-
expect(startCallbackServer).toHaveBeenCalledWith(33418, expect.any(String), callbackHost)
234+
expect(startCallbackServer).toHaveBeenCalledWith(33418, expect.any(String), callbackHost, "/callback")
235235
await provider.close()
236236
},
237237
)
238238

239+
it("should listen on the configured callback path for a static client", async () => {
240+
setupCallbackServerMock()
241+
const redirectUri = "http://127.0.0.1:19876/mcp/oauth/callback"
242+
const provider = await McpOAuthClientProvider.create(
243+
"https://example.com/mcp",
244+
createMockSecretStorage(),
245+
undefined,
246+
{ clientId: "registered-client", redirectUri },
247+
)
248+
249+
expect(provider.redirectUrl).toBe(redirectUri)
250+
expect(await provider.clientInformation()).toMatchObject({ redirect_uris: [redirectUri] })
251+
252+
await provider.redirectToAuthorization(new URL("https://auth.example.com/authorize"))
253+
expect(startCallbackServer).toHaveBeenCalledWith(
254+
19876,
255+
expect.any(String),
256+
"127.0.0.1",
257+
"/mcp/oauth/callback",
258+
)
259+
await provider.close()
260+
})
261+
239262
it.each([
240263
["https://example.com:33418/callback", "must use a loopback host"],
241264
["http://example.com:33418/callback", "must use a loopback host"],
242265
["https://localhost:33418/callback", "must use HTTP on a loopback host"],
243-
["http://localhost:33418/wrong", "path must be /callback"],
266+
["http://localhost:33418/", "must specify a callback path"],
244267
["http://localhost:33418/callback?x=1", "must not contain credentials, a query, or a fragment"],
245268
["http://localhost:33418/callback#fragment", "must not contain credentials, a query, or a fragment"],
246269
["http://u:p@localhost:33418/callback", "must not contain credentials, a query, or a fragment"],
@@ -1398,7 +1421,7 @@ describe("McpOAuthClientProvider", () => {
13981421
// reads redirect_uris, so the advertised URI carries the real port and never :0.
13991422
expect(startCallbackServer).toHaveBeenCalledTimes(1)
14001423
// Port 0 asks the OS for an ephemeral port; the mock binds it to 12345.
1401-
expect(startCallbackServer).toHaveBeenCalledWith(0, expect.any(String), "127.0.0.1")
1424+
expect(startCallbackServer).toHaveBeenCalledWith(0, expect.any(String), "127.0.0.1", "/callback")
14021425
expect(provider.redirectUrl).toBe("http://127.0.0.1:12345/callback")
14031426
expect(provider.redirectUrl).not.toContain(":0/")
14041427
expect(provider.clientMetadata.redirect_uris).toEqual(["http://127.0.0.1:12345/callback"])

‎src/services/mcp/utils/__tests__/callbackServer.spec.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,23 @@ describe("startCallbackServer", () => {
8484
await cancellation
8585
})
8686

87+
it("should resolve only on the configured callback path", async () => {
88+
const mockServer = createMockServer()
89+
90+
vi.mocked(http.createServer).mockReturnValue(mockServer as unknown as http.Server)
91+
92+
const { result } = await startCallbackServer(19876, undefined, "127.0.0.1", "/mcp/oauth/callback")
93+
const requestCall = mockServer.on.mock.calls.find((call) => call[0] === "request")
94+
const requestHandler = requestCall ? requestCall[1] : vi.fn()
95+
96+
const defaultPathRes = createMockResponse()
97+
requestHandler({ url: "/callback?code=wrong-path", method: "GET" }, defaultPathRes)
98+
expect(defaultPathRes.writeHead).toHaveBeenCalledWith(404)
99+
100+
requestHandler({ url: "/mcp/oauth/callback?code=test-code", method: "GET" }, createMockResponse())
101+
expect((await result).code).toBe("test-code")
102+
})
103+
87104
it("should reject invalid state", async () => {
88105
const mockServer = createMockServer()
89106

‎src/services/mcp/utils/__tests__/oauth.spec.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@ import { describe, it, expect, vi, beforeEach, afterAll } from "vitest"
33
// Mock the SDK's discoverOAuthProtectedResourceMetadata
44
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
55
discoverOAuthProtectedResourceMetadata: vi.fn(),
6+
extractResourceMetadataUrl: vi.fn(),
67
}))
78

8-
import { discoverOAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/client/auth.js"
9+
import {
10+
discoverOAuthProtectedResourceMetadata,
11+
extractResourceMetadataUrl,
12+
} from "@modelcontextprotocol/sdk/client/auth.js"
913
import { fetchOAuthAuthServerMetadata } from "../oauth"
1014

1115
const mockFetch = vi.fn()
@@ -33,9 +37,51 @@ describe("fetchOAuthAuthServerMetadata", () => {
3337

3438
it("returns null when discoverOAuthProtectedResourceMetadata throws", async () => {
3539
;(discoverOAuthProtectedResourceMetadata as any).mockRejectedValue(new Error("network error"))
40+
mockFetch.mockResolvedValueOnce({ status: 200, body: null })
3641

3742
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
3843
expect(result).toBeNull()
44+
expect(extractResourceMetadataUrl).not.toHaveBeenCalled()
45+
})
46+
47+
it("falls back to the resource_metadata URL from the 401 WWW-Authenticate header", async () => {
48+
const resourceMetadataUrl = new URL("https://example.com/core/.well-known/oauth-protected-resource/mcp")
49+
vi.mocked(discoverOAuthProtectedResourceMetadata)
50+
.mockRejectedValueOnce(
51+
new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata."),
52+
)
53+
.mockResolvedValueOnce({
54+
resource: "https://example.com/core/mcp",
55+
authorization_servers: ["https://auth.example.com"],
56+
})
57+
vi.mocked(extractResourceMetadataUrl).mockReturnValueOnce(resourceMetadataUrl)
58+
const meta = { issuer: "https://auth.example.com" }
59+
mockFetch
60+
.mockResolvedValueOnce({ status: 401, body: null })
61+
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(meta) })
62+
63+
const result = await fetchOAuthAuthServerMetadata("https://example.com/core/mcp")
64+
65+
expect(mockFetch).toHaveBeenNthCalledWith(
66+
1,
67+
"https://example.com/core/mcp",
68+
expect.objectContaining({ method: "POST" }),
69+
)
70+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenLastCalledWith("https://example.com/core/mcp", {
71+
resourceMetadataUrl,
72+
})
73+
expect(result).toEqual({ authServerMeta: meta, resourceIndicator: "https://example.com/core/mcp" })
74+
})
75+
76+
it("returns null when the 401 response has no resource_metadata URL", async () => {
77+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValueOnce(new Error("not found"))
78+
vi.mocked(extractResourceMetadataUrl).mockReturnValueOnce(undefined)
79+
mockFetch.mockResolvedValueOnce({ status: 401, body: null })
80+
81+
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
82+
83+
expect(result).toBeNull()
84+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(1)
3985
})
4086

4187
it("constructs the RFC 8414 discovery URL correctly for an issuer with a path", async () => {

‎src/services/mcp/utils/callbackServer.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,14 @@ type CallbackHost = "localhost" | "127.0.0.1"
1919
* @param port Optional port to use (defaults to random available port)
2020
* @param expectedState Optional expected state for CSRF protection
2121
* @param host Loopback host used by the OAuth redirect URI
22+
* @param callbackPath Path of the OAuth redirect URI that receives the authorization code
2223
* @returns Promise<{server: http.Server, port: number, result: Promise<CallbackResult>}>
2324
*/
2425
export function startCallbackServer(
2526
port?: number,
2627
expectedState?: string,
2728
host: CallbackHost = "127.0.0.1",
29+
callbackPath = "/callback",
2830
): Promise<{
2931
server: http.Server
3032
port: number
@@ -87,7 +89,7 @@ export function startCallbackServer(
8789
const url = new URL(req.url || "", `http://localhost:${actualPort}`)
8890
const pathname = url.pathname
8991

90-
if (pathname === "/callback") {
92+
if (pathname === callbackPath) {
9193
resolved = true
9294
clearTimeout(timeout)
9395

‎src/services/mcp/utils/oauth.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import { discoverOAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/client/auth.js"
1+
import {
2+
discoverOAuthProtectedResourceMetadata,
3+
extractResourceMetadataUrl,
4+
} from "@modelcontextprotocol/sdk/client/auth.js"
5+
import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"
26

37
/**
48
* Result of a successful OAuth discovery for an MCP server.
@@ -34,7 +38,9 @@ export interface OAuthDiscoveryResult {
3438
*
3539
* Performs two discovery steps:
3640
* 1. RFC 9728 – fetches the Protected Resource Metadata to find the issuer URL
37-
* and the RFC 8707 resource indicator.
41+
* and the RFC 8707 resource indicator. When the well-known URLs fail, falls
42+
* back to the `resource_metadata` URL from the server's 401 `WWW-Authenticate`
43+
* header (RFC 9728 §5.1), for servers that host the metadata elsewhere.
3844
* 2. RFC 8414 §3.1 – constructs the well-known discovery URL by inserting
3945
* `/.well-known/oauth-authorization-server` *between* the host and the issuer
4046
* path (not appended after the path).
@@ -52,7 +58,7 @@ export async function fetchOAuthAuthServerMetadata(serverUrl: string): Promise<O
5258
// capture the resource indicator for RFC 8707.
5359
// The SDK does not accept an AbortSignal, so we race it against a timeout.
5460
const resourceMeta = await Promise.race([
55-
discoverOAuthProtectedResourceMetadata(serverUrl),
61+
discoverProtectedResourceMetadata(serverUrl),
5662
new Promise<never>((_, reject) =>
5763
setTimeout(() => reject(new Error("OAuth discovery timeout")), DISCOVERY_TIMEOUT_MS),
5864
),
@@ -85,3 +91,40 @@ export async function fetchOAuthAuthServerMetadata(serverUrl: string): Promise<O
8591
return null
8692
}
8793
}
94+
95+
async function discoverProtectedResourceMetadata(serverUrl: string): Promise<OAuthProtectedResourceMetadata> {
96+
try {
97+
return await discoverOAuthProtectedResourceMetadata(serverUrl)
98+
} catch (wellKnownError) {
99+
const resourceMetadataUrl = await probeResourceMetadataUrl(serverUrl)
100+
if (!resourceMetadataUrl) throw wellKnownError
101+
return discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl })
102+
}
103+
}
104+
105+
/**
106+
* Sends an unauthenticated MCP `initialize` request and returns the
107+
* `resource_metadata` URL from the 401 `WWW-Authenticate` header, if any.
108+
*/
109+
async function probeResourceMetadataUrl(serverUrl: string): Promise<URL | undefined> {
110+
const response = await fetch(serverUrl, {
111+
method: "POST",
112+
headers: {
113+
"Content-Type": "application/json",
114+
Accept: "application/json, text/event-stream",
115+
},
116+
body: JSON.stringify({
117+
jsonrpc: "2.0",
118+
id: 0,
119+
method: "initialize",
120+
params: {
121+
protocolVersion: "2025-06-18",
122+
capabilities: {},
123+
clientInfo: { name: "oauth-discovery", version: "1.0.0" },
124+
},
125+
}),
126+
signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
127+
})
128+
await response.body?.cancel().catch(() => {})
129+
return response.status === 401 ? extractResourceMetadataUrl(response) : undefined
130+
}

0 commit comments

Comments
 (0)