@aexol/spectral 0.2.5 → 0.2.7

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 (40) hide show
  1. package/dist/cli.js +10 -47
  2. package/dist/mcp/agent-dir.js +18 -0
  3. package/dist/mcp/app-bridge.bundle.js +67 -0
  4. package/dist/mcp/commands.js +263 -0
  5. package/dist/mcp/config.js +532 -0
  6. package/dist/mcp/consent-manager.js +59 -0
  7. package/dist/mcp/direct-tools.js +354 -0
  8. package/dist/mcp/errors.js +165 -0
  9. package/dist/mcp/glimpse-ui.js +67 -0
  10. package/dist/mcp/host-html-template.js +412 -0
  11. package/dist/mcp/index.js +291 -0
  12. package/dist/mcp/init.js +280 -0
  13. package/dist/mcp/lifecycle.js +79 -0
  14. package/dist/mcp/logger.js +130 -0
  15. package/dist/mcp/mcp-auth-flow.js +283 -0
  16. package/dist/mcp/mcp-auth.js +226 -0
  17. package/dist/mcp/mcp-callback-server.js +225 -0
  18. package/dist/mcp/mcp-oauth-provider.js +243 -0
  19. package/dist/mcp/mcp-panel.js +646 -0
  20. package/dist/mcp/mcp-setup-panel.js +485 -0
  21. package/dist/mcp/metadata-cache.js +158 -0
  22. package/dist/mcp/npx-resolver.js +385 -0
  23. package/dist/mcp/oauth-handler.js +54 -0
  24. package/dist/mcp/onboarding-state.js +56 -0
  25. package/dist/mcp/proxy-modes.js +714 -0
  26. package/dist/mcp/resource-tools.js +14 -0
  27. package/dist/mcp/sampling-handler.js +206 -0
  28. package/dist/mcp/server-manager.js +301 -0
  29. package/dist/mcp/state.js +1 -0
  30. package/dist/mcp/tool-metadata.js +128 -0
  31. package/dist/mcp/tool-registrar.js +43 -0
  32. package/dist/mcp/types.js +93 -0
  33. package/dist/mcp/ui-resource-handler.js +113 -0
  34. package/dist/mcp/ui-server.js +522 -0
  35. package/dist/mcp/ui-session.js +306 -0
  36. package/dist/mcp/ui-stream-types.js +58 -0
  37. package/dist/mcp/utils.js +104 -0
  38. package/dist/mcp/vitest.config.js +13 -0
  39. package/dist/server/pi-bridge.js +9 -30
  40. package/package.json +6 -3
@@ -0,0 +1,225 @@
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
+ import { createServer } from "http";
8
+ import { OAUTH_CALLBACK_PATH, getConfiguredOAuthCallbackPort, getOAuthCallbackPort, setOAuthCallbackPort, } from "./mcp-oauth-provider.js";
9
+ // HTML templates for callback responses
10
+ const HTML_SUCCESS = `<!DOCTYPE html>
11
+ <html>
12
+ <head>
13
+ <title>Pi - Authorization Successful</title>
14
+ <style>
15
+ 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; }
16
+ .container { text-align: center; padding: 2rem; }
17
+ h1 { color: #4ade80; margin-bottom: 1rem; }
18
+ p { color: #aaa; }
19
+ </style>
20
+ </head>
21
+ <body>
22
+ <div class="container">
23
+ <h1>Authorization Successful</h1>
24
+ <p>You can close this window and return to Pi.</p>
25
+ </div>
26
+ <script>setTimeout(() => window.close(), 2000);</script>
27
+ </body>
28
+ </html>`;
29
+ const HTML_ERROR = (error) => `<!DOCTYPE html>
30
+ <html>
31
+ <head>
32
+ <title>Pi - Authorization Failed</title>
33
+ <style>
34
+ 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; }
35
+ .container { text-align: center; padding: 2rem; }
36
+ h1 { color: #f87171; margin-bottom: 1rem; }
37
+ p { color: #aaa; }
38
+ .error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
39
+ </style>
40
+ </head>
41
+ <body>
42
+ <div class="container">
43
+ <h1>Authorization Failed</h1>
44
+ <p>An error occurred during authorization.</p>
45
+ <div class="error">${error}</div>
46
+ </div>
47
+ </body>
48
+ </html>`;
49
+ /** Server singleton state */
50
+ let server;
51
+ const pendingAuths = new Map();
52
+ /** Timeout for callback completion (5 minutes) */
53
+ const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
54
+ const MAX_PORT_SCAN_ATTEMPTS = 25;
55
+ /**
56
+ * Handle incoming HTTP requests to the callback server.
57
+ */
58
+ function handleRequest(req, res) {
59
+ const url = new URL(req.url || "/", `http://${req.headers.host}`);
60
+ // Only handle the callback path
61
+ if (url.pathname !== OAUTH_CALLBACK_PATH) {
62
+ res.writeHead(404, { "Content-Type": "text/plain" });
63
+ res.end("Not found");
64
+ return;
65
+ }
66
+ const code = url.searchParams.get("code");
67
+ const state = url.searchParams.get("state");
68
+ const error = url.searchParams.get("error");
69
+ const errorDescription = url.searchParams.get("error_description");
70
+ // Enforce state parameter presence for CSRF protection
71
+ if (!state) {
72
+ const errorMsg = "Missing required state parameter - potential CSRF attack";
73
+ res.writeHead(400, { "Content-Type": "text/html" });
74
+ res.end(HTML_ERROR(errorMsg));
75
+ return;
76
+ }
77
+ // Handle OAuth errors
78
+ if (error) {
79
+ const errorMsg = errorDescription || error;
80
+ // Send HTTP response first before rejecting promise
81
+ res.writeHead(200, { "Content-Type": "text/html" });
82
+ res.end(HTML_ERROR(errorMsg));
83
+ // Reject promise after response is sent (defer to allow test to attach handler)
84
+ if (pendingAuths.has(state)) {
85
+ const pending = pendingAuths.get(state);
86
+ clearTimeout(pending.timeout);
87
+ pendingAuths.delete(state);
88
+ setTimeout(() => pending.reject(new Error(errorMsg)), 0);
89
+ }
90
+ return;
91
+ }
92
+ // Require authorization code
93
+ if (!code) {
94
+ res.writeHead(400, { "Content-Type": "text/html" });
95
+ res.end(HTML_ERROR("No authorization code provided"));
96
+ return;
97
+ }
98
+ // Validate state parameter
99
+ if (!pendingAuths.has(state)) {
100
+ const errorMsg = "Invalid or expired state parameter - potential CSRF attack";
101
+ res.writeHead(400, { "Content-Type": "text/html" });
102
+ res.end(HTML_ERROR(errorMsg));
103
+ return;
104
+ }
105
+ const pending = pendingAuths.get(state);
106
+ // Clear timeout and resolve the pending promise
107
+ clearTimeout(pending.timeout);
108
+ pendingAuths.delete(state);
109
+ pending.resolve(code);
110
+ res.writeHead(200, { "Content-Type": "text/html" });
111
+ res.end(HTML_SUCCESS);
112
+ }
113
+ /**
114
+ * Ensure the callback server is running.
115
+ * If strictPort is true, requires binding on the configured callback port.
116
+ * If strictPort is false, scans forward for an available local port.
117
+ */
118
+ export async function ensureCallbackServer(options = {}) {
119
+ const configuredPort = getConfiguredOAuthCallbackPort();
120
+ const strictPort = options.strictPort === true;
121
+ if (server) {
122
+ if (!strictPort || getOAuthCallbackPort() === configuredPort)
123
+ return;
124
+ if (pendingAuths.size > 0) {
125
+ throw new Error(`OAuth callback server is running on port ${getOAuthCallbackPort()}, but strict callback port ${configuredPort} is required and cannot be switched while authorizations are pending`);
126
+ }
127
+ await stopCallbackServer();
128
+ }
129
+ const preferredPort = configuredPort;
130
+ const maxAttempts = strictPort ? 1 : MAX_PORT_SCAN_ATTEMPTS;
131
+ let lastError;
132
+ for (let offset = 0; offset < maxAttempts; offset++) {
133
+ const candidatePort = preferredPort + offset;
134
+ const candidateServer = createServer(handleRequest);
135
+ try {
136
+ await new Promise((resolve, reject) => {
137
+ candidateServer.once("error", (err) => {
138
+ reject(err);
139
+ });
140
+ candidateServer.listen(candidatePort, "localhost", () => {
141
+ resolve();
142
+ });
143
+ });
144
+ server = candidateServer;
145
+ server.unref();
146
+ setOAuthCallbackPort(candidatePort);
147
+ return;
148
+ }
149
+ catch (error) {
150
+ const nodeError = error;
151
+ await new Promise((resolve) => {
152
+ candidateServer.close(() => resolve());
153
+ });
154
+ if (nodeError.code !== "EADDRINUSE") {
155
+ throw error;
156
+ }
157
+ lastError = error instanceof Error ? error : new Error(String(error));
158
+ }
159
+ }
160
+ if (strictPort) {
161
+ throw new Error(`OAuth callback port ${preferredPort} is already in use. Pre-registered OAuth clients require an exact redirect URI; set MCP_OAUTH_CALLBACK_PORT to your registered port or free port ${preferredPort}`, { cause: lastError });
162
+ }
163
+ throw new Error(`OAuth callback port ${preferredPort} is already in use and no free port was found in range ${preferredPort}-${preferredPort + MAX_PORT_SCAN_ATTEMPTS - 1}`, { cause: lastError });
164
+ }
165
+ /**
166
+ * Wait for a callback with the given OAuth state.
167
+ * Returns a promise that resolves with the authorization code.
168
+ */
169
+ export function waitForCallback(oauthState) {
170
+ return new Promise((resolve, reject) => {
171
+ const timeout = setTimeout(() => {
172
+ if (pendingAuths.has(oauthState)) {
173
+ pendingAuths.delete(oauthState);
174
+ reject(new Error("OAuth callback timeout - authorization took too long"));
175
+ }
176
+ }, CALLBACK_TIMEOUT_MS);
177
+ pendingAuths.set(oauthState, { resolve, reject, timeout });
178
+ });
179
+ }
180
+ /**
181
+ * Cancel a pending authorization by state.
182
+ */
183
+ export function cancelPendingCallback(oauthState) {
184
+ const pending = pendingAuths.get(oauthState);
185
+ if (pending) {
186
+ clearTimeout(pending.timeout);
187
+ pendingAuths.delete(oauthState);
188
+ pending.reject(new Error("Authorization cancelled"));
189
+ }
190
+ }
191
+ /**
192
+ * Stop the callback server and reject all pending authorizations.
193
+ */
194
+ export async function stopCallbackServer() {
195
+ if (server) {
196
+ await new Promise((resolve) => {
197
+ server.close(() => {
198
+ resolve();
199
+ });
200
+ });
201
+ server = undefined;
202
+ }
203
+ setOAuthCallbackPort(getConfiguredOAuthCallbackPort());
204
+ // Reject all pending auths (defer to allow any pending operations to complete)
205
+ const pendingList = Array.from(pendingAuths.entries());
206
+ pendingAuths.clear();
207
+ setTimeout(() => {
208
+ for (const [, pending] of pendingList) {
209
+ clearTimeout(pending.timeout);
210
+ pending.reject(new Error("OAuth callback server stopped"));
211
+ }
212
+ }, 0);
213
+ }
214
+ /**
215
+ * Check if the callback server is running.
216
+ */
217
+ export function isCallbackServerRunning() {
218
+ return server !== undefined;
219
+ }
220
+ /**
221
+ * Get the number of pending authorizations.
222
+ */
223
+ export function getPendingAuthCount() {
224
+ return pendingAuths.size;
225
+ }
@@ -0,0 +1,243 @@
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
+ import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
8
+ import { getAuthEntry, getAuthForUrl, updateTokens, updateClientInfo, updateCodeVerifier, updateOAuthState, clearAllCredentials, clearClientInfo, clearTokens, } from "./mcp-auth.js";
9
+ // Callback server configuration
10
+ const DEFAULT_OAUTH_CALLBACK_PORT = 19876;
11
+ const OAUTH_CALLBACK_PATH = "/callback";
12
+ let configuredOAuthCallbackPort = DEFAULT_OAUTH_CALLBACK_PORT;
13
+ if (process.env.MCP_OAUTH_CALLBACK_PORT) {
14
+ const parsedPort = Number.parseInt(process.env.MCP_OAUTH_CALLBACK_PORT, 10);
15
+ if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) {
16
+ configuredOAuthCallbackPort = parsedPort;
17
+ }
18
+ }
19
+ let oauthCallbackPort = configuredOAuthCallbackPort;
20
+ export function getConfiguredOAuthCallbackPort() {
21
+ return configuredOAuthCallbackPort;
22
+ }
23
+ export function getOAuthCallbackPort() {
24
+ return oauthCallbackPort;
25
+ }
26
+ export function setOAuthCallbackPort(port) {
27
+ oauthCallbackPort = port;
28
+ }
29
+ /**
30
+ * OAuth provider implementation for MCP servers.
31
+ * Implements the OAuthClientProvider interface from the MCP SDK.
32
+ */
33
+ export class McpOAuthProvider {
34
+ serverName;
35
+ serverUrl;
36
+ config;
37
+ callbacks;
38
+ constructor(serverName, serverUrl, config, callbacks) {
39
+ this.serverName = serverName;
40
+ this.serverUrl = serverUrl;
41
+ this.config = config;
42
+ this.callbacks = callbacks;
43
+ }
44
+ get usesClientCredentials() {
45
+ return this.config.grantType === "client_credentials";
46
+ }
47
+ /**
48
+ * The redirect URL for OAuth callbacks.
49
+ * This must match the redirect_uri in client metadata.
50
+ */
51
+ get redirectUrl() {
52
+ if (this.usesClientCredentials)
53
+ return undefined;
54
+ return `http://localhost:${getOAuthCallbackPort()}${OAUTH_CALLBACK_PATH}`;
55
+ }
56
+ /**
57
+ * Client metadata for dynamic registration.
58
+ * Describes this client to the OAuth authorization server.
59
+ */
60
+ get clientMetadata() {
61
+ if (this.usesClientCredentials) {
62
+ return {
63
+ client_name: "Pi Coding Agent",
64
+ redirect_uris: [],
65
+ grant_types: ["client_credentials"],
66
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
67
+ };
68
+ }
69
+ const redirectUrl = this.redirectUrl;
70
+ if (!redirectUrl) {
71
+ throw new Error("redirectUrl is required for authorization_code flow");
72
+ }
73
+ return {
74
+ redirect_uris: [redirectUrl],
75
+ client_name: "Pi Coding Agent",
76
+ client_uri: "https://github.com/nicobailon/pi-mcp-adapter",
77
+ grant_types: ["authorization_code", "refresh_token"],
78
+ response_types: ["code"],
79
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
80
+ };
81
+ }
82
+ /**
83
+ * Get client information (for pre-registered or dynamically registered clients).
84
+ * Returns undefined if no client info exists or if the server URL has changed.
85
+ */
86
+ async clientInformation() {
87
+ // Check config first (pre-registered client)
88
+ if (this.config.clientId) {
89
+ return {
90
+ client_id: this.config.clientId,
91
+ client_secret: this.config.clientSecret,
92
+ };
93
+ }
94
+ // Check stored client info (from dynamic registration)
95
+ // Use getAuthForUrl to validate credentials are for the current server URL
96
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl);
97
+ if (entry?.clientInfo) {
98
+ // Check if client secret has expired
99
+ if (entry.clientInfo.clientSecretExpiresAt && entry.clientInfo.clientSecretExpiresAt < Date.now() / 1000) {
100
+ return undefined;
101
+ }
102
+ return {
103
+ client_id: entry.clientInfo.clientId,
104
+ client_secret: entry.clientInfo.clientSecret,
105
+ };
106
+ }
107
+ // No client info or URL changed - will trigger dynamic registration
108
+ return undefined;
109
+ }
110
+ /**
111
+ * Save client information from dynamic registration.
112
+ */
113
+ async saveClientInformation(info) {
114
+ const clientInfo = {
115
+ clientId: info.client_id,
116
+ clientSecret: info.client_secret,
117
+ clientIdIssuedAt: info.client_id_issued_at,
118
+ clientSecretExpiresAt: info.client_secret_expires_at,
119
+ };
120
+ updateClientInfo(this.serverName, clientInfo, this.serverUrl);
121
+ }
122
+ /**
123
+ * Get stored OAuth tokens.
124
+ * Returns undefined if no tokens exist or if the server URL has changed.
125
+ */
126
+ async tokens() {
127
+ // Use getAuthForUrl to validate tokens are for the current server URL
128
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl);
129
+ if (!entry?.tokens)
130
+ return undefined;
131
+ return {
132
+ access_token: entry.tokens.accessToken,
133
+ token_type: "Bearer",
134
+ refresh_token: entry.tokens.refreshToken,
135
+ expires_in: entry.tokens.expiresAt
136
+ ? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
137
+ : undefined,
138
+ scope: entry.tokens.scope,
139
+ };
140
+ }
141
+ /**
142
+ * Save OAuth tokens.
143
+ */
144
+ async saveTokens(tokens) {
145
+ const storedTokens = {
146
+ accessToken: tokens.access_token,
147
+ refreshToken: tokens.refresh_token,
148
+ expiresAt: tokens.expires_in ? Date.now() / 1000 + tokens.expires_in : undefined,
149
+ scope: tokens.scope,
150
+ };
151
+ updateTokens(this.serverName, storedTokens, this.serverUrl);
152
+ }
153
+ /**
154
+ * Redirect the user to the authorization URL.
155
+ * This opens the browser for the user to authenticate.
156
+ *
157
+ * Throws UnauthorizedError when called outside of a user-initiated flow
158
+ * (no oauthState saved by startAuth). That path is reached when the SDK
159
+ * falls through from a failed refresh into a fresh authorization_code
160
+ * flow, which library hosts cannot complete in-process.
161
+ */
162
+ async redirectToAuthorization(authorizationUrl) {
163
+ if (this.usesClientCredentials) {
164
+ throw new Error("redirectToAuthorization is not used for client_credentials flow");
165
+ }
166
+ // No saved oauthState means we're on the post-refresh authorize fallback.
167
+ const entry = await getAuthEntry(this.serverName);
168
+ if (!entry?.oauthState) {
169
+ throw new UnauthorizedError(`Re-authentication required for MCP server: ${this.serverName}`);
170
+ }
171
+ // URL is passed to callback, not logged (may contain sensitive params)
172
+ await this.callbacks.onRedirect(authorizationUrl);
173
+ }
174
+ /**
175
+ * Save the PKCE code verifier.
176
+ */
177
+ async saveCodeVerifier(codeVerifier) {
178
+ updateCodeVerifier(this.serverName, codeVerifier);
179
+ }
180
+ /**
181
+ * Get the stored PKCE code verifier.
182
+ * @throws Error if no code verifier is stored
183
+ */
184
+ async codeVerifier() {
185
+ if (this.usesClientCredentials) {
186
+ throw new Error("codeVerifier is not used for client_credentials flow");
187
+ }
188
+ const entry = await getAuthEntry(this.serverName);
189
+ if (!entry?.codeVerifier) {
190
+ throw new Error(`No code verifier saved for MCP server: ${this.serverName}`);
191
+ }
192
+ return entry.codeVerifier;
193
+ }
194
+ /**
195
+ * Save the OAuth state parameter for CSRF protection.
196
+ */
197
+ async saveState(state) {
198
+ updateOAuthState(this.serverName, state);
199
+ }
200
+ /**
201
+ * Get the stored OAuth state parameter.
202
+ * @throws UnauthorizedError if no flow is in progress (see redirectToAuthorization)
203
+ */
204
+ async state() {
205
+ if (this.usesClientCredentials) {
206
+ throw new Error("state is not used for client_credentials flow");
207
+ }
208
+ const entry = await getAuthEntry(this.serverName);
209
+ if (!entry?.oauthState) {
210
+ throw new UnauthorizedError(`Re-authentication required for MCP server: ${this.serverName}`);
211
+ }
212
+ return entry.oauthState;
213
+ }
214
+ /**
215
+ * Invalidate credentials when authentication fails.
216
+ * Clears tokens, client info, or all credentials based on the type.
217
+ */
218
+ async invalidateCredentials(type) {
219
+ switch (type) {
220
+ case "all":
221
+ clearAllCredentials(this.serverName);
222
+ break;
223
+ case "client":
224
+ clearClientInfo(this.serverName);
225
+ break;
226
+ case "tokens":
227
+ clearTokens(this.serverName);
228
+ break;
229
+ }
230
+ }
231
+ prepareTokenRequest(scope) {
232
+ if (!this.usesClientCredentials) {
233
+ return undefined;
234
+ }
235
+ const params = new URLSearchParams({ grant_type: "client_credentials" });
236
+ const requestedScope = scope ?? this.config.scope;
237
+ if (requestedScope) {
238
+ params.set("scope", requestedScope);
239
+ }
240
+ return params;
241
+ }
242
+ }
243
+ export { DEFAULT_OAUTH_CALLBACK_PORT, OAUTH_CALLBACK_PATH };