@myrialabs/clopen 0.4.17 → 0.4.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/backend/auth/auth-service.ts +265 -13
- package/backend/auth/permissions.ts +3 -0
- package/backend/auth/rate-limiter.ts +1 -0
- package/backend/auth/session-cleanup.ts +5 -0
- package/backend/auth/tokens.ts +8 -1
- package/backend/chat/stream-manager.ts +8 -0
- package/backend/database/migrations/060_create_device_codes_table.ts +38 -0
- package/backend/database/migrations/061_add_session_device_metadata.ts +42 -0
- package/backend/database/migrations/062_add_session_source.ts +43 -0
- package/backend/database/migrations/063_add_invite_project_ids.ts +42 -0
- package/backend/database/migrations/064_create_messages_fts.ts +71 -0
- package/backend/database/migrations/index.ts +35 -0
- package/backend/database/queries/auth-queries.ts +100 -6
- package/backend/database/queries/message-queries.ts +44 -0
- package/backend/database/queries/session-queries.ts +117 -12
- package/backend/engine/README.md +21 -4
- package/backend/engine/adapters/claude/stream.ts +4 -2
- package/backend/engine/adapters/cline/agent-tool.ts +3 -2
- package/backend/engine/adapters/cline/ask-question-tool.ts +3 -2
- package/backend/engine/adapters/cline/credential.ts +2 -1
- package/backend/engine/adapters/cline/mcp-tools.ts +2 -1
- package/backend/engine/adapters/cline/models.ts +3 -1
- package/backend/engine/adapters/cline/presets.ts +5 -3
- package/backend/engine/adapters/cline/stream.ts +10 -7
- package/backend/engine/adapters/codex/stream.ts +3 -1
- package/backend/engine/adapters/copilot/stream.ts +8 -1
- package/backend/engine/adapters/cursor/environment.ts +4 -2
- package/backend/engine/adapters/cursor/models.ts +2 -1
- package/backend/engine/adapters/cursor/stream.ts +5 -3
- package/backend/engine/adapters/opencode/server.ts +2 -1
- package/backend/engine/adapters/pi/presets.ts +3 -1
- package/backend/engine/adapters/pi/session-fork.ts +3 -1
- package/backend/engine/adapters/pi/stream.ts +11 -8
- package/backend/engine/adapters/qwen/stream.ts +10 -8
- package/backend/engine/bootstrap-default-engine.ts +69 -0
- package/backend/engine/docs/adding-an-engine.md +29 -6
- package/backend/engine/docs/frontend-and-chat.md +21 -5
- package/backend/engine/docs/lessons-learned.md +41 -0
- package/backend/engine/docs/quick-reference.md +3 -2
- package/backend/engine/docs/system-tools.md +65 -9
- package/backend/engine/docs/websocket-routes.md +4 -3
- package/backend/engine/engine-setup.ts +72 -0
- package/backend/engine/install-recipes.ts +82 -77
- package/backend/engine/install-runner.ts +27 -2
- package/backend/engine/sdk-loader.ts +180 -0
- package/backend/engine/version-check.ts +6 -6
- package/backend/http/files-upload.test.ts +4 -1
- package/backend/index.ts +32 -2
- package/backend/mcp/README.md +26 -8
- package/backend/mcp/index.ts +2 -2
- package/backend/mcp/internal/config.ts +54 -63
- package/backend/mcp/internal/remote-server.test.ts +4 -1
- package/backend/mcp/internal/servers/helper.ts +4 -34
- package/backend/mcp/internal/servers/index.ts +4 -13
- package/backend/tunnel/public-origin.ts +118 -0
- package/backend/utils/ws.ts +126 -1
- package/backend/ws/auth/device.ts +239 -0
- package/backend/ws/auth/index.ts +8 -0
- package/backend/ws/auth/invites.ts +16 -6
- package/backend/ws/auth/login.test.ts +2 -2
- package/backend/ws/auth/login.ts +12 -6
- package/backend/ws/engine/claude/status.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +3 -2
- package/backend/ws/engine/cline/status.ts +4 -12
- package/backend/ws/engine/codex/status.ts +4 -12
- package/backend/ws/engine/copilot/status.ts +5 -12
- package/backend/ws/engine/cursor/accounts.ts +2 -1
- package/backend/ws/engine/cursor/status.ts +5 -12
- package/backend/ws/engine/opencode/status.ts +4 -4
- package/backend/ws/engine/pi/status.ts +4 -12
- package/backend/ws/engine/qwen/status.ts +5 -12
- package/backend/ws/sessions/crud.ts +29 -4
- package/backend/ws/settings/crud.ts +10 -1
- package/backend/ws/system/operations.ts +34 -18
- package/backend/ws/system-tools/install.ts +3 -0
- package/backend/ws/system-tools/status.ts +7 -2
- package/backend/ws/tunnel/index.ts +3 -1
- package/backend/ws/tunnel/share.ts +27 -0
- package/bin/clopen.ts +1 -1
- package/dist/assets/{index-kME3THy5.js → index-BqBxKeAv.js} +1 -1
- package/dist/assets/{index-Bu5loFQE.js → index-DdrcY5TE.js} +1 -1
- package/dist/assets/{main-HirJLquI.js → main-BBxAj17T.js} +337 -330
- package/dist/assets/main-Cry3pLcl.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +15 -14
- package/shared/constants/engines.ts +39 -40
- package/shared/constants/tool-icons.ts +49 -0
- package/shared/types/stores/settings.ts +9 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-D7ATW8pp.css +0 -1
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engine SDK lazy loader
|
|
3
|
+
*
|
|
4
|
+
* Engine SDKs (Claude Agent SDK, Copilot SDK, Codex SDK, …) are NOT bundled
|
|
5
|
+
* into the clopen global install. They are installed on demand into a directory
|
|
6
|
+
* clopen manages — `~/.clopen/stack/engines` — which keeps them:
|
|
7
|
+
* - out of the user's global bun store (no PATH pollution, no version clashes),
|
|
8
|
+
* - out of the user's projects (never touches their package.json/node_modules),
|
|
9
|
+
* - isolated to clopen and surviving clopen reinstalls.
|
|
10
|
+
* This is the runtime half of the "Stack" concept (Settings → Stack).
|
|
11
|
+
*
|
|
12
|
+
* package.json (devDependencies) remains the single source of truth for the
|
|
13
|
+
* exact pinned version each engine installs; this module only resolves and
|
|
14
|
+
* loads whatever is present in the managed directory. When an SDK is not
|
|
15
|
+
* installed the import throws a typed `EngineSdkNotInstalledError` so a missing
|
|
16
|
+
* engine degrades to "not installed" in the UI instead of crashing the backend.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
21
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
22
|
+
import { debug } from '$shared/utils/logger';
|
|
23
|
+
|
|
24
|
+
export type EngineSdkId =
|
|
25
|
+
| 'claude-code'
|
|
26
|
+
| 'copilot'
|
|
27
|
+
| 'codex'
|
|
28
|
+
| 'qwen'
|
|
29
|
+
| 'opencode'
|
|
30
|
+
| 'pi'
|
|
31
|
+
| 'cline'
|
|
32
|
+
| 'cursor';
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Thrown when an engine's SDK package cannot be resolved at runtime — i.e. the
|
|
36
|
+
* engine has not been installed on demand yet. Carries the engine id and the
|
|
37
|
+
* npm package name so callers can render an actionable "install this engine"
|
|
38
|
+
* message rather than surfacing a raw module-resolution error.
|
|
39
|
+
*/
|
|
40
|
+
export type EngineSetupReason = 'not-installed' | 'needs-update';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Thrown when an engine cannot be used because its SDK is not ready in the
|
|
44
|
+
* managed stack dir: either not installed, or installed at a version other than
|
|
45
|
+
* the one clopen pins (a mandatory update). Carries enough for the UI to render
|
|
46
|
+
* an actionable prompt; the message is also human-readable for the chat error
|
|
47
|
+
* surface. `reason` drives the wording and the target action.
|
|
48
|
+
*/
|
|
49
|
+
export class EngineNotReadyError extends Error {
|
|
50
|
+
readonly engine: EngineSdkId;
|
|
51
|
+
readonly packageName: string;
|
|
52
|
+
readonly reason: EngineSetupReason;
|
|
53
|
+
readonly installedVersion: string | null;
|
|
54
|
+
readonly requiredVersion: string | null;
|
|
55
|
+
|
|
56
|
+
constructor(
|
|
57
|
+
engine: EngineSdkId,
|
|
58
|
+
packageName: string,
|
|
59
|
+
reason: EngineSetupReason,
|
|
60
|
+
installedVersion: string | null,
|
|
61
|
+
requiredVersion: string | null,
|
|
62
|
+
cause?: unknown
|
|
63
|
+
) {
|
|
64
|
+
const detail = reason === 'needs-update'
|
|
65
|
+
? `needs an update (installed ${installedVersion ?? 'unknown'}, ` +
|
|
66
|
+
`required ${requiredVersion ?? 'unknown'}). Open Settings → Stack to ` +
|
|
67
|
+
`update it before using this engine.`
|
|
68
|
+
: `is not installed. Open Settings → Stack to install it.`;
|
|
69
|
+
super(`Engine "${engine}" ${detail}`);
|
|
70
|
+
this.name = 'EngineNotReadyError';
|
|
71
|
+
this.engine = engine;
|
|
72
|
+
this.packageName = packageName;
|
|
73
|
+
this.reason = reason;
|
|
74
|
+
this.installedVersion = installedVersion;
|
|
75
|
+
this.requiredVersion = requiredVersion;
|
|
76
|
+
if (cause !== undefined) (this as { cause?: unknown }).cause = cause;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The clopen-managed directory that on-demand engine SDKs are installed into.
|
|
82
|
+
* It is a self-contained bun project (`node_modules` + a minimal package.json),
|
|
83
|
+
* so a globally-installed clopen never has to touch the user's global store.
|
|
84
|
+
*/
|
|
85
|
+
export function getStackEnginesDir(): string {
|
|
86
|
+
return join(getClopenDir(), 'stack', 'engines');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Absolute path of an installed engine package inside the managed dir. */
|
|
90
|
+
function stackPackageDir(packageName: string): string {
|
|
91
|
+
return join(getStackEnginesDir(), 'node_modules', packageName);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Exact versions clopen pins for its dependencies (read from package.json —
|
|
96
|
+
* the single source of truth). An engine SDK installed in the stack dir must
|
|
97
|
+
* match its pinned version, or it is considered out of date and must be updated.
|
|
98
|
+
*/
|
|
99
|
+
let cachedRequiredVersions: Record<string, string> | null = null;
|
|
100
|
+
function requiredVersions(): Record<string, string> {
|
|
101
|
+
if (cachedRequiredVersions) return cachedRequiredVersions;
|
|
102
|
+
try {
|
|
103
|
+
const pkgPath = join(import.meta.dir, '..', '..', 'package.json');
|
|
104
|
+
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {
|
|
105
|
+
dependencies?: Record<string, string>;
|
|
106
|
+
devDependencies?: Record<string, string>;
|
|
107
|
+
};
|
|
108
|
+
cachedRequiredVersions = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
109
|
+
} catch {
|
|
110
|
+
cachedRequiredVersions = {};
|
|
111
|
+
}
|
|
112
|
+
return cachedRequiredVersions;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The exact version clopen pins for an SDK package (from package.json), or null. */
|
|
116
|
+
export function getRequiredSdkVersion(packageName: string): string | null {
|
|
117
|
+
return requiredVersions()[packageName] ?? null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Resolved-module cache so repeat loads of the same SDK are cheap. */
|
|
121
|
+
const moduleCache = new Map<string, unknown>();
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Dynamically import an engine SDK from the managed stack directory, caching the
|
|
125
|
+
* module. Throws `EngineSdkNotInstalledError` when the package is not installed.
|
|
126
|
+
*
|
|
127
|
+
* Type the result via the `T` parameter using `typeof import('<pkg>')`, e.g.:
|
|
128
|
+
* const { CopilotClient } = await loadEngineSdk<typeof import('@github/copilot-sdk')>(
|
|
129
|
+
* 'copilot', '@github/copilot-sdk'
|
|
130
|
+
* );
|
|
131
|
+
* Keep all compile-time type references on `import type` so they are erased at
|
|
132
|
+
* runtime and never force resolution of an absent package.
|
|
133
|
+
*/
|
|
134
|
+
export async function loadEngineSdk<T>(engine: EngineSdkId, packageName: string): Promise<T> {
|
|
135
|
+
const cached = moduleCache.get(packageName);
|
|
136
|
+
if (cached !== undefined) return cached as T;
|
|
137
|
+
|
|
138
|
+
// Guard readiness before loading: not installed, or installed at a version
|
|
139
|
+
// other than the one clopen pins (a mandatory update).
|
|
140
|
+
const installed = readEngineSdkVersion(packageName);
|
|
141
|
+
const required = getRequiredSdkVersion(packageName);
|
|
142
|
+
if (installed === null) {
|
|
143
|
+
throw new EngineNotReadyError(engine, packageName, 'not-installed', null, required);
|
|
144
|
+
}
|
|
145
|
+
if (required !== null && installed !== required) {
|
|
146
|
+
throw new EngineNotReadyError(engine, packageName, 'needs-update', installed, required);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
try {
|
|
150
|
+
// Resolve the package's entry point (respecting its `exports`/`main`) from
|
|
151
|
+
// the managed dir, then import by absolute path.
|
|
152
|
+
const entry = Bun.resolveSync(packageName, getStackEnginesDir());
|
|
153
|
+
const mod = (await import(entry)) as T;
|
|
154
|
+
moduleCache.set(packageName, mod);
|
|
155
|
+
return mod;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
debug.warn('engine', `Engine SDK "${packageName}" (${engine}) failed to load`, error);
|
|
158
|
+
throw new EngineNotReadyError(engine, packageName, 'not-installed', installed, required, error);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Installed version of an engine SDK in the managed stack dir, or null when not
|
|
164
|
+
* installed. Reads package.json directly (bypassing any `exports` map that would
|
|
165
|
+
* hide `./package.json`), so detection is robust across packages.
|
|
166
|
+
*/
|
|
167
|
+
export function readEngineSdkVersion(packageName: string): string | null {
|
|
168
|
+
try {
|
|
169
|
+
const pkgJsonPath = join(stackPackageDir(packageName), 'package.json');
|
|
170
|
+
const json = JSON.parse(readFileSync(pkgJsonPath, 'utf8')) as { version?: string };
|
|
171
|
+
return json.version ?? null;
|
|
172
|
+
} catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Whether an engine's SDK package is installed in the managed stack dir. */
|
|
178
|
+
export function isEngineSdkInstalled(packageName: string): boolean {
|
|
179
|
+
return existsSync(join(stackPackageDir(packageName), 'package.json'));
|
|
180
|
+
}
|
|
@@ -12,12 +12,11 @@ type VersionSource =
|
|
|
12
12
|
| { type: 'github-release'; repo: string }
|
|
13
13
|
| { type: 'chrome-for-testing' };
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
qwen: { type: 'npm', pkg: '@qwen-code/qwen-code' },
|
|
15
|
+
// Engines are intentionally absent: their SDK versions are pinned in
|
|
16
|
+
// package.json (the single source of truth) and move in lockstep with clopen
|
|
17
|
+
// releases, so we do not nag users to drift off the tested version. Only host
|
|
18
|
+
// tools (git, chrome) self-update independently.
|
|
19
|
+
const SOURCES: Partial<Record<ToolId, VersionSource>> = {
|
|
21
20
|
git: { type: 'homebrew-formula', formula: 'git' },
|
|
22
21
|
chrome: { type: 'chrome-for-testing' },
|
|
23
22
|
};
|
|
@@ -118,6 +117,7 @@ export async function checkToolUpdate(
|
|
|
118
117
|
installedVersion: string | null
|
|
119
118
|
): Promise<UpdateCheckResult> {
|
|
120
119
|
const source = SOURCES[tool];
|
|
120
|
+
if (!source) return { latestVersion: null, hasUpdate: null };
|
|
121
121
|
|
|
122
122
|
let latestVersion: string | null;
|
|
123
123
|
switch (source.type) {
|
|
@@ -76,7 +76,10 @@ beforeAll(async () => {
|
|
|
76
76
|
token_hash: hashToken(testToken),
|
|
77
77
|
expires_at: expiresAt,
|
|
78
78
|
created_at: new Date().toISOString(),
|
|
79
|
-
last_active_at: new Date().toISOString()
|
|
79
|
+
last_active_at: new Date().toISOString(),
|
|
80
|
+
user_agent: null,
|
|
81
|
+
ip_address: null,
|
|
82
|
+
source: null
|
|
80
83
|
});
|
|
81
84
|
|
|
82
85
|
// Create test project
|
package/backend/index.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { loggerMiddleware } from './middleware/logger';
|
|
|
23
23
|
|
|
24
24
|
// Database initialization
|
|
25
25
|
import { initializeDatabase, closeDatabase } from './database';
|
|
26
|
+
import { ensureDefaultEngineInstalled } from './engine/bootstrap-default-engine';
|
|
26
27
|
import { syncInternalServers } from './mcp';
|
|
27
28
|
import { disposeAllEngines } from './engine';
|
|
28
29
|
import { connectionManager } from './db-client/connection-manager';
|
|
@@ -49,18 +50,43 @@ import { browserPreviewServiceManager } from './preview';
|
|
|
49
50
|
import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
|
|
50
51
|
|
|
51
52
|
// Auth middleware
|
|
52
|
-
import { checkRouteAccess } from './auth/permissions';
|
|
53
|
+
import { checkRouteAccess, PUBLIC_ROUTES } from './auth/permissions';
|
|
54
|
+
import { getAuthMode } from './auth/auth-service';
|
|
55
|
+
import { authQueries } from './database/queries';
|
|
53
56
|
import { authRateLimiter } from './auth';
|
|
54
57
|
import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
55
58
|
import { uploadTempCleanup } from './http/upload-temp-cleanup';
|
|
56
59
|
import { ws as wsServer } from './utils/ws';
|
|
57
60
|
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
58
61
|
|
|
62
|
+
/** How often (ms) the auth gate re-confirms a connection's session against the DB. */
|
|
63
|
+
const SESSION_REVALIDATE_MS = 15_000;
|
|
64
|
+
|
|
59
65
|
// Register auth gate on WebSocket router — blocks unauthenticated/unauthorized access
|
|
60
66
|
wsRouter.setAuthMiddleware(async (conn, action) => {
|
|
61
67
|
const isAuth = wsServer.isAuthenticated(conn);
|
|
62
68
|
const role = wsServer.getRole(conn);
|
|
63
|
-
|
|
69
|
+
const result = checkRouteAccess(action, isAuth, role);
|
|
70
|
+
if (!result.allowed) return result;
|
|
71
|
+
|
|
72
|
+
// Defense-in-depth: an authenticated connection trusts the in-memory auth set
|
|
73
|
+
// at login. If its session was revoked/expired/deleted afterwards (sign-out
|
|
74
|
+
// from another device, admin removal, expiry), the live socket would otherwise
|
|
75
|
+
// keep full access until it reconnects. Periodically re-confirm the session
|
|
76
|
+
// still exists in the DB and kick the connection the moment it doesn't.
|
|
77
|
+
if (isAuth && getAuthMode() === 'required' && !PUBLIC_ROUTES.has(action)) {
|
|
78
|
+
if (wsServer.dueForSessionCheck(conn, SESSION_REVALIDATE_MS)) {
|
|
79
|
+
const hash = wsServer.getSessionTokenHash(conn);
|
|
80
|
+
const session = hash ? authQueries.getSessionByTokenHash(hash) : null;
|
|
81
|
+
const valid = !!session && new Date(session.expires_at) >= new Date();
|
|
82
|
+
if (!valid) {
|
|
83
|
+
wsServer.invalidateConnection(conn, 'Your session has ended');
|
|
84
|
+
return { allowed: false, error: 'Session ended' };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return result;
|
|
64
90
|
});
|
|
65
91
|
|
|
66
92
|
// Register message rate limiter on WebSocket router — prevents DoS via message spam
|
|
@@ -215,6 +241,10 @@ async function startServer() {
|
|
|
215
241
|
// Start expired session cleanup now that the database is ready
|
|
216
242
|
sessionCleanupScheduler.start();
|
|
217
243
|
uploadTempCleanup.start();
|
|
244
|
+
// Fresh installs: auto-install OpenCode (free, no account) in the
|
|
245
|
+
// background so first-time users have a working engine without any manual
|
|
246
|
+
// setup. Non-blocking; no-ops once any engine is already installed.
|
|
247
|
+
void ensureDefaultEngineInstalled();
|
|
218
248
|
} catch (error) {
|
|
219
249
|
debug.warn('database', '⚠️ Database initialization failed:', error);
|
|
220
250
|
}
|
package/backend/mcp/README.md
CHANGED
|
@@ -52,7 +52,14 @@ System for adding custom tools to AI engines with type-safe TypeScript definitio
|
|
|
52
52
|
|
|
53
53
|
**Features:**
|
|
54
54
|
- Single source of truth — define tools once, use in every engine
|
|
55
|
-
-
|
|
55
|
+
- **Decoupled from the Claude Agent SDK.** `internal/` holds only
|
|
56
|
+
engine-agnostic raw tool defs (built on `@modelcontextprotocol/sdk`). The
|
|
57
|
+
Claude-SDK-shaped in-process servers are built **lazily** — only on the Claude
|
|
58
|
+
path — inside `getEnabledMcpServers()` (now `async`), which lazy-loads
|
|
59
|
+
`createSdkMcpServer`/`tool` from `@anthropic-ai/claude-agent-sdk` via
|
|
60
|
+
`loadEngineSdk`. Non-Claude engines never touch the Claude SDK; they already
|
|
61
|
+
use the remote HTTP bridge (`createRemoteMcpServer`).
|
|
62
|
+
- In-process execution for Claude Code via `createSdkMcpServer` (loaded on demand)
|
|
56
63
|
- Remote HTTP MCP server (Streamable HTTP) for Open Code, Codex, and
|
|
57
64
|
Copilot via `createRemoteMcpServer` mounted at `/mcp`
|
|
58
65
|
- All engines execute handlers in-process (no subprocess, no bridge)
|
|
@@ -238,7 +245,8 @@ servers/browser-automation/
|
|
|
238
245
|
└─> User config merged with registry automatically
|
|
239
246
|
↓
|
|
240
247
|
4. Claude Agent SDK (stream.ts)
|
|
241
|
-
└─> Uses getEnabledMcpServers()
|
|
248
|
+
└─> Uses await getEnabledMcpServers() — builds Claude-SDK servers lazily
|
|
249
|
+
from the raw defs (lazy-loads @anthropic-ai/claude-agent-sdk)
|
|
242
250
|
↓
|
|
243
251
|
5. Claude uses the tool (in-process handler execution)
|
|
244
252
|
↓
|
|
@@ -272,8 +280,11 @@ servers/browser-automation/
|
|
|
272
280
|
|
|
273
281
|
**`defineServer`**
|
|
274
282
|
Helper function to define MCP server with automatic metadata extraction.
|
|
275
|
-
Stores
|
|
276
|
-
|
|
283
|
+
Stores **engine-agnostic** raw tool definitions (`toolDefs`, built on
|
|
284
|
+
`@modelcontextprotocol/sdk`) — no Claude SDK dependency. The Claude-SDK-shaped
|
|
285
|
+
in-process server is constructed lazily from these defs on the Claude path only
|
|
286
|
+
(`getEnabledMcpServers()`); the remote HTTP bridge (`createRemoteMcpServer`)
|
|
287
|
+
builds its `McpServer` from the same defs for every other engine.
|
|
277
288
|
|
|
278
289
|
**`buildServerRegistries`**
|
|
279
290
|
Function to build server registries from server array.
|
|
@@ -529,13 +540,18 @@ const weatherServer = serverRegistry["weather-service"];
|
|
|
529
540
|
### Main Functions
|
|
530
541
|
|
|
531
542
|
#### `getEnabledMcpServers()`
|
|
532
|
-
Returns all enabled MCP servers
|
|
543
|
+
Returns all enabled MCP servers as Claude-SDK-shaped in-process servers. This
|
|
544
|
+
is the **only** path that touches the Claude Agent SDK: it is `async` and
|
|
545
|
+
lazy-loads `createSdkMcpServer`/`tool` from `@anthropic-ai/claude-agent-sdk`
|
|
546
|
+
(via `loadEngineSdk`) only when called — so non-Claude engines never pull the
|
|
547
|
+
Claude SDK in. Every other engine consumes the raw tool defs through the remote
|
|
548
|
+
HTTP bridge instead.
|
|
533
549
|
|
|
534
550
|
```typescript
|
|
535
551
|
import { getEnabledMcpServers } from '$backend/mcp';
|
|
536
552
|
|
|
537
|
-
const servers = getEnabledMcpServers();
|
|
538
|
-
// Returns: Record<string, McpServerConfig
|
|
553
|
+
const servers = await getEnabledMcpServers();
|
|
554
|
+
// Returns: Promise<Record<string, McpServerConfig>>
|
|
539
555
|
```
|
|
540
556
|
|
|
541
557
|
#### `getAllowedMcpTools()`
|
|
@@ -1127,7 +1143,9 @@ export default defineServer({
|
|
|
1127
1143
|
**Problem:** TypeScript errors in custom tool.
|
|
1128
1144
|
|
|
1129
1145
|
**Solutions:**
|
|
1130
|
-
1. Install dependencies: `bun install
|
|
1146
|
+
1. Install dependencies: `bun install` (internal tools depend only on `zod`
|
|
1147
|
+
+ `@modelcontextprotocol/sdk` — NOT the Claude Agent SDK, which is loaded on
|
|
1148
|
+
demand elsewhere)
|
|
1131
1149
|
2. Verify you're importing `defineServer` from `../helper`
|
|
1132
1150
|
3. Check that server name matches between `defineServer` and `config.ts`
|
|
1133
1151
|
4. Verify tool names in `config.ts` match tool keys in `defineServer`
|
package/backend/mcp/index.ts
CHANGED
|
@@ -105,9 +105,9 @@ export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse
|
|
|
105
105
|
// existing behaviour, unchanged.
|
|
106
106
|
|
|
107
107
|
/** Claude Agent SDK `mcpServers`: in-process internal servers + external stdio/remote. */
|
|
108
|
-
export function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Record<string, McpServerConfig
|
|
108
|
+
export async function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Promise<Record<string, McpServerConfig>> {
|
|
109
109
|
return {
|
|
110
|
-
...internal.getEnabledMcpServers(context, profileFilter),
|
|
110
|
+
...(await internal.getEnabledMcpServers(context, profileFilter)),
|
|
111
111
|
...external.getClaudeExternalMcpConfig(profileFilter)
|
|
112
112
|
};
|
|
113
113
|
}
|
|
@@ -5,14 +5,15 @@
|
|
|
5
5
|
* to avoid duplication and make it easier to add new servers.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import
|
|
8
|
+
import type { McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
|
|
9
9
|
import type { McpRemoteConfig } from '@opencode-ai/sdk';
|
|
10
10
|
import type { MCPHTTPServerConfig } from '@github/copilot-sdk';
|
|
11
11
|
import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
|
|
12
12
|
import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
|
|
13
13
|
import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
|
|
14
14
|
import type { McpExecutionContext } from '../../engine/types';
|
|
15
|
-
import {
|
|
15
|
+
import { serverMetadata } from './servers';
|
|
16
|
+
import { loadEngineSdk } from '$backend/engine/sdk-loader';
|
|
16
17
|
import { projectContextService } from './project-context';
|
|
17
18
|
import { mcpServerQueries } from '$backend/database/queries';
|
|
18
19
|
import { debug } from '$shared/utils/logger';
|
|
@@ -56,30 +57,14 @@ export const mcpServersConfig: Record<ServerName, ServerConfig> = {
|
|
|
56
57
|
};
|
|
57
58
|
|
|
58
59
|
/**
|
|
59
|
-
*
|
|
60
|
-
*/
|
|
61
|
-
function createServerConfig<T extends Record<ServerName, ServerConfig>>(
|
|
62
|
-
config: T
|
|
63
|
-
): { [K in keyof T]: T[K] & { instance: McpSdkServerConfigWithInstance } } {
|
|
64
|
-
const result = {} as any;
|
|
65
|
-
|
|
66
|
-
for (const [serverName, serverConfig] of Object.entries(config)) {
|
|
67
|
-
result[serverName] = {
|
|
68
|
-
...serverConfig,
|
|
69
|
-
instance: serverRegistry[serverName as ServerName]
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
return result;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/**
|
|
77
|
-
* MCP Servers Configuration with instances
|
|
60
|
+
* MCP Servers Configuration
|
|
78
61
|
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
62
|
+
* The final configuration used throughout the application. SDK-shaped
|
|
63
|
+
* in-process server instances (Claude Code) are built on demand in
|
|
64
|
+
* `getEnabledMcpServers`; every other path works off server names + the raw
|
|
65
|
+
* tool defs held in `serverMetadata`.
|
|
81
66
|
*/
|
|
82
|
-
export const mcpServers: Record<string, ServerConfig
|
|
67
|
+
export const mcpServers: Record<string, ServerConfig> = mcpServersConfig;
|
|
83
68
|
|
|
84
69
|
// ============================================================================
|
|
85
70
|
// Runtime enabled state (DB-backed)
|
|
@@ -130,50 +115,56 @@ function serverEnabled(serverName: string): boolean {
|
|
|
130
115
|
* propagation — without this, background streams from Project A would
|
|
131
116
|
* resolve to Project B's preview browser when the user switches projects.
|
|
132
117
|
*/
|
|
133
|
-
export function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Record<string, McpServerConfig
|
|
118
|
+
export async function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Promise<Record<string, McpServerConfig>> {
|
|
134
119
|
const enabledServers: Record<string, McpServerConfig> = {};
|
|
135
120
|
const active = new Set(activeInternalServerNames(profileFilter));
|
|
121
|
+
const activeNames = Object.keys(mcpServers).filter(name => active.has(name));
|
|
136
122
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
// short-circuit if the owning stream's AbortSignal has fired
|
|
143
|
-
// — handler never runs, no half-completed browser ops.
|
|
144
|
-
const meta = serverMetadata[serverName as ServerName];
|
|
145
|
-
const sdkTools = (serverConfig.tools as readonly string[]).map(toolName => {
|
|
146
|
-
const def = meta.toolDefs[toolName];
|
|
147
|
-
const boundHandler = async (args: any) => {
|
|
148
|
-
return projectContextService.runWithContextAsync(context, async () => {
|
|
149
|
-
const signal = projectContextService.getCurrentSignal();
|
|
150
|
-
if (signal?.aborted) {
|
|
151
|
-
return abortedToolResult(toolName);
|
|
152
|
-
}
|
|
153
|
-
const result = await def.handler(args);
|
|
154
|
-
result.content = validateMcpOutput(result.content, toolName);
|
|
155
|
-
return result;
|
|
156
|
-
});
|
|
157
|
-
};
|
|
158
|
-
return tool(toolName, def.description, def.schema, boundHandler as any);
|
|
159
|
-
});
|
|
160
|
-
enabledServers[serverName] = createSdkMcpServer({
|
|
161
|
-
name: meta.name,
|
|
162
|
-
version: '1.0.0',
|
|
163
|
-
tools: sdkTools
|
|
164
|
-
});
|
|
165
|
-
} else {
|
|
166
|
-
const factory = serverFactories[serverName as ServerName];
|
|
167
|
-
enabledServers[serverName] = factory ? factory() : serverConfig.instance;
|
|
168
|
-
}
|
|
169
|
-
debug.log('mcp', `✓ Enabled MCP server: ${serverName}${context ? ' (context-bound)' : ''}`);
|
|
170
|
-
} else {
|
|
171
|
-
debug.log('mcp', `✗ Disabled MCP server: ${serverName}`);
|
|
172
|
-
}
|
|
173
|
-
});
|
|
123
|
+
// Nothing to build → don't load the Claude Agent SDK at all.
|
|
124
|
+
if (activeNames.length === 0) {
|
|
125
|
+
debug.log('mcp', 'Total enabled MCP servers: 0');
|
|
126
|
+
return enabledServers;
|
|
127
|
+
}
|
|
174
128
|
|
|
175
|
-
|
|
129
|
+
// This is the Claude in-process path ONLY (other engines consume the remote
|
|
130
|
+
// HTTP bridge via createRemoteMcpServer, which uses @modelcontextprotocol/sdk
|
|
131
|
+
// directly). Load the Claude Agent SDK's `createSdkMcpServer`/`tool` lazily so
|
|
132
|
+
// it is never required unless the Claude engine actually streams.
|
|
133
|
+
const { createSdkMcpServer, tool } = await loadEngineSdk<typeof import('@anthropic-ai/claude-agent-sdk')>(
|
|
134
|
+
'claude-code', '@anthropic-ai/claude-agent-sdk'
|
|
135
|
+
);
|
|
176
136
|
|
|
137
|
+
for (const serverName of activeNames) {
|
|
138
|
+
const serverConfig = mcpServers[serverName];
|
|
139
|
+
const meta = serverMetadata[serverName as ServerName];
|
|
140
|
+
const sdkTools = (serverConfig.tools as readonly string[]).map(toolName => {
|
|
141
|
+
const def = meta.toolDefs[toolName];
|
|
142
|
+
// With context: wrap each handler so AsyncLocalStorage context is
|
|
143
|
+
// restored on invocation, then short-circuit if the owning stream's
|
|
144
|
+
// AbortSignal has fired — handler never runs, no half-completed
|
|
145
|
+
// browser ops. Without context: the raw handler (unchanged behavior).
|
|
146
|
+
const handler = context
|
|
147
|
+
? async (args: any) => projectContextService.runWithContextAsync(context, async () => {
|
|
148
|
+
const signal = projectContextService.getCurrentSignal();
|
|
149
|
+
if (signal?.aborted) {
|
|
150
|
+
return abortedToolResult(toolName);
|
|
151
|
+
}
|
|
152
|
+
const result = await def.handler(args);
|
|
153
|
+
result.content = validateMcpOutput(result.content, toolName);
|
|
154
|
+
return result;
|
|
155
|
+
})
|
|
156
|
+
: def.handler;
|
|
157
|
+
return tool(toolName, def.description, def.schema, handler as any);
|
|
158
|
+
});
|
|
159
|
+
enabledServers[serverName] = createSdkMcpServer({
|
|
160
|
+
name: meta.name,
|
|
161
|
+
version: '1.0.0',
|
|
162
|
+
tools: sdkTools
|
|
163
|
+
});
|
|
164
|
+
debug.log('mcp', `✓ Enabled MCP server: ${serverName}${context ? ' (context-bound)' : ''}`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
debug.log('mcp', `Total enabled MCP servers: ${Object.keys(enabledServers).length}`);
|
|
177
168
|
return enabledServers;
|
|
178
169
|
}
|
|
179
170
|
|
|
@@ -70,7 +70,10 @@ beforeAll(async () => {
|
|
|
70
70
|
token_hash: hashToken(sessionToken),
|
|
71
71
|
expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
|
72
72
|
created_at: new Date().toISOString(),
|
|
73
|
-
last_active_at: new Date().toISOString()
|
|
73
|
+
last_active_at: new Date().toISOString(),
|
|
74
|
+
user_agent: null,
|
|
75
|
+
ip_address: null,
|
|
76
|
+
source: null
|
|
74
77
|
});
|
|
75
78
|
});
|
|
76
79
|
|
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
* Open Code: createRemoteMcpServer() → HTTP MCP server (same process, same handlers)
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
13
12
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
14
13
|
import type { z } from "zod";
|
|
15
14
|
import { projectContextService } from '../project-context';
|
|
@@ -56,9 +55,6 @@ interface ServerWithMeta<
|
|
|
56
55
|
TName extends string,
|
|
57
56
|
TToolNames extends readonly string[]
|
|
58
57
|
> {
|
|
59
|
-
server: ReturnType<typeof createSdkMcpServer>;
|
|
60
|
-
/** Factory that creates a fresh SDK server instance (new Protocol, safe for concurrent use) */
|
|
61
|
-
createInstance: () => ReturnType<typeof createSdkMcpServer>;
|
|
62
58
|
meta: {
|
|
63
59
|
readonly name: TName;
|
|
64
60
|
/** Human-facing title shown in Settings → MCP and the Chat tool header. */
|
|
@@ -96,10 +92,8 @@ export function defineServer<
|
|
|
96
92
|
// Extract tool names
|
|
97
93
|
const toolNames = Object.keys(config.tools) as Array<keyof TConfig['tools'] & string>;
|
|
98
94
|
|
|
99
|
-
// Build raw tool definitions (engine-agnostic)
|
|
95
|
+
// Build raw tool definitions (engine-agnostic) and store for reuse.
|
|
100
96
|
const toolDefs: Record<string, RawToolDef> = {};
|
|
101
|
-
|
|
102
|
-
// Build raw tool definitions (engine-agnostic) and store for reuse
|
|
103
97
|
toolNames.forEach((toolName) => {
|
|
104
98
|
const toolDef = config.tools[toolName] as any;
|
|
105
99
|
const schema = toolDef.schema || {};
|
|
@@ -111,24 +105,10 @@ export function defineServer<
|
|
|
111
105
|
};
|
|
112
106
|
});
|
|
113
107
|
|
|
114
|
-
//
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
const def = toolDefs[toolName as string];
|
|
118
|
-
return tool(toolName as string, def.description, def.schema, def.handler as any);
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
return createSdkMcpServer({
|
|
122
|
-
name: config.name,
|
|
123
|
-
version: config.version,
|
|
124
|
-
tools: sdkTools
|
|
125
|
-
});
|
|
126
|
-
};
|
|
127
|
-
|
|
128
|
-
// Return server with metadata and factory
|
|
108
|
+
// Return metadata + raw tool defs only. The SDK-shaped in-process server
|
|
109
|
+
// instances (Claude Code) are built lazily in mcp/internal/config.ts, so the
|
|
110
|
+
// Claude Agent SDK is not imported unless the Claude engine actually streams.
|
|
129
111
|
return {
|
|
130
|
-
server: createInstance(),
|
|
131
|
-
createInstance,
|
|
132
112
|
meta: {
|
|
133
113
|
name: config.name,
|
|
134
114
|
title: config.title,
|
|
@@ -147,24 +127,14 @@ export function buildServerRegistries<
|
|
|
147
127
|
T extends readonly ServerWithMeta<string, readonly string[]>[]
|
|
148
128
|
>(servers: T) {
|
|
149
129
|
const metadata = {} as any;
|
|
150
|
-
const registry = {} as any;
|
|
151
|
-
const factories = {} as any;
|
|
152
130
|
|
|
153
131
|
for (const server of servers) {
|
|
154
132
|
metadata[server.meta.name] = server.meta;
|
|
155
|
-
registry[server.meta.name] = server.server;
|
|
156
|
-
factories[server.meta.name] = server.createInstance;
|
|
157
133
|
}
|
|
158
134
|
|
|
159
135
|
return {
|
|
160
136
|
metadata: metadata as {
|
|
161
137
|
[K in T[number]['meta']['name']]: Extract<T[number], { meta: { name: K } }>['meta']
|
|
162
|
-
},
|
|
163
|
-
registry: registry as {
|
|
164
|
-
[K in T[number]['meta']['name']]: Extract<T[number], { meta: { name: K } }>['server']
|
|
165
|
-
},
|
|
166
|
-
factories: factories as {
|
|
167
|
-
[K in T[number]['meta']['name']]: () => Extract<T[number], { meta: { name: K } }>['server']
|
|
168
138
|
}
|
|
169
139
|
};
|
|
170
140
|
}
|
|
@@ -29,21 +29,12 @@ export const allServers = [
|
|
|
29
29
|
] as const;
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
|
-
* Auto-build
|
|
32
|
+
* Auto-build the metadata registry from the server array. Only engine-agnostic
|
|
33
|
+
* metadata + raw tool defs live here; SDK-shaped instances are built on demand.
|
|
33
34
|
*/
|
|
34
|
-
const { metadata
|
|
35
|
+
const { metadata } = buildServerRegistries(allServers);
|
|
35
36
|
|
|
36
37
|
/**
|
|
37
38
|
* Server Metadata Registry - Defines available servers and their tools
|
|
38
39
|
*/
|
|
39
|
-
export const serverMetadata = metadata;
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Server Instance Registry - Maps server names to SDK instances
|
|
43
|
-
*/
|
|
44
|
-
export const serverRegistry = registry;
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Server Factory Registry - Creates fresh SDK instances (safe for concurrent streams)
|
|
48
|
-
*/
|
|
49
|
-
export const serverFactories = factories;
|
|
40
|
+
export const serverMetadata = metadata;
|