@myrialabs/clopen 0.4.44 → 0.4.45

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 (67) hide show
  1. package/backend/artifacts/project/bridge.ts +218 -0
  2. package/backend/artifacts/project/edit.ts +243 -0
  3. package/backend/artifacts/project/index.ts +38 -0
  4. package/backend/artifacts/project/project.test.ts +181 -0
  5. package/backend/artifacts/project/scan.ts +368 -0
  6. package/backend/artifacts/project/sources.ts +100 -0
  7. package/backend/artifacts/sync.ts +1 -1
  8. package/backend/auth/permissions.ts +15 -0
  9. package/backend/chat/stream-manager.ts +20 -3
  10. package/backend/database/migrations/083_create_project_mcp_trust.ts +32 -0
  11. package/backend/database/migrations/index.ts +7 -0
  12. package/backend/database/queries/index.ts +2 -0
  13. package/backend/database/queries/project-mcp-trust-queries.ts +43 -0
  14. package/backend/engine/adapters/claude/stream.ts +27 -1
  15. package/backend/engine/adapters/cline/mcp-tools.ts +26 -4
  16. package/backend/engine/adapters/cline/stream.ts +20 -6
  17. package/backend/engine/adapters/codex/stream.ts +21 -4
  18. package/backend/engine/adapters/copilot/stream.ts +6 -3
  19. package/backend/engine/adapters/cursor/stream.ts +19 -8
  20. package/backend/engine/adapters/opencode/server.ts +14 -4
  21. package/backend/engine/adapters/opencode/stream.ts +18 -3
  22. package/backend/engine/adapters/pi/mcp-tools.ts +26 -4
  23. package/backend/engine/adapters/pi/stream.ts +35 -3
  24. package/backend/engine/adapters/qwen/stream.ts +8 -0
  25. package/backend/engine/artifact-sync.ts +12 -5
  26. package/backend/files/file-watcher.test.ts +77 -0
  27. package/backend/files/file-watcher.ts +92 -60
  28. package/backend/files/watch-ignore.test.ts +182 -0
  29. package/backend/files/watch-ignore.ts +244 -0
  30. package/backend/git/git-executor.ts +14 -4
  31. package/backend/index.ts +11 -1
  32. package/backend/instructions/service.ts +5 -3
  33. package/backend/instructions/sync.ts +10 -27
  34. package/backend/mcp/external/config.ts +65 -23
  35. package/backend/mcp/external/project.ts +124 -0
  36. package/backend/mcp/external/proxy.ts +65 -11
  37. package/backend/mcp/index.ts +14 -9
  38. package/backend/mcp/internal/remote-server.ts +11 -1
  39. package/backend/skills/marketplace.ts +1 -1
  40. package/backend/snapshot/blob-store.ts +9 -5
  41. package/backend/snapshot/git-attribution.test.ts +42 -0
  42. package/backend/snapshot/git-attribution.ts +306 -0
  43. package/backend/snapshot/gitignore.test.ts +62 -0
  44. package/backend/snapshot/gitignore.ts +158 -78
  45. package/backend/snapshot/snapshot-service.test.ts +270 -0
  46. package/backend/snapshot/snapshot-service.ts +412 -136
  47. package/backend/snapshot/turn-activity.test.ts +52 -0
  48. package/backend/snapshot/turn-activity.ts +83 -0
  49. package/backend/snapshot/turn-changes.test.ts +58 -1
  50. package/backend/snapshot/turn-changes.ts +66 -0
  51. package/backend/worktrees/tree.ts +1 -1
  52. package/backend/ws/chat/composer.ts +504 -0
  53. package/backend/ws/chat/index.ts +3 -1
  54. package/backend/ws/chat/stream.ts +252 -440
  55. package/backend/ws/index.ts +4 -0
  56. package/backend/ws/project-artifacts/index.ts +236 -0
  57. package/backend/ws/snapshot/changes.ts +66 -31
  58. package/dist/assets/{index-BWyhqUi5.js → index-Am-rJRxA.js} +1 -1
  59. package/dist/assets/{index-DX5OwLOc.js → index-D-Ad1N96.js} +1 -1
  60. package/dist/assets/main--PLCDxSy.css +1 -0
  61. package/dist/assets/main-DelPm2Xt.js +1239 -0
  62. package/dist/index.html +2 -2
  63. package/package.json +1 -1
  64. package/shared/types/stores/settings.ts +5 -0
  65. package/shared/types/unified/message.ts +2 -0
  66. package/dist/assets/main-DOkwqXRU.js +0 -1215
  67. package/dist/assets/main-DzCY0n-j.css +0 -1
@@ -32,6 +32,7 @@ import { SERVER_ENV } from '../../utils/env';
32
32
  import type { McpServerRow } from '$backend/database/queries';
33
33
  import type { EngineType } from '$shared/types/unified';
34
34
  import type { ResolvedExternalServer } from './types';
35
+ import { getTrustedProjectServers, knownProjectNamespaces } from './project';
35
36
 
36
37
  /**
37
38
  * Codex `mcp_servers.<name>` config, flattened by the SDK to `--config` flags.
@@ -56,6 +57,28 @@ function bridgeUrl(slug: string, engine: EngineType): string {
56
57
  return `http://localhost:${SERVER_ENV.PORT}/mcp/ext/${slug}?engine=${engine}`;
57
58
  }
58
59
 
60
+ /** Loopback URL of the per-project bridge for a server in `.agents/mcp.json`. */
61
+ function projectBridgeUrl(projectId: string, name: string, engine: EngineType): string {
62
+ return `http://localhost:${SERVER_ENV.PORT}/mcp/proj/${encodeURIComponent(projectId)}/${encodeURIComponent(name)}?engine=${engine}`;
63
+ }
64
+
65
+ /**
66
+ * Every bridge an engine should receive for this stream: the enabled installed
67
+ * servers (profile-filtered) plus, when the stream has a project, the servers of
68
+ * its APPROVED `.agents/mcp.json`. Project servers are not profile-filtered —
69
+ * they belong to the repository, not to a bundle — and never shadow an
70
+ * installed server that happens to share the namespace.
71
+ */
72
+ function bridgesFor(engine: EngineType, profileFilter?: Set<string>, projectId?: string | null): { namespace: string; url: string }[] {
73
+ const out = getEnabledExternalServers(profileFilter).map(s => ({ namespace: s.namespace, url: bridgeUrl(s.slug, engine) }));
74
+ const taken = new Set(out.map(b => b.namespace));
75
+ for (const s of getTrustedProjectServers(projectId)) {
76
+ if (taken.has(s.namespace)) continue;
77
+ out.push({ namespace: s.namespace, url: projectBridgeUrl(s.projectId, s.name, engine) });
78
+ }
79
+ return out;
80
+ }
81
+
59
82
  /** The service-token bearer header every engine→bridge hop carries. */
60
83
  function serviceAuthHeaders(): Record<string, string> {
61
84
  return { Authorization: `Bearer ${getMcpServiceToken()}` };
@@ -145,22 +168,22 @@ export function remoteNeedsOAuth(s: ResolvedExternalServer): boolean {
145
168
  // ---------------------------------------------------------------------------
146
169
 
147
170
  /** Claude Agent SDK: Streamable-HTTP remote keyed by namespace. */
148
- export function getClaudeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpServerConfig> {
171
+ export function getClaudeExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, McpServerConfig> {
149
172
  const out: Record<string, McpServerConfig> = {};
150
- for (const s of getEnabledExternalServers(profileFilter)) {
151
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'claude-code'), headers: serviceAuthHeaders() };
173
+ for (const b of bridgesFor('claude-code', profileFilter, projectId)) {
174
+ out[b.namespace] = { type: 'http', url: b.url, headers: serviceAuthHeaders() };
152
175
  }
153
176
  logBuilt('Claude', out);
154
177
  return out;
155
178
  }
156
179
 
157
180
  /** Open Code: `McpRemoteConfig` pointing at the bridge proxy. */
158
- export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpRemoteConfig> {
181
+ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, McpRemoteConfig> {
159
182
  const out: Record<string, McpRemoteConfig> = {};
160
- for (const s of getEnabledExternalServers(profileFilter)) {
161
- out[s.namespace] = {
183
+ for (const b of bridgesFor('opencode', profileFilter, projectId)) {
184
+ out[b.namespace] = {
162
185
  type: 'remote',
163
- url: bridgeUrl(s.slug, 'opencode'),
186
+ url: b.url,
164
187
  enabled: true,
165
188
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
166
189
  headers: serviceAuthHeaders()
@@ -170,6 +193,25 @@ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Recor
170
193
  return out;
171
194
  }
172
195
 
196
+ /**
197
+ * Open Code entries for the project's approved `.agents/mcp.json` ONLY. The
198
+ * server pool caches the installed-server config per scope, so project servers
199
+ * are layered on at spawn-assembly time instead (see opencode/server.ts).
200
+ */
201
+ export function getOpenCodeProjectMcpConfig(projectId: string | null | undefined): Record<string, McpRemoteConfig> {
202
+ const out: Record<string, McpRemoteConfig> = {};
203
+ for (const s of getTrustedProjectServers(projectId)) {
204
+ out[s.namespace] = {
205
+ type: 'remote',
206
+ url: projectBridgeUrl(s.projectId, s.name, 'opencode'),
207
+ enabled: true,
208
+ timeout: MCP_TOOL_CALL_TIMEOUT_MS,
209
+ headers: serviceAuthHeaders()
210
+ };
211
+ }
212
+ return out;
213
+ }
214
+
173
215
  /**
174
216
  * Codex: `mcp_servers.<name>.url` pointing at the bridge proxy.
175
217
  *
@@ -179,26 +221,26 @@ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Recor
179
221
  * The server is registered so interactive/known-tool flows work; this limit is
180
222
  * unchanged by the proxy.
181
223
  */
182
- export function getCodexExternalMcpConfig(profileFilter?: Set<string>): Record<string, CodexMcpServerConfig> {
224
+ export function getCodexExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CodexMcpServerConfig> {
183
225
  const out: Record<string, CodexMcpServerConfig> = {};
184
- for (const s of getEnabledExternalServers(profileFilter)) {
185
- out[s.namespace] = { url: bridgeUrl(s.slug, 'codex'), http_headers: serviceAuthHeaders() };
226
+ for (const b of bridgesFor('codex', profileFilter, projectId)) {
227
+ out[b.namespace] = { url: b.url, http_headers: serviceAuthHeaders() };
186
228
  }
187
229
  logBuilt('Codex', out);
188
230
  return out;
189
231
  }
190
232
 
191
233
  /** Copilot: `MCPHTTPServerConfig` pointing at the bridge proxy. */
192
- export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record<string, CopilotMcpServerConfig> {
234
+ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CopilotMcpServerConfig> {
193
235
  const out: Record<string, CopilotMcpServerConfig> = {};
194
- for (const s of getEnabledExternalServers(profileFilter)) {
236
+ for (const b of bridgesFor('copilot', profileFilter, projectId)) {
195
237
  // `tools: ['*']` makes the Copilot runtime expose ALL of the proxy's
196
238
  // tools. Leaving it unset relies on the SDK's documented "undefined =
197
239
  // all" default, which the bundled CLI does not honour for dynamically
198
240
  // discovered servers — the tools never reach the model.
199
- out[s.namespace] = {
241
+ out[b.namespace] = {
200
242
  type: 'http',
201
- url: bridgeUrl(s.slug, 'copilot'),
243
+ url: b.url,
202
244
  tools: ['*'],
203
245
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
204
246
  headers: serviceAuthHeaders()
@@ -210,20 +252,20 @@ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record
210
252
 
211
253
  /** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
212
254
  /** Cursor: `McpServerConfig` (http variant) pointing at the bridge proxy. */
213
- export function getCursorExternalMcpConfig(profileFilter?: Set<string>): Record<string, CursorMcpServerConfig> {
255
+ export function getCursorExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, CursorMcpServerConfig> {
214
256
  const out: Record<string, CursorMcpServerConfig> = {};
215
- for (const s of getEnabledExternalServers(profileFilter)) {
216
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'cursor'), headers: serviceAuthHeaders() };
257
+ for (const b of bridgesFor('cursor', profileFilter, projectId)) {
258
+ out[b.namespace] = { type: 'http', url: b.url, headers: serviceAuthHeaders() };
217
259
  }
218
260
  logBuilt('Cursor', out);
219
261
  return out;
220
262
  }
221
263
 
222
- export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
264
+ export function getQwenExternalMcpConfig(profileFilter?: Set<string>, projectId?: string | null): Record<string, QwenMcpServerConfig> {
223
265
  const out: Record<string, QwenMcpServerConfig> = {};
224
- for (const s of getEnabledExternalServers(profileFilter)) {
225
- out[s.namespace] = {
226
- httpUrl: bridgeUrl(s.slug, 'qwen'),
266
+ for (const b of bridgesFor('qwen', profileFilter, projectId)) {
267
+ out[b.namespace] = {
268
+ httpUrl: b.url,
227
269
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
228
270
  trust: true,
229
271
  headers: serviceAuthHeaders()
@@ -251,8 +293,8 @@ export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<st
251
293
  * Returns null if the name doesn't belong to any enabled external server.
252
294
  */
253
295
  export function resolveExternalToolName(toolName: string): string | null {
254
- for (const s of getEnabledExternalServers()) {
255
- const ns = s.namespace;
296
+ const namespaces = [...getEnabledExternalServers().map(s => s.namespace), ...knownProjectNamespaces()];
297
+ for (const ns of namespaces) {
256
298
  if (toolName.startsWith(`mcp__${ns}__`)) return toolName;
257
299
  for (const sep of ['_', '-']) {
258
300
  const prefix = `${ns}${sep}`;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Project MCP — servers a repository declares in `.agents/mcp.json`.
3
+ *
4
+ * They ride the same proxy as installed servers (Clopen is the upstream client,
5
+ * engines only ever see a loopback bridge URL), on a project-addressed route:
6
+ * `/mcp/proj/<projectId>/<name>`. Two things differ from installed servers:
7
+ *
8
+ * - TRUST. The file lives in the repo, so anyone who can push to it could make
9
+ * the server run a command. A server is emitted — and the bridge will only
10
+ * connect it — while the file's current sha256 matches the hash an admin
11
+ * approved (`project_mcp_trust`). Any edit makes it inert until re-approved.
12
+ * The check runs at config-build time AND again when the bridge connects, so
13
+ * a file swapped between the two is still refused.
14
+ * - PLACE. stdio servers start with the repository as their working
15
+ * directory, which is what a repo-relative `command`/`args` expects.
16
+ *
17
+ * Namespace: `project-<name>`, so tools surface as `mcp__project-<name>__<tool>`
18
+ * and never collide with an installed server of the same name.
19
+ */
20
+
21
+ import { readFileSync, statSync } from 'node:fs';
22
+ import { join } from 'path';
23
+ import { projectQueries, projectMcpTrustQueries } from '$backend/database/queries';
24
+ import { parseProjectMcpJson, hashContent } from '$backend/artifacts/project/scan';
25
+ import { PROJECT_WRITE_PATHS } from '$backend/artifacts/project/sources';
26
+ import { slugify } from '$backend/artifacts/slug';
27
+ import { debug } from '$shared/utils/logger';
28
+ import type { ResolvedExternalServer } from './types';
29
+
30
+ export interface ResolvedProjectServer extends ResolvedExternalServer {
31
+ projectId: string;
32
+ /** Repository root — the working directory for stdio servers. */
33
+ cwd: string;
34
+ }
35
+
36
+ /** Largest `.agents/mcp.json` Clopen will read. */
37
+ const MAX_BYTES = 256 * 1024;
38
+
39
+ /**
40
+ * Namespaces of project servers emitted so far. Engines report MCP tools under
41
+ * `<namespace><sep><tool>` with an SDK-specific separator, and the resolver has
42
+ * no project context — so it matches against the namespaces actually handed out.
43
+ */
44
+ const knownNamespaces = new Set<string>();
45
+
46
+ export function projectNamespace(name: string): string {
47
+ return `project-${slugify(name)}`;
48
+ }
49
+
50
+ export function knownProjectNamespaces(): string[] {
51
+ return [...knownNamespaces];
52
+ }
53
+
54
+ /** Expand `${VAR}` / `${VAR:-default}` from the server's environment, as `.mcp.json` does. */
55
+ function expand(value: string): string {
56
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_m, name: string, fallback?: string) =>
57
+ process.env[name] ?? fallback ?? ''
58
+ );
59
+ }
60
+
61
+ function expandRecord(record: Record<string, string>): Record<string, string> {
62
+ return Object.fromEntries(Object.entries(record).map(([k, v]) => [k, expand(v)]));
63
+ }
64
+
65
+ /** The raw file for a project, or null when absent/oversized. */
66
+ export function readProjectMcpFile(projectPath: string): string | null {
67
+ const file = join(projectPath, PROJECT_WRITE_PATHS.mcp);
68
+ try {
69
+ const info = statSync(file);
70
+ if (!info.isFile() || info.size > MAX_BYTES) return null;
71
+ return readFileSync(file, 'utf8');
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Every server in the project's `.agents/mcp.json`, but only while the file is
79
+ * the approved version. Synchronous on purpose: the per-engine MCP builders it
80
+ * feeds are synchronous, and the file is small.
81
+ */
82
+ export function getTrustedProjectServers(projectId: string | null | undefined): ResolvedProjectServer[] {
83
+ if (!projectId) return [];
84
+ const project = projectQueries.getById(projectId);
85
+ if (!project?.path) return [];
86
+ const raw = readProjectMcpFile(project.path);
87
+ if (raw == null) return [];
88
+ if (!projectMcpTrustQueries.isTrusted(projectId, hashContent(raw))) {
89
+ debug.log('mcp', `🔒 Project ${projectId}: .agents/mcp.json is not approved (or changed since) — not loading it`);
90
+ return [];
91
+ }
92
+ let parsed;
93
+ try {
94
+ parsed = parseProjectMcpJson(raw);
95
+ } catch (error) {
96
+ debug.warn('mcp', `Project ${projectId}: .agents/mcp.json is invalid:`, error);
97
+ return [];
98
+ }
99
+ return parsed.map(s => {
100
+ const namespace = projectNamespace(s.name);
101
+ knownNamespaces.add(namespace);
102
+ return {
103
+ id: 0,
104
+ slug: s.name,
105
+ namespace,
106
+ name: s.name,
107
+ transport: s.transport,
108
+ command: s.command ? expand(s.command) : null,
109
+ args: s.args.map(expand),
110
+ env: expandRecord(s.env),
111
+ url: s.url ? expand(s.url) : null,
112
+ headers: expandRecord(s.headers),
113
+ projectId,
114
+ cwd: project.path
115
+ };
116
+ });
117
+ }
118
+
119
+ /** One trusted project server by name, or a readable error. */
120
+ export function requireTrustedProjectServer(projectId: string, name: string): ResolvedProjectServer {
121
+ const server = getTrustedProjectServers(projectId).find(s => s.name === name);
122
+ if (!server) throw new Error(`Project MCP server "${name}" is not declared in an approved .agents/mcp.json`);
123
+ return server;
124
+ }
@@ -40,6 +40,7 @@ import { debug } from '$shared/utils/logger';
40
40
  import { mcpServerQueries, permissionSetQueries, profileQueries } from '$backend/database/queries';
41
41
  import type { EngineType } from '$shared/types/unified';
42
42
  import { resolveServerRow } from './config';
43
+ import { requireTrustedProjectServer, type ResolvedProjectServer } from './project';
43
44
  import { parseToolOverrides, isToolExposed } from './tools';
44
45
  // Import the PURE resolver (no `$backend/mcp` dependency) to avoid an
45
46
  // mcp → permissions/service → mcp import cycle.
@@ -54,7 +55,7 @@ const UPSTREAM_CONNECT_TIMEOUT_MS = 30_000;
54
55
  * subprocess or remote HTTP/SSE). OAuth/API-key headers come from
55
56
  * `resolveServerRow`, which injects the Clopen-managed bearer.
56
57
  */
57
- async function connectUpstream(s: ResolvedExternalServer): Promise<Client> {
58
+ async function connectUpstream(s: ResolvedExternalServer & { cwd?: string }): Promise<Client> {
58
59
  const client = new Client({ name: 'clopen-proxy', version: '1.0.0' }, { capabilities: {} });
59
60
 
60
61
  if (s.transport === 'stdio') {
@@ -65,6 +66,8 @@ async function connectUpstream(s: ResolvedExternalServer): Promise<Client> {
65
66
  command: s.command,
66
67
  args: s.args,
67
68
  env: { ...getDefaultEnvironment(), ...s.env },
69
+ // Project servers (`.agents/mcp.json`) start inside their repository.
70
+ ...(s.cwd ? { cwd: s.cwd } : {}),
68
71
  stderr: 'ignore'
69
72
  });
70
73
  await client.connect(transport, { timeout: UPSTREAM_CONNECT_TIMEOUT_MS });
@@ -185,20 +188,46 @@ export async function createExternalProxyServer(slug: string, engine?: EngineTyp
185
188
  throw new Error(`External MCP server is disabled: ${slug}`);
186
189
  }
187
190
 
188
- const resolved = resolveServerRow(row);
189
- const overrides = parseToolOverrides(row.tool_overrides);
190
- const client = await connectUpstream(resolved);
191
-
192
- // Global tool-permission policy for this engine (Settings → Permissions).
193
- // MCP tools carry no permission hook on some engines (e.g. OpenCode only gates
191
+ // Global tool-permission policy for this engine (Settings → Permissions). MCP
192
+ // tools carry no permission hook on some engines (e.g. OpenCode only gates
194
193
  // edit/bash/webfetch), so the bridge is the single reliable enforcement point
195
- // for MCP deny/allow across every engine — it filters the tool out before the
196
- // engine ever sees it. Rules are matched against the canonical engine-facing
197
- // name `mcp__<namespace>__<tool>` (the identity the Permissions UI uses).
198
- // Global scope only: the bridge has no session/project context.
194
+ // for MCP deny/allow across every engine. Global scope only: this bridge has
195
+ // no session/project context.
199
196
  const permissions = engine
200
197
  ? mergePermissions(pickEngineSet(permissionSetQueries.getGlobal(), engine), undefined)
201
198
  : null;
199
+ return buildProxyServer(resolveServerRow(row), parseToolOverrides(row.tool_overrides), engine, permissions);
200
+ }
201
+
202
+ /**
203
+ * Proxy for one server of a project's approved `.agents/mcp.json` — the
204
+ * `/mcp/proj/<projectId>/<name>` bridge. Trust is re-checked here, at connect
205
+ * time: a file edited after the engine received its config is refused rather
206
+ * than run. Project-scoped permission rules apply on top of the global ones,
207
+ * because unlike the installed-server bridge this one knows its project.
208
+ */
209
+ export async function createProjectProxyServer(projectId: string, name: string, engine?: EngineType): Promise<ExternalProxy> {
210
+ const resolved = requireTrustedProjectServer(projectId, name);
211
+ const permissions = engine
212
+ ? mergePermissions(
213
+ pickEngineSet(permissionSetQueries.getGlobal(), engine),
214
+ pickEngineSet(permissionSetQueries.getForProject(projectId), engine)
215
+ )
216
+ : null;
217
+ return buildProxyServer(resolved, {}, engine, permissions);
218
+ }
219
+
220
+ async function buildProxyServer(
221
+ resolved: ResolvedExternalServer | ResolvedProjectServer,
222
+ overrides: ReturnType<typeof parseToolOverrides>,
223
+ engine: EngineType | undefined,
224
+ permissions: ReturnType<typeof mergePermissions> | null
225
+ ): Promise<ExternalProxy> {
226
+ const slug = resolved.slug;
227
+ const client = await connectUpstream(resolved);
228
+
229
+ // Rules match the canonical engine-facing name `mcp__<namespace>__<tool>`
230
+ // (the identity the Permissions UI uses).
202
231
  const permitted = (toolName: string): boolean =>
203
232
  !permissions || isToolAllowed(permissions, `mcp__${resolved.namespace}__${toolName}`);
204
233
 
@@ -266,6 +295,31 @@ async function withUpstreamClient<T>(slug: string, fn: (client: Client) => Promi
266
295
  }
267
296
  }
268
297
 
298
+ /** Same as {@link withUpstreamClient} for a project server (trust-checked). */
299
+ async function withProjectUpstreamClient<T>(projectId: string, name: string, fn: (client: Client) => Promise<T>): Promise<T> {
300
+ const client = await connectUpstream(requireTrustedProjectServer(projectId, name));
301
+ try {
302
+ return await fn(client);
303
+ } finally {
304
+ client.close().catch(error => debug.warn('mcp', `Project MCP ${name}: error closing client:`, error));
305
+ }
306
+ }
307
+
308
+ /** Sanitized tools of a trusted project server — for the in-process engines (Pi, Cline). */
309
+ export async function listProjectServerTools(projectId: string, name: string): Promise<Tool[]> {
310
+ return withProjectUpstreamClient(projectId, name, async (client) => (await listAllToolsRaw(client)).map(sanitizeTool));
311
+ }
312
+
313
+ /** Call one tool of a trusted project server — for the in-process engines (Pi, Cline). */
314
+ export async function callProjectServerTool(projectId: string, name: string, toolName: string, args: unknown): Promise<unknown> {
315
+ return withProjectUpstreamClient(projectId, name, async (client) =>
316
+ client.request(
317
+ { method: 'tools/call', params: { name: toolName, arguments: (args ?? {}) as Record<string, unknown> } },
318
+ CompatibilityCallToolResultSchema
319
+ )
320
+ );
321
+ }
322
+
269
323
  /** List a server's sanitized tools live (unfiltered) — for the Settings tool panel. */
270
324
  export async function listExternalServerTools(slug: string): Promise<Tool[]> {
271
325
  return withUpstreamClient(slug, async (client) => (await listAllToolsRaw(client)).map(sanitizeTool));
@@ -59,7 +59,7 @@ export {
59
59
  export * from './internal/servers';
60
60
 
61
61
  // Remote MCP HTTP bridge (serves internal tools + external proxies to non-Claude engines)
62
- export { handleMcpRequest, handleExternalMcpRequest, closeMcpServer } from './internal/remote-server';
62
+ export { handleMcpRequest, handleExternalMcpRequest, handleProjectMcpRequest, closeMcpServer } from './internal/remote-server';
63
63
 
64
64
  // Project context service for MCP tool handlers
65
65
  export { projectContextService } from './internal/project-context';
@@ -75,8 +75,10 @@ export {
75
75
 
76
76
  // External catalog + types (used by the WS layer and Settings → MCP)
77
77
  export { listRegistryServers, mapRegistryServer } from './external/registry-client';
78
- export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth, getEngineConfigsForServer } from './external/config';
79
- export { listExternalServerTools, callExternalServerTool } from './external/proxy';
78
+ export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth, getEngineConfigsForServer, getOpenCodeProjectMcpConfig } from './external/config';
79
+ export { listExternalServerTools, callExternalServerTool, listProjectServerTools, callProjectServerTool } from './external/proxy';
80
+ export { getTrustedProjectServers, projectNamespace, readProjectMcpFile } from './external/project';
81
+ export type { ResolvedProjectServer } from './external/project';
80
82
  export { parseToolOverrides, resolveToolExposure, pruneToolOverrides, MCP_ENGINES } from './external/tools';
81
83
  export type { ToolExposure } from './external/tools';
82
84
  export { probeServer } from './external/probe';
@@ -108,11 +110,14 @@ export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse
108
110
  export async function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Promise<Record<string, McpServerConfig>> {
109
111
  return {
110
112
  ...(await internal.getEnabledMcpServers(context, profileFilter)),
111
- ...external.getClaudeExternalMcpConfig(profileFilter)
113
+ ...external.getClaudeExternalMcpConfig(profileFilter, context?.projectId)
112
114
  };
113
115
  }
114
116
 
115
- /** Open Code MCP config: internal `clopen-mcp` remote bridge + external servers. */
117
+ /**
118
+ * Open Code MCP config: internal `clopen-mcp` remote bridge + external servers.
119
+ * Project servers are NOT included — see {@link getOpenCodeProjectMcpConfig}.
120
+ */
116
121
  export function getOpenCodeMcpConfig(profileFilter?: Set<string>) {
117
122
  return {
118
123
  ...internal.getOpenCodeMcpConfig(profileFilter),
@@ -124,7 +129,7 @@ export function getOpenCodeMcpConfig(profileFilter?: Set<string>) {
124
129
  export function getCodexMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
125
130
  return {
126
131
  ...internal.getCodexMcpConfig(profileFilter, context),
127
- ...external.getCodexExternalMcpConfig(profileFilter)
132
+ ...external.getCodexExternalMcpConfig(profileFilter, context?.projectId)
128
133
  };
129
134
  }
130
135
 
@@ -132,7 +137,7 @@ export function getCodexMcpConfig(profileFilter?: Set<string>, context?: McpExec
132
137
  export function getCopilotMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
133
138
  return {
134
139
  ...internal.getCopilotMcpConfig(profileFilter, context),
135
- ...external.getCopilotExternalMcpConfig(profileFilter)
140
+ ...external.getCopilotExternalMcpConfig(profileFilter, context?.projectId)
136
141
  };
137
142
  }
138
143
 
@@ -140,7 +145,7 @@ export function getCopilotMcpConfig(profileFilter?: Set<string>, context?: McpEx
140
145
  export function getCursorMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
141
146
  return {
142
147
  ...internal.getCursorMcpConfig(profileFilter, context),
143
- ...external.getCursorExternalMcpConfig(profileFilter)
148
+ ...external.getCursorExternalMcpConfig(profileFilter, context?.projectId)
144
149
  };
145
150
  }
146
151
 
@@ -148,7 +153,7 @@ export function getCursorMcpConfig(profileFilter?: Set<string>, context?: McpExe
148
153
  export function getQwenMcpConfig(profileFilter?: Set<string>, context?: McpExecutionContext) {
149
154
  return {
150
155
  ...internal.getQwenMcpConfig(profileFilter, context),
151
- ...external.getQwenExternalMcpConfig(profileFilter)
156
+ ...external.getQwenExternalMcpConfig(profileFilter, context?.projectId)
152
157
  };
153
158
  }
154
159
 
@@ -19,7 +19,7 @@
19
19
  import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
20
20
  import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
21
21
  import { createRemoteMcpServer, type RemoteMcpCaller } from './servers/helper';
22
- import { createExternalProxyServer } from '../external/proxy';
22
+ import { createExternalProxyServer, createProjectProxyServer } from '../external/proxy';
23
23
  import { debug } from '$shared/utils/logger';
24
24
  import { authQueries } from '$backend/database/queries';
25
25
  import { hashToken } from '$backend/auth/tokens';
@@ -273,6 +273,16 @@ export async function handleExternalMcpRequest(request: Request, slug: string):
273
273
  return handleStreamable(request, `External MCP (${slug}${engine ? `, ${engine}` : ''})`, () => createExternalProxyServer(slug, engine));
274
274
  }
275
275
 
276
+ /**
277
+ * Handle a request to the per-project proxy `/mcp/proj/<projectId>/<name>` — a
278
+ * server from the project's approved `.agents/mcp.json` (see
279
+ * `backend/mcp/external/project.ts`).
280
+ */
281
+ export async function handleProjectMcpRequest(request: Request, projectId: string, name: string): Promise<Response> {
282
+ const engine = (new URL(request.url).searchParams.get('engine') as EngineType | null) ?? undefined;
283
+ return handleStreamable(request, `Project MCP (${projectId}/${name}${engine ? `, ${engine}` : ''})`, () => createProjectProxyServer(projectId, name, engine));
284
+ }
285
+
276
286
  /**
277
287
  * Close all active MCP sessions and transports.
278
288
  * Called during graceful server shutdown.
@@ -39,7 +39,7 @@ export interface FetchedSkill {
39
39
  }
40
40
 
41
41
  const PAGE_SIZE = 30;
42
- const COMMUNITY_INDEX_URL = 'https://majiayu000.github.io/claude-skill-registry-core/search-index-lite.json';
42
+ const COMMUNITY_INDEX_URL = 'https://majiayu000.github.io/claude-skill-registry/search-index-lite.json';
43
43
 
44
44
  /**
45
45
  * A lite-index entry. The index uses full keys (`name`/`description`/`install`/
@@ -32,7 +32,7 @@ class BlobStore {
32
32
  private initialized = false;
33
33
 
34
34
  /**
35
- * Cache: filepath -> { mtimeMs, size, hash }
35
+ * Cache: absolute path -> { mtimeMs, size, hash }
36
36
  * Avoids re-reading files that haven't changed (based on mtime + size).
37
37
  */
38
38
  private fileHashCache = new Map<string, FileHashCacheEntry>();
@@ -115,22 +115,26 @@ class BlobStore {
115
115
  * If the file has changed, reads content, hashes it, stores blob, and caches.
116
116
  * Reads as Buffer to safely handle binary files (images, PDFs, etc.).
117
117
  *
118
+ * Cached by absolute path. It used to be keyed by whatever the caller passed,
119
+ * which was the project-relative path — shared by every project and every
120
+ * worktree copy, where the same file often has the same size.
121
+ *
118
122
  * @returns hash and content Buffer (content is null if cache hit and blob already exists)
119
123
  */
120
- async hashFile(filepath: string, fullPath: string): Promise<{ hash: string; content: Buffer | null; cached: boolean }> {
124
+ async hashFile(fullPath: string): Promise<{ hash: string; content: Buffer | null; cached: boolean }> {
121
125
  await this.init();
122
126
 
123
127
  const stat = await fs.stat(fullPath);
124
128
 
125
129
  // Check mtime cache
126
- const cached = this.fileHashCache.get(filepath);
130
+ const cached = this.fileHashCache.get(fullPath);
127
131
  if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
128
132
  // Verify blob still exists on disk (could have been cleaned up)
129
133
  if (await this.hasBlob(cached.hash)) {
130
134
  return { hash: cached.hash, content: null, cached: true };
131
135
  }
132
136
  // Blob was deleted — invalidate cache, fall through to re-read and re-store
133
- this.fileHashCache.delete(filepath);
137
+ this.fileHashCache.delete(fullPath);
134
138
  }
135
139
 
136
140
  // File changed or cache miss - read as Buffer (binary-safe, no encoding conversion)
@@ -141,7 +145,7 @@ class BlobStore {
141
145
  await this.storeBlob(content);
142
146
 
143
147
  // Update cache
144
- this.fileHashCache.set(filepath, {
148
+ this.fileHashCache.set(fullPath, {
145
149
  mtimeMs: stat.mtimeMs,
146
150
  size: stat.size,
147
151
  hash
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Reading the reflog for HEAD moves that rewrote the working tree.
3
+ *
4
+ * The line that matters is between a commit and everything else: a commit
5
+ * records files somebody already wrote, so treating it as git's own change
6
+ * would erase an agent's work the moment it committed it.
7
+ */
8
+
9
+ import { describe, it, expect } from 'bun:test';
10
+ import { isAuthoredCommit, parseReflog, workingTreeTransitions } from './git-attribution';
11
+
12
+ describe('isAuthoredCommit', () => {
13
+ it('knows a commit from the working tree from one that ends a merge', () => {
14
+ expect(isAuthoredCommit('commit: fix things')).toBe(true);
15
+ expect(isAuthoredCommit('commit (amend): fix things')).toBe(true);
16
+ expect(isAuthoredCommit('commit (initial): init')).toBe(true);
17
+ expect(isAuthoredCommit('commit (merge): Merge branch x')).toBe(false);
18
+ expect(isAuthoredCommit('merge origin/main: Merge made by the \'ort\' strategy.')).toBe(false);
19
+ expect(isAuthoredCommit('pull: Fast-forward')).toBe(false);
20
+ });
21
+ });
22
+
23
+ describe('workingTreeTransitions', () => {
24
+ const reflog = parseReflog([
25
+ 'c3\tHEAD@{1000}\tmerge origin/main: Fast-forward',
26
+ 'c2\tHEAD@{990}\tcommit: agent work',
27
+ 'c1\tHEAD@{500}\tcheckout: moving from a to main'
28
+ ].join('\n'));
29
+
30
+ it('parses sha, time and subject, newest first', () => {
31
+ expect(reflog[0]).toEqual({ sha: 'c3', time: 1000, subject: 'merge origin/main: Fast-forward' });
32
+ expect(reflog).toHaveLength(3);
33
+ });
34
+
35
+ it('keeps the moves inside the turn and skips commits', () => {
36
+ expect(workingTreeTransitions(reflog, 'c1', 980_000)).toEqual([{ from: 'c2', to: 'c3' }]);
37
+ });
38
+
39
+ it('finds nothing when the turn began after the last move', () => {
40
+ expect(workingTreeTransitions(reflog, 'c3', 2_000_000)).toEqual([]);
41
+ });
42
+ });