-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathmcp-oauth-provider.ts
More file actions
322 lines (287 loc) · 10.1 KB
/
mcp-oauth-provider.ts
File metadata and controls
322 lines (287 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/**
* MCP OAuth Provider
*
* Implementation of the MCP SDK's OAuthClientProvider interface.
* Handles OAuth client registration, token storage, and authorization redirection.
*/
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
import type {
OAuthClientMetadata,
OAuthTokens,
OAuthClientInformation,
OAuthClientInformationFull,
} from "@modelcontextprotocol/sdk/shared/auth.js"
import {
getAuthForUrl,
updateTokens,
updateClientInfo,
updateCodeVerifier,
updateOAuthState,
clearAllCredentials,
clearClientInfo,
clearTokens,
type StoredTokens,
type StoredClientInfo,
} from "./mcp-auth.ts"
// Callback server configuration
const DEFAULT_OAUTH_CALLBACK_PORT = 19876
const DEFAULT_OAUTH_CALLBACK_PATH = "/callback"
let configuredOAuthCallbackPort = DEFAULT_OAUTH_CALLBACK_PORT
if (process.env.MCP_OAUTH_CALLBACK_PORT) {
const parsedPort = Number.parseInt(process.env.MCP_OAUTH_CALLBACK_PORT, 10)
if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) {
configuredOAuthCallbackPort = parsedPort
}
}
let oauthCallbackPort = configuredOAuthCallbackPort
let oauthCallbackPath = DEFAULT_OAUTH_CALLBACK_PATH
export function getConfiguredOAuthCallbackPort(): number {
return configuredOAuthCallbackPort
}
export function getOAuthCallbackPort(): number {
return oauthCallbackPort
}
export function setOAuthCallbackPort(port: number): void {
oauthCallbackPort = port
}
export function getOAuthCallbackPath(): string {
return oauthCallbackPath
}
export function setOAuthCallbackPath(path: string): void {
oauthCallbackPath = path.startsWith("/") ? path : `/${path}`
}
/** Configuration options for OAuth */
export interface McpOAuthConfig {
grantType?: "authorization_code" | "client_credentials"
clientId?: string
clientSecret?: string
scope?: string
redirectUri?: string
clientName?: string
clientUri?: string
}
/** Callbacks for OAuth flow interactions */
export interface McpOAuthCallbacks {
onRedirect: (url: URL) => void | Promise<void>
}
/**
* OAuth provider implementation for MCP servers.
* Implements the OAuthClientProvider interface from the MCP SDK.
*/
export class McpOAuthProvider implements OAuthClientProvider {
private readonly redirectUrlSnapshot: string | undefined
constructor(
private serverName: string,
private serverUrl: string,
private config: McpOAuthConfig,
private callbacks: McpOAuthCallbacks,
) {
this.redirectUrlSnapshot = config.grantType === "client_credentials"
? undefined
: config.redirectUri ?? `http://localhost:${getOAuthCallbackPort()}${getOAuthCallbackPath()}`
}
private get usesClientCredentials(): boolean {
return this.config.grantType === "client_credentials"
}
/**
* The redirect URL for OAuth callbacks.
* This must match the redirect_uri in client metadata.
*/
get redirectUrl(): string | undefined {
return this.redirectUrlSnapshot
}
/**
* Client metadata for dynamic registration.
* Describes this client to the OAuth authorization server.
*/
get clientMetadata(): OAuthClientMetadata {
if (this.usesClientCredentials) {
return {
client_name: this.config.clientName ?? "Pi Coding Agent",
client_uri: this.config.clientUri ?? "https://github.com/nicobailon/pi-mcp-adapter",
redirect_uris: [],
grant_types: ["client_credentials"],
token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
}
}
const redirectUrl = this.redirectUrl
if (!redirectUrl) {
throw new Error("redirectUrl is required for authorization_code flow")
}
return {
redirect_uris: [redirectUrl],
client_name: this.config.clientName ?? "Pi Coding Agent",
client_uri: this.config.clientUri ?? "https://github.com/nicobailon/pi-mcp-adapter",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
}
}
/**
* Get client information (for pre-registered or dynamically registered clients).
* Returns undefined if no client info exists or if the server URL has changed.
*/
async clientInformation(): Promise<OAuthClientInformation | undefined> {
// Check config first (pre-registered client)
if (this.config.clientId) {
return {
client_id: this.config.clientId,
client_secret: this.config.clientSecret,
}
}
// Check stored client info (from dynamic registration)
// Use getAuthForUrl to validate credentials are for the current server URL
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
if (entry?.clientInfo) {
// Check if client secret has expired
if (entry.clientInfo.clientSecretExpiresAt && entry.clientInfo.clientSecretExpiresAt < Date.now() / 1000) {
return undefined
}
return {
client_id: entry.clientInfo.clientId,
client_secret: entry.clientInfo.clientSecret,
}
}
// No client info or URL changed - will trigger dynamic registration
return undefined
}
/**
* Save client information from dynamic registration.
*/
async saveClientInformation(info: OAuthClientInformationFull): Promise<void> {
const redirectUris = info.redirect_uris ?? (this.redirectUrl ? [this.redirectUrl] : undefined)
const clientInfo: StoredClientInfo = {
clientId: info.client_id,
clientSecret: info.client_secret,
clientIdIssuedAt: info.client_id_issued_at,
clientSecretExpiresAt: info.client_secret_expires_at,
redirectUris,
}
updateClientInfo(this.serverName, clientInfo, this.serverUrl)
}
/**
* Get stored OAuth tokens.
* Returns undefined if no tokens exist or if the server URL has changed.
*/
async tokens(): Promise<OAuthTokens | undefined> {
// Use getAuthForUrl to validate tokens are for the current server URL
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
if (!entry?.tokens) return undefined
return {
access_token: entry.tokens.accessToken,
token_type: "Bearer",
refresh_token: entry.tokens.refreshToken,
expires_in: entry.tokens.expiresAt
? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
: undefined,
scope: entry.tokens.scope,
}
}
/**
* Save OAuth tokens.
*/
async saveTokens(tokens: OAuthTokens): Promise<void> {
const storedTokens: StoredTokens = {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
expiresAt: tokens.expires_in ? Date.now() / 1000 + tokens.expires_in : undefined,
scope: tokens.scope,
}
updateTokens(this.serverName, storedTokens, this.serverUrl)
}
/**
* Redirect the user to the authorization URL.
* This opens the browser for the user to authenticate.
*
* Throws UnauthorizedError when called outside of a user-initiated flow
* (no oauthState saved by startAuth). That path is reached when the SDK
* falls through from a failed refresh into a fresh authorization_code
* flow, which library hosts cannot complete in-process.
*/
async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
if (this.usesClientCredentials) {
throw new Error("redirectToAuthorization is not used for client_credentials flow")
}
// No saved oauthState means we're on the post-refresh authorize fallback.
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
if (!entry?.oauthState) {
throw new UnauthorizedError(
`Re-authentication required for MCP server: ${this.serverName}`,
)
}
// URL is passed to callback, not logged (may contain sensitive params)
await this.callbacks.onRedirect(authorizationUrl)
}
/**
* Save the PKCE code verifier.
*/
async saveCodeVerifier(codeVerifier: string): Promise<void> {
updateCodeVerifier(this.serverName, codeVerifier, this.serverUrl)
}
/**
* Get the stored PKCE code verifier.
* @throws Error if no code verifier is stored
*/
async codeVerifier(): Promise<string> {
if (this.usesClientCredentials) {
throw new Error("codeVerifier is not used for client_credentials flow")
}
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
if (!entry?.codeVerifier) {
throw new Error(`No code verifier saved for MCP server: ${this.serverName}`)
}
return entry.codeVerifier
}
/**
* Save the OAuth state parameter for CSRF protection.
*/
async saveState(state: string): Promise<void> {
updateOAuthState(this.serverName, state, this.serverUrl)
}
/**
* Get the stored OAuth state parameter.
* @throws UnauthorizedError if no flow is in progress (see redirectToAuthorization)
*/
async state(): Promise<string> {
if (this.usesClientCredentials) {
throw new Error("state is not used for client_credentials flow")
}
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
if (!entry?.oauthState) {
throw new UnauthorizedError(
`Re-authentication required for MCP server: ${this.serverName}`,
)
}
return entry.oauthState
}
/**
* Invalidate credentials when authentication fails.
* Clears tokens, client info, or all credentials based on the type.
*/
async invalidateCredentials(type: "all" | "client" | "tokens"): Promise<void> {
switch (type) {
case "all":
clearAllCredentials(this.serverName)
break
case "client":
clearClientInfo(this.serverName)
break
case "tokens":
clearTokens(this.serverName)
break
}
}
prepareTokenRequest(scope?: string): URLSearchParams | undefined {
if (!this.usesClientCredentials) {
return undefined
}
const params = new URLSearchParams({ grant_type: "client_credentials" })
const requestedScope = scope ?? this.config.scope
if (requestedScope) {
params.set("scope", requestedScope)
}
return params
}
}
export { DEFAULT_OAUTH_CALLBACK_PORT, DEFAULT_OAUTH_CALLBACK_PATH }