@myrialabs/clopen 0.4.2 → 0.4.4

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 (41) hide show
  1. package/README.md +2 -0
  2. package/backend/auth/permissions.ts +4 -1
  3. package/backend/chat/stream-manager.ts +7 -1
  4. package/backend/database/migrations/041_add_mcp_config_schema.ts +16 -0
  5. package/backend/database/migrations/042_add_mcp_oauth.ts +20 -0
  6. package/backend/database/migrations/043_relocate_engine_config_dirs.ts +71 -0
  7. package/backend/database/migrations/index.ts +21 -0
  8. package/backend/database/queries/index.ts +1 -1
  9. package/backend/database/queries/mcp-server-queries.ts +42 -2
  10. package/backend/engine/README.md +12 -8
  11. package/backend/engine/adapters/claude/environment.ts +3 -3
  12. package/backend/engine/adapters/codex/credential.ts +6 -2
  13. package/backend/engine/adapters/codex/stream.ts +6 -0
  14. package/backend/engine/adapters/copilot/stream.ts +5 -1
  15. package/backend/engine/adapters/opencode/server.ts +57 -21
  16. package/backend/engine/adapters/qwen/environment.ts +7 -0
  17. package/backend/engine/adapters/qwen/session-fork.ts +13 -1
  18. package/backend/engine/docs/adding-an-engine.md +8 -0
  19. package/backend/engine/docs/database.md +9 -6
  20. package/backend/engine/docs/lessons-learned.md +177 -16
  21. package/backend/git/git-service.ts +21 -2
  22. package/backend/index.ts +23 -1
  23. package/backend/mcp/README.md +81 -0
  24. package/backend/mcp/external/config.ts +70 -14
  25. package/backend/mcp/external/oauth.ts +329 -0
  26. package/backend/mcp/external/probe.ts +308 -0
  27. package/backend/mcp/external/registry-client.ts +8 -1
  28. package/backend/mcp/index.ts +12 -1
  29. package/backend/mcp/internal/config.ts +6 -0
  30. package/backend/mcp/internal/remote-server.test.ts +14 -0
  31. package/backend/mcp/internal/remote-server.ts +8 -0
  32. package/backend/mcp/internal/service-token.ts +51 -0
  33. package/backend/utils/paths.ts +16 -0
  34. package/backend/ws/engine/codex/accounts.ts +3 -0
  35. package/backend/ws/git/remote.ts +3 -2
  36. package/backend/ws/mcp/crud.ts +131 -12
  37. package/dist/assets/{main-qT_RedHf.js → main-AqTMkV9D.js} +272 -266
  38. package/dist/assets/main-DJf71Zum.css +1 -0
  39. package/dist/index.html +2 -2
  40. package/package.json +1 -1
  41. package/dist/assets/main-DKLZPDUN.css +0 -1
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Centralized MCP OAuth client.
3
+ *
4
+ * Clopen performs the OAuth 2.1 authorization-code + PKCE flow ITSELF (with
5
+ * RFC 8414/9728 discovery and RFC 7591 dynamic client registration), stores the
6
+ * resulting access/refresh tokens in the `mcp_servers.oauth` column, and injects
7
+ * `Authorization: Bearer <token>` into EVERY engine's config. This replaces the
8
+ * old per-engine delegation, where each engine kept its own token store so only
9
+ * OpenCode could sign in and the result never reached Codex/Claude/etc.
10
+ *
11
+ * The redirect lands on Clopen's own stable callback route
12
+ * (`/api/mcp/oauth/callback`), so there is no ephemeral per-flow loopback server
13
+ * to race against — the earlier "localhost:NNNNN refused to connect" failure.
14
+ */
15
+
16
+ import { debug } from '$shared/utils/logger';
17
+ import { SERVER_ENV } from '$backend/utils/env';
18
+ import { mcpServerQueries } from '$backend/database/queries';
19
+
20
+ /** Persisted per-server OAuth state (JSON in `mcp_servers.oauth`). */
21
+ export interface OAuthRecord {
22
+ clientId: string;
23
+ clientSecret?: string;
24
+ authorizationEndpoint: string;
25
+ tokenEndpoint: string;
26
+ registrationEndpoint?: string;
27
+ redirectUri: string;
28
+ scope?: string;
29
+ resource?: string;
30
+ accessToken?: string;
31
+ refreshToken?: string;
32
+ /** Epoch ms when the access token expires. */
33
+ expiresAt?: number;
34
+ }
35
+
36
+ /** Refresh tokens whose access token expires within this window. */
37
+ const REFRESH_SKEW_MS = 60_000;
38
+
39
+ // In-memory authorization flows awaiting their callback, keyed by `state`.
40
+ interface PendingFlow {
41
+ serverId: number;
42
+ codeVerifier: string;
43
+ record: OAuthRecord;
44
+ }
45
+ const pendingFlows = new Map<string, PendingFlow>();
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Storage helpers
49
+ // ---------------------------------------------------------------------------
50
+
51
+ export function loadOAuth(serverId: number): OAuthRecord | null {
52
+ const row = mcpServerQueries.getById(serverId);
53
+ if (!row?.oauth) return null;
54
+ try { return JSON.parse(row.oauth) as OAuthRecord; } catch { return null; }
55
+ }
56
+
57
+ function saveOAuth(serverId: number, record: OAuthRecord): void {
58
+ mcpServerQueries.setOAuth(serverId, JSON.stringify(record));
59
+ }
60
+
61
+ export function clearOAuth(serverId: number): void {
62
+ mcpServerQueries.setOAuth(serverId, null);
63
+ }
64
+
65
+ /** The fixed redirect URI served by Clopen's HTTP layer. */
66
+ export function oauthRedirectUri(): string {
67
+ return `http://localhost:${SERVER_ENV.PORT}/api/mcp/oauth/callback`;
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // PKCE + crypto
72
+ // ---------------------------------------------------------------------------
73
+
74
+ function base64url(bytes: Uint8Array): string {
75
+ let str = '';
76
+ for (const b of bytes) str += String.fromCharCode(b);
77
+ return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
78
+ }
79
+
80
+ function randomToken(byteLength = 32): string {
81
+ return base64url(crypto.getRandomValues(new Uint8Array(byteLength)));
82
+ }
83
+
84
+ async function pkceChallenge(verifier: string): Promise<string> {
85
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
86
+ return base64url(new Uint8Array(digest));
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // Discovery (RFC 9728 protected-resource → RFC 8414 authorization-server)
91
+ // ---------------------------------------------------------------------------
92
+
93
+ interface DiscoveredAuthServer {
94
+ authorizationEndpoint: string;
95
+ tokenEndpoint: string;
96
+ registrationEndpoint?: string;
97
+ scope?: string;
98
+ resource?: string;
99
+ }
100
+
101
+ /** Pull the `resource_metadata` URL out of a `WWW-Authenticate: Bearer …` header. */
102
+ function resourceMetadataFromHeader(wwwAuthenticate?: string): string | null {
103
+ if (!wwwAuthenticate) return null;
104
+ const match = wwwAuthenticate.match(/resource_metadata="([^"]+)"/i);
105
+ return match?.[1] ?? null;
106
+ }
107
+
108
+ async function fetchJson(url: string): Promise<Record<string, unknown> | null> {
109
+ try {
110
+ const res = await fetch(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(10_000) });
111
+ if (!res.ok) return null;
112
+ return await res.json() as Record<string, unknown>;
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Resolve the authorization server metadata for a remote MCP `resourceUrl`,
120
+ * preferring the `resource_metadata` hint from its 401 challenge.
121
+ */
122
+ export async function discover(resourceUrl: string, wwwAuthenticate?: string): Promise<DiscoveredAuthServer> {
123
+ const origin = new URL(resourceUrl).origin;
124
+
125
+ // 1. Protected-resource metadata → authorization server + resource id.
126
+ const prmUrl = resourceMetadataFromHeader(wwwAuthenticate) ?? `${origin}/.well-known/oauth-protected-resource`;
127
+ const prm = await fetchJson(prmUrl);
128
+ const authServers = Array.isArray(prm?.authorization_servers) ? prm.authorization_servers as string[] : [];
129
+ const asBase = (authServers[0] ?? origin).replace(/\/$/, '');
130
+ const resource = typeof prm?.resource === 'string' ? prm.resource : undefined;
131
+
132
+ // 2. Authorization-server metadata (try OAuth, then OpenID locations).
133
+ const asMeta = await fetchJson(`${asBase}/.well-known/oauth-authorization-server`)
134
+ ?? await fetchJson(`${asBase}/.well-known/openid-configuration`);
135
+ if (!asMeta?.authorization_endpoint || !asMeta?.token_endpoint) {
136
+ throw new Error('Server does not advertise an OAuth authorization server');
137
+ }
138
+
139
+ const scopesSupported = Array.isArray(asMeta.scopes_supported) ? (asMeta.scopes_supported as string[]).join(' ') : undefined;
140
+ return {
141
+ authorizationEndpoint: asMeta.authorization_endpoint as string,
142
+ tokenEndpoint: asMeta.token_endpoint as string,
143
+ registrationEndpoint: typeof asMeta.registration_endpoint === 'string' ? asMeta.registration_endpoint : undefined,
144
+ scope: scopesSupported,
145
+ resource
146
+ };
147
+ }
148
+
149
+ // ---------------------------------------------------------------------------
150
+ // Dynamic client registration (RFC 7591)
151
+ // ---------------------------------------------------------------------------
152
+
153
+ async function registerClient(registrationEndpoint: string, redirectUri: string, scope?: string): Promise<{ clientId: string; clientSecret?: string }> {
154
+ const res = await fetch(registrationEndpoint, {
155
+ method: 'POST',
156
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
157
+ signal: AbortSignal.timeout(10_000),
158
+ body: JSON.stringify({
159
+ client_name: 'Clopen',
160
+ redirect_uris: [redirectUri],
161
+ grant_types: ['authorization_code', 'refresh_token'],
162
+ response_types: ['code'],
163
+ token_endpoint_auth_method: 'none',
164
+ ...(scope ? { scope } : {})
165
+ })
166
+ });
167
+ if (!res.ok) {
168
+ throw new Error(`Dynamic client registration failed (${res.status})`);
169
+ }
170
+ const data = await res.json() as { client_id?: string; client_secret?: string };
171
+ if (!data.client_id) throw new Error('Registration response missing client_id');
172
+ return { clientId: data.client_id, clientSecret: data.client_secret };
173
+ }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // Token endpoint
177
+ // ---------------------------------------------------------------------------
178
+
179
+ interface TokenResponse {
180
+ access_token: string;
181
+ refresh_token?: string;
182
+ expires_in?: number;
183
+ }
184
+
185
+ async function postToken(tokenEndpoint: string, params: Record<string, string>, clientSecret?: string): Promise<TokenResponse> {
186
+ const headers: Record<string, string> = { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' };
187
+ if (clientSecret) {
188
+ headers.Authorization = `Basic ${btoa(`${params.client_id}:${clientSecret}`)}`;
189
+ }
190
+ const res = await fetch(tokenEndpoint, {
191
+ method: 'POST',
192
+ headers,
193
+ signal: AbortSignal.timeout(10_000),
194
+ body: new URLSearchParams(params).toString()
195
+ });
196
+ if (!res.ok) {
197
+ const text = await res.text().catch(() => '');
198
+ throw new Error(`Token request failed (${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`);
199
+ }
200
+ return await res.json() as TokenResponse;
201
+ }
202
+
203
+ function withExpiry(record: OAuthRecord, token: TokenResponse): OAuthRecord {
204
+ return {
205
+ ...record,
206
+ accessToken: token.access_token,
207
+ refreshToken: token.refresh_token ?? record.refreshToken,
208
+ expiresAt: token.expires_in ? Date.now() + token.expires_in * 1000 : undefined
209
+ };
210
+ }
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // Public flow API
214
+ // ---------------------------------------------------------------------------
215
+
216
+ /**
217
+ * Begin an authorization flow for a server. Discovers + (re)registers a client,
218
+ * remembers the PKCE verifier keyed by `state`, and returns the URL the user
219
+ * must open. Completion arrives at the callback route (or the manual paste).
220
+ */
221
+ export async function startAuthorization(serverId: number, resourceUrl: string, wwwAuthenticate?: string): Promise<{ authorizationUrl: string }> {
222
+ const disc = await discover(resourceUrl, wwwAuthenticate);
223
+ const redirectUri = oauthRedirectUri();
224
+
225
+ // Reuse a prior registration when present; otherwise register dynamically.
226
+ const existing = loadOAuth(serverId);
227
+ let clientId = existing?.clientId;
228
+ let clientSecret = existing?.clientSecret;
229
+ if (!clientId) {
230
+ if (!disc.registrationEndpoint) throw new Error('Server requires a pre-registered OAuth client (no dynamic registration)');
231
+ ({ clientId, clientSecret } = await registerClient(disc.registrationEndpoint, redirectUri, disc.scope));
232
+ }
233
+
234
+ const codeVerifier = randomToken(32);
235
+ const codeChallenge = await pkceChallenge(codeVerifier);
236
+ const state = randomToken(16);
237
+
238
+ const record: OAuthRecord = {
239
+ clientId,
240
+ clientSecret,
241
+ authorizationEndpoint: disc.authorizationEndpoint,
242
+ tokenEndpoint: disc.tokenEndpoint,
243
+ registrationEndpoint: disc.registrationEndpoint,
244
+ redirectUri,
245
+ scope: disc.scope,
246
+ resource: disc.resource
247
+ };
248
+ pendingFlows.set(state, { serverId, codeVerifier, record });
249
+
250
+ const url = new URL(disc.authorizationEndpoint);
251
+ url.searchParams.set('response_type', 'code');
252
+ url.searchParams.set('client_id', clientId);
253
+ url.searchParams.set('redirect_uri', redirectUri);
254
+ url.searchParams.set('code_challenge', codeChallenge);
255
+ url.searchParams.set('code_challenge_method', 'S256');
256
+ url.searchParams.set('state', state);
257
+ if (disc.scope) url.searchParams.set('scope', disc.scope);
258
+ if (disc.resource) url.searchParams.set('resource', disc.resource);
259
+
260
+ debug.log('mcp', `🔐 OAuth flow started for server ${serverId} (state ${state.slice(0, 6)}…)`);
261
+ return { authorizationUrl: url.toString() };
262
+ }
263
+
264
+ /** Whether a `state` belongs to a known pending flow (callback validation). */
265
+ export function hasPendingFlow(state: string): boolean {
266
+ return pendingFlows.has(state);
267
+ }
268
+
269
+ /**
270
+ * Exchange the authorization `code` for tokens and persist them. Returns the
271
+ * server id the flow belonged to so callers can refresh the UI.
272
+ */
273
+ export async function completeAuthorization(state: string, code: string): Promise<number> {
274
+ const flow = pendingFlows.get(state);
275
+ if (!flow) throw new Error('Unknown or expired authorization state');
276
+ pendingFlows.delete(state);
277
+
278
+ const token = await postToken(flow.record.tokenEndpoint, {
279
+ grant_type: 'authorization_code',
280
+ code,
281
+ redirect_uri: flow.record.redirectUri,
282
+ client_id: flow.record.clientId,
283
+ code_verifier: flow.codeVerifier,
284
+ ...(flow.record.resource ? { resource: flow.record.resource } : {})
285
+ }, flow.record.clientSecret);
286
+
287
+ saveOAuth(flow.serverId, withExpiry(flow.record, token));
288
+ debug.log('mcp', `🔓 OAuth tokens stored for server ${flow.serverId}`);
289
+ return flow.serverId;
290
+ }
291
+
292
+ /**
293
+ * Return a usable access token for a server, refreshing it first if it is about
294
+ * to expire. Returns null when the server has no OAuth or the refresh fails.
295
+ */
296
+ export async function getValidAccessToken(serverId: number): Promise<string | null> {
297
+ const record = loadOAuth(serverId);
298
+ if (!record?.accessToken) return null;
299
+
300
+ const expiringSoon = record.expiresAt != null && record.expiresAt - Date.now() < REFRESH_SKEW_MS;
301
+ if (expiringSoon && record.refreshToken) {
302
+ try {
303
+ const token = await postToken(record.tokenEndpoint, {
304
+ grant_type: 'refresh_token',
305
+ refresh_token: record.refreshToken,
306
+ client_id: record.clientId,
307
+ ...(record.resource ? { resource: record.resource } : {})
308
+ }, record.clientSecret);
309
+ const next = withExpiry(record, token);
310
+ saveOAuth(serverId, next);
311
+ return next.accessToken ?? null;
312
+ } catch (error) {
313
+ debug.warn('mcp', `OAuth refresh failed for server ${serverId}:`, error);
314
+ return record.accessToken; // try the (possibly stale) token rather than nothing
315
+ }
316
+ }
317
+ return record.accessToken;
318
+ }
319
+
320
+ /**
321
+ * Refresh every enabled server's token that is close to expiry. Called at chat
322
+ * stream start so the sync per-engine config builders read fresh tokens.
323
+ */
324
+ export async function refreshExpiringExternalOAuth(): Promise<void> {
325
+ for (const row of mcpServerQueries.getEnabled()) {
326
+ if (row.source === 'internal' || !row.oauth) continue;
327
+ await getValidAccessToken(row.id).catch(() => undefined);
328
+ }
329
+ }
@@ -0,0 +1,308 @@
1
+ /**
2
+ * External MCP — connection health probe.
3
+ *
4
+ * Performs the MCP handshake (`initialize` → `tools/list`) against a stored
5
+ * server using its own config, and classifies the outcome. This is what makes
6
+ * a broken external server VISIBLE in Settings instead of silently exposing
7
+ * zero tools to an engine — the failure mode that hid `com-notion-mcp`
8
+ * (OAuth 401) and `ai-trendsmcp-google-trends` (missing API key).
9
+ *
10
+ * The probe is engine-agnostic: it talks to the remote URL directly with the
11
+ * stored headers. It therefore reflects whether the server is reachable and
12
+ * whether the *stored* credential is sufficient. For OAuth servers (no static
13
+ * credential) it reports `needs_auth` — the engine still authenticates via its
14
+ * own per-engine token store, but the user gets a clear, actionable signal.
15
+ */
16
+
17
+ import { debug } from '$shared/utils/logger';
18
+ import type { ResolvedExternalServer } from './types';
19
+
20
+ /**
21
+ * Classified outcome of a connection probe.
22
+ * - `needs_auth` : OAuth sign-in required (offer Authenticate)
23
+ * - `needs_config` : a static credential / API key is missing (offer Configure)
24
+ */
25
+ export type McpHealthState = 'ok' | 'needs_auth' | 'needs_config' | 'unreachable' | 'error' | 'local';
26
+
27
+ export interface McpHealth {
28
+ state: McpHealthState;
29
+ /** Tool count when `ok`. */
30
+ toolCount?: number;
31
+ /** Human-readable detail for non-ok states. */
32
+ message?: string;
33
+ }
34
+
35
+ const PROBE_TIMEOUT_MS = 12_000;
36
+ const STDIO_PROBE_TIMEOUT_MS = 15_000;
37
+ const PROTOCOL_VERSION = '2025-03-26';
38
+
39
+ /** Patterns in an error payload that indicate a missing/invalid credential. */
40
+ const AUTH_HINT = /\b(api[\s-]?key|unauthor|forbidden|token|auth|sign[\s-]?in|login|credential)\b/i;
41
+
42
+ interface JsonRpcResponse {
43
+ result?: {
44
+ tools?: unknown[];
45
+ isError?: boolean;
46
+ content?: Array<{ type?: string; text?: string }>;
47
+ };
48
+ error?: { message?: string };
49
+ }
50
+
51
+ /**
52
+ * Read a streamable-HTTP MCP response body, which may be either plain JSON or
53
+ * an SSE stream (`text/event-stream`). Returns the first JSON-RPC object found.
54
+ */
55
+ async function readRpc(res: Response): Promise<JsonRpcResponse | null> {
56
+ const text = await res.text();
57
+ const trimmed = text.trim();
58
+ if (!trimmed) return null;
59
+ // Plain JSON.
60
+ if (trimmed.startsWith('{')) {
61
+ try { return JSON.parse(trimmed) as JsonRpcResponse; } catch { /* fall through */ }
62
+ }
63
+ // SSE: pick the last `data:` line carrying a JSON-RPC object.
64
+ for (const line of trimmed.split('\n').reverse()) {
65
+ const t = line.trim();
66
+ if (t.startsWith('data:')) {
67
+ const payload = t.slice(5).trim();
68
+ try { return JSON.parse(payload) as JsonRpcResponse; } catch { /* keep scanning */ }
69
+ }
70
+ }
71
+ return null;
72
+ }
73
+
74
+ function rpcBody(method: string, id?: number, params?: unknown): string {
75
+ return JSON.stringify({ jsonrpc: '2.0', ...(id != null ? { id } : {}), method, ...(params != null ? { params } : {}) });
76
+ }
77
+
78
+ /**
79
+ * A 401/403 with a `Bearer` challenge is an OAuth server → offer sign-in.
80
+ * Otherwise the server wants a static credential we don't have → offer Configure.
81
+ */
82
+ function classifyUnauthorized(res: Response): McpHealth {
83
+ const challenge = res.headers.get('www-authenticate') ?? '';
84
+ if (/bearer/i.test(challenge)) {
85
+ return { state: 'needs_auth', message: 'OAuth sign-in required' };
86
+ }
87
+ return { state: 'needs_config', message: 'A credential (API key / token) is required' };
88
+ }
89
+
90
+ /** Cap on captured stderr so a chatty subprocess can't balloon memory. */
91
+ const STDERR_CAP = 4000;
92
+
93
+ /** Drain a subprocess's stderr into a bounded string (best-effort). */
94
+ async function drainStderr(stream: ReadableStream<Uint8Array>): Promise<string> {
95
+ const reader = stream.getReader();
96
+ const decoder = new TextDecoder();
97
+ let text = '';
98
+ try {
99
+ while (text.length < STDERR_CAP) {
100
+ const { done, value } = await reader.read();
101
+ if (done) break;
102
+ text += decoder.decode(value, { stream: true });
103
+ }
104
+ } catch { /* stream closed/cancelled */ } finally {
105
+ reader.cancel().catch(() => undefined);
106
+ }
107
+ return text;
108
+ }
109
+
110
+ /** Condense captured stderr into a short, single-line diagnostic. */
111
+ function stderrTail(text: string): string {
112
+ return text.replace(/\s+/g, ' ').trim().slice(0, 300);
113
+ }
114
+
115
+ /**
116
+ * Spawn a stdio server and run the same handshake over its stdin/stdout
117
+ * (newline-delimited JSON-RPC) so "local" servers report a real connection
118
+ * status, consistent with remote ones. The subprocess is always killed.
119
+ */
120
+ async function probeStdio(s: ResolvedExternalServer): Promise<McpHealth> {
121
+ if (!s.command) return { state: 'error', message: 'No command configured' };
122
+
123
+ let proc: ReturnType<typeof Bun.spawn>;
124
+ try {
125
+ proc = Bun.spawn([s.command, ...s.args], {
126
+ stdin: 'pipe',
127
+ stdout: 'pipe',
128
+ stderr: 'pipe',
129
+ env: { ...process.env, ...s.env }
130
+ });
131
+ } catch (error) {
132
+ return { state: 'unreachable', message: error instanceof Error ? error.message : 'Failed to start command' };
133
+ }
134
+
135
+ // Capture stderr concurrently so a process that prints usage/errors and then
136
+ // exits (e.g. a CLI that needs a `mcp` subcommand to actually start the
137
+ // server) yields an actionable message instead of a misleading timeout.
138
+ const stderrPromise = drainStderr(proc.stderr as unknown as ReadableStream<Uint8Array>);
139
+
140
+ try {
141
+ const stdin = proc.stdin as unknown as { write(data: Uint8Array): number; flush?(): Promise<number> | number };
142
+ const stdout = proc.stdout as unknown as ReadableStream<Uint8Array>;
143
+ const write = (obj: unknown) => stdin.write(new TextEncoder().encode(`${JSON.stringify(obj)}\n`));
144
+ write({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'clopen-probe', version: '1.0.0' } } });
145
+ write({ jsonrpc: '2.0', method: 'notifications/initialized' });
146
+ write({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
147
+ await stdin.flush?.();
148
+
149
+ const rpc = await readStdoutForId(stdout, 2, STDIO_PROBE_TIMEOUT_MS);
150
+ if (rpc) {
151
+ if (Array.isArray(rpc.result?.tools)) return { state: 'ok', toolCount: rpc.result.tools.length };
152
+ const detail = rpc.error?.message ?? 'Server did not return a tool list';
153
+ return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
154
+ }
155
+
156
+ // No JSON-RPC reply. Distinguish a process that already exited (a real,
157
+ // reportable error — wrong command, missing subcommand, crash) from one
158
+ // that's still alive but silent (a genuine timeout).
159
+ const exitCode = await Promise.race([
160
+ proc.exited,
161
+ new Promise<number | null>(resolve => setTimeout(() => resolve(null), 250))
162
+ ]);
163
+ if (exitCode !== null) {
164
+ const tail = stderrTail(await Promise.race([
165
+ stderrPromise,
166
+ new Promise<string>(resolve => setTimeout(() => resolve(''), 200))
167
+ ]));
168
+ const detail = tail
169
+ ? `Process exited (code ${exitCode}): ${tail}`
170
+ : `Process exited (code ${exitCode}) before responding`;
171
+ return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
172
+ }
173
+ return { state: 'unreachable', message: `No response within ${STDIO_PROBE_TIMEOUT_MS / 1000}s` };
174
+ } catch (error) {
175
+ return { state: 'error', message: error instanceof Error ? error.message : 'Probe failed' };
176
+ } finally {
177
+ proc.kill();
178
+ }
179
+ }
180
+
181
+ /** Read newline-delimited JSON-RPC from a stream until the response `id` arrives. */
182
+ async function readStdoutForId(stream: ReadableStream<Uint8Array>, id: number, timeoutMs: number): Promise<JsonRpcResponse | null> {
183
+ const reader = stream.getReader();
184
+ const decoder = new TextDecoder();
185
+ let buffer = '';
186
+ const deadline = Date.now() + timeoutMs;
187
+ try {
188
+ while (Date.now() < deadline) {
189
+ const remaining = deadline - Date.now();
190
+ const chunk = await Promise.race([
191
+ reader.read(),
192
+ new Promise<{ done: true; value: undefined }>(resolve => setTimeout(() => resolve({ done: true, value: undefined }), remaining))
193
+ ]);
194
+ if (chunk.done) break;
195
+ buffer += decoder.decode(chunk.value, { stream: true });
196
+ let nl: number;
197
+ while ((nl = buffer.indexOf('\n')) >= 0) {
198
+ const line = buffer.slice(0, nl).trim();
199
+ buffer = buffer.slice(nl + 1);
200
+ if (!line) continue;
201
+ try {
202
+ const msg = JSON.parse(line) as JsonRpcResponse & { id?: number };
203
+ if (msg.id === id) return msg;
204
+ } catch { /* ignore non-JSON log lines */ }
205
+ }
206
+ }
207
+ return null;
208
+ } finally {
209
+ // cancel() (not releaseLock) settles any still-pending read() so this
210
+ // never throws on an outstanding request.
211
+ reader.cancel().catch(() => undefined);
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Probe a single resolved server. Remote servers do a network handshake; stdio
217
+ * servers are spawned and handshaken over stdio so every server reports a real
218
+ * connection status.
219
+ */
220
+ export async function probeServer(s: ResolvedExternalServer): Promise<McpHealth> {
221
+ if (s.transport === 'stdio') return probeStdio(s);
222
+ if (!s.url) return { state: 'error', message: 'No URL configured' };
223
+
224
+ const controller = new AbortController();
225
+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
226
+ const baseHeaders: Record<string, string> = {
227
+ 'Content-Type': 'application/json',
228
+ Accept: 'application/json, text/event-stream',
229
+ ...s.headers
230
+ };
231
+
232
+ try {
233
+ // 1. initialize
234
+ const initRes = await fetch(s.url, {
235
+ method: 'POST',
236
+ headers: baseHeaders,
237
+ signal: controller.signal,
238
+ body: rpcBody('initialize', 1, {
239
+ protocolVersion: PROTOCOL_VERSION,
240
+ capabilities: {},
241
+ clientInfo: { name: 'clopen-probe', version: '1.0.0' }
242
+ })
243
+ });
244
+
245
+ if (initRes.status === 401 || initRes.status === 403) {
246
+ return classifyUnauthorized(initRes);
247
+ }
248
+ if (!initRes.ok) {
249
+ return { state: 'error', message: `Server responded ${initRes.status} ${initRes.statusText}` };
250
+ }
251
+
252
+ const sessionId = initRes.headers.get('mcp-session-id') ?? undefined;
253
+ await readRpc(initRes); // drain
254
+ const sessionHeaders = sessionId ? { ...baseHeaders, 'mcp-session-id': sessionId } : baseHeaders;
255
+
256
+ // 2. initialized notification (best-effort; some servers require it)
257
+ await fetch(s.url, {
258
+ method: 'POST',
259
+ headers: sessionHeaders,
260
+ signal: controller.signal,
261
+ body: rpcBody('notifications/initialized')
262
+ }).catch(() => undefined);
263
+
264
+ // 3. tools/list
265
+ const listRes = await fetch(s.url, {
266
+ method: 'POST',
267
+ headers: sessionHeaders,
268
+ signal: controller.signal,
269
+ body: rpcBody('tools/list', 2)
270
+ });
271
+
272
+ if (listRes.status === 401 || listRes.status === 403) {
273
+ return classifyUnauthorized(listRes);
274
+ }
275
+ if (!listRes.ok) {
276
+ return { state: 'error', message: `Server responded ${listRes.status} ${listRes.statusText}` };
277
+ }
278
+
279
+ const rpc = await readRpc(listRes);
280
+ if (!rpc) return { state: 'error', message: 'Server returned an unreadable response' };
281
+
282
+ // A proper tools/list returns `result.tools`. Servers that gate listing
283
+ // behind a credential (e.g. trendsmcp) instead return an error result
284
+ // such as "No API key …" — surface that as needs_auth so the user knows
285
+ // to add the credential rather than seeing a generic failure.
286
+ if (Array.isArray(rpc.result?.tools)) {
287
+ return { state: 'ok', toolCount: rpc.result.tools.length };
288
+ }
289
+
290
+ const detail = rpc.error?.message
291
+ ?? rpc.result?.content?.map(c => c.text).filter(Boolean).join(' ')
292
+ ?? 'Server did not return a tool list';
293
+ // Listing gated behind a credential (e.g. trendsmcp "No API key …") — the
294
+ // server is reachable, so this is a missing static credential, not OAuth.
295
+ if (AUTH_HINT.test(detail)) {
296
+ return { state: 'needs_config', message: detail };
297
+ }
298
+ return { state: 'error', message: detail };
299
+ } catch (error) {
300
+ if (error instanceof Error && error.name === 'AbortError') {
301
+ return { state: 'unreachable', message: `No response within ${PROBE_TIMEOUT_MS / 1000}s` };
302
+ }
303
+ debug.warn('mcp', `Probe failed for ${s.slug}:`, error);
304
+ return { state: 'unreachable', message: error instanceof Error ? error.message : 'Could not reach server' };
305
+ } finally {
306
+ clearTimeout(timeout);
307
+ }
308
+ }
@@ -109,7 +109,14 @@ function resolveStdioPackage(pkg: RegistryPackage): { command: string; args: str
109
109
  if (!command || !pkg.identifier) return null;
110
110
 
111
111
  const args: string[] = [];
112
- for (const a of pkg.runtimeArguments ?? []) args.push(...argTokens(a));
112
+ const runtimeArgs = pkg.runtimeArguments ?? [];
113
+ // `npx` prompts before fetching an uncached package; `-y` keeps the
114
+ // non-interactive spawn (health probe + engine) from stalling on that prompt.
115
+ // Skip if the registry already supplies a confirm flag.
116
+ if (/(^|\/)npx$/.test(command) && !runtimeArgs.some(a => a.name === '-y' || a.name === '--yes')) {
117
+ args.push('-y');
118
+ }
119
+ for (const a of runtimeArgs) args.push(...argTokens(a));
113
120
 
114
121
  // Package identifier token (with version for npm-style registries).
115
122
  const identifier = pkg.version && pkg.registryType === 'npm'
@@ -74,7 +74,18 @@ export {
74
74
 
75
75
  // External catalog + types (used by the WS layer and Settings → MCP)
76
76
  export { listRegistryServers, mapRegistryServer } from './external/registry-client';
77
- export { getEnabledExternalServers } from './external/config';
77
+ export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth } from './external/config';
78
+ export { probeServer } from './external/probe';
79
+ export type { McpHealth, McpHealthState } from './external/probe';
80
+ export {
81
+ startAuthorization,
82
+ completeAuthorization,
83
+ getValidAccessToken,
84
+ refreshExpiringExternalOAuth,
85
+ hasPendingFlow,
86
+ clearOAuth,
87
+ loadOAuth
88
+ } from './external/oauth';
78
89
  export type { CatalogServer, CatalogEnvVar, CatalogPage, ResolvedExternalServer } from './external/types';
79
90
 
80
91
  // ---------------------------------------------------------------------------