pi-mcp-adapter 2.2.1 → 2.3.2
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 +36 -0
- package/README.md +1 -2
- package/commands.ts +48 -20
- package/direct-tools.ts +11 -3
- package/index.ts +96 -38
- package/init.ts +19 -3
- 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 +14 -6
- package/proxy-modes.ts +31 -0
- package/server-manager.ts +66 -24
- package/types.ts +27 -1
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP OAuth Callback Server
|
|
3
|
+
*
|
|
4
|
+
* HTTP server that handles OAuth callbacks from the authorization server.
|
|
5
|
+
* Uses Node.js http module for compatibility.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { createServer, type Server, type IncomingMessage, type ServerResponse } from "http"
|
|
9
|
+
import { connect } from "net"
|
|
10
|
+
import { OAUTH_CALLBACK_PORT, OAUTH_CALLBACK_PATH } from "./mcp-oauth-provider.js"
|
|
11
|
+
|
|
12
|
+
// HTML templates for callback responses
|
|
13
|
+
const HTML_SUCCESS = `<!DOCTYPE html>
|
|
14
|
+
<html>
|
|
15
|
+
<head>
|
|
16
|
+
<title>Pi - Authorization Successful</title>
|
|
17
|
+
<style>
|
|
18
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
19
|
+
.container { text-align: center; padding: 2rem; }
|
|
20
|
+
h1 { color: #4ade80; margin-bottom: 1rem; }
|
|
21
|
+
p { color: #aaa; }
|
|
22
|
+
</style>
|
|
23
|
+
</head>
|
|
24
|
+
<body>
|
|
25
|
+
<div class="container">
|
|
26
|
+
<h1>Authorization Successful</h1>
|
|
27
|
+
<p>You can close this window and return to Pi.</p>
|
|
28
|
+
</div>
|
|
29
|
+
<script>setTimeout(() => window.close(), 2000);</script>
|
|
30
|
+
</body>
|
|
31
|
+
</html>`
|
|
32
|
+
|
|
33
|
+
const HTML_ERROR = (error: string) => `<!DOCTYPE html>
|
|
34
|
+
<html>
|
|
35
|
+
<head>
|
|
36
|
+
<title>Pi - Authorization Failed</title>
|
|
37
|
+
<style>
|
|
38
|
+
body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
|
|
39
|
+
.container { text-align: center; padding: 2rem; }
|
|
40
|
+
h1 { color: #f87171; margin-bottom: 1rem; }
|
|
41
|
+
p { color: #aaa; }
|
|
42
|
+
.error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
|
|
43
|
+
</style>
|
|
44
|
+
</head>
|
|
45
|
+
<body>
|
|
46
|
+
<div class="container">
|
|
47
|
+
<h1>Authorization Failed</h1>
|
|
48
|
+
<p>An error occurred during authorization.</p>
|
|
49
|
+
<div class="error">${error}</div>
|
|
50
|
+
</div>
|
|
51
|
+
</body>
|
|
52
|
+
</html>`
|
|
53
|
+
|
|
54
|
+
/** Pending authorization request */
|
|
55
|
+
interface PendingAuth {
|
|
56
|
+
resolve: (code: string) => void
|
|
57
|
+
reject: (error: Error) => void
|
|
58
|
+
timeout: ReturnType<typeof setTimeout>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Server singleton state */
|
|
62
|
+
let server: Server | undefined
|
|
63
|
+
const pendingAuths = new Map<string, PendingAuth>()
|
|
64
|
+
|
|
65
|
+
/** Timeout for callback completion (5 minutes) */
|
|
66
|
+
const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Check if the callback port is already in use.
|
|
70
|
+
* Used to detect if another instance is running the server.
|
|
71
|
+
*/
|
|
72
|
+
async function isPortInUse(): Promise<boolean> {
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
const socket = connect({ host: "127.0.0.1", port: OAUTH_CALLBACK_PORT })
|
|
75
|
+
socket.setTimeout(1000)
|
|
76
|
+
|
|
77
|
+
socket.on("connect", () => {
|
|
78
|
+
socket.end()
|
|
79
|
+
resolve(true)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
socket.on("error", () => {
|
|
83
|
+
resolve(false)
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
socket.on("timeout", () => {
|
|
87
|
+
socket.destroy()
|
|
88
|
+
resolve(false)
|
|
89
|
+
})
|
|
90
|
+
})
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Handle incoming HTTP requests to the callback server.
|
|
95
|
+
*/
|
|
96
|
+
function handleRequest(req: IncomingMessage, res: ServerResponse): void {
|
|
97
|
+
const url = new URL(req.url || "/", `http://${req.headers.host}`)
|
|
98
|
+
|
|
99
|
+
// Only handle the callback path
|
|
100
|
+
if (url.pathname !== OAUTH_CALLBACK_PATH) {
|
|
101
|
+
res.writeHead(404, { "Content-Type": "text/plain" })
|
|
102
|
+
res.end("Not found")
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const code = url.searchParams.get("code")
|
|
107
|
+
const state = url.searchParams.get("state")
|
|
108
|
+
const error = url.searchParams.get("error")
|
|
109
|
+
const errorDescription = url.searchParams.get("error_description")
|
|
110
|
+
|
|
111
|
+
// Enforce state parameter presence for CSRF protection
|
|
112
|
+
if (!state) {
|
|
113
|
+
const errorMsg = "Missing required state parameter - potential CSRF attack"
|
|
114
|
+
res.writeHead(400, { "Content-Type": "text/html" })
|
|
115
|
+
res.end(HTML_ERROR(errorMsg))
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Handle OAuth errors
|
|
120
|
+
if (error) {
|
|
121
|
+
const errorMsg = errorDescription || error
|
|
122
|
+
// Send HTTP response first before rejecting promise
|
|
123
|
+
res.writeHead(200, { "Content-Type": "text/html" })
|
|
124
|
+
res.end(HTML_ERROR(errorMsg))
|
|
125
|
+
// Reject promise after response is sent (defer to allow test to attach handler)
|
|
126
|
+
if (pendingAuths.has(state)) {
|
|
127
|
+
const pending = pendingAuths.get(state)!
|
|
128
|
+
clearTimeout(pending.timeout)
|
|
129
|
+
pendingAuths.delete(state)
|
|
130
|
+
setTimeout(() => pending.reject(new Error(errorMsg)), 0)
|
|
131
|
+
}
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Require authorization code
|
|
136
|
+
if (!code) {
|
|
137
|
+
res.writeHead(400, { "Content-Type": "text/html" })
|
|
138
|
+
res.end(HTML_ERROR("No authorization code provided"))
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Validate state parameter
|
|
143
|
+
if (!pendingAuths.has(state)) {
|
|
144
|
+
const errorMsg = "Invalid or expired state parameter - potential CSRF attack"
|
|
145
|
+
res.writeHead(400, { "Content-Type": "text/html" })
|
|
146
|
+
res.end(HTML_ERROR(errorMsg))
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const pending = pendingAuths.get(state)!
|
|
151
|
+
|
|
152
|
+
// Clear timeout and resolve the pending promise
|
|
153
|
+
clearTimeout(pending.timeout)
|
|
154
|
+
pendingAuths.delete(state)
|
|
155
|
+
pending.resolve(code)
|
|
156
|
+
|
|
157
|
+
res.writeHead(200, { "Content-Type": "text/html" })
|
|
158
|
+
res.end(HTML_SUCCESS)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Ensure the callback server is running.
|
|
163
|
+
* If the port is in use by another process, fail fast with a clear error.
|
|
164
|
+
*/
|
|
165
|
+
export async function ensureCallbackServer(): Promise<void> {
|
|
166
|
+
if (server) return
|
|
167
|
+
|
|
168
|
+
const running = await isPortInUse()
|
|
169
|
+
if (running) {
|
|
170
|
+
throw new Error(`OAuth callback port ${OAUTH_CALLBACK_PORT} is already in use`)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
server = createServer(handleRequest)
|
|
174
|
+
|
|
175
|
+
await new Promise<void>((resolve, reject) => {
|
|
176
|
+
server!.once("error", (err) => {
|
|
177
|
+
reject(err)
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
server!.listen(OAUTH_CALLBACK_PORT, "127.0.0.1", () => {
|
|
181
|
+
resolve()
|
|
182
|
+
})
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Wait for a callback with the given OAuth state.
|
|
188
|
+
* Returns a promise that resolves with the authorization code.
|
|
189
|
+
*/
|
|
190
|
+
export function waitForCallback(oauthState: string): Promise<string> {
|
|
191
|
+
return new Promise((resolve, reject) => {
|
|
192
|
+
const timeout = setTimeout(() => {
|
|
193
|
+
if (pendingAuths.has(oauthState)) {
|
|
194
|
+
pendingAuths.delete(oauthState)
|
|
195
|
+
reject(new Error("OAuth callback timeout - authorization took too long"))
|
|
196
|
+
}
|
|
197
|
+
}, CALLBACK_TIMEOUT_MS)
|
|
198
|
+
|
|
199
|
+
pendingAuths.set(oauthState, { resolve, reject, timeout })
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Cancel a pending authorization by state.
|
|
205
|
+
*/
|
|
206
|
+
export function cancelPendingCallback(oauthState: string): void {
|
|
207
|
+
const pending = pendingAuths.get(oauthState)
|
|
208
|
+
if (pending) {
|
|
209
|
+
clearTimeout(pending.timeout)
|
|
210
|
+
pendingAuths.delete(oauthState)
|
|
211
|
+
pending.reject(new Error("Authorization cancelled"))
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Stop the callback server and reject all pending authorizations.
|
|
217
|
+
*/
|
|
218
|
+
export async function stopCallbackServer(): Promise<void> {
|
|
219
|
+
if (server) {
|
|
220
|
+
await new Promise<void>((resolve) => {
|
|
221
|
+
server!.close(() => {
|
|
222
|
+
resolve()
|
|
223
|
+
})
|
|
224
|
+
})
|
|
225
|
+
server = undefined
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Reject all pending auths (defer to allow any pending operations to complete)
|
|
229
|
+
const pendingList = Array.from(pendingAuths.entries())
|
|
230
|
+
pendingAuths.clear()
|
|
231
|
+
setTimeout(() => {
|
|
232
|
+
for (const [state, pending] of pendingList) {
|
|
233
|
+
clearTimeout(pending.timeout)
|
|
234
|
+
pending.reject(new Error("OAuth callback server stopped"))
|
|
235
|
+
}
|
|
236
|
+
}, 0)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Check if the callback server is running.
|
|
241
|
+
*/
|
|
242
|
+
export function isCallbackServerRunning(): boolean {
|
|
243
|
+
return server !== undefined
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Get the number of pending authorizations.
|
|
248
|
+
*/
|
|
249
|
+
export function getPendingAuthCount(): number {
|
|
250
|
+
return pendingAuths.size
|
|
251
|
+
}
|
|
@@ -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,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-adapter",
|
|
3
|
-
"version": "2.2
|
|
3
|
+
"version": "2.3.2",
|
|
4
4
|
"description": "MCP (Model Context Protocol) adapter extension for Pi coding agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
"bin": {
|
|
9
9
|
"pi-mcp-adapter": "./cli.js"
|
|
10
10
|
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "vitest run",
|
|
13
|
+
"test:watch": "vitest",
|
|
14
|
+
"test:coverage": "vitest run --coverage"
|
|
15
|
+
},
|
|
11
16
|
"repository": {
|
|
12
17
|
"type": "git",
|
|
13
18
|
"url": "https://github.com/nicobailon/pi-mcp-adapter"
|
|
@@ -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);
|