Skip to content

Commit 8383de4

Browse files
Add static OAuth client settings for MCP servers (Zoo-Code-Org#2129)
* feat(mcp): add static OAuth client configuration (Zoo-Code-Org#2096) * fix(mcp): preserve SDK OAuth resource (Zoo-Code-Org#2096) * fix(mcp): keep OAuth requests consistent (Zoo-Code-Org#2096) * fix(mcp): persist OAuth request constraints (Zoo-Code-Org#2096) * test(mcp): cover OAuth creation constraints (Zoo-Code-Org#2096) * fix(mcp): close OAuth lifecycle gaps (Zoo-Code-Org#2096) * fix(mcp): harden callback and token storage (Zoo-Code-Org#2096) * test(mcp): cover static OAuth client isolation and discovery gating - SecretStorageService: isolate hasOAuthData, deleteOAuthData, and onDidChange per client ID on one server URL, next to the dynamic key. - McpHub: check the hasOAuthData arguments and each skipDiscovery term. - McpOAuthClientProvider: start the callback server eagerly for a static client without a redirectUri, so redirect_uris never use :0. * fix(mcp): harden static OAuth callback lifecycle * fix(mcp): close failed OAuth callback listeners
1 parent e879f8d commit 8383de4

9 files changed

Lines changed: 1365 additions & 108 deletions

‎src/eslint-suppressions.json‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1481,7 +1481,7 @@
14811481
},
14821482
"services/mcp/McpHub.ts": {
14831483
"@typescript-eslint/no-explicit-any": {
1484-
"count": 8
1484+
"count": 7
14851485
}
14861486
},
14871487
"services/mcp/McpOAuthClientProvider.ts": {
@@ -1501,19 +1501,14 @@
15011501
},
15021502
"services/mcp/__tests__/McpOAuthClientProvider.spec.ts": {
15031503
"@typescript-eslint/no-explicit-any": {
1504-
"count": 20
1504+
"count": 18
15051505
}
15061506
},
15071507
"services/mcp/__tests__/SecretStorageService.spec.ts": {
15081508
"@typescript-eslint/no-explicit-any": {
15091509
"count": 1
15101510
}
15111511
},
1512-
"services/mcp/utils/__tests__/callbackServer.spec.ts": {
1513-
"@typescript-eslint/no-explicit-any": {
1514-
"count": 4
1515-
}
1516-
},
15171512
"services/mcp/utils/__tests__/oauth.spec.ts": {
15181513
"@typescript-eslint/no-explicit-any": {
15191514
"count": 9

‎src/services/mcp/McpHub.ts‎

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ const stdioFieldsErrorMessage =
8484
const sseFieldsErrorMessage =
8585
"For 'sse' type servers, you must provide a 'url' field and can optionally include 'headers'"
8686
const streamableHttpFieldsErrorMessage =
87-
"For 'streamable-http' type servers, you must provide a 'url' field and can optionally include 'headers'"
87+
"For 'streamable-http' type servers, you must provide a 'url' field and can optionally include 'headers' and 'oauth'"
8888
const mixedFieldsErrorMessage =
8989
"Cannot mix 'stdio' and ('sse' or 'streamable-http') fields. For 'stdio' use 'command', 'args', and 'env'. For 'sse'/'streamable-http' use 'url' and 'headers'"
9090
const missingFieldsErrorMessage =
@@ -103,6 +103,7 @@ const createServerTypeSchema = () => {
103103
// Ensure no SSE fields are present
104104
url: z.undefined().optional(),
105105
headers: z.undefined().optional(),
106+
oauth: z.undefined().optional(),
106107
})
107108
.transform((data) => ({
108109
...data,
@@ -114,6 +115,7 @@ const createServerTypeSchema = () => {
114115
type: z.enum(["sse"]).optional(),
115116
url: z.string().url("URL must be a valid URL format"),
116117
headers: z.record(z.string(), z.string()).optional(),
118+
oauth: z.undefined().optional(),
117119
// Ensure no stdio fields are present
118120
command: z.undefined().optional(),
119121
args: z.undefined().optional(),
@@ -129,6 +131,14 @@ const createServerTypeSchema = () => {
129131
type: z.enum(["streamable-http"]).optional(),
130132
url: z.string().url("URL must be a valid URL format"),
131133
headers: z.record(z.string(), z.string()).optional(),
134+
oauth: z
135+
.object({
136+
clientId: z.string().min(1, "OAuth clientId cannot be empty"),
137+
scope: z.string().optional(),
138+
redirectUri: z.string().url("OAuth redirectUri must be a valid URL").optional(),
139+
resource: z.union([z.literal("auto"), z.literal(false), z.string().url()]).optional(),
140+
})
141+
.optional(),
132142
// Ensure no stdio fields are present
133143
command: z.undefined().optional(),
134144
args: z.undefined().optional(),
@@ -713,6 +723,7 @@ export class McpHub {
713723
// Set up file watchers for enabled servers
714724
this.setupFileWatcher(name, config, source)
715725

726+
let pendingAuthProvider: McpOAuthClientProvider | undefined
716727
try {
717728
const client = new Client(
718729
{
@@ -821,19 +832,26 @@ export class McpHub {
821832
// 1. SecretStorage has OAuth data → known OAuth server → discover
822833
// 2. In-memory negative cache says non-OAuth → skip discovery
823834
// 3. Unknown server (first connection) → discover once, cache result
824-
const hasOAuthData = await this.secretStorage.hasOAuthData(configInjected.url)
835+
const oauthClientId = configInjected.oauth?.clientId
836+
const hasOAuthData = await this.secretStorage.hasOAuthData(configInjected.url, oauthClientId)
825837
const knownNonOAuth = McpOAuthClientProvider.isKnownNonOAuth(configInjected.url)
826-
const skipDiscovery = !hasOAuthData && knownNonOAuth
838+
const skipDiscovery = !oauthClientId && !hasOAuthData && knownNonOAuth
827839

828840
const authProvider = await McpOAuthClientProvider.create(configInjected.url, this.secretStorage, name, {
829841
skipDiscovery,
842+
...configInjected.oauth,
830843
})
844+
pendingAuthProvider = authProvider
845+
if (this.isDisposed) {
846+
await authProvider.close()
847+
return
848+
}
831849

832850
// Pre-register the OAuth client so the SDK can skip its own
833851
// registration step (broken for path-prefixed issuers — see
834852
// utils/oauth.ts for upstream issue links).
835853
// Skip when discovery was skipped — there's no metadata to register with.
836-
if (!skipDiscovery) {
854+
if (!skipDiscovery && !oauthClientId) {
837855
try {
838856
await authProvider.registerClientIfNeeded()
839857
} catch {
@@ -979,6 +997,7 @@ export class McpHub {
979997
authProvider: streamableHttpAuthProvider,
980998
}
981999
this.connections.push(connection)
1000+
pendingAuthProvider = undefined
9821001

9831002
// Connect (this will automatically start the transport)
9841003
try {
@@ -1033,6 +1052,7 @@ export class McpHub {
10331052
connection.server.resources = await this.fetchResourcesList(name, source)
10341053
connection.server.resourceTemplates = await this.fetchResourceTemplatesList(name, source)
10351054
} catch (error) {
1055+
await pendingAuthProvider?.close()
10361056
// Update status with error
10371057
const connection = this.findConnection(name, source)
10381058
if (connection) {
@@ -1066,7 +1086,8 @@ export class McpHub {
10661086
transport: StreamableHTTPClientTransport,
10671087
connection: ConnectedMcpConnection,
10681088
): Promise<void> {
1069-
const serverUrl = "url" in config ? (config as any).url : undefined
1089+
const serverUrl = "url" in config ? config.url : undefined
1090+
const oauthClientId = config.type === "streamable-http" ? config.oauth?.clientId : undefined
10701091
if (!serverUrl || !this.secretStorage) {
10711092
return
10721093
}
@@ -1078,21 +1099,27 @@ export class McpHub {
10781099
// Note: onDidChange fires on both writes AND deletes — the re-read below is
10791100
// authoritative; we only reconnect if it returns a valid (non-expired) token.
10801101
let tokenChangedDuringRead = false
1081-
const unsubscribeCrossWindow = this.secretStorage.onDidChange(serverUrl, () => {
1082-
tokenChangedDuringRead = true
1083-
})
1102+
const unsubscribeCrossWindow = this.secretStorage.onDidChange(
1103+
serverUrl,
1104+
() => {
1105+
tokenChangedDuringRead = true
1106+
},
1107+
oauthClientId,
1108+
)
10841109

10851110
// Check if another window already saved valid tokens.
10861111
// Re-read after registering the watcher in case a write landed in the gap.
1087-
const existing = await this.secretStorage.getOAuthData(serverUrl)
1112+
const existing = await this.secretStorage.getOAuthData(serverUrl, oauthClientId)
10881113
if (this.isDisposed) {
10891114
unsubscribeCrossWindow()
1115+
await authProvider.close()
10901116
return
10911117
}
10921118
// If the first read missed but the watcher fired during it, re-read — a write
10931119
// may have landed between subscription and read completion.
10941120
const tokenToUse =
1095-
existing ?? (tokenChangedDuringRead ? await this.secretStorage.getOAuthData(serverUrl) : undefined)
1121+
existing ??
1122+
(tokenChangedDuringRead ? await this.secretStorage.getOAuthData(serverUrl, oauthClientId) : undefined)
10961123
unsubscribeCrossWindow()
10971124

10981125
if (!this.isDisposed && tokenToUse && Date.now() < tokenToUse.expires_at - TOKEN_EXPIRY_BUFFER_MS) {
@@ -1122,6 +1149,7 @@ export class McpHub {
11221149
connection,
11231150
progress,
11241151
cancellationToken,
1152+
oauthClientId,
11251153
),
11261154
)
11271155
}
@@ -1136,6 +1164,7 @@ export class McpHub {
11361164
connection: ConnectedMcpConnection,
11371165
progress: vscode.Progress<{ message?: string; increment?: number }>,
11381166
cancellationToken: vscode.CancellationToken,
1167+
oauthClientId?: string,
11391168
): Promise<void> {
11401169
const watcherKey = `${name}:${source}`
11411170

@@ -1170,7 +1199,7 @@ export class McpHub {
11701199
return
11711200
}
11721201
try {
1173-
const data = await this.secretStorage?.getOAuthData(serverUrl)
1202+
const data = await this.secretStorage?.getOAuthData(serverUrl, oauthClientId)
11741203
// Re-check after the async yield — cancellation or completion may have
11751204
// fired while getOAuthData was in flight.
11761205
if (disposed || this.isDisposed) return
@@ -1188,9 +1217,13 @@ export class McpHub {
11881217
}
11891218
}
11901219

1191-
const unsubscribe = this.secretStorage!.onDidChange(serverUrl, () => {
1192-
void onTokensChanged()
1193-
})
1220+
const unsubscribe = this.secretStorage!.onDidChange(
1221+
serverUrl,
1222+
() => {
1223+
void onTokensChanged()
1224+
},
1225+
oauthClientId,
1226+
)
11941227

11951228
// --- Timeout ---
11961229
const timeoutHandle = setTimeout(() => {
@@ -1273,7 +1306,7 @@ export class McpHub {
12731306
}
12741307

12751308
// Guard: another window may have authed while the toast was open
1276-
const tokens = await this.secretStorage!.getOAuthData(serverUrl)
1309+
const tokens = await this.secretStorage!.getOAuthData(serverUrl, oauthClientId)
12771310
if (disposed) return
12781311
if (tokens && Date.now() < tokens.expires_at - TOKEN_EXPIRY_BUFFER_MS) {
12791312
cleanup(cancellationDisposable)
@@ -1757,7 +1790,7 @@ export class McpHub {
17571790

17581791
// Clear OAuth tokens for streamable-http servers on restart
17591792
if (validatedConfig.type === "streamable-http" && this.secretStorage) {
1760-
await this.secretStorage.deleteOAuthData(validatedConfig.url)
1793+
await this.secretStorage.deleteOAuthData(validatedConfig.url, validatedConfig.oauth?.clientId)
17611794
}
17621795

17631796
// Try to connect again using validated config

0 commit comments

Comments
 (0)