@myrialabs/clopen 0.4.8 → 0.4.10

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 (107) hide show
  1. package/README.md +10 -7
  2. package/backend/artifacts/detect.ts +129 -0
  3. package/backend/artifacts/engine-map.ts +53 -0
  4. package/backend/artifacts/frontmatter.ts +68 -0
  5. package/backend/artifacts/generate.ts +105 -0
  6. package/backend/artifacts/index.ts +34 -0
  7. package/backend/artifacts/markers.ts +76 -0
  8. package/backend/artifacts/matrix.ts +247 -0
  9. package/backend/artifacts/slug.ts +35 -0
  10. package/backend/artifacts/sync.ts +130 -0
  11. package/backend/artifacts/types.ts +152 -0
  12. package/backend/auth/permissions.ts +51 -1
  13. package/backend/chat/stream-manager.ts +14 -1
  14. package/backend/commands/detect.ts +25 -0
  15. package/backend/commands/index.ts +9 -0
  16. package/backend/commands/service.ts +178 -0
  17. package/backend/commands/store.ts +45 -0
  18. package/backend/commands/sync.ts +94 -0
  19. package/backend/database/migrations/045_create_commands_table.ts +28 -0
  20. package/backend/database/migrations/046_create_subagents_table.ts +29 -0
  21. package/backend/database/migrations/047_create_instructions_table.ts +29 -0
  22. package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
  23. package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
  24. package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
  25. package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
  26. package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
  27. package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
  28. package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
  29. package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
  30. package/backend/database/migrations/index.ts +77 -0
  31. package/backend/database/queries/command-queries.ts +82 -0
  32. package/backend/database/queries/index.ts +12 -2
  33. package/backend/database/queries/instruction-queries.ts +62 -0
  34. package/backend/database/queries/mcp-server-queries.ts +25 -0
  35. package/backend/database/queries/permission-set-queries.ts +155 -0
  36. package/backend/database/queries/profile-queries.ts +118 -0
  37. package/backend/database/queries/project-queries.ts +14 -0
  38. package/backend/database/queries/session-queries.ts +21 -0
  39. package/backend/database/queries/subagent-queries.ts +92 -0
  40. package/backend/engine/adapters/claude/stream.ts +27 -3
  41. package/backend/engine/adapters/codex/stream.ts +46 -14
  42. package/backend/engine/adapters/copilot/stream.ts +58 -4
  43. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  44. package/backend/engine/adapters/opencode/server.ts +166 -210
  45. package/backend/engine/adapters/opencode/stream.ts +150 -24
  46. package/backend/engine/adapters/qwen/stream.ts +23 -3
  47. package/backend/engine/artifact-sync.ts +51 -0
  48. package/backend/engine/types.ts +6 -0
  49. package/backend/instructions/index.ts +8 -0
  50. package/backend/instructions/service.ts +63 -0
  51. package/backend/instructions/sync.ts +56 -0
  52. package/backend/mcp/external/config.ts +42 -20
  53. package/backend/mcp/external/proxy.ts +89 -5
  54. package/backend/mcp/external/tools.ts +88 -0
  55. package/backend/mcp/index.ts +38 -15
  56. package/backend/mcp/internal/config.ts +48 -11
  57. package/backend/mcp/internal/remote-server.ts +9 -1
  58. package/backend/permissions/index.ts +27 -0
  59. package/backend/permissions/materialize.ts +96 -0
  60. package/backend/permissions/resolve.test.ts +162 -0
  61. package/backend/permissions/resolve.ts +106 -0
  62. package/backend/permissions/service.ts +167 -0
  63. package/backend/profiles/index.ts +10 -0
  64. package/backend/profiles/service.ts +169 -0
  65. package/backend/project/status-manager.ts +7 -25
  66. package/backend/skills/index.ts +1 -1
  67. package/backend/skills/sync.ts +88 -128
  68. package/backend/subagents/detect.ts +23 -0
  69. package/backend/subagents/index.ts +10 -0
  70. package/backend/subagents/service.ts +166 -0
  71. package/backend/subagents/store.ts +44 -0
  72. package/backend/subagents/sync.ts +144 -0
  73. package/backend/utils/static-curl.ts +12 -54
  74. package/backend/ws/artifacts/generate.ts +51 -0
  75. package/backend/ws/artifacts/index.ts +8 -0
  76. package/backend/ws/chat/stream.ts +33 -2
  77. package/backend/ws/commands/crud.ts +157 -0
  78. package/backend/ws/commands/index.ts +8 -0
  79. package/backend/ws/git/branch.ts +4 -2
  80. package/backend/ws/git/remote.ts +21 -11
  81. package/backend/ws/index.ts +17 -1
  82. package/backend/ws/instructions/crud.ts +53 -0
  83. package/backend/ws/instructions/index.ts +8 -0
  84. package/backend/ws/mcp/crud.ts +7 -1
  85. package/backend/ws/mcp/index.ts +4 -1
  86. package/backend/ws/mcp/tools.ts +112 -0
  87. package/backend/ws/permissions/crud.ts +72 -0
  88. package/backend/ws/permissions/index.ts +8 -0
  89. package/backend/ws/profiles/crud.ts +149 -0
  90. package/backend/ws/profiles/index.ts +9 -0
  91. package/backend/ws/sessions/crud.ts +12 -0
  92. package/backend/ws/subagents/crud.ts +136 -0
  93. package/backend/ws/subagents/index.ts +8 -0
  94. package/dist/assets/{index-jGo0X72U.js → index-C3kp8wpM.js} +1 -1
  95. package/dist/assets/{index-B_F_OgoC.js → index-cVUk7das.js} +1 -1
  96. package/dist/assets/main-CuCxUeqZ.js +533 -0
  97. package/dist/assets/main-D4pdkiQK.css +1 -0
  98. package/dist/index.html +2 -2
  99. package/package.json +24 -24
  100. package/shared/constants/engine-tools.ts +56 -0
  101. package/shared/types/database/schema.ts +2 -0
  102. package/shared/types/stores/settings.ts +15 -0
  103. package/shared/types/unified/stream.ts +7 -0
  104. package/shared/utils/interactive-input.ts +71 -0
  105. package/shared/utils/logger.ts +6 -0
  106. package/dist/assets/main-BkCc3WEB.js +0 -481
  107. package/dist/assets/main-CWDwET4x.css +0 -1
@@ -29,6 +29,7 @@ import { externalNamespace, MCP_TOOL_CALL_TIMEOUT_MS } from '../shared/constants
29
29
  import { getMcpServiceToken } from '../internal/service-token';
30
30
  import { SERVER_ENV } from '../../utils/env';
31
31
  import type { McpServerRow } from '$backend/database/queries';
32
+ import type { EngineType } from '$shared/types/unified';
32
33
  import type { ResolvedExternalServer } from './types';
33
34
 
34
35
  /**
@@ -42,9 +43,16 @@ type CodexMcpServerConfig = {
42
43
  http_headers?: Record<string, string>;
43
44
  };
44
45
 
45
- /** Loopback URL of the per-server external proxy bridge for `slug`. */
46
- function bridgeUrl(slug: string): string {
47
- return `http://localhost:${SERVER_ENV.PORT}/mcp/ext/${slug}`;
46
+ /**
47
+ * Loopback URL of the per-server external proxy bridge for `slug`.
48
+ *
49
+ * The `engine` query param identifies the caller so the proxy can apply that
50
+ * engine's per-tool exposure filter (see `./proxy.ts` / `./tools.ts`). Each
51
+ * engine's config builder passes its own `EngineType`, giving every engine a
52
+ * distinct bridge session with its own filtered tool list.
53
+ */
54
+ function bridgeUrl(slug: string, engine: EngineType): string {
55
+ return `http://localhost:${SERVER_ENV.PORT}/mcp/ext/${slug}?engine=${engine}`;
48
56
  }
49
57
 
50
58
  /** The service-token bearer header every engine→bridge hop carries. */
@@ -88,12 +96,26 @@ export function resolveServerRow(row: McpServerRow): ResolvedExternalServer {
88
96
  /**
89
97
  * Load every enabled external server from the DB, parsing JSON columns and
90
98
  * computing its `<slug>` namespace key.
99
+ *
100
+ * `profileFilter` (when a Profile is active for the stream) restricts the result
101
+ * to the connectors the profile references, by slug. `undefined` = no active
102
+ * profile / the profile bundles no connector → every enabled server is emitted
103
+ * (presence-per-type, see `backend/profiles`).
91
104
  */
92
- export function getEnabledExternalServers(): ResolvedExternalServer[] {
105
+ export function getEnabledExternalServers(profileFilter?: Set<string>): ResolvedExternalServer[] {
93
106
  // `mcp_servers` also holds INTERNAL (code-defined) rows used only for the
94
107
  // Settings listing + toggle — exclude them here so they're never emitted as
95
108
  // real external servers the engine would try to connect to.
96
- return mcpServerQueries.getEnabled().filter(row => row.source !== 'internal').map(resolveServerRow);
109
+ //
110
+ // When a Profile is active it is the source of truth for which connectors run:
111
+ // a connector it references is emitted even if globally disabled in the
112
+ // Connectors settings, and the global enable toggle is ignored. Without a
113
+ // profile filter, only enabled servers apply (unchanged).
114
+ const rows = profileFilter ? mcpServerQueries.getAll() : mcpServerQueries.getEnabled();
115
+ return rows
116
+ .filter(row => row.source !== 'internal')
117
+ .filter(row => !profileFilter || profileFilter.has(row.slug))
118
+ .map(resolveServerRow);
97
119
  }
98
120
 
99
121
  /**
@@ -122,22 +144,22 @@ export function remoteNeedsOAuth(s: ResolvedExternalServer): boolean {
122
144
  // ---------------------------------------------------------------------------
123
145
 
124
146
  /** Claude Agent SDK: Streamable-HTTP remote keyed by namespace. */
125
- export function getClaudeExternalMcpConfig(): Record<string, McpServerConfig> {
147
+ export function getClaudeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpServerConfig> {
126
148
  const out: Record<string, McpServerConfig> = {};
127
- for (const s of getEnabledExternalServers()) {
128
- out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug), headers: serviceAuthHeaders() };
149
+ for (const s of getEnabledExternalServers(profileFilter)) {
150
+ out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'claude-code'), headers: serviceAuthHeaders() };
129
151
  }
130
152
  logBuilt('Claude', out);
131
153
  return out;
132
154
  }
133
155
 
134
156
  /** Open Code: `McpRemoteConfig` pointing at the bridge proxy. */
135
- export function getOpenCodeExternalMcpConfig(): Record<string, McpRemoteConfig> {
157
+ export function getOpenCodeExternalMcpConfig(profileFilter?: Set<string>): Record<string, McpRemoteConfig> {
136
158
  const out: Record<string, McpRemoteConfig> = {};
137
- for (const s of getEnabledExternalServers()) {
159
+ for (const s of getEnabledExternalServers(profileFilter)) {
138
160
  out[s.namespace] = {
139
161
  type: 'remote',
140
- url: bridgeUrl(s.slug),
162
+ url: bridgeUrl(s.slug, 'opencode'),
141
163
  enabled: true,
142
164
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
143
165
  headers: serviceAuthHeaders()
@@ -156,26 +178,26 @@ export function getOpenCodeExternalMcpConfig(): Record<string, McpRemoteConfig>
156
178
  * The server is registered so interactive/known-tool flows work; this limit is
157
179
  * unchanged by the proxy.
158
180
  */
159
- export function getCodexExternalMcpConfig(): Record<string, CodexMcpServerConfig> {
181
+ export function getCodexExternalMcpConfig(profileFilter?: Set<string>): Record<string, CodexMcpServerConfig> {
160
182
  const out: Record<string, CodexMcpServerConfig> = {};
161
- for (const s of getEnabledExternalServers()) {
162
- out[s.namespace] = { url: bridgeUrl(s.slug), http_headers: serviceAuthHeaders() };
183
+ for (const s of getEnabledExternalServers(profileFilter)) {
184
+ out[s.namespace] = { url: bridgeUrl(s.slug, 'codex'), http_headers: serviceAuthHeaders() };
163
185
  }
164
186
  logBuilt('Codex', out);
165
187
  return out;
166
188
  }
167
189
 
168
190
  /** Copilot: `MCPHTTPServerConfig` pointing at the bridge proxy. */
169
- export function getCopilotExternalMcpConfig(): Record<string, CopilotMcpServerConfig> {
191
+ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record<string, CopilotMcpServerConfig> {
170
192
  const out: Record<string, CopilotMcpServerConfig> = {};
171
- for (const s of getEnabledExternalServers()) {
193
+ for (const s of getEnabledExternalServers(profileFilter)) {
172
194
  // `tools: ['*']` makes the Copilot runtime expose ALL of the proxy's
173
195
  // tools. Leaving it unset relies on the SDK's documented "undefined =
174
196
  // all" default, which the bundled CLI does not honour for dynamically
175
197
  // discovered servers — the tools never reach the model.
176
198
  out[s.namespace] = {
177
199
  type: 'http',
178
- url: bridgeUrl(s.slug),
200
+ url: bridgeUrl(s.slug, 'copilot'),
179
201
  tools: ['*'],
180
202
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
181
203
  headers: serviceAuthHeaders()
@@ -186,11 +208,11 @@ export function getCopilotExternalMcpConfig(): Record<string, CopilotMcpServerCo
186
208
  }
187
209
 
188
210
  /** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
189
- export function getQwenExternalMcpConfig(): Record<string, QwenMcpServerConfig> {
211
+ export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
190
212
  const out: Record<string, QwenMcpServerConfig> = {};
191
- for (const s of getEnabledExternalServers()) {
213
+ for (const s of getEnabledExternalServers(profileFilter)) {
192
214
  out[s.namespace] = {
193
- httpUrl: bridgeUrl(s.slug),
215
+ httpUrl: bridgeUrl(s.slug, 'qwen'),
194
216
  timeout: MCP_TOOL_CALL_TIMEOUT_MS,
195
217
  trust: true,
196
218
  headers: serviceAuthHeaders()
@@ -37,8 +37,13 @@ import {
37
37
  type Tool
38
38
  } from '@modelcontextprotocol/sdk/types.js';
39
39
  import { debug } from '$shared/utils/logger';
40
- import { mcpServerQueries } from '$backend/database/queries';
40
+ import { mcpServerQueries, permissionSetQueries, profileQueries } from '$backend/database/queries';
41
+ import type { EngineType } from '$shared/types/unified';
41
42
  import { resolveServerRow } from './config';
43
+ import { parseToolOverrides, isToolExposed } from './tools';
44
+ // Import the PURE resolver (no `$backend/mcp` dependency) to avoid an
45
+ // mcp → permissions/service → mcp import cycle.
46
+ import { isToolAllowed, mergePermissions, pickEngineSet } from '$backend/permissions/resolve';
42
47
  import type { ResolvedExternalServer } from './types';
43
48
 
44
49
  /** Cap on how long we wait for an upstream server to complete its handshake. */
@@ -163,27 +168,69 @@ export interface ExternalProxy {
163
168
  * forwards verbatim. Throws if the slug isn't an enabled external server or the
164
169
  * upstream handshake fails (the caller surfaces this as a per-server failure,
165
170
  * never taking down the whole bridge).
171
+ *
172
+ * `engine` identifies the caller (each engine's config points at
173
+ * `/mcp/ext/<slug>?engine=<engine>`). It is the SINGLE enforcement point for
174
+ * per-tool exposure: `tools/list` hides tools the user disabled for this engine
175
+ * and `tools/call` refuses them — so filtering behaves identically on every
176
+ * engine, even those whose SDK has no tool-allowlist config.
166
177
  */
167
- export async function createExternalProxyServer(slug: string): Promise<ExternalProxy> {
178
+ export async function createExternalProxyServer(slug: string, engine?: EngineType): Promise<ExternalProxy> {
168
179
  const row = mcpServerQueries.getBySlug(slug);
169
180
  if (!row || row.source === 'internal') throw new Error(`Unknown external MCP server: ${slug}`);
170
- if (row.is_enabled !== 1) throw new Error(`External MCP server is disabled: ${slug}`);
181
+ // A globally-disabled server is still servable when a Profile references it — an
182
+ // active profile is the source of truth for which connectors run, overriding the
183
+ // enable toggle (the config builder only emits its bridge URL in that case).
184
+ if (row.is_enabled !== 1 && !profileQueries.isArtifactReferenced('mcp', slug)) {
185
+ throw new Error(`External MCP server is disabled: ${slug}`);
186
+ }
171
187
 
172
188
  const resolved = resolveServerRow(row);
189
+ const overrides = parseToolOverrides(row.tool_overrides);
173
190
  const client = await connectUpstream(resolved);
174
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
194
+ // 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.
199
+ const permissions = engine
200
+ ? mergePermissions(pickEngineSet(permissionSetQueries.getGlobal(), engine), undefined)
201
+ : null;
202
+ const permitted = (toolName: string): boolean =>
203
+ !permissions || isToolAllowed(permissions, `mcp__${resolved.namespace}__${toolName}`);
204
+
175
205
  const server = new Server(
176
206
  { name: `clopen-ext-${slug}`, version: '1.0.0' },
177
207
  { capabilities: { tools: {} } }
178
208
  );
179
209
 
180
210
  server.setRequestHandler(ListToolsRequestSchema, async () => {
181
- const tools = (await listAllToolsRaw(client)).map(sanitizeTool);
182
- debug.log('mcp', `🔌 Proxy ${slug}: serving ${tools.length} tool(s)`);
211
+ const all = (await listAllToolsRaw(client)).map(sanitizeTool);
212
+ const tools = all.filter(t => isToolExposed(overrides, t.name, engine) && permitted(t.name));
213
+ const hidden = all.length - tools.length;
214
+ debug.log('mcp', `🔌 Proxy ${slug}${engine ? ` (${engine})` : ''}: serving ${tools.length} tool(s)${hidden > 0 ? `, ${hidden} hidden` : ''}`);
183
215
  return { tools };
184
216
  });
185
217
 
186
218
  server.setRequestHandler(CallToolRequestSchema, async (req) => {
219
+ // Defense in depth: a disabled tool should never have been advertised, but
220
+ // refuse the call outright in case the engine cached an older tool list.
221
+ if (!isToolExposed(overrides, req.params.name, engine)) {
222
+ return {
223
+ content: [{ type: 'text' as const, text: `Tool ${req.params.name} is disabled for this engine.` }],
224
+ isError: true
225
+ };
226
+ }
227
+ // Same guard for a permission-denied tool (Settings → Permissions).
228
+ if (!permitted(req.params.name)) {
229
+ return {
230
+ content: [{ type: 'text' as const, text: `Tool ${req.params.name} is blocked by Clopen permission policy.` }],
231
+ isError: true
232
+ };
233
+ }
187
234
  // Forward verbatim. CompatibilityCallToolResultSchema tolerates both the
188
235
  // modern and 2024-10-07 result shapes; we never cached an output
189
236
  // validator (we bypass listTools), so no schema check runs here.
@@ -200,3 +247,40 @@ export async function createExternalProxyServer(slug: string): Promise<ExternalP
200
247
 
201
248
  return { server, close };
202
249
  }
250
+
251
+ /**
252
+ * Open a short-lived upstream connection for a slug (no bridge, no session).
253
+ * Used by the Settings tool panel / inspector — reuses the same connect +
254
+ * credential path as the bridge but tears the client down immediately. Unlike
255
+ * the bridge it does NOT require the server to be enabled, so tools can be
256
+ * inspected before the server is switched on.
257
+ */
258
+ async function withUpstreamClient<T>(slug: string, fn: (client: Client) => Promise<T>): Promise<T> {
259
+ const row = mcpServerQueries.getBySlug(slug);
260
+ if (!row || row.source === 'internal') throw new Error(`Unknown external MCP server: ${slug}`);
261
+ const client = await connectUpstream(resolveServerRow(row));
262
+ try {
263
+ return await fn(client);
264
+ } finally {
265
+ client.close().catch(error => debug.warn('mcp', `Introspect ${slug}: error closing client:`, error));
266
+ }
267
+ }
268
+
269
+ /** List a server's sanitized tools live (unfiltered) — for the Settings tool panel. */
270
+ export async function listExternalServerTools(slug: string): Promise<Tool[]> {
271
+ return withUpstreamClient(slug, async (client) => (await listAllToolsRaw(client)).map(sanitizeTool));
272
+ }
273
+
274
+ /**
275
+ * Call a single tool live and return its raw MCP result — for the inspector.
276
+ * A tool that fails returns an `isError` result (not a throw), so the inspector
277
+ * can render the error content; connection/handshake failures still throw.
278
+ */
279
+ export async function callExternalServerTool(slug: string, toolName: string, args: unknown): Promise<unknown> {
280
+ return withUpstreamClient(slug, async (client) =>
281
+ client.request(
282
+ { method: 'tools/call', params: { name: toolName, arguments: (args ?? {}) as Record<string, unknown> } },
283
+ CompatibilityCallToolResultSchema
284
+ )
285
+ );
286
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * External MCP — per-tool exposure control.
3
+ *
4
+ * A user-installed server exposes many tools; not all of them are wanted on
5
+ * every engine. This module owns the small amount of pure logic that decides
6
+ * whether a given tool is exposed — used in two places:
7
+ *
8
+ * 1. The `/mcp/ext/<slug>` proxy bridge (`./proxy.ts`) filters its
9
+ * `tools/list` (and guards `tools/call`) per engine, so the decision is
10
+ * enforced ONCE for every engine regardless of whether that engine's SDK
11
+ * supports a tool allowlist.
12
+ * 2. The Settings tool panel (`backend/ws/mcp/tools.ts`) reads back the same
13
+ * state to render per-tool + per-engine toggles.
14
+ *
15
+ * The state lives in the `mcp_servers.tool_overrides` JSON column; an absent
16
+ * override means "exposed everywhere" so an empty map is the (all-on) default.
17
+ */
18
+
19
+ import { ENGINES } from '$shared/constants/engines';
20
+ import type { EngineType } from '$shared/types/unified';
21
+ import type { McpToolOverride, McpToolOverrides } from '$backend/database/queries';
22
+
23
+ /** Engines whose external-MCP surface can be filtered (the ones routed through the bridge). */
24
+ export const MCP_ENGINES: EngineType[] = ENGINES.map(e => e.type);
25
+
26
+ /** Parse the raw `tool_overrides` column, tolerating legacy/corrupt JSON. */
27
+ export function parseToolOverrides(raw: string | null | undefined): McpToolOverrides {
28
+ if (!raw) return {};
29
+ try {
30
+ const parsed = JSON.parse(raw);
31
+ return parsed && typeof parsed === 'object' ? (parsed as McpToolOverrides) : {};
32
+ } catch {
33
+ return {};
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Whether `toolName` is exposed. With `engine` omitted (introspection), only the
39
+ * global `enabled` flag applies; with an engine, the per-engine override is also
40
+ * consulted. Unknown tools (no override entry) are exposed by default.
41
+ */
42
+ export function isToolExposed(overrides: McpToolOverrides, toolName: string, engine?: EngineType): boolean {
43
+ const override = overrides[toolName];
44
+ if (!override) return true;
45
+ if (override.enabled === false) return false;
46
+ if (engine && override.engines?.[engine] === false) return false;
47
+ return true;
48
+ }
49
+
50
+ /** Per-tool exposure for the Settings UI, split into two INDEPENDENT controls. */
51
+ export interface ToolExposure {
52
+ /** Whole-tool kill switch — `false` hides the tool from every engine. */
53
+ enabled: boolean;
54
+ /**
55
+ * Per-engine picks, independent of `enabled`. Kept separate so the UI can
56
+ * distinguish "tool off" from "tool on but hidden from engine X" and so a
57
+ * per-engine choice survives a master off→on round-trip.
58
+ */
59
+ engines: Record<EngineType, boolean>;
60
+ }
61
+
62
+ /** Expand a stored (possibly absent) override into the two independent controls. */
63
+ export function resolveToolExposure(override: McpToolOverride | undefined): ToolExposure {
64
+ const enabled = override?.enabled !== false;
65
+ const engines = Object.fromEntries(
66
+ MCP_ENGINES.map(engine => [engine, override?.engines?.[engine] !== false])
67
+ ) as Record<EngineType, boolean>;
68
+ return { enabled, engines };
69
+ }
70
+
71
+ /**
72
+ * Drop overrides that carry no information (enabled + every engine on) so the
73
+ * stored map only ever contains real restrictions — keeps the column small and
74
+ * makes "any restriction at all?" a simple emptiness check.
75
+ */
76
+ export function pruneToolOverrides(overrides: McpToolOverrides): McpToolOverrides {
77
+ const out: McpToolOverrides = {};
78
+ for (const [name, override] of Object.entries(overrides)) {
79
+ const disabledGlobally = override.enabled === false;
80
+ const disabledEngines = Object.entries(override.engines ?? {}).filter(([, on]) => on === false);
81
+ if (!disabledGlobally && disabledEngines.length === 0) continue;
82
+ out[name] = {
83
+ ...(disabledGlobally ? { enabled: false } : {}),
84
+ ...(disabledEngines.length > 0 ? { engines: Object.fromEntries(disabledEngines) } : {})
85
+ };
86
+ }
87
+ return out;
88
+ }
@@ -76,6 +76,9 @@ export {
76
76
  // External catalog + types (used by the WS layer and Settings → MCP)
77
77
  export { listRegistryServers, mapRegistryServer } from './external/registry-client';
78
78
  export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth } from './external/config';
79
+ export { listExternalServerTools, callExternalServerTool } from './external/proxy';
80
+ export { parseToolOverrides, resolveToolExposure, pruneToolOverrides, MCP_ENGINES } from './external/tools';
81
+ export type { ToolExposure } from './external/tools';
79
82
  export { probeServer } from './external/probe';
80
83
  export type { McpHealth, McpHealthState } from './external/probe';
81
84
  export {
@@ -95,43 +98,49 @@ export type { ParsedMcpServer, ParsedField, ParseResult } from './external/parse
95
98
  // Merged config builders (internal `clopen-mcp` + external bare `<slug>`)
96
99
  // ---------------------------------------------------------------------------
97
100
 
101
+ // Each builder takes an optional `profileFilter` — the set of connector slugs an
102
+ // active Profile bundles. It restricts the EXTERNAL servers only; Clopen's own
103
+ // internal `clopen-mcp` tools are always present. `undefined` = no active profile
104
+ // (or the profile bundles no connector) → every enabled external server, i.e. the
105
+ // existing behaviour, unchanged.
106
+
98
107
  /** Claude Agent SDK `mcpServers`: in-process internal servers + external stdio/remote. */
99
- export function getEnabledMcpServers(context?: McpExecutionContext): Record<string, McpServerConfig> {
108
+ export function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Record<string, McpServerConfig> {
100
109
  return {
101
- ...internal.getEnabledMcpServers(context),
102
- ...external.getClaudeExternalMcpConfig()
110
+ ...internal.getEnabledMcpServers(context, profileFilter),
111
+ ...external.getClaudeExternalMcpConfig(profileFilter)
103
112
  };
104
113
  }
105
114
 
106
115
  /** Open Code MCP config: internal `clopen-mcp` remote bridge + external servers. */
107
- export function getOpenCodeMcpConfig() {
116
+ export function getOpenCodeMcpConfig(profileFilter?: Set<string>) {
108
117
  return {
109
- ...internal.getOpenCodeMcpConfig(),
110
- ...external.getOpenCodeExternalMcpConfig()
118
+ ...internal.getOpenCodeMcpConfig(profileFilter),
119
+ ...external.getOpenCodeExternalMcpConfig(profileFilter)
111
120
  };
112
121
  }
113
122
 
114
123
  /** Codex MCP config. */
115
- export function getCodexMcpConfig() {
124
+ export function getCodexMcpConfig(profileFilter?: Set<string>) {
116
125
  return {
117
- ...internal.getCodexMcpConfig(),
118
- ...external.getCodexExternalMcpConfig()
126
+ ...internal.getCodexMcpConfig(profileFilter),
127
+ ...external.getCodexExternalMcpConfig(profileFilter)
119
128
  };
120
129
  }
121
130
 
122
131
  /** Copilot MCP config. */
123
- export function getCopilotMcpConfig() {
132
+ export function getCopilotMcpConfig(profileFilter?: Set<string>) {
124
133
  return {
125
- ...internal.getCopilotMcpConfig(),
126
- ...external.getCopilotExternalMcpConfig()
134
+ ...internal.getCopilotMcpConfig(profileFilter),
135
+ ...external.getCopilotExternalMcpConfig(profileFilter)
127
136
  };
128
137
  }
129
138
 
130
139
  /** Qwen Code MCP config. */
131
- export function getQwenMcpConfig() {
140
+ export function getQwenMcpConfig(profileFilter?: Set<string>) {
132
141
  return {
133
- ...internal.getQwenMcpConfig(),
134
- ...external.getQwenExternalMcpConfig()
142
+ ...internal.getQwenMcpConfig(profileFilter),
143
+ ...external.getQwenExternalMcpConfig(profileFilter)
135
144
  };
136
145
  }
137
146
 
@@ -143,3 +152,17 @@ export function getQwenMcpConfig() {
143
152
  export function resolveOpenCodeToolName(toolName: string): string | null {
144
153
  return internal.resolveOpenCodeToolName(toolName) ?? external.resolveExternalToolName(toolName);
145
154
  }
155
+
156
+ /**
157
+ * Open Code tool ids to DISABLE for INTERNAL connectors excluded by an active
158
+ * Profile, for the per-prompt `tools` map (per-session → concurrency-safe). All
159
+ * internal tools ride the single `clopen-mcp` bridge, which is all-or-nothing at
160
+ * the MCP-config level, so per-connector scoping must happen here. EXTERNAL
161
+ * connectors are handled at the server level instead — each is its own MCP entry,
162
+ * dropped from the per-Profile server's config when excluded (see
163
+ * `getOpenCodeMcpConfig(profileFilter)` in the server pool). `undefined` filter
164
+ * (profile doesn't constrain connectors) → none.
165
+ */
166
+ export function getOpenCodeProfileDisabledToolIds(profileFilter?: Set<string>): string[] {
167
+ return internal.getOpenCodeProfileDisabledInternalToolIds(profileFilter);
168
+ }
@@ -129,11 +129,12 @@ function serverEnabled(serverName: string): boolean {
129
129
  * propagation — without this, background streams from Project A would
130
130
  * resolve to Project B's preview browser when the user switches projects.
131
131
  */
132
- export function getEnabledMcpServers(context?: McpExecutionContext): Record<string, McpServerConfig> {
132
+ export function getEnabledMcpServers(context?: McpExecutionContext, profileFilter?: Set<string>): Record<string, McpServerConfig> {
133
133
  const enabledServers: Record<string, McpServerConfig> = {};
134
+ const active = new Set(activeInternalServerNames(profileFilter));
134
135
 
135
136
  Object.entries(mcpServers).forEach(([serverName, serverConfig]) => {
136
- if (serverEnabled(serverName)) {
137
+ if (active.has(serverName)) {
137
138
  if (context) {
138
139
  // Create context-bound instance: wrap each tool handler so
139
140
  // AsyncLocalStorage context is restored on invocation, then
@@ -302,6 +303,19 @@ export function getEnabledServerNames(): string[] {
302
303
  .map(([name]) => name);
303
304
  }
304
305
 
306
+ /**
307
+ * Internal server names ACTIVE for a stream. When a Profile is active, its
308
+ * referenced connector set is the source of truth — a referenced internal server
309
+ * counts even if globally disabled, and one NOT referenced is excluded (built-in
310
+ * connectors appear in the profile's Connectors picker, so this is an explicit
311
+ * choice). Without a profile, every globally-enabled server is active (unchanged).
312
+ */
313
+ export function activeInternalServerNames(profileFilter?: Set<string>): string[] {
314
+ return Object.keys(mcpServers).filter(name =>
315
+ profileFilter ? profileFilter.has(name) : serverEnabled(name)
316
+ );
317
+ }
318
+
305
319
  /**
306
320
  * Get all enabled tool names for a specific server
307
321
  */
@@ -314,6 +328,28 @@ export function getEnabledToolsForServer(serverName: string): string[] {
314
328
  return serverConfig.tools.map((toolName) => `mcp__${serverName}__${toolName}`);
315
329
  }
316
330
 
331
+ /**
332
+ * Open Code tool ids (`clopen-mcp_<tool>`) for INTERNAL connectors EXCLUDED by an
333
+ * active Profile — every globally-enabled internal server whose slug is NOT in the
334
+ * profile's connector set. Fed to Open Code's per-prompt `tools` disable map so
335
+ * those tools are removed for THIS session, even though the persistent server was
336
+ * built with every enabled connector. `undefined` filter (profile doesn't
337
+ * constrain connectors) → none. All internal tools share the single `clopen-mcp`
338
+ * bridge namespace, so the id is `clopen-mcp_<tool>` regardless of owning server.
339
+ */
340
+ export function getOpenCodeProfileDisabledInternalToolIds(profileFilter?: Set<string>): string[] {
341
+ if (!profileFilter) return [];
342
+ const ids: string[] = [];
343
+ for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
344
+ if (!serverEnabled(serverName)) continue; // not in the running config anyway
345
+ if (profileFilter.has(serverName)) continue; // allowed by the profile
346
+ for (const toolName of serverConfig.tools as readonly string[]) {
347
+ ids.push(`clopen-mcp_${toolName}`);
348
+ }
349
+ }
350
+ return ids;
351
+ }
352
+
317
353
  /**
318
354
  * Get statistics about MCP servers and tools
319
355
  */
@@ -429,9 +465,10 @@ export function resolveOpenCodeToolName(toolName: string): string | null {
429
465
  *
430
466
  * This is the Open Code equivalent of Claude Code's in-process MCP servers.
431
467
  */
432
- export function getOpenCodeMcpConfig(): Record<string, McpRemoteConfig> {
433
- // Check if any servers are enabled
434
- const enabledServers = getEnabledServerNames();
468
+ export function getOpenCodeMcpConfig(profileFilter?: Set<string>): Record<string, McpRemoteConfig> {
469
+ // Drop the internal bridge entirely when an active profile excludes every
470
+ // internal connector (else include it; the bridge serves the enabled ones).
471
+ const enabledServers = activeInternalServerNames(profileFilter);
435
472
  if (enabledServers.length === 0) {
436
473
  return {};
437
474
  }
@@ -489,8 +526,8 @@ type CodexMcpServerConfig = {
489
526
  * `--config mcp_servers.clopen-mcp.<dotted-key>=<value>` flags when the SDK
490
527
  * invokes the CLI subprocess for each turn.
491
528
  */
492
- export function getCodexMcpConfig(): Record<string, CodexMcpServerConfig> {
493
- const enabledServers = getEnabledServerNames();
529
+ export function getCodexMcpConfig(profileFilter?: Set<string>): Record<string, CodexMcpServerConfig> {
530
+ const enabledServers = activeInternalServerNames(profileFilter);
494
531
  if (enabledServers.length === 0) {
495
532
  return {};
496
533
  }
@@ -539,8 +576,8 @@ export function getCodexMcpConfig(): Record<string, CodexMcpServerConfig> {
539
576
  * `resolveOpenCodeToolName()` to recover the canonical
540
577
  * `mcp__<server>__<tool>` form.
541
578
  */
542
- export function getCopilotMcpConfig(): Record<string, MCPHTTPServerConfig> {
543
- const enabledServers = getEnabledServerNames();
579
+ export function getCopilotMcpConfig(profileFilter?: Set<string>): Record<string, MCPHTTPServerConfig> {
580
+ const enabledServers = activeInternalServerNames(profileFilter);
544
581
  if (enabledServers.length === 0) {
545
582
  return {};
546
583
  }
@@ -587,8 +624,8 @@ export function getCopilotMcpConfig(): Record<string, MCPHTTPServerConfig> {
587
624
  * so the model never sees it. The callback covers MCP tool calls too — no
588
625
  * per-tool enumeration needed.
589
626
  */
590
- export function getQwenMcpConfig(): Record<string, QwenMcpServerConfig> {
591
- const enabledServers = getEnabledServerNames();
627
+ export function getQwenMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
628
+ const enabledServers = activeInternalServerNames(profileFilter);
592
629
  if (enabledServers.length === 0) {
593
630
  return {};
594
631
  }
@@ -25,6 +25,7 @@ import { authQueries } from '$backend/database/queries';
25
25
  import { hashToken } from '$backend/auth/tokens';
26
26
  import { getAuthMode } from '$backend/auth/auth-service';
27
27
  import { isMcpServiceToken } from './service-token';
28
+ import type { EngineType } from '$shared/types/unified';
28
29
 
29
30
  /** Anything we can `.connect(transport)` — both `McpServer` and low-level `Server`. */
30
31
  interface ConnectableServer {
@@ -227,9 +228,16 @@ export async function handleMcpRequest(request: Request): Promise<Response> {
227
228
  * Handle an incoming request to an EXTERNAL proxy bridge
228
229
  * (`/mcp/ext/<slug>`). Clopen connects to the upstream third-party server and
229
230
  * re-exposes its (sanitized) tools, so engines never connect to it directly.
231
+ *
232
+ * The `?engine=<engine>` query param (set by each engine's config builder in
233
+ * `backend/mcp/external/config.ts`) tells the proxy which engine is calling so
234
+ * it can apply that engine's per-tool exposure filter. It is read from the
235
+ * initialize request only — the resulting proxy (and its filter) stays bound to
236
+ * that session, so per-engine filtering holds for the whole connection.
230
237
  */
231
238
  export async function handleExternalMcpRequest(request: Request, slug: string): Promise<Response> {
232
- return handleStreamable(request, `External MCP (${slug})`, () => createExternalProxyServer(slug));
239
+ const engine = (new URL(request.url).searchParams.get('engine') as EngineType | null) ?? undefined;
240
+ return handleStreamable(request, `External MCP (${slug}${engine ? `, ${engine}` : ''})`, () => createExternalProxyServer(slug, engine));
233
241
  }
234
242
 
235
243
  /**
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Permissions — public facade. Settings → Permissions manages per-engine tool
3
+ * allow/deny rules; enforcement is a runtime hook each engine adapter consults
4
+ * at its auto-approve point (see `resolvePermissionsFromDb` + `isToolAllowed`).
5
+ */
6
+
7
+ export {
8
+ permissionService,
9
+ resolvePermissionsFromDb,
10
+ excludedBuiltinTools,
11
+ toArtifactEngine,
12
+ type PermissionSetDTO,
13
+ type PermissionInventory,
14
+ type EngineInventory,
15
+ type ArtifactEngineKey
16
+ } from './service';
17
+ export {
18
+ isToolAllowed,
19
+ hasAnyRestriction,
20
+ matchesPattern,
21
+ matchesAny,
22
+ mergePermissions,
23
+ pickEngineSet,
24
+ EMPTY_PERMISSIONS,
25
+ type ResolvedPermissions
26
+ } from './resolve';
27
+ export { syncPermissions } from './materialize';