@myrialabs/clopen 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,258 @@
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
+ /**
91
+ * Spawn a stdio server and run the same handshake over its stdin/stdout
92
+ * (newline-delimited JSON-RPC) so "local" servers report a real connection
93
+ * status, consistent with remote ones. The subprocess is always killed.
94
+ */
95
+ async function probeStdio(s: ResolvedExternalServer): Promise<McpHealth> {
96
+ if (!s.command) return { state: 'error', message: 'No command configured' };
97
+
98
+ let proc: ReturnType<typeof Bun.spawn>;
99
+ try {
100
+ proc = Bun.spawn([s.command, ...s.args], {
101
+ stdin: 'pipe',
102
+ stdout: 'pipe',
103
+ stderr: 'ignore',
104
+ env: { ...process.env, ...s.env }
105
+ });
106
+ } catch (error) {
107
+ return { state: 'unreachable', message: error instanceof Error ? error.message : 'Failed to start command' };
108
+ }
109
+
110
+ try {
111
+ const stdin = proc.stdin as unknown as { write(data: Uint8Array): number; flush?(): Promise<number> | number };
112
+ const stdout = proc.stdout as unknown as ReadableStream<Uint8Array>;
113
+ const write = (obj: unknown) => stdin.write(new TextEncoder().encode(`${JSON.stringify(obj)}\n`));
114
+ write({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'clopen-probe', version: '1.0.0' } } });
115
+ write({ jsonrpc: '2.0', method: 'notifications/initialized' });
116
+ write({ jsonrpc: '2.0', id: 2, method: 'tools/list' });
117
+ await stdin.flush?.();
118
+
119
+ const rpc = await readStdoutForId(stdout, 2, STDIO_PROBE_TIMEOUT_MS);
120
+ if (!rpc) return { state: 'unreachable', message: `No response within ${STDIO_PROBE_TIMEOUT_MS / 1000}s` };
121
+ if (Array.isArray(rpc.result?.tools)) return { state: 'ok', toolCount: rpc.result.tools.length };
122
+ const detail = rpc.error?.message ?? 'Server did not return a tool list';
123
+ return AUTH_HINT.test(detail) ? { state: 'needs_config', message: detail } : { state: 'error', message: detail };
124
+ } catch (error) {
125
+ return { state: 'error', message: error instanceof Error ? error.message : 'Probe failed' };
126
+ } finally {
127
+ proc.kill();
128
+ }
129
+ }
130
+
131
+ /** Read newline-delimited JSON-RPC from a stream until the response `id` arrives. */
132
+ async function readStdoutForId(stream: ReadableStream<Uint8Array>, id: number, timeoutMs: number): Promise<JsonRpcResponse | null> {
133
+ const reader = stream.getReader();
134
+ const decoder = new TextDecoder();
135
+ let buffer = '';
136
+ const deadline = Date.now() + timeoutMs;
137
+ try {
138
+ while (Date.now() < deadline) {
139
+ const remaining = deadline - Date.now();
140
+ const chunk = await Promise.race([
141
+ reader.read(),
142
+ new Promise<{ done: true; value: undefined }>(resolve => setTimeout(() => resolve({ done: true, value: undefined }), remaining))
143
+ ]);
144
+ if (chunk.done) break;
145
+ buffer += decoder.decode(chunk.value, { stream: true });
146
+ let nl: number;
147
+ while ((nl = buffer.indexOf('\n')) >= 0) {
148
+ const line = buffer.slice(0, nl).trim();
149
+ buffer = buffer.slice(nl + 1);
150
+ if (!line) continue;
151
+ try {
152
+ const msg = JSON.parse(line) as JsonRpcResponse & { id?: number };
153
+ if (msg.id === id) return msg;
154
+ } catch { /* ignore non-JSON log lines */ }
155
+ }
156
+ }
157
+ return null;
158
+ } finally {
159
+ // cancel() (not releaseLock) settles any still-pending read() so this
160
+ // never throws on an outstanding request.
161
+ reader.cancel().catch(() => undefined);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Probe a single resolved server. Remote servers do a network handshake; stdio
167
+ * servers are spawned and handshaken over stdio so every server reports a real
168
+ * connection status.
169
+ */
170
+ export async function probeServer(s: ResolvedExternalServer): Promise<McpHealth> {
171
+ if (s.transport === 'stdio') return probeStdio(s);
172
+ if (!s.url) return { state: 'error', message: 'No URL configured' };
173
+
174
+ const controller = new AbortController();
175
+ const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
176
+ const baseHeaders: Record<string, string> = {
177
+ 'Content-Type': 'application/json',
178
+ Accept: 'application/json, text/event-stream',
179
+ ...s.headers
180
+ };
181
+
182
+ try {
183
+ // 1. initialize
184
+ const initRes = await fetch(s.url, {
185
+ method: 'POST',
186
+ headers: baseHeaders,
187
+ signal: controller.signal,
188
+ body: rpcBody('initialize', 1, {
189
+ protocolVersion: PROTOCOL_VERSION,
190
+ capabilities: {},
191
+ clientInfo: { name: 'clopen-probe', version: '1.0.0' }
192
+ })
193
+ });
194
+
195
+ if (initRes.status === 401 || initRes.status === 403) {
196
+ return classifyUnauthorized(initRes);
197
+ }
198
+ if (!initRes.ok) {
199
+ return { state: 'error', message: `Server responded ${initRes.status} ${initRes.statusText}` };
200
+ }
201
+
202
+ const sessionId = initRes.headers.get('mcp-session-id') ?? undefined;
203
+ await readRpc(initRes); // drain
204
+ const sessionHeaders = sessionId ? { ...baseHeaders, 'mcp-session-id': sessionId } : baseHeaders;
205
+
206
+ // 2. initialized notification (best-effort; some servers require it)
207
+ await fetch(s.url, {
208
+ method: 'POST',
209
+ headers: sessionHeaders,
210
+ signal: controller.signal,
211
+ body: rpcBody('notifications/initialized')
212
+ }).catch(() => undefined);
213
+
214
+ // 3. tools/list
215
+ const listRes = await fetch(s.url, {
216
+ method: 'POST',
217
+ headers: sessionHeaders,
218
+ signal: controller.signal,
219
+ body: rpcBody('tools/list', 2)
220
+ });
221
+
222
+ if (listRes.status === 401 || listRes.status === 403) {
223
+ return classifyUnauthorized(listRes);
224
+ }
225
+ if (!listRes.ok) {
226
+ return { state: 'error', message: `Server responded ${listRes.status} ${listRes.statusText}` };
227
+ }
228
+
229
+ const rpc = await readRpc(listRes);
230
+ if (!rpc) return { state: 'error', message: 'Server returned an unreadable response' };
231
+
232
+ // A proper tools/list returns `result.tools`. Servers that gate listing
233
+ // behind a credential (e.g. trendsmcp) instead return an error result
234
+ // such as "No API key …" — surface that as needs_auth so the user knows
235
+ // to add the credential rather than seeing a generic failure.
236
+ if (Array.isArray(rpc.result?.tools)) {
237
+ return { state: 'ok', toolCount: rpc.result.tools.length };
238
+ }
239
+
240
+ const detail = rpc.error?.message
241
+ ?? rpc.result?.content?.map(c => c.text).filter(Boolean).join(' ')
242
+ ?? 'Server did not return a tool list';
243
+ // Listing gated behind a credential (e.g. trendsmcp "No API key …") — the
244
+ // server is reachable, so this is a missing static credential, not OAuth.
245
+ if (AUTH_HINT.test(detail)) {
246
+ return { state: 'needs_config', message: detail };
247
+ }
248
+ return { state: 'error', message: detail };
249
+ } catch (error) {
250
+ if (error instanceof Error && error.name === 'AbortError') {
251
+ return { state: 'unreachable', message: `No response within ${PROBE_TIMEOUT_MS / 1000}s` };
252
+ }
253
+ debug.warn('mcp', `Probe failed for ${s.slug}:`, error);
254
+ return { state: 'unreachable', message: error instanceof Error ? error.message : 'Could not reach server' };
255
+ } finally {
256
+ clearTimeout(timeout);
257
+ }
258
+ }
@@ -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
  // ---------------------------------------------------------------------------
@@ -18,6 +18,7 @@ import { debug } from '$shared/utils/logger';
18
18
  import { SERVER_ENV } from '../../utils/env';
19
19
  import { validateMcpOutput } from './output-validator';
20
20
  import { MCP_TOOL_CALL_TIMEOUT_MS } from '../shared/constants';
21
+ import { getMcpServiceToken } from './service-token';
21
22
 
22
23
  /**
23
24
  * User-defined MCP Servers Configuration
@@ -445,6 +446,7 @@ export function getOpenCodeMcpConfig(): Record<string, McpRemoteConfig> {
445
446
  url: `http://localhost:${port}/mcp`,
446
447
  enabled: true,
447
448
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
449
+ headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
448
450
  },
449
451
  };
450
452
  }
@@ -462,6 +464,7 @@ export function getOpenCodeMcpConfig(): Record<string, McpRemoteConfig> {
462
464
  */
463
465
  type CodexMcpServerConfig = {
464
466
  url: string;
467
+ http_headers?: Record<string, string>;
465
468
  tools?: Record<string, { approval_mode: 'auto' | 'prompt' | 'approve' }>;
466
469
  };
467
470
 
@@ -507,6 +510,7 @@ export function getCodexMcpConfig(): Record<string, CodexMcpServerConfig> {
507
510
  return {
508
511
  'clopen-mcp': {
509
512
  url: `http://localhost:${port}/mcp`,
513
+ http_headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
510
514
  tools,
511
515
  },
512
516
  };
@@ -559,6 +563,7 @@ export function getCopilotMcpConfig(): Record<string, MCPHTTPServerConfig> {
559
563
  url: `http://localhost:${port}/mcp`,
560
564
  tools,
561
565
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
566
+ headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
562
567
  },
563
568
  };
564
569
  }
@@ -606,6 +611,7 @@ export function getQwenMcpConfig(): Record<string, QwenMcpServerConfig> {
606
611
  includeTools,
607
612
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
608
613
  trust: true,
614
+ headers: { Authorization: `Bearer ${getMcpServiceToken()}` },
609
615
  },
610
616
  };
611
617
  }
@@ -12,6 +12,7 @@ import { describe, expect, test, beforeAll, afterAll, beforeEach } from 'bun:tes
12
12
  import { randomUUID } from 'node:crypto';
13
13
 
14
14
  import { handleMcpRequest } from './remote-server';
15
+ import { getMcpServiceToken } from './service-token';
15
16
  import { authQueries, settingsQueries } from '../../database/queries';
16
17
  import { generatePAT, generateSessionToken, hashToken } from '../../auth/tokens';
17
18
  import { initializeDatabase, closeDatabase, getDatabase } from '../../database';
@@ -130,6 +131,19 @@ describe('MCP Remote Server Authentication', () => {
130
131
  expect(response.status).not.toBe(401);
131
132
  });
132
133
 
134
+ test('accepts the internal service token even when auth is required', async () => {
135
+ // The non-Claude engines authenticate to the bridge with this loopback
136
+ // token, not a user session. Without it the whole clopen-mcp bridge 401s.
137
+ const response = await handleMcpRequest(mcpRequest(getMcpServiceToken()));
138
+ expect(response.status).not.toBe(401);
139
+ });
140
+
141
+ test('does not mint a session for the service token', async () => {
142
+ const before = sessionCount(testUserId);
143
+ await handleMcpRequest(mcpRequest(getMcpServiceToken()));
144
+ expect(sessionCount(testUserId)).toBe(before);
145
+ });
146
+
133
147
  test('skips authentication in no-auth mode', async () => {
134
148
  setAuthMode('none');
135
149
  const response = await handleMcpRequest(mcpRequest());