Add cross-harness MCP server manager #4634
Closedm-de-graaff(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/4634/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/mcpServers/McpServerToggle.ts lines 88 to 95Resolvedby m-de-graaff(GitHub profile, opens in a new tab)@@ -0,0 +75,21 @@75+ };76+ }77+78+ for (const driver of TOGGLEABLE_DRIVERS) {79+ if (defaultInstanceIdForDriver(driver as never) !== input.instanceId) continue;80+ const legacyKey = driver as keyof ServerSettings["providers"];81+ const legacyConfig = settings.providers[legacyKey];82+ if (legacyConfig === undefined) return { kind: "unsupported" };83+ const disabledMcpServers = nextDisabledMcpServers(84+ readDisabledMcpServers(legacyConfig),85+ input.name,86+ input.enabled,87+ );88+ return {89+ kind: "legacyProvider",90+ patch: {91+ providers: {92+ [legacyKey]: { disabledMcpServers: [...disabledMcpServers] },93+ },94+ } as ServerSettingsPatch,95+ };apps/web/src/components/settings/McpServersSettings.tsx line 141Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +115,21 @@115+ </SettingsSection>116+ </SettingsPageContainer>117+ );118+}119+120+function EnvironmentMcpInventory({121+ environment,122+ query,123+ refreshKey,124+}: {125+ environment: EnvironmentPresentation;126+ query: string;127+ refreshKey: number;128+}) {129+ const prepared = usePreparedConnection(environment.environmentId);130+ const [state, setState] = useState<InventoryState>({ status: "loading" });131+ const [collapsed, setCollapsed] = useState(false);132+ const [pendingKeys, setPendingKeys] = useState<ReadonlySet<string>>(() => new Set());133+ const panelId = useId();134+135+ useEffect(() => {apps/server/src/provider/Layers/ClaudeAdapter.ts line 902Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -887,3 +888,9 @@887888 "local",888889 ] as const satisfies ReadonlyArray<SettingSource>;889890891+/**892+ * Configured MCP servers minus the ones disabled in T3 Code, in the shape the893+ * Agent SDK's `mcpServers` option accepts. Paired with `strictMcpConfig` so894+ * this map is the whole set the session sees.895+ */896+const buildEnabledClaudeMcpServerMap = Effect.fn("buildEnabledClaudeMcpServerMap")(function* (apps/server/src/mcpServers/ClaudeMcpConfig.ts line 46OutdatedResolvedby m-de-graaff(GitHub profile, opens in a new tab)@@ -0,0 +26,21 @@26+ readonly definition: Record<string, unknown>;27+}28+29+/**30+ * Resolve the file Claude Code reads user-scoped MCP servers from. With31+ * `CLAUDE_CONFIG_DIR` set (T3's `homePath`), `.claude.json` lives inside that32+ * directory; otherwise it sits at `~/.claude.json`.33+ */34+export const resolveClaudeMcpConfigFilePath = Effect.fn("resolveClaudeMcpConfigFilePath")(35+ function* (36+ config: Pick<ClaudeSettings, "homePath">,37+ environment: NodeJS.ProcessEnv,38+ ): Effect.fn.Return<string, never, Path.Path> {39+ const path = yield* Path.Path;40+ const homePath = config.homePath.trim();41+ if (homePath.length > 0) {42+ return path.join(path.resolve(expandHomePath(homePath)), ".claude.json");43+ }44+ const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";45+ if (environmentConfigDir.length > 0) {46+ return path.join(path.resolve(environmentConfigDir), ".claude.json");
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 3617Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3550,8 +3583,13 @@3550- "t3-code": {3551- type: "http",3552- url: mcpSession.endpoint,3553- headers: {3554- Authorization: mcpSession.authorizationHeader,3555- },3556- },3557- },3583+ ...enabledConfiguredMcpServers,3584+ ...(mcpSession3585+ ? {3586+ "t3-code": {3587+ type: "http",3588+ url: mcpSession.endpoint,3589+ headers: {3590+ Authorization: mcpSession.authorizationHeader,3591+ },3592+ },3593+ }3594+ : {}),3595+ } as NonNullable<ClaudeQueryOptions["mcpServers"]>,apps/server/src/mcpServers/http.ts line 63OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +34,21 @@34+ .handle(35+ "setEnabled",36+ Effect.fn("environment.mcpServers.setEnabled")(function* (args) {37+ yield* annotateEnvironmentRequest(args.endpoint.name);38+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);39+40+ const settings = yield* settingsService.getSettings.pipe(41+ Effect.catch((cause) => failEnvironmentInternal("internal_error", cause)),42+ );43+ const plan = planDisabledMcpServersWrite(settings, {44+ instanceId: args.payload.providerInstanceId,45+ name: args.payload.name,46+ enabled: args.payload.enabled,47+ });48+ if (plan.kind === "unsupported") {49+ return yield* failEnvironmentInvalidRequest("invalid_command");50+ }51+52+ yield* settingsService53+ .updateSettings(plan.patch)54+ .pipe(Effect.catch((cause) => failEnvironmentInternal("internal_error", cause)));apps/web/src/components/settings/McpServersSettings.logic.ts line 58OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +38,21 @@38+ };39+}40+41+export function displayedMcpServerCount(42+ inventory: McpServerInventory | null,43+ isConnected: boolean,44+): number | null {45+ if (!isConnected || !inventory) return null;46+ return inventory.servers.length;47+}48+49+export function setKeyCollapsed(50+ keys: ReadonlySet<string>,51+ key: string,52+ collapsed: boolean,53+): ReadonlySet<string> {54+ const next = new Set(keys);55+ if (collapsed) next.add(key);56+ else next.delete(key);57+ return next;58+}
- apps/server/src/mcpServers/http.ts line 46OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +26,21 @@26+ // computed from a settings snapshot read before that lock. Serialize the27+ // whole read-plan-write here so two overlapping toggles cannot both plan28+ // from the same snapshot and drop one another's entry.29+ const toggleSemaphore = yield* Semaphore.make(1);30+31+ return handlers32+ .handle(33+ "inventory",34+ Effect.fn("environment.mcpServers.inventory")(function* (args) {35+ yield* annotateEnvironmentRequest(args.endpoint.name);36+ yield* requireEnvironmentScope(AuthOrchestrationReadScope);37+ return yield* discoverGlobalMcpInventory();38+ }),39+ )40+ .handle(41+ "setEnabled",42+ Effect.fn("environment.mcpServers.setEnabled")(function* (args) {43+ yield* annotateEnvironmentRequest(args.endpoint.name);44+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);45+46+ yield* toggleSemaphore.withPermits(1)(apps/web/src/components/settings/McpServersSettings.tsx line 194Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +172,21 @@172+ status: "loaded",173+ inventory: withServerEnabled(174+ current.inventory,175+ { providerInstanceId: server.providerInstanceId, name: server.name },176+ enabled,177+ ),178+ }179+ : current,180+ );181+ void runtime182+ .runPromise(183+ setEnvironmentMcpServerEnabled({184+ prepared: prepared.value,185+ patch: {186+ providerInstanceId: server.providerInstanceId,187+ name: server.name,188+ enabled,189+ },190+ }),191+ )192+ .then((inventory) => {apps/server/src/mcpServers/McpServerInventory.ts lines 99 to 99OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +79,21 @@79+80+const discoverClaudeMcpServers = Effect.fn("McpServerInventory.discoverClaudeMcpServers")(81+ function* (82+ instanceId: string,83+ instance: ProviderInstanceConfig,84+ environment: NodeJS.ProcessEnv,85+ cwd: string | undefined,86+ ): Effect.fn.Return<ReadonlyArray<McpServerInventoryEntry>, never, McpInventoryEnv> {87+ const decoded = decodeClaudeSettings(instance.config ?? {});88+ if (decoded._tag === "None") return [];89+ const settings = decoded.value;90+91+ const definitions = yield* readClaudeMcpServers(settings, environment, cwd);92+93+ const disabled = new Set(settings.disabledMcpServers);94+ const entries: McpServerInventoryEntry[] = [];95+ for (const { name, scope, sourcePath, definition: entry } of definitions) {96+ const transport = claudeTransport(entry);97+ const command = trimmedOrUndefined(entry.command);98+ const url = trimmedOrUndefined(entry.url);99+ const detail = transport === "stdio" && command ? stdioDetail(command, entry.args) : url;apps/server/src/provider/Layers/ClaudeAdapter.ts line 903OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -887,3 +888,16 @@887888 "local",888889 ] as const satisfies ReadonlyArray<SettingSource>;889890891+/**892+ * Configured MCP servers minus the ones disabled in T3 Code, in the shape the893+ * Agent SDK's `mcpServers` option accepts. Paired with `strictMcpConfig` so894+ * this map is the whole set the session sees.895+ */896+const buildEnabledClaudeMcpServerMap = Effect.fn("buildEnabledClaudeMcpServerMap")(function* (897+ claudeSettings: ClaudeSettings,898+ environment: NodeJS.ProcessEnv,899+ // The session workspace cwd, so a relative `CLAUDE_CONFIG_DIR` resolves the900+ // same way it will inside the spawned CLI.901+ cwd: string | undefined,902+): Effect.fn.Return<Record<string, unknown>, never, FileSystem.FileSystem | Path.Path> {903+ const definitions = yield* readClaudeMcpServers(claudeSettings, environment, cwd);
- apps/server/src/mcpServers/McpServerInventory.ts line 278Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +233,21 @@233+export const discoverGlobalMcpInventory = Effect.fn(234+ "McpServerInventory.discoverGlobalMcpInventory",235+)(function* (236+ environment?: NodeJS.ProcessEnv,237+): Effect.fn.Return<238+ McpServerInventory,239+ never,240+ McpInventoryEnv | ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService | ServerConfig241+> {242+ const settingsService = yield* ServerSettingsService;243+ const settings = yield* settingsService.getSettings.pipe(Effect.orDie);244+ const providerInstances = deriveProviderInstanceConfigMap(settings);245+ const resolvedEnvironment = environment ?? process.env;246+ // Sessions resolve a relative `CLAUDE_CONFIG_DIR` against the workspace cwd,247+ // so the inventory has to report the same file the runtime will read.248+ const { cwd } = yield* ServerConfig;249+250+ const discovered = yield* Effect.forEach(251+ Object.entries(providerInstances),252+ ([instanceId, instance]) =>253+ discoverInstanceMcpServers(instanceId, instance, resolvedEnvironment, cwd),apps/web/src/components/settings/McpServersSettings.tsx line 193OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +173,21 @@173+ inventory: withServerEnabled(174+ current.inventory,175+ { providerInstanceId: server.providerInstanceId, name: server.name },176+ enabled,177+ ),178+ }179+ : current,180+ );181+ void runtime182+ .runPromise(183+ setEnvironmentMcpServerEnabled({184+ prepared: prepared.value,185+ patch: {186+ providerInstanceId: server.providerInstanceId,187+ name: server.name,188+ enabled,189+ },190+ }),191+ )192+ .then((inventory) => {193+ if (generation !== generationRef.current) return;
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 918OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -889,0 +898,21 @@898+ * session over a transient read error, so the session falls back to the CLI's899+ * own resolution — the user's disable list is ignored for that run, which is900+ * the safer direction to fail.901+ */902+const buildEnabledClaudeMcpServerMap = Effect.fn("buildEnabledClaudeMcpServerMap")(function* (903+ claudeSettings: ClaudeSettings,904+ environment: NodeJS.ProcessEnv,905+ // The session workspace cwd, so a relative `CLAUDE_CONFIG_DIR` resolves the906+ // same way it will inside the spawned CLI.907+ cwd: string | undefined,908+): Effect.fn.Return<Record<string, unknown> | undefined, never, FileSystem.FileSystem | Path.Path> {909+ const { complete, definitions } = yield* readClaudeMcpServers(claudeSettings, environment, cwd);910+ if (!complete) {911+ yield* Effect.logWarning(912+ "Could not read every Claude MCP config file; leaving MCP resolution to the CLI for this session.",913+ );914+ return undefined;915+ }916+917+ const disabled = new Set(claudeSettings.disabledMcpServers);918+ const enabled: Record<string, unknown> = {};apps/server/src/mcpServers/http.ts line 56Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +35,21 @@35+ "setEnabled",36+ Effect.fn("environment.mcpServers.setEnabled")(function* (args) {37+ yield* annotateEnvironmentRequest(args.endpoint.name);38+ yield* requireEnvironmentScope(AuthOrchestrationOperateScope);39+40+ const target = {41+ instanceId: args.payload.providerInstanceId,42+ name: args.payload.name,43+ enabled: args.payload.enabled,44+ };45+ const settings = yield* settingsService.getSettings.pipe(46+ Effect.catch((cause) => failEnvironmentInternal("internal_error", cause)),47+ );48+ if (planDisabledMcpServersWrite(settings, target).kind === "unsupported") {49+ return yield* failEnvironmentInvalidRequest("invalid_command");50+ }51+52+ // Re-plan inside the settings write lock: the disable list is a53+ // read-modify-write, so planning from a snapshot taken outside the54+ // lock could drop a concurrent writer's changes.55+ yield* settingsServiceapps/server/src/mcpServers/ClaudeMcpConfig.ts lines 86 to 87OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ return Array.isArray(value)68+ ? value.filter((entry): entry is string => typeof entry === "string")69+ : [];70+}71+72+/**73+ * A config file is either absent (no servers, and that is the truth), readable74+ * (its parsed contents), or unusable — unreadable or malformed, meaning the75+ * server list this file would contribute is unknown.76+ */77+type JsonFileRead =78+ | { readonly kind: "absent" }79+ | { readonly kind: "object"; readonly value: Record<string, unknown> }80+ | { readonly kind: "unusable" };81+82+const readJsonObject = Effect.fn("readClaudeJsonObject")(function* (83+ filePath: string,84+): Effect.fn.Return<JsonFileRead, never, FileSystem.FileSystem> {85+ const fileSystem = yield* FileSystem.FileSystem;86+ const exists = yield* fileSystem.exists(filePath).pipe(Effect.orElseSucceed(() => false));87+ if (!exists) return { kind: "absent" };
- apps/server/src/mcpServers/McpServerInventory.ts line 113OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+94+function claudeTransport(entry: Record<string, unknown>): McpServerTransport {95+ const declared = trimmedOrUndefined(entry.type);96+ if (declared === "http" || declared === "sse") return declared;97+ if (declared === "stdio") return "stdio";98+ // Older entries omit `type`; a `url` means a remote server.99+ return trimmedOrUndefined(entry.url) ? "http" : "stdio";100+}101+102+const discoverClaudeMcpServers = Effect.fn("McpServerInventory.discoverClaudeMcpServers")(103+ function* (104+ instanceId: string,105+ instance: ProviderInstanceConfig,106+ environment: NodeJS.ProcessEnv,107+ cwd: string | undefined,108+ ): Effect.fn.Return<ReadonlyArray<McpServerInventoryEntry>, never, McpInventoryEnv> {109+ const decoded = decodeClaudeSettings(instance.config ?? {});110+ if (decoded._tag === "None") return [];111+ const settings = decoded.value;112+113+ const { definitions } = yield* readClaudeMcpServers(settings, environment, cwd);apps/server/src/mcpServers/ClaudeMcpConfig.ts line 87OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ return Array.isArray(value)68+ ? value.filter((entry): entry is string => typeof entry === "string")69+ : [];70+}71+72+/**73+ * A config file is either absent (no servers, and that is the truth), readable74+ * (its parsed contents), or unusable — unreadable or malformed, meaning the75+ * server list this file would contribute is unknown.76+ */77+type JsonFileRead =78+ | { readonly kind: "absent" }79+ | { readonly kind: "object"; readonly value: Record<string, unknown> }80+ | { readonly kind: "unusable" };81+82+const readJsonObject = Effect.fn("readClaudeJsonObject")(function* (83+ filePath: string,84+): Effect.fn.Return<JsonFileRead, never, FileSystem.FileSystem> {85+ const fileSystem = yield* FileSystem.FileSystem;86+ const exists = yield* fileSystem.exists(filePath).pipe(Effect.orElseSucceed(() => false));87+ if (!exists) return { kind: "absent" };
- @@ -0,0 +102,21 @@102+export const discoverClaudeMcpServerEntries = Effect.fn(103+ "McpServerInventory.discoverClaudeMcpServers",104+)(function* (105+ instanceId: string,106+ instance: ProviderInstanceConfig,107+ environment: NodeJS.ProcessEnv,108+ cwd: string | undefined,109+): Effect.fn.Return<ReadonlyArray<McpServerInventoryEntry>, never, McpInventoryEnv> {110+ const decoded = decodeClaudeSettings(instance.config ?? {});111+ if (decoded._tag === "None") return [];112+ const settings = decoded.value;113+114+ const { complete, definitions } = yield* readClaudeMcpServers(settings, environment, cwd);115+116+ const disabled = new Set(settings.disabledMcpServers);117+ const entries: McpServerInventoryEntry[] = [];118+ for (const { name, scope, sourcePath, definition: entry } of definitions) {119+ const transport = claudeTransport(entry);120+ const command = trimmedOrUndefined(entry.command);121+ const url = trimmedOrUndefined(entry.url);122+ const detail = transport === "stdio" && command ? stdioDetail(command, entry.args) : url;@@ -0,0 +183,21 @@183+ typeof projectEntry === "object" && projectEntry !== null184+ ? (projectEntry as Record<string, unknown>)185+ : undefined;186+187+ const mcpJsonPath = path.join(cwd, ".mcp.json");188+ const mcpJsonRead = yield* readJsonObject(mcpJsonPath);189+ const mcpJson = mcpJsonRead.kind === "object" ? mcpJsonRead.value : undefined;190+ if (mcpJsonRead.kind === "unusable") complete = false;191+ const approveAll = projectConfig?.enableAllProjectMcpServers === true;192+ const approved = new Set(readStringArray(projectConfig?.enabledMcpjsonServers));193+ const rejected = new Set(readStringArray(projectConfig?.disabledMcpjsonServers));194+ for (const [name, definition] of readServerMap(mcpJson?.mcpServers)) {195+ if (rejected.has(name) || (!approveAll && !approved.has(name))) continue;196+ byName.set(name, { name, scope: "project", sourcePath: mcpJsonPath, definition });197+ }198+199+ for (const [name, definition] of readServerMap(projectConfig?.mcpServers)) {200+ byName.set(name, { name, scope: "local", sourcePath: configPath, definition });201+ }202+203+ return { complete, definitions: [...byName.values()] };
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
767524e5-59d6-455a-8c78-3478190ea5afYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share