pi-mcp-adapter 2.2.2 → 2.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +1 -2
- package/commands.ts +48 -20
- package/direct-tools.ts +7 -0
- package/index.ts +5 -0
- package/init.ts +20 -4
- package/mcp-auth-flow.ts +378 -0
- package/mcp-auth.ts +277 -0
- package/mcp-callback-server.ts +251 -0
- package/mcp-oauth-provider.ts +265 -0
- package/package.json +16 -8
- package/proxy-modes.ts +31 -0
- package/server-manager.ts +66 -24
- package/types.ts +27 -1
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP OAuth Provider
|
|
3
|
+
*
|
|
4
|
+
* Implementation of the MCP SDK's OAuthClientProvider interface.
|
|
5
|
+
* Handles OAuth client registration, token storage, and authorization redirection.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
|
|
9
|
+
import type {
|
|
10
|
+
OAuthClientMetadata,
|
|
11
|
+
OAuthTokens,
|
|
12
|
+
OAuthClientInformation,
|
|
13
|
+
OAuthClientInformationFull,
|
|
14
|
+
} from "@modelcontextprotocol/sdk/shared/auth.js"
|
|
15
|
+
import {
|
|
16
|
+
getAuthEntry,
|
|
17
|
+
getAuthForUrl,
|
|
18
|
+
updateTokens,
|
|
19
|
+
updateClientInfo,
|
|
20
|
+
updateCodeVerifier,
|
|
21
|
+
updateOAuthState,
|
|
22
|
+
clearAllCredentials,
|
|
23
|
+
clearClientInfo,
|
|
24
|
+
clearTokens,
|
|
25
|
+
type StoredTokens,
|
|
26
|
+
type StoredClientInfo,
|
|
27
|
+
} from "./mcp-auth.js"
|
|
28
|
+
|
|
29
|
+
// Callback server configuration
|
|
30
|
+
const OAUTH_CALLBACK_PORT = 19876
|
|
31
|
+
const OAUTH_CALLBACK_PATH = "/mcp/oauth/callback"
|
|
32
|
+
|
|
33
|
+
/** Configuration options for OAuth */
|
|
34
|
+
export interface McpOAuthConfig {
|
|
35
|
+
grantType?: "authorization_code" | "client_credentials"
|
|
36
|
+
clientId?: string
|
|
37
|
+
clientSecret?: string
|
|
38
|
+
scope?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Callbacks for OAuth flow interactions */
|
|
42
|
+
export interface McpOAuthCallbacks {
|
|
43
|
+
onRedirect: (url: URL) => void | Promise<void>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* OAuth provider implementation for MCP servers.
|
|
48
|
+
* Implements the OAuthClientProvider interface from the MCP SDK.
|
|
49
|
+
*/
|
|
50
|
+
export class McpOAuthProvider implements OAuthClientProvider {
|
|
51
|
+
constructor(
|
|
52
|
+
private serverName: string,
|
|
53
|
+
private serverUrl: string,
|
|
54
|
+
private config: McpOAuthConfig,
|
|
55
|
+
private callbacks: McpOAuthCallbacks,
|
|
56
|
+
) {}
|
|
57
|
+
|
|
58
|
+
private get usesClientCredentials(): boolean {
|
|
59
|
+
return this.config.grantType === "client_credentials"
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The redirect URL for OAuth callbacks.
|
|
64
|
+
* This must match the redirect_uri in client metadata.
|
|
65
|
+
*/
|
|
66
|
+
get redirectUrl(): string | undefined {
|
|
67
|
+
if (this.usesClientCredentials) return undefined
|
|
68
|
+
return `http://127.0.0.1:${OAUTH_CALLBACK_PORT}${OAUTH_CALLBACK_PATH}`
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Client metadata for dynamic registration.
|
|
73
|
+
* Describes this client to the OAuth authorization server.
|
|
74
|
+
*/
|
|
75
|
+
get clientMetadata(): OAuthClientMetadata {
|
|
76
|
+
if (this.usesClientCredentials) {
|
|
77
|
+
return {
|
|
78
|
+
client_name: "Pi Coding Agent",
|
|
79
|
+
redirect_uris: [],
|
|
80
|
+
grant_types: ["client_credentials"],
|
|
81
|
+
token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const redirectUrl = this.redirectUrl
|
|
86
|
+
if (!redirectUrl) {
|
|
87
|
+
throw new Error("redirectUrl is required for authorization_code flow")
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
redirect_uris: [redirectUrl],
|
|
92
|
+
client_name: "Pi Coding Agent",
|
|
93
|
+
client_uri: "https://github.com/nicobailon/pi-mcp-adapter",
|
|
94
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
95
|
+
response_types: ["code"],
|
|
96
|
+
token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Get client information (for pre-registered or dynamically registered clients).
|
|
102
|
+
* Returns undefined if no client info exists or if the server URL has changed.
|
|
103
|
+
*/
|
|
104
|
+
async clientInformation(): Promise<OAuthClientInformation | undefined> {
|
|
105
|
+
// Check config first (pre-registered client)
|
|
106
|
+
if (this.config.clientId) {
|
|
107
|
+
return {
|
|
108
|
+
client_id: this.config.clientId,
|
|
109
|
+
client_secret: this.config.clientSecret,
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Check stored client info (from dynamic registration)
|
|
114
|
+
// Use getAuthForUrl to validate credentials are for the current server URL
|
|
115
|
+
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
|
|
116
|
+
if (entry?.clientInfo) {
|
|
117
|
+
// Check if client secret has expired
|
|
118
|
+
if (entry.clientInfo.clientSecretExpiresAt && entry.clientInfo.clientSecretExpiresAt < Date.now() / 1000) {
|
|
119
|
+
return undefined
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
client_id: entry.clientInfo.clientId,
|
|
123
|
+
client_secret: entry.clientInfo.clientSecret,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// No client info or URL changed - will trigger dynamic registration
|
|
128
|
+
return undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Save client information from dynamic registration.
|
|
133
|
+
*/
|
|
134
|
+
async saveClientInformation(info: OAuthClientInformationFull): Promise<void> {
|
|
135
|
+
const clientInfo: StoredClientInfo = {
|
|
136
|
+
clientId: info.client_id,
|
|
137
|
+
clientSecret: info.client_secret,
|
|
138
|
+
clientIdIssuedAt: info.client_id_issued_at,
|
|
139
|
+
clientSecretExpiresAt: info.client_secret_expires_at,
|
|
140
|
+
}
|
|
141
|
+
updateClientInfo(this.serverName, clientInfo, this.serverUrl)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Get stored OAuth tokens.
|
|
146
|
+
* Returns undefined if no tokens exist or if the server URL has changed.
|
|
147
|
+
*/
|
|
148
|
+
async tokens(): Promise<OAuthTokens | undefined> {
|
|
149
|
+
// Use getAuthForUrl to validate tokens are for the current server URL
|
|
150
|
+
const entry = await getAuthForUrl(this.serverName, this.serverUrl)
|
|
151
|
+
if (!entry?.tokens) return undefined
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
access_token: entry.tokens.accessToken,
|
|
155
|
+
token_type: "Bearer",
|
|
156
|
+
refresh_token: entry.tokens.refreshToken,
|
|
157
|
+
expires_in: entry.tokens.expiresAt
|
|
158
|
+
? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
|
|
159
|
+
: undefined,
|
|
160
|
+
scope: entry.tokens.scope,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Save OAuth tokens.
|
|
166
|
+
*/
|
|
167
|
+
async saveTokens(tokens: OAuthTokens): Promise<void> {
|
|
168
|
+
const storedTokens: StoredTokens = {
|
|
169
|
+
accessToken: tokens.access_token,
|
|
170
|
+
refreshToken: tokens.refresh_token,
|
|
171
|
+
expiresAt: tokens.expires_in ? Date.now() / 1000 + tokens.expires_in : undefined,
|
|
172
|
+
scope: tokens.scope,
|
|
173
|
+
}
|
|
174
|
+
updateTokens(this.serverName, storedTokens, this.serverUrl)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Redirect the user to the authorization URL.
|
|
179
|
+
* This opens the browser for the user to authenticate.
|
|
180
|
+
*/
|
|
181
|
+
async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
|
|
182
|
+
if (this.usesClientCredentials) {
|
|
183
|
+
throw new Error("redirectToAuthorization is not used for client_credentials flow")
|
|
184
|
+
}
|
|
185
|
+
// URL is passed to callback, not logged (may contain sensitive params)
|
|
186
|
+
await this.callbacks.onRedirect(authorizationUrl)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Save the PKCE code verifier.
|
|
191
|
+
*/
|
|
192
|
+
async saveCodeVerifier(codeVerifier: string): Promise<void> {
|
|
193
|
+
updateCodeVerifier(this.serverName, codeVerifier)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Get the stored PKCE code verifier.
|
|
198
|
+
* @throws Error if no code verifier is stored
|
|
199
|
+
*/
|
|
200
|
+
async codeVerifier(): Promise<string> {
|
|
201
|
+
if (this.usesClientCredentials) {
|
|
202
|
+
throw new Error("codeVerifier is not used for client_credentials flow")
|
|
203
|
+
}
|
|
204
|
+
const entry = await getAuthEntry(this.serverName)
|
|
205
|
+
if (!entry?.codeVerifier) {
|
|
206
|
+
throw new Error(`No code verifier saved for MCP server: ${this.serverName}`)
|
|
207
|
+
}
|
|
208
|
+
return entry.codeVerifier
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Save the OAuth state parameter for CSRF protection.
|
|
213
|
+
*/
|
|
214
|
+
async saveState(state: string): Promise<void> {
|
|
215
|
+
updateOAuthState(this.serverName, state)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Get the stored OAuth state parameter.
|
|
220
|
+
* @throws Error if no state is stored
|
|
221
|
+
*/
|
|
222
|
+
async state(): Promise<string> {
|
|
223
|
+
if (this.usesClientCredentials) {
|
|
224
|
+
throw new Error("state is not used for client_credentials flow")
|
|
225
|
+
}
|
|
226
|
+
const entry = await getAuthEntry(this.serverName)
|
|
227
|
+
if (!entry?.oauthState) {
|
|
228
|
+
throw new Error(`No OAuth state saved for MCP server: ${this.serverName}`)
|
|
229
|
+
}
|
|
230
|
+
return entry.oauthState
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Invalidate credentials when authentication fails.
|
|
235
|
+
* Clears tokens, client info, or all credentials based on the type.
|
|
236
|
+
*/
|
|
237
|
+
async invalidateCredentials(type: "all" | "client" | "tokens"): Promise<void> {
|
|
238
|
+
switch (type) {
|
|
239
|
+
case "all":
|
|
240
|
+
clearAllCredentials(this.serverName)
|
|
241
|
+
break
|
|
242
|
+
case "client":
|
|
243
|
+
clearClientInfo(this.serverName)
|
|
244
|
+
break
|
|
245
|
+
case "tokens":
|
|
246
|
+
clearTokens(this.serverName)
|
|
247
|
+
break
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
prepareTokenRequest(scope?: string): URLSearchParams | undefined {
|
|
252
|
+
if (!this.usesClientCredentials) {
|
|
253
|
+
return undefined
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const params = new URLSearchParams({ grant_type: "client_credentials" })
|
|
257
|
+
const requestedScope = scope ?? this.config.scope
|
|
258
|
+
if (requestedScope) {
|
|
259
|
+
params.set("scope", requestedScope)
|
|
260
|
+
}
|
|
261
|
+
return params
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export { OAUTH_CALLBACK_PORT, OAUTH_CALLBACK_PATH }
|
package/package.json
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-adapter",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.3",
|
|
4
4
|
"description": "MCP (Model Context Protocol) adapter extension for Pi coding agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Nico Bailon",
|
|
8
8
|
"bin": {
|
|
9
|
-
"pi-mcp-adapter": "
|
|
9
|
+
"pi-mcp-adapter": "cli.js"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "vitest run",
|
|
13
|
+
"test:watch": "vitest",
|
|
14
|
+
"test:coverage": "vitest run --coverage"
|
|
10
15
|
},
|
|
11
16
|
"repository": {
|
|
12
17
|
"type": "git",
|
|
13
|
-
"url": "https://github.com/nicobailon/pi-mcp-adapter"
|
|
18
|
+
"url": "git+https://github.com/nicobailon/pi-mcp-adapter.git"
|
|
14
19
|
},
|
|
15
20
|
"keywords": [
|
|
16
21
|
"pi-package",
|
|
@@ -23,11 +28,6 @@
|
|
|
23
28
|
"claude",
|
|
24
29
|
"llm"
|
|
25
30
|
],
|
|
26
|
-
"scripts": {
|
|
27
|
-
"test": "vitest run",
|
|
28
|
-
"test:watch": "vitest",
|
|
29
|
-
"test:coverage": "vitest run --coverage"
|
|
30
|
-
},
|
|
31
31
|
"pi": {
|
|
32
32
|
"extensions": [
|
|
33
33
|
"./index.ts"
|
|
@@ -60,6 +60,10 @@
|
|
|
60
60
|
"glimpse-ui.ts",
|
|
61
61
|
"npx-resolver.ts",
|
|
62
62
|
"oauth-handler.ts",
|
|
63
|
+
"mcp-auth.ts",
|
|
64
|
+
"mcp-oauth-provider.ts",
|
|
65
|
+
"mcp-callback-server.ts",
|
|
66
|
+
"mcp-auth-flow.ts",
|
|
63
67
|
"mcp-panel.ts",
|
|
64
68
|
"logger.ts",
|
|
65
69
|
"errors.ts",
|
|
@@ -72,13 +76,17 @@
|
|
|
72
76
|
"@modelcontextprotocol/ext-apps": "^1.2.2",
|
|
73
77
|
"@modelcontextprotocol/sdk": "^1.25.1",
|
|
74
78
|
"@sinclair/typebox": "^0.32.0",
|
|
79
|
+
"open": "^10.2.0",
|
|
75
80
|
"zod": "^3.25.0 || ^4.0.0"
|
|
76
81
|
},
|
|
77
82
|
"peerDependencies": {
|
|
78
83
|
"zod": "^3.25.0 || ^4.0.0"
|
|
79
84
|
},
|
|
80
85
|
"devDependencies": {
|
|
86
|
+
"@types/bun": "^1.0.0",
|
|
81
87
|
"@types/node": "^20.0.0",
|
|
88
|
+
"@types/open": "^6.2.1",
|
|
89
|
+
"tsx": "^4.21.0",
|
|
82
90
|
"typescript": "^5.0.0",
|
|
83
91
|
"vitest": "^3.0.0"
|
|
84
92
|
}
|
package/proxy-modes.ts
CHANGED
|
@@ -99,6 +99,8 @@ export function executeStatus(state: McpExtensionState): ProxyToolResult {
|
|
|
99
99
|
let status = "not connected";
|
|
100
100
|
if (connection?.status === "connected") {
|
|
101
101
|
status = "connected";
|
|
102
|
+
} else if (connection?.status === "needs-auth") {
|
|
103
|
+
status = "needs-auth";
|
|
102
104
|
} else if (failedAgo !== null) {
|
|
103
105
|
status = "failed";
|
|
104
106
|
} else if (metadata !== undefined) {
|
|
@@ -117,6 +119,10 @@ export function executeStatus(state: McpExtensionState): ProxyToolResult {
|
|
|
117
119
|
text += `✓ ${server.name} (${server.toolCount} tools)\n`;
|
|
118
120
|
continue;
|
|
119
121
|
}
|
|
122
|
+
if (server.status === "needs-auth") {
|
|
123
|
+
text += `⚠ ${server.name} (needs auth)\n`;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
120
126
|
if (server.status === "cached") {
|
|
121
127
|
text += `○ ${server.name} (${server.toolCount} tools, cached)\n`;
|
|
122
128
|
continue;
|
|
@@ -371,6 +377,12 @@ export async function executeConnect(state: McpExtensionState, serverName: strin
|
|
|
371
377
|
state.ui.setStatus("mcp", `MCP: connecting to ${serverName}...`);
|
|
372
378
|
}
|
|
373
379
|
const connection = await state.manager.connect(serverName, definition);
|
|
380
|
+
if (connection.status === "needs-auth") {
|
|
381
|
+
return {
|
|
382
|
+
content: [{ type: "text" as const, text: `Server "${serverName}" requires OAuth authentication. Run /mcp-auth ${serverName} first.` }],
|
|
383
|
+
details: { mode: "connect", error: "auth_required", server: serverName },
|
|
384
|
+
};
|
|
385
|
+
}
|
|
374
386
|
const prefix = state.config.settings?.toolPrefix ?? "server";
|
|
375
387
|
const { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix);
|
|
376
388
|
state.toolMetadata.set(serverName, metadata);
|
|
@@ -424,6 +436,13 @@ export async function executeCall(
|
|
|
424
436
|
if (connected) {
|
|
425
437
|
toolMeta = findToolByName(state.toolMetadata.get(serverName), toolName);
|
|
426
438
|
} else {
|
|
439
|
+
const needsAuthConnection = state.manager.getConnection(serverName);
|
|
440
|
+
if (needsAuthConnection?.status === "needs-auth") {
|
|
441
|
+
return {
|
|
442
|
+
content: [{ type: "text" as const, text: `Server "${serverName}" requires OAuth authentication. Run /mcp-auth ${serverName} first.` }],
|
|
443
|
+
details: { mode: "call", error: "auth_required", server: serverName },
|
|
444
|
+
};
|
|
445
|
+
}
|
|
427
446
|
const failedAgo = getFailureAgeSeconds(state, serverName);
|
|
428
447
|
if (failedAgo !== null) {
|
|
429
448
|
return {
|
|
@@ -472,6 +491,12 @@ export async function executeCall(
|
|
|
472
491
|
}
|
|
473
492
|
|
|
474
493
|
let connection = state.manager.getConnection(serverName);
|
|
494
|
+
if (connection?.status === "needs-auth") {
|
|
495
|
+
return {
|
|
496
|
+
content: [{ type: "text" as const, text: `Server "${serverName}" requires OAuth authentication. Run /mcp-auth ${serverName} first.` }],
|
|
497
|
+
details: { mode: "call", error: "auth_required", server: serverName },
|
|
498
|
+
};
|
|
499
|
+
}
|
|
475
500
|
if (!connection || connection.status !== "connected") {
|
|
476
501
|
const failedAgo = getFailureAgeSeconds(state, serverName);
|
|
477
502
|
if (failedAgo !== null) {
|
|
@@ -494,6 +519,12 @@ export async function executeCall(
|
|
|
494
519
|
state.ui.setStatus("mcp", `MCP: connecting to ${serverName}...`);
|
|
495
520
|
}
|
|
496
521
|
connection = await state.manager.connect(serverName, definition);
|
|
522
|
+
if (connection.status === "needs-auth") {
|
|
523
|
+
return {
|
|
524
|
+
content: [{ type: "text" as const, text: `Server "${serverName}" requires OAuth authentication. Run /mcp-auth ${serverName} first.` }],
|
|
525
|
+
details: { mode: "call", error: "auth_required", server: serverName },
|
|
526
|
+
};
|
|
527
|
+
}
|
|
497
528
|
state.failureTracker.delete(serverName);
|
|
498
529
|
updateServerMetadata(state, serverName);
|
|
499
530
|
updateMetadataCache(state, serverName);
|
package/server-manager.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
|
2
2
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
3
3
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
4
4
|
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
5
|
+
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
5
6
|
import type { ReadResourceResult } from "@modelcontextprotocol/sdk/types.js";
|
|
6
7
|
import type {
|
|
7
8
|
McpTool,
|
|
@@ -11,9 +12,10 @@ import type {
|
|
|
11
12
|
Transport,
|
|
12
13
|
} from "./types.js";
|
|
13
14
|
import { serverStreamResultPatchNotificationSchema } from "./types.js";
|
|
14
|
-
import { getStoredTokens } from "./oauth-handler.js";
|
|
15
15
|
import { resolveNpxBinary } from "./npx-resolver.js";
|
|
16
16
|
import { logger } from "./logger.js";
|
|
17
|
+
import { McpOAuthProvider } from "./mcp-oauth-provider.js";
|
|
18
|
+
import { supportsOAuth } from "./mcp-auth-flow.js";
|
|
17
19
|
|
|
18
20
|
interface ServerConnection {
|
|
19
21
|
client: Client;
|
|
@@ -23,7 +25,7 @@ interface ServerConnection {
|
|
|
23
25
|
resources: McpResource[];
|
|
24
26
|
lastUsedAt: number;
|
|
25
27
|
inFlight: number;
|
|
26
|
-
status: "connected" | "closed";
|
|
28
|
+
status: "connected" | "closed" | "needs-auth";
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
type UiStreamListener = (serverName: string, notification: ServerStreamResultPatchNotification["params"]) => void;
|
|
@@ -96,7 +98,7 @@ export class McpServerManager {
|
|
|
96
98
|
try {
|
|
97
99
|
await client.connect(transport);
|
|
98
100
|
this.attachAdapterNotificationHandlers(name, client);
|
|
99
|
-
|
|
101
|
+
|
|
100
102
|
// Discover tools and resources
|
|
101
103
|
const [tools, resources] = await Promise.all([
|
|
102
104
|
this.fetchAllTools(client),
|
|
@@ -114,6 +116,24 @@ export class McpServerManager {
|
|
|
114
116
|
status: "connected",
|
|
115
117
|
};
|
|
116
118
|
} catch (error) {
|
|
119
|
+
// Check for UnauthorizedError - server requires OAuth
|
|
120
|
+
if (error instanceof UnauthorizedError && supportsOAuth(definition)) {
|
|
121
|
+
// Clean up both client and transport before reporting needs-auth.
|
|
122
|
+
await client.close().catch(() => {});
|
|
123
|
+
await transport.close().catch(() => {});
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
client,
|
|
127
|
+
transport,
|
|
128
|
+
definition,
|
|
129
|
+
tools: [],
|
|
130
|
+
resources: [],
|
|
131
|
+
lastUsedAt: Date.now(),
|
|
132
|
+
inFlight: 0,
|
|
133
|
+
status: "needs-auth",
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
117
137
|
// Clean up both client and transport on any error
|
|
118
138
|
await client.close().catch(() => {});
|
|
119
139
|
await transport.close().catch(() => {});
|
|
@@ -121,11 +141,16 @@ export class McpServerManager {
|
|
|
121
141
|
}
|
|
122
142
|
}
|
|
123
143
|
|
|
124
|
-
private async createHttpTransport(
|
|
144
|
+
private async createHttpTransport(
|
|
145
|
+
definition: ServerDefinition,
|
|
146
|
+
serverName: string
|
|
147
|
+
): Promise<Transport> {
|
|
125
148
|
const url = new URL(definition.url!);
|
|
149
|
+
|
|
150
|
+
// Build headers first (including any bearer token)
|
|
126
151
|
const headers = resolveHeaders(definition.headers) ?? {};
|
|
127
152
|
|
|
128
|
-
//
|
|
153
|
+
// For bearer auth, add the token to headers BEFORE creating requestInit
|
|
129
154
|
if (definition.auth === "bearer") {
|
|
130
155
|
const token = definition.bearerToken
|
|
131
156
|
?? (definition.bearerTokenEnv ? process.env[definition.bearerTokenEnv] : undefined);
|
|
@@ -134,41 +159,58 @@ export class McpServerManager {
|
|
|
134
159
|
}
|
|
135
160
|
}
|
|
136
161
|
|
|
137
|
-
//
|
|
138
|
-
if (definition.auth === "oauth") {
|
|
139
|
-
if (!serverName) {
|
|
140
|
-
throw new Error("Server name required for OAuth authentication");
|
|
141
|
-
}
|
|
142
|
-
const tokens = getStoredTokens(serverName);
|
|
143
|
-
if (!tokens) {
|
|
144
|
-
throw new Error(
|
|
145
|
-
`No OAuth tokens found for "${serverName}". Run /mcp-auth ${serverName} to authenticate.`
|
|
146
|
-
);
|
|
147
|
-
}
|
|
148
|
-
headers["Authorization"] = `Bearer ${tokens.access_token}`;
|
|
149
|
-
}
|
|
150
|
-
|
|
162
|
+
// Create request init with headers (Authorization now included for bearer auth)
|
|
151
163
|
const requestInit = Object.keys(headers).length > 0 ? { headers } : undefined;
|
|
152
164
|
|
|
165
|
+
// For OAuth servers, create an auth provider
|
|
166
|
+
let authProvider: McpOAuthProvider | undefined;
|
|
167
|
+
if (supportsOAuth(definition)) {
|
|
168
|
+
// Extract OAuth config (handles both object and false cases)
|
|
169
|
+
const oauthConfig = definition.oauth === false ? {} : {
|
|
170
|
+
grantType: definition.oauth?.grantType,
|
|
171
|
+
clientId: definition.oauth?.clientId,
|
|
172
|
+
clientSecret: definition.oauth?.clientSecret,
|
|
173
|
+
scope: definition.oauth?.scope,
|
|
174
|
+
};
|
|
175
|
+
authProvider = new McpOAuthProvider(
|
|
176
|
+
serverName,
|
|
177
|
+
definition.url!,
|
|
178
|
+
oauthConfig,
|
|
179
|
+
{
|
|
180
|
+
onRedirect: async (_authUrl) => {
|
|
181
|
+
// URL is captured by startAuth, no need to log
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
153
187
|
// Try StreamableHTTP first (modern MCP servers)
|
|
154
|
-
const streamableTransport = new StreamableHTTPClientTransport(url, {
|
|
188
|
+
const streamableTransport = new StreamableHTTPClientTransport(url, {
|
|
189
|
+
requestInit,
|
|
190
|
+
authProvider,
|
|
191
|
+
});
|
|
155
192
|
|
|
156
193
|
try {
|
|
157
194
|
// Create a test client to verify the transport works
|
|
158
|
-
const testClient = new Client({ name: "pi-mcp-probe", version: "1.
|
|
195
|
+
const testClient = new Client({ name: "pi-mcp-probe", version: "2.1.2" });
|
|
159
196
|
await testClient.connect(streamableTransport);
|
|
160
197
|
await testClient.close().catch(() => {});
|
|
161
198
|
// Close probe transport before creating fresh one
|
|
162
199
|
await streamableTransport.close().catch(() => {});
|
|
163
200
|
|
|
164
201
|
// StreamableHTTP works - create fresh transport for actual use
|
|
165
|
-
return new StreamableHTTPClientTransport(url, { requestInit });
|
|
166
|
-
} catch {
|
|
202
|
+
return new StreamableHTTPClientTransport(url, { requestInit, authProvider });
|
|
203
|
+
} catch (error) {
|
|
167
204
|
// StreamableHTTP failed, close and try SSE fallback
|
|
168
205
|
await streamableTransport.close().catch(() => {});
|
|
169
206
|
|
|
207
|
+
// If this was an UnauthorizedError, don't try SSE - the server needs auth
|
|
208
|
+
if (error instanceof UnauthorizedError) {
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
|
|
170
212
|
// SSE is the legacy transport
|
|
171
|
-
return new SSEClientTransport(url, { requestInit });
|
|
213
|
+
return new SSEClientTransport(url, { requestInit, authProvider });
|
|
172
214
|
}
|
|
173
215
|
}
|
|
174
216
|
|
package/types.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdi
|
|
|
3
3
|
import type { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
4
4
|
import type { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
5
|
import type { TextContent, ImageContent } from "@mariozechner/pi-ai";
|
|
6
|
+
import type { UiStreamMode } from "./ui-stream-types.js";
|
|
6
7
|
|
|
7
8
|
// Transport type (stdio + HTTP)
|
|
8
9
|
export type Transport =
|
|
@@ -261,6 +262,18 @@ export interface McpContent {
|
|
|
261
262
|
// Pi content block type
|
|
262
263
|
export type ContentBlock = TextContent | ImageContent;
|
|
263
264
|
|
|
265
|
+
// OAuth configuration (SDK handles auto-discovery and dynamic registration)
|
|
266
|
+
export interface OAuthConfig {
|
|
267
|
+
/** OAuth grant type (defaults to authorization_code) */
|
|
268
|
+
grantType?: "authorization_code" | "client_credentials";
|
|
269
|
+
/** Pre-registered client ID (optional, dynamic registration used if not provided) */
|
|
270
|
+
clientId?: string;
|
|
271
|
+
/** Client secret for confidential clients */
|
|
272
|
+
clientSecret?: string;
|
|
273
|
+
/** Requested OAuth scopes */
|
|
274
|
+
scope?: string;
|
|
275
|
+
}
|
|
276
|
+
|
|
264
277
|
// Server configuration
|
|
265
278
|
export interface ServerEntry {
|
|
266
279
|
command?: string;
|
|
@@ -270,9 +283,22 @@ export interface ServerEntry {
|
|
|
270
283
|
// HTTP fields
|
|
271
284
|
url?: string;
|
|
272
285
|
headers?: Record<string, string>;
|
|
273
|
-
|
|
286
|
+
/**
|
|
287
|
+
* Authentication type:
|
|
288
|
+
* - 'oauth' - Use OAuth 2.1 (auto-discovers endpoints, supports dynamic client registration)
|
|
289
|
+
* - 'bearer' - Use static Bearer token
|
|
290
|
+
* - false - Disable authentication
|
|
291
|
+
* If not specified and url is present, OAuth will be auto-detected
|
|
292
|
+
*/
|
|
293
|
+
auth?: "oauth" | "bearer" | false;
|
|
274
294
|
bearerToken?: string;
|
|
275
295
|
bearerTokenEnv?: string;
|
|
296
|
+
/**
|
|
297
|
+
* OAuth configuration (optional).
|
|
298
|
+
* If not provided, the SDK will attempt dynamic client registration.
|
|
299
|
+
* Set to false to explicitly disable OAuth for this server.
|
|
300
|
+
*/
|
|
301
|
+
oauth?: OAuthConfig | false;
|
|
276
302
|
lifecycle?: "keep-alive" | "lazy" | "eager";
|
|
277
303
|
idleTimeout?: number; // minutes, overrides global setting
|
|
278
304
|
// Resource handling
|