pi-soly 1.9.3 → 1.11.0

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.
Files changed (104) hide show
  1. package/ask/index.ts +12 -11
  2. package/ask/picker.ts +356 -76
  3. package/ask/prompt.ts +6 -2
  4. package/ask/tests/picker.test.ts +273 -82
  5. package/codemap.ts +276 -0
  6. package/hotreload.ts +239 -0
  7. package/init.ts +302 -0
  8. package/mcp/CHANGELOG.md +384 -0
  9. package/mcp/LICENSE +21 -0
  10. package/mcp/OAUTH.md +355 -0
  11. package/mcp/README.md +410 -0
  12. package/mcp/__tests__/agent-dir-paths.upstream-test.ts +80 -0
  13. package/mcp/__tests__/cli.upstream-test.ts +97 -0
  14. package/mcp/__tests__/commands-onboarding.upstream-test.ts +157 -0
  15. package/mcp/__tests__/config.upstream-test.ts +303 -0
  16. package/mcp/__tests__/consent-manager.upstream-test.ts +151 -0
  17. package/mcp/__tests__/direct-tools-auto-auth.upstream-test.ts +218 -0
  18. package/mcp/__tests__/direct-tools.upstream-test.ts +299 -0
  19. package/mcp/__tests__/elicitation-handler.upstream-test.ts +346 -0
  20. package/mcp/__tests__/elicitation-sdk-integration.upstream-test.ts +140 -0
  21. package/mcp/__tests__/errors.upstream-test.ts +218 -0
  22. package/mcp/__tests__/fixtures/elicitation-server.mjs +98 -0
  23. package/mcp/__tests__/host-html-template.upstream-test.ts +278 -0
  24. package/mcp/__tests__/index-lifecycle.upstream-test.ts +484 -0
  25. package/mcp/__tests__/init-elicitation.upstream-test.ts +86 -0
  26. package/mcp/__tests__/interactive-visualizer-server.upstream-test.ts +28 -0
  27. package/mcp/__tests__/logger.upstream-test.ts +175 -0
  28. package/mcp/__tests__/mcp-auth-flow-client-credentials.upstream-test.ts +612 -0
  29. package/mcp/__tests__/mcp-auth-storage.upstream-test.ts +47 -0
  30. package/mcp/__tests__/mcp-callback-server-unref.upstream-test.ts +264 -0
  31. package/mcp/__tests__/mcp-oauth-provider.upstream-test.ts +216 -0
  32. package/mcp/__tests__/mcp-panel-auth.upstream-test.ts +206 -0
  33. package/mcp/__tests__/mcp-panel-exclude-tools.upstream-test.ts +69 -0
  34. package/mcp/__tests__/mcp-panel-keybindings.upstream-test.ts +186 -0
  35. package/mcp/__tests__/npx-resolver.upstream-test.ts +54 -0
  36. package/mcp/__tests__/oauth-handler.upstream-test.ts +77 -0
  37. package/mcp/__tests__/onboarding-state.upstream-test.ts +52 -0
  38. package/mcp/__tests__/package-manifest.upstream-test.ts +22 -0
  39. package/mcp/__tests__/proxy-modes-auto-auth.upstream-test.ts +253 -0
  40. package/mcp/__tests__/proxy-modes-discovery.upstream-test.ts +84 -0
  41. package/mcp/__tests__/proxy-modes-manual-auth.upstream-test.ts +91 -0
  42. package/mcp/__tests__/proxy-modes-ui-messages.upstream-test.ts +72 -0
  43. package/mcp/__tests__/sampling-handler.upstream-test.ts +285 -0
  44. package/mcp/__tests__/server-manager-http-auth.upstream-test.ts +144 -0
  45. package/mcp/__tests__/server-manager-sampling.upstream-test.ts +236 -0
  46. package/mcp/__tests__/tool-metadata.upstream-test.ts +111 -0
  47. package/mcp/__tests__/tool-result-renderer.upstream-test.ts +147 -0
  48. package/mcp/__tests__/ui-integration.upstream-test.ts +551 -0
  49. package/mcp/__tests__/ui-resource-handler.upstream-test.ts +303 -0
  50. package/mcp/__tests__/ui-server.upstream-test.ts +967 -0
  51. package/mcp/__tests__/ui-session-messages.upstream-test.ts +72 -0
  52. package/mcp/__tests__/ui-streaming.upstream-test.ts +543 -0
  53. package/mcp/agent-dir.ts +20 -0
  54. package/mcp/app-bridge.bundle.js +67 -0
  55. package/mcp/cli.js +184 -0
  56. package/mcp/commands.ts +422 -0
  57. package/mcp/config.ts +666 -0
  58. package/mcp/consent-manager.ts +64 -0
  59. package/mcp/direct-tools.ts +439 -0
  60. package/mcp/elicitation-handler.ts +347 -0
  61. package/mcp/errors.ts +219 -0
  62. package/mcp/glimpse-ui.ts +80 -0
  63. package/mcp/host-html-template.ts +427 -0
  64. package/mcp/index.ts +362 -0
  65. package/mcp/init.ts +362 -0
  66. package/mcp/lifecycle.ts +93 -0
  67. package/mcp/logger.ts +169 -0
  68. package/mcp/mcp-auth-flow.ts +559 -0
  69. package/mcp/mcp-auth-flow.upstream-test.ts +259 -0
  70. package/mcp/mcp-auth.ts +302 -0
  71. package/mcp/mcp-auth.upstream-test.ts +373 -0
  72. package/mcp/mcp-callback-server.ts +372 -0
  73. package/mcp/mcp-callback-server.upstream-test.ts +416 -0
  74. package/mcp/mcp-oauth-provider.ts +369 -0
  75. package/mcp/mcp-oauth-provider.upstream-test.ts +518 -0
  76. package/mcp/mcp-panel.ts +829 -0
  77. package/mcp/mcp-setup-panel.ts +580 -0
  78. package/mcp/metadata-cache.ts +201 -0
  79. package/mcp/notify.ts +111 -0
  80. package/mcp/npx-resolver.ts +424 -0
  81. package/mcp/oauth-handler.ts +57 -0
  82. package/mcp/onboarding-state.ts +68 -0
  83. package/mcp/package.json +106 -0
  84. package/mcp/panel-keys.ts +37 -0
  85. package/mcp/proxy-modes.ts +949 -0
  86. package/mcp/resource-tools.ts +17 -0
  87. package/mcp/sampling-handler.ts +268 -0
  88. package/mcp/server-manager.ts +545 -0
  89. package/mcp/state.ts +41 -0
  90. package/mcp/tool-metadata.ts +216 -0
  91. package/mcp/tool-registrar.ts +46 -0
  92. package/mcp/tool-result-renderer.ts +161 -0
  93. package/mcp/types.ts +448 -0
  94. package/mcp/ui-resource-handler.ts +146 -0
  95. package/mcp/ui-server.ts +623 -0
  96. package/mcp/ui-session.ts +386 -0
  97. package/mcp/ui-stream-types.ts +89 -0
  98. package/mcp/utils.ts +129 -0
  99. package/mcp/vitest.config.ts +14 -0
  100. package/migrate.ts +258 -0
  101. package/notification.ts +218 -0
  102. package/notifications-log.ts +83 -0
  103. package/package.json +20 -3
  104. package/status.ts +140 -0
@@ -0,0 +1,369 @@
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 { AddClientAuthentication, OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"
9
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
10
+ import type {
11
+ OAuthClientMetadata,
12
+ OAuthTokens,
13
+ OAuthClientInformation,
14
+ OAuthClientInformationFull,
15
+ } from "@modelcontextprotocol/sdk/shared/auth.js"
16
+ import {
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.ts"
28
+
29
+ // Callback server configuration
30
+ const DEFAULT_OAUTH_CALLBACK_PORT = 19876
31
+ const DEFAULT_OAUTH_CALLBACK_PATH = "/callback"
32
+
33
+ let configuredOAuthCallbackPort = DEFAULT_OAUTH_CALLBACK_PORT
34
+
35
+ if (process.env.MCP_OAUTH_CALLBACK_PORT) {
36
+ const parsedPort = Number.parseInt(process.env.MCP_OAUTH_CALLBACK_PORT, 10)
37
+ if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) {
38
+ configuredOAuthCallbackPort = parsedPort
39
+ }
40
+ }
41
+
42
+ let oauthCallbackPort = configuredOAuthCallbackPort
43
+ let oauthCallbackPath = DEFAULT_OAUTH_CALLBACK_PATH
44
+
45
+ export function getConfiguredOAuthCallbackPort(): number {
46
+ return configuredOAuthCallbackPort
47
+ }
48
+
49
+ export function getOAuthCallbackPort(): number {
50
+ return oauthCallbackPort
51
+ }
52
+
53
+ export function setOAuthCallbackPort(port: number): void {
54
+ oauthCallbackPort = port
55
+ }
56
+
57
+ export function getOAuthCallbackPath(): string {
58
+ return oauthCallbackPath
59
+ }
60
+
61
+ export function setOAuthCallbackPath(path: string): void {
62
+ oauthCallbackPath = path.startsWith("/") ? path : `/${path}`
63
+ }
64
+
65
+ /** Configuration options for OAuth */
66
+ export interface McpOAuthConfig {
67
+ grantType?: "authorization_code" | "client_credentials"
68
+ clientId?: string
69
+ clientSecret?: string
70
+ scope?: string
71
+ redirectUri?: string
72
+ clientName?: string
73
+ clientUri?: string
74
+ }
75
+
76
+ /** Callbacks for OAuth flow interactions */
77
+ export interface McpOAuthCallbacks {
78
+ onRedirect: (url: URL) => void | Promise<void>
79
+ }
80
+
81
+ /**
82
+ * OAuth provider implementation for MCP servers.
83
+ * Implements the OAuthClientProvider interface from the MCP SDK.
84
+ */
85
+ export class McpOAuthProvider implements OAuthClientProvider {
86
+ private readonly redirectUrlSnapshot: string | undefined
87
+
88
+ constructor(
89
+ private serverName: string,
90
+ private serverUrl: string,
91
+ private config: McpOAuthConfig,
92
+ private callbacks: McpOAuthCallbacks,
93
+ ) {
94
+ this.redirectUrlSnapshot = config.grantType === "client_credentials"
95
+ ? undefined
96
+ : config.redirectUri ?? `http://localhost:${getOAuthCallbackPort()}${getOAuthCallbackPath()}`
97
+ }
98
+
99
+ private get usesClientCredentials(): boolean {
100
+ return this.config.grantType === "client_credentials"
101
+ }
102
+
103
+ /**
104
+ * The redirect URL for OAuth callbacks.
105
+ * This must match the redirect_uri in client metadata.
106
+ */
107
+ get redirectUrl(): string | undefined {
108
+ return this.redirectUrlSnapshot
109
+ }
110
+
111
+ /**
112
+ * Client metadata for dynamic registration.
113
+ * Describes this client to the OAuth authorization server.
114
+ */
115
+ get clientMetadata(): OAuthClientMetadata {
116
+ if (this.usesClientCredentials) {
117
+ return {
118
+ client_name: this.config.clientName ?? "Pi Coding Agent",
119
+ client_uri: this.config.clientUri ?? "https://github.com/nicobailon/pi-mcp-adapter",
120
+ redirect_uris: [],
121
+ grant_types: ["client_credentials"],
122
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
123
+ }
124
+ }
125
+
126
+ const redirectUrl = this.redirectUrl
127
+ if (!redirectUrl) {
128
+ throw new Error("redirectUrl is required for authorization_code flow")
129
+ }
130
+
131
+ return {
132
+ redirect_uris: [redirectUrl],
133
+ client_name: this.config.clientName ?? "Pi Coding Agent",
134
+ client_uri: this.config.clientUri ?? "https://github.com/nicobailon/pi-mcp-adapter",
135
+ grant_types: ["authorization_code", "refresh_token"],
136
+ response_types: ["code"],
137
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
138
+ ...(this.config.scope !== undefined ? { scope: this.config.scope } : {}),
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Get client information (for pre-registered or dynamically registered clients).
144
+ * Returns undefined if no client info exists or if the server URL has changed.
145
+ */
146
+ async clientInformation(): Promise<OAuthClientInformation | undefined> {
147
+ // Check config first (pre-registered client)
148
+ if (this.config.clientId) {
149
+ return {
150
+ client_id: this.config.clientId,
151
+ client_secret: this.config.clientSecret,
152
+ }
153
+ }
154
+
155
+ // Check stored client info (from dynamic registration)
156
+ // Use getAuthForUrl to validate credentials are for the current server URL
157
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl)
158
+ if (entry?.clientInfo) {
159
+ // Check if client secret has expired
160
+ if (entry.clientInfo.clientSecretExpiresAt && entry.clientInfo.clientSecretExpiresAt < Date.now() / 1000) {
161
+ return undefined
162
+ }
163
+ return {
164
+ client_id: entry.clientInfo.clientId,
165
+ client_secret: entry.clientInfo.clientSecret,
166
+ }
167
+ }
168
+
169
+ // No client info or URL changed - will trigger dynamic registration
170
+ return undefined
171
+ }
172
+
173
+ /**
174
+ * Save client information from dynamic registration.
175
+ */
176
+ async saveClientInformation(info: OAuthClientInformationFull): Promise<void> {
177
+ const redirectUris = info.redirect_uris ?? (this.redirectUrl ? [this.redirectUrl] : undefined)
178
+ const clientInfo: StoredClientInfo = {
179
+ clientId: info.client_id,
180
+ clientSecret: info.client_secret,
181
+ clientIdIssuedAt: info.client_id_issued_at,
182
+ clientSecretExpiresAt: info.client_secret_expires_at,
183
+ redirectUris,
184
+ }
185
+ updateClientInfo(this.serverName, clientInfo, this.serverUrl)
186
+ }
187
+
188
+ /**
189
+ * Get stored OAuth tokens.
190
+ * Returns undefined if no tokens exist or if the server URL has changed.
191
+ */
192
+ async tokens(): Promise<OAuthTokens | undefined> {
193
+ // Use getAuthForUrl to validate tokens are for the current server URL
194
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl)
195
+ if (!entry?.tokens) return undefined
196
+
197
+ return {
198
+ access_token: entry.tokens.accessToken,
199
+ token_type: "Bearer",
200
+ refresh_token: entry.tokens.refreshToken,
201
+ expires_in: entry.tokens.expiresAt
202
+ ? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
203
+ : undefined,
204
+ scope: entry.tokens.scope,
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Save OAuth tokens.
210
+ */
211
+ async saveTokens(tokens: OAuthTokens): Promise<void> {
212
+ const storedTokens: StoredTokens = {
213
+ accessToken: tokens.access_token,
214
+ refreshToken: tokens.refresh_token,
215
+ expiresAt: tokens.expires_in ? Date.now() / 1000 + tokens.expires_in : undefined,
216
+ scope: tokens.scope,
217
+ }
218
+ updateTokens(this.serverName, storedTokens, this.serverUrl)
219
+ }
220
+
221
+ /**
222
+ * Redirect the user to the authorization URL.
223
+ * This opens the browser for the user to authenticate.
224
+ *
225
+ * Throws UnauthorizedError when called outside of a user-initiated flow
226
+ * (no oauthState saved by startAuth). That path is reached when the SDK
227
+ * falls through from a failed refresh into a fresh authorization_code
228
+ * flow, which library hosts cannot complete in-process.
229
+ */
230
+ async redirectToAuthorization(authorizationUrl: URL): Promise<void> {
231
+ if (this.usesClientCredentials) {
232
+ throw new Error("redirectToAuthorization is not used for client_credentials flow")
233
+ }
234
+ // No saved oauthState means we're on the post-refresh authorize fallback.
235
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl)
236
+ if (!entry?.oauthState) {
237
+ throw new UnauthorizedError(
238
+ `Re-authentication required for MCP server: ${this.serverName}`,
239
+ )
240
+ }
241
+ // URL is passed to callback, not logged (may contain sensitive params)
242
+ await this.callbacks.onRedirect(authorizationUrl)
243
+ }
244
+
245
+ /**
246
+ * Save the PKCE code verifier.
247
+ */
248
+ async saveCodeVerifier(codeVerifier: string): Promise<void> {
249
+ updateCodeVerifier(this.serverName, codeVerifier, this.serverUrl)
250
+ }
251
+
252
+ /**
253
+ * Get the stored PKCE code verifier.
254
+ * @throws Error if no code verifier is stored
255
+ */
256
+ async codeVerifier(): Promise<string> {
257
+ if (this.usesClientCredentials) {
258
+ throw new Error("codeVerifier is not used for client_credentials flow")
259
+ }
260
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl)
261
+ if (!entry?.codeVerifier) {
262
+ throw new Error(`No code verifier saved for MCP server: ${this.serverName}`)
263
+ }
264
+ return entry.codeVerifier
265
+ }
266
+
267
+ /**
268
+ * Save the OAuth state parameter for CSRF protection.
269
+ */
270
+ async saveState(state: string): Promise<void> {
271
+ updateOAuthState(this.serverName, state, this.serverUrl)
272
+ }
273
+
274
+ /**
275
+ * Get the stored OAuth state parameter.
276
+ * @throws UnauthorizedError if no flow is in progress (see redirectToAuthorization)
277
+ */
278
+ async state(): Promise<string> {
279
+ if (this.usesClientCredentials) {
280
+ throw new Error("state is not used for client_credentials flow")
281
+ }
282
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl)
283
+ if (!entry?.oauthState) {
284
+ throw new UnauthorizedError(
285
+ `Re-authentication required for MCP server: ${this.serverName}`,
286
+ )
287
+ }
288
+ return entry.oauthState
289
+ }
290
+
291
+ /**
292
+ * Invalidate credentials when authentication fails.
293
+ * Clears tokens, client info, or all credentials based on the type.
294
+ */
295
+ async invalidateCredentials(type: "all" | "client" | "tokens"): Promise<void> {
296
+ switch (type) {
297
+ case "all":
298
+ clearAllCredentials(this.serverName)
299
+ break
300
+ case "client":
301
+ clearClientInfo(this.serverName)
302
+ break
303
+ case "tokens":
304
+ clearTokens(this.serverName)
305
+ break
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Adds configured authorization-code scope without replacing the SDK's
311
+ * default token endpoint authentication behavior.
312
+ */
313
+ addClientAuthentication: AddClientAuthentication = async (headers, params, _url, metadata) => {
314
+ if (params.get("grant_type") === "authorization_code" && !params.has("scope") && this.config.scope) {
315
+ params.set("scope", this.config.scope)
316
+ }
317
+
318
+ const clientInfo = await this.clientInformation()
319
+ if (!clientInfo) {
320
+ return
321
+ }
322
+
323
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? []
324
+ const hasClientSecret = clientInfo.client_secret !== undefined
325
+ let authMethod: "client_secret_basic" | "client_secret_post" | "none"
326
+
327
+ if (supportedMethods.length === 0) {
328
+ authMethod = hasClientSecret ? "client_secret_post" : "none"
329
+ } else if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
330
+ authMethod = "client_secret_basic"
331
+ } else if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
332
+ authMethod = "client_secret_post"
333
+ } else if (supportedMethods.includes("none")) {
334
+ authMethod = "none"
335
+ } else {
336
+ authMethod = hasClientSecret ? "client_secret_post" : "none"
337
+ }
338
+
339
+ if (authMethod === "client_secret_basic") {
340
+ if (!clientInfo.client_secret) {
341
+ throw new Error("client_secret_basic authentication requires a client_secret")
342
+ }
343
+ headers.set("Authorization", `Basic ${Buffer.from(`${clientInfo.client_id}:${clientInfo.client_secret}`).toString("base64")}`)
344
+ return
345
+ }
346
+
347
+ if (!params.has("client_id")) {
348
+ params.set("client_id", clientInfo.client_id)
349
+ }
350
+ if (authMethod === "client_secret_post" && clientInfo.client_secret && !params.has("client_secret")) {
351
+ params.set("client_secret", clientInfo.client_secret)
352
+ }
353
+ }
354
+
355
+ prepareTokenRequest(scope?: string): URLSearchParams | undefined {
356
+ if (!this.usesClientCredentials) {
357
+ return undefined
358
+ }
359
+
360
+ const params = new URLSearchParams({ grant_type: "client_credentials" })
361
+ const requestedScope = scope ?? this.config.scope
362
+ if (requestedScope) {
363
+ params.set("scope", requestedScope)
364
+ }
365
+ return params
366
+ }
367
+ }
368
+
369
+ export { DEFAULT_OAUTH_CALLBACK_PORT, DEFAULT_OAUTH_CALLBACK_PATH }