diff --git a/.github/fork-seams.json b/.github/fork-seams.json index 7227c25c8231b..827e8c2feb742 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -150,39 +150,27 @@ }, "apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts": { "why": "MCP profiles part 2: a Claude thread's MCP profile is applied to its session (strict MCP mode or an allowlist of outside servers, from apps/server/src/fork/claudeMcpProfile.ts), is part of the live-query key, refuses the turn when it cannot be applied, and adds a PreToolUse hook (merged into the adapter's hooks) that refuses a call to a server outside the profile. Additions only; tested in apps/server/src/fork/claudeMcpProfile.adapter.test.ts.", - "added": [], - "announced": { - "since": "2026-11-19", - "added": [ - "import * as ClaudeMcpProfile from \"../../fork/claudeMcpProfile.ts\";", - "readonly mcpProfileOptions?: ClaudeMcpProfile.ClaudeMcpProfilePlan[\"options\"];", - "...input.mcpProfileOptions,", - "mcpProfile: ClaudeMcpProfile.planKeyFor(mcpOverrides),", - "const mcpProfiles = yield* ClaudeMcpProfile.makeClaudeMcpProfiles;", - "// Fork: a profile that cannot apply refuses here, before the live process is replaced.", - "const mcpProfile = yield* mcpProfiles(turnInput.appThread, mcpOverrides);", - "const checkMcpProfile = ClaudeMcpProfile.checkClaudeSession(mcpProfile, mcpOverrides);", - "mcpProfileOptions: mcpProfile.options,", - "Effect.tap(checkMcpProfile),", - "...input.mcpProfileOptions?.hooks," - ] - } + "added": [ + "import * as ClaudeMcpProfile from \"../../fork/claudeMcpProfile.ts\";", + "readonly mcpProfileOptions?: ClaudeMcpProfile.ClaudeMcpProfilePlan[\"options\"];", + "...input.mcpProfileOptions,", + "mcpProfile: ClaudeMcpProfile.planKeyFor(mcpOverrides),", + "const mcpProfiles = yield* ClaudeMcpProfile.makeClaudeMcpProfiles;", + "// Fork: a profile that cannot apply refuses here, before the live process is replaced.", + "const mcpProfile = yield* mcpProfiles(turnInput.appThread, mcpOverrides);", + "const checkMcpProfile = ClaudeMcpProfile.checkClaudeSession(mcpProfile, mcpOverrides);", + "mcpProfileOptions: mcpProfile.options,", + "Effect.tap(checkMcpProfile),", + "...input.mcpProfileOptions?.hooks," + ] }, "apps/server/src/orchestration-v2/ProviderTurnStartService.ts": { "why": "MCP profiles part 2: a Claude turn its MCP profile refuses never reached Claude, like the other refusals in this list.", - "added": [], - "announced": { - "since": "2026-11-19", - "added": ["\"ClaudeMcpProfileError\","] - } + "added": ["\"ClaudeMcpProfileError\","] }, "packages/provider-core/src/server/failure.ts": { "why": "MCP profiles part 2: the refusal of a Claude turn by its MCP profile says why and how to fix it, so its message is shown.", - "added": [], - "announced": { - "since": "2026-11-19", - "added": ["case \"ClaudeMcpProfileError\":"] - } + "added": ["case \"ClaudeMcpProfileError\":"] } }, "//pending": "Upstream files whose fork lines predate counting every upstream file, each with its ceiling: the most fork lines it may hold against upstream (counted from upstream, as fork-follow runs the check). To move into fork files or pin as seams; lower a ceiling when lines move out and take a file off when none are left. A pull request may change them but not grow them.", diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index 714069cfef286..3bf70e2fabc39 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -31,7 +31,7 @@ setting is missing here or a setting named here does not exist. | A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on, and where. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | | `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | | Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | -| MCP profiles, part 1: settings for named profiles (which outside MCP servers and which T3 tool groups a thread gets), a default, a sub-agent rule and a pick per thread, and the rules that decide a thread's profile. Nothing applies a profile yet. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227) | +| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude applies the outside servers and refuses a turn when its profile cannot. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528) | | Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | | Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | | Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | diff --git a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts new file mode 100644 index 0000000000000..f2999ab234ae9 --- /dev/null +++ b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts @@ -0,0 +1,335 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import type { HookInput, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; +import { assert, describe, it } from "@effect/vitest"; +import { + ClaudeSettings, + EnvironmentId, + ProjectId, + ProviderInstanceId, + ProviderSessionId, + type ServerSettings, + ThreadId, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; +import type * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { makeTurnInput } from "../orchestration-v2/Adapters/AcpAdapterV2.testkit.ts"; +import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import { type LineageThread, makeClaudeMcpProfiles } from "./claudeMcpProfile.ts"; + +const MODEL = { + instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), + model: "claude-sonnet-4-6", +}; +const CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({}); +const POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", +}); + +type McpSettings = Partial>; +const NATIVE_THREAD = "native-thread-mcp-profile"; + +/** + * Runs Claude turns on one thread with these server settings, saving each of `saves` before the + * next turn; records each open and the sessions' closes. Stops at the first refused turn. + */ +const runTurns = ( + settings: McpSettings, + statuses: ReadonlyArray<{ readonly name: string; readonly status: "connected" }> | "unexpected", + saves: ReadonlyArray = [], +) => + Effect.gen(function* () { + const opened: Array = []; + const processes: Array> = []; + let closed = 0; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: CLAUDE_SETTINGS, + environment: {}, + attachmentsDir: yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped(), + fileSystem: yield* FileSystem.FileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + queryRunner: { + allocateSessionId: Effect.succeed(NATIVE_THREAD), + open: (input) => + Effect.gen(function* () { + const messages = yield* Queue.unbounded(); + processes.push(messages); + opened.push(input.options); + return { + messages: Stream.fromQueue(messages), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + renameSession: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: + statuses === "unexpected" + ? Effect.die("the default profile asked Claude for its MCP servers") + : Effect.succeed(statuses), + readMcpResource: () => Effect.die("unused"), + callMcpTool: () => Effect.die("unused"), + listPermissionRules: Effect.die("unused"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.sync(() => void closed++), + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-mcp-profile"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-mcp-profile"), + modelSelection: MODEL, + runtimePolicy: POLICY, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: MODEL, + runtimePolicy: POLICY, + }); + const terminals = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runForEach((event) => Queue.offer(terminals, event)), + Effect.forkScoped, + ); + const settingsService = yield* ServerSettingsService.ServerSettingsService; + let refusal: string | undefined; + for (const [index, save] of [undefined, ...saves].entries()) { + if (save !== undefined) yield* settingsService.updateSettings(save); + const started = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId: MODEL.instanceId, + runtimePolicy: POLICY, + now: yield* DateTime.now, + modelSelection: MODEL, + ordinal: index + 1, + }), + ) + .pipe(Effect.exit); + if (started._tag === "Failure") { + refusal = makeProviderFailure({ cause: started.cause, class: "provider_error" }).message; + break; + } + if (index === saves.length) break; + // Ends the turn so the next one may reuse the live process. + yield* Queue.offer(processes.at(-1)!, resultFrame(index + 1)); + yield* Queue.take(terminals); + } + return { opened, closed, refusal }; + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ServerSettingsService.layerTest(settings), + ), + ), + ); + +const resultFrame = (ordinal: number) => + ({ + type: "result", + subtype: "success", + duration_ms: 1, + duration_api_ms: 1, + is_error: false, + num_turns: 1, + result: "Done.", + stop_reason: "end_turn", + total_cost_usd: 0, + usage: { + input_tokens: 1, + output_tokens: 1, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + modelUsage: {}, + permission_denials: [], + uuid: `00000000-0000-4000-8000-00000000000${ordinal}`, + session_id: NATIVE_THREAD, + terminal_reason: "completed", + }) as unknown as SDKMessage; + +/** What the session's PreToolUse hooks answer for a call to this tool. */ +const preToolUse = ( + options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined, + tool: string, +) => + Effect.promise(async () => { + const input = { + hook_event_name: "PreToolUse", + tool_name: tool, + tool_input: {}, + tool_use_id: "toolu_profile", + session_id: NATIVE_THREAD, + transcript_path: "/tmp/transcript.jsonl", + cwd: "/workspace", + } as unknown as HookInput; + const answers = []; + for (const matcher of options?.hooks?.PreToolUse ?? []) { + for (const hook of matcher.hooks) { + answers.push(await hook(input, "toolu_profile", { signal: new AbortController().signal })); + } + } + return answers; + }); + +describe("ClaudeAdapterV2 MCP profile", () => { + it.effect("with no profile set, opens Claude as before and never checks its servers", () => + Effect.gen(function* () { + const { opened, refusal } = yield* runTurns({}, "unexpected"); + assert.isUndefined(refusal); + assert.lengthOf(opened, 1); + assert.notProperty(opened[0], "strictMcpConfig"); + assert.notProperty(opened[0], "managedSettings"); + assert.deepStrictEqual(yield* preToolUse(opened[0], "mcp__github__x"), []); + }), + ); + + it.effect("t3-only opens Claude in strict MCP mode", () => + Effect.gen(function* () { + const { opened, refusal } = yield* runTurns({ mcpProfile: "t3-only" }, []); + assert.isUndefined(refusal); + assert.isTrue(opened[0]?.strictMcpConfig); + }), + ); + + it.effect("a list opens Claude with only those servers allowed", () => + Effect.gen(function* () { + const { opened, refusal } = yield* runTurns( + { mcpProfile: "docs", mcpProfiles: { docs: { servers: ["docs"], t3Tools: "all" } } }, + [{ name: "docs", status: "connected" }], + ); + assert.isUndefined(refusal); + assert.deepStrictEqual(opened[0]?.managedSettings, { + allowedMcpServers: [{ serverName: "docs" }], + }); + }), + ); + + it.effect("refuses, at the call, a tool of a server the profile leaves out", () => + Effect.gen(function* () { + const { opened } = yield* runTurns( + { mcpProfile: "docs", mcpProfiles: { docs: { servers: ["docs"], t3Tools: "all" } } }, + [{ name: "docs", status: "connected" }], + ); + const [refused] = yield* preToolUse(opened[0], "mcp__github__x"); + assert.deepInclude(refused, { + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: `MCP profile "docs" leaves out the MCP server "github", so T3 refused this call. Claude loaded it anyway: a managed Claude policy on this machine, --mcp-config in the Claude launch arguments, or an agent file's servers can add one. To use it, pick "all" for this thread, or fix the profile in Settings so the profile names it.`, + }, + }); + assert.deepStrictEqual(yield* preToolUse(opened[0], "mcp__docs__search"), [{}]); + }), + ); + + it.effect("a narrowed profile opens a new Claude process; the same profile reuses it", () => + Effect.gen(function* () { + const narrowed = yield* runTurns({}, [], [{ mcpProfile: "t3-only" }]); + assert.isUndefined(narrowed.refusal); + assert.lengthOf(narrowed.opened, 2); + assert.isTrue(narrowed.opened[1]?.strictMcpConfig); + const same = yield* runTurns({ mcpProfile: "t3-only" }, [], [{ mcpProfile: "t3-only" }]); + assert.isUndefined(same.refusal); + assert.lengthOf(same.opened, 1); + }), + ); + + it.effect("refuses the turn, without opening Claude, when the profile is missing", () => + Effect.gen(function* () { + const { opened, refusal } = yield* runTurns({ mcpProfile: "lean" }, []); + assert.lengthOf(opened, 0); + assert.include(refusal, 'MCP profile "lean" is not set up, so this thread cannot start'); + }), + ); + + it.effect( + "refuses the turn and closes Claude when it still loads a server the profile leaves out", + () => + Effect.gen(function* () { + const { closed, refusal } = yield* runTurns({ mcpProfile: "t3-only" }, [ + { name: "claude.ai Calendar", status: "connected" }, + ]); + assert.equal(closed, 1); + assert.include(refusal, "Claude still loaded claude.ai Calendar"); + }), + ); + + // Upstream's "invalidates live-query reuse when MCP credentials rotate" keys overrides no profile + // planned, which now always differ; this keys planned ones, so it fails if the T3 server's + // credentials leave the key. + it.effect( + "planned turns reuse a process for the same MCP credentials, not after a rotation", + () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread-mcp-profile-rotation"); + const overridesFor = (authorizationHeader: string) => + ClaudeAdapterV2.claudeMcpQueryOverrides({ + mcpSession: { + environmentId: EnvironmentId.make("environment-mcp-profile"), + threadId, + providerSessionId: "mcp-session-mcp-profile", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader, + browserToolsAvailable: true, + } satisfies McpProviderSession.McpProviderSessionConfig, + readOnlySandbox: false, + }); + const thread: LineageThread = { + id: threadId, + projectId: ProjectId.make("project-mcp-profile"), + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + }; + const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(POLICY); + for (const settings of [{}, { mcpProfile: "t3-only" }] satisfies Array) { + const plan = yield* makeClaudeMcpProfiles.pipe( + Effect.provide(ServerSettingsService.layerTest(settings)), + ); + const keyFor = (authorizationHeader: string) => + Effect.gen(function* () { + const overrides = overridesFor(authorizationHeader); + yield* plan(thread, overrides); + return ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy, overrides); + }); + const first = yield* keyFor("Bearer first-token"); + assert.strictEqual(yield* keyFor("Bearer first-token"), first); + assert.notStrictEqual(yield* keyFor("Bearer rotated-token"), first); + } + }), + ); +}); diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts new file mode 100644 index 0000000000000..ab040fdadf18e --- /dev/null +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -0,0 +1,305 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + ManagedPolicyDocument, + ProjectId, + ServerSettings, + ServerSettingsError, + ThreadId, +} from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import * as ServerConfig from "../config.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import { + CHECK_SESSION_TIMEOUT, + ClaudeMcpProfileError, + EVERY_MCP_SERVER, + type ClaudeMcpProfilePlan, + type LineageThread, + checkClaudeSession, + claudeMcpCallOutsideProfile, + claudeMcpProfileForThread, + claudeMcpProfilePlan, + claudeMcpServersOutsidePlan, + makeClaudeMcpProfiles, + planKeyFor, +} from "./claudeMcpProfile.ts"; + +const fromFile = Schema.decodeSync(ServerSettings); +const policyDocument = Schema.decodeUnknownSync(ManagedPolicyDocument); +const isRefusal = Schema.is(ClaudeMcpProfileError); +const T3 = ["t3-code"]; + +const thread = (id: string, parent: string | null = null): LineageThread => ({ + id: ThreadId.make(id), + projectId: ProjectId.make("project"), + lineage: { + parentThreadId: parent === null ? null : ThreadId.make(parent), + relationshipToParent: parent === null ? null : "subagent", + rootThreadId: ThreadId.make("root"), + }, +}); +const store = (threads: ReadonlyArray) => (threadId: ThreadId) => + Effect.succeed(threads.find((entry) => entry.id === threadId) ?? null); +const noReads = () => Effect.die("read a parent thread"); + +const outcome = (result: ClaudeMcpProfilePlan | ClaudeMcpProfileError) => + isRefusal(result) ? result.message : result.options; + +describe("claudeMcpProfilePlan", () => { + it("refuses a profile that limits T3's own tools, which nothing applies yet", () => { + const result = claudeMcpProfilePlan("lean", { servers: [], t3Tools: ["threads"] }, T3); + assert.include(String(outcome(result)), 'MCP profile "lean" limits T3\'s own tools'); + }); +}); + +describe("claudeMcpServersOutsidePlan", () => { + const statuses = [ + { name: "t3-code", status: "connected" as const }, + { name: "docs", status: "pending" as const }, + { name: "claude.ai Calendar", status: "needs-auth" as const }, + { name: "off", status: "disabled" as const }, + ]; + it.each([ + { servers: "all" as const, outside: [] }, + { servers: [], outside: ["docs", "claude.ai Calendar"] }, + { servers: ["docs"], outside: ["claude.ai Calendar"] }, + ])("names what $servers leaves out, at any status but disabled", ({ servers, outside }) => { + const plan = { name: "p", options: {}, servers }; + assert.deepStrictEqual(claudeMcpServersOutsidePlan(plan, T3, statuses), outside); + }); +}); + +describe("claudeMcpCallOutsideProfile", () => { + const call = (tool_name: string, extra: object = {}) => ({ tool_name, tool_input: {}, ...extra }); + it.each([ + { name: "a tool of a named server", call: call("mcp__docs__search"), outside: undefined }, + { name: "a tool of T3's own server", call: call("mcp__t3-code__x"), outside: undefined }, + { name: "a tool of another server", call: call("mcp__github__x"), outside: "github" }, + { + name: "a server Claude names, by its configured name", + call: call("mcp__claude_ai_Calendar__x", { mcp_server: { name: "claude.ai Calendar" } }), + outside: "claude.ai Calendar", + }, + { + name: "a named server whose name Claude rewrites in tool names", + call: call("mcp__claude_ai_Drive__x"), + outside: undefined, + }, + { + name: "a resource read from another server", + call: { tool_name: "ReadMcpResourceTool", tool_input: { server: "github", uri: "x" } }, + outside: "github", + }, + { + name: "a resource listing of every server", + call: { tool_name: "ListMcpResourcesTool", tool_input: {} }, + outside: EVERY_MCP_SERVER, + }, + { + name: "a resource listing of a named server", + call: { tool_name: "ListMcpResourcesTool", tool_input: { server: "docs" } }, + outside: undefined, + }, + { + name: "a skill another server serves, run through Skill", + call: { tool_name: "Skill", tool_input: { skill: "/mcp__github__triage" } }, + outside: "github", + }, + { + name: "a skill a named server serves, run through Skill", + call: { tool_name: "Skill", tool_input: { skill: "mcp__docs__triage", args: "x" } }, + outside: undefined, + }, + { + name: "a skill no MCP server serves", + call: { tool_name: "Skill", tool_input: { skill: "plugin:mcp__github__x" } }, + outside: undefined, + }, + { + name: "another server's prompt, run through the older SlashCommand", + call: { tool_name: "SlashCommand", tool_input: { command: "/mcp__github__triage 12" } }, + outside: "github", + }, + { name: "a tool that is not MCP", call: call("Bash"), outside: undefined }, + ])("$name", ({ call: input, outside }) => { + assert.strictEqual( + claudeMcpCallOutsideProfile(["docs", "claude.ai Drive"], T3, input), + outside, + ); + }); +}); + +describe("planKeyFor", () => { + it("gives overrides with no worked-out plan a key no other turn has, never all's", () => { + const first = planKeyFor({}); + assert.isDefined(first); + assert.notStrictEqual(planKeyFor({}), first); + }); +}); + +describe("makeClaudeMcpProfiles", () => { + const readFailure = new ServerSettingsError({ + settingsPath: "settings.json", + operation: "read-secret", + cause: new Error("secret store unreadable"), + }); + /** + * A fresh start (a server restart or a Claude adapter rebuild) that plans a thread once per + * entry: the settings, or a failed read (it reads provider secrets too). `file` is what + * settings.json holds: its text, `undefined` for no file, or "unreadable". + */ + const plansFor = ( + reads: ReadonlyArray | "fails">, + file: string | undefined | "unreadable" = undefined, + policy?: unknown, + ) => + Effect.gen(function* () { + const { settingsPath } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + if (file === "unreadable") yield* fs.makeDirectory(settingsPath); + else if (file !== undefined) yield* fs.writeFileString(settingsPath, file); + const service = yield* ServerSettingsService.ServerSettingsService; + let next = 0; + const getSettings = Effect.suspend(() => { + const read = reads[next++]; + return read === "fails" ? Effect.fail(readFailure) : Effect.succeed(fromFile(read ?? {})); + }); + const plan = yield* makeClaudeMcpProfiles.pipe( + Effect.provideService(ServerSettingsService.ServerSettingsService, { + ...service, + getSettings, + }), + ); + const outcomes: Array = []; + for (const _ of reads) { + outcomes.push( + yield* plan(thread("t"), {}).pipe( + Effect.match({ + onFailure: (refusal) => refusal.message, + onSuccess: (result) => result.name, + }), + ), + ); + } + return outcomes; + }).pipe( + Effect.provide( + Layer.mergeAll( + ServerSettingsService.ServerSettingsService.layerTest(), + ManagedPolicy.layerTest(policy === undefined ? undefined : policyDocument(policy)), + Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-mcp-profile-" })), + ).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ); + + it.effect("with no profile anywhere, a failed settings read gives all instead of refusing", () => + Effect.gen(function* () { + assert.deepStrictEqual(yield* plansFor(["fails", {}, "fails"]), ["all", "all", "all"]); + assert.deepStrictEqual(yield* plansFor(["fails"], "{}"), ["all"]); + }), + ); + + it.effect("after a restart, a failed secret read keeps the profile settings.json sets", () => + Effect.gen(function* () { + const file = JSON.stringify({ mcpProfile: "t3-only" }); + assert.deepStrictEqual(yield* plansFor(["fails", "fails"], file), ["t3-only", "t3-only"]); + const named = JSON.stringify({ + mcpProfile: "docs", + mcpProfiles: { docs: { servers: ["docs"], t3Tools: "all" } }, + }); + assert.deepStrictEqual(yield* plansFor(["fails"], named), ["docs"]); + }), + ); + + it.effect("a failed secret read follows a profile the managed policy locks", () => + Effect.gen(function* () { + const policy = { + schemaVersion: 1, + organization: "Example Corp", + settings: { mcpProfile: { value: "t3-only", locked: true } }, + }; + assert.deepStrictEqual(yield* plansFor(["fails"], "{}", policy), ["t3-only"]); + }), + ); + + it.effect("refuses when settings.json cannot be read either, even after a read with none", () => + Effect.gen(function* () { + const [first, second] = yield* plansFor([{}, "fails"], "unreadable"); + assert.strictEqual(first, "all"); + assert.include(second, "could not read this thread's MCP profile settings"); + }), + ); +}); + +describe("checkClaudeSession", () => { + it.effect("refuses and closes a session that does not list its servers in time", () => + Effect.gen(function* () { + let closed = 0; + const plan = { name: "t3-only", options: {}, servers: [] }; + const check = yield* checkClaudeSession( + plan, + {}, + )({ + mcpServerStatus: Effect.never, + close: Effect.sync(() => void closed++), + }).pipe(Effect.flip, Effect.forkChild); + yield* TestClock.adjust(CHECK_SESSION_TIMEOUT); + const refusal = yield* Fiber.join(check); + assert.include(refusal.message, "could not check which MCP servers Claude loaded"); + assert.strictEqual(closed, 1); + }), + ); +}); + +describe("claudeMcpProfileForThread", () => { + const forThread = ( + file: Record, + self: LineageThread, + findThread?: (threadId: ThreadId) => Effect.Effect, + ) => + claudeMcpProfileForThread(fromFile(file), self, T3, findThread).pipe( + Effect.match({ onFailure: (refusal) => refusal.message, onSuccess: (plan) => plan.servers }), + ); + + it.effect("with no profile set, a child gets all and no parent is read", () => + Effect.gen(function* () { + assert.strictEqual(yield* forThread({}, thread("child", "gone"), noReads), "all"); + }), + ); + + it.effect("an inheriting child is cut to its parent's pick, read from the store", () => + Effect.gen(function* () { + const file = { mcpThreadProfiles: { parent: "t3-only" } }; + const child = yield* forThread(file, thread("child", "parent"), store([thread("parent")])); + assert.deepStrictEqual(child, []); + }), + ); + + it.effect("a parent that cannot be read refuses the child, unless the child has a pick", () => + Effect.gen(function* () { + const orphan = yield* forThread( + { mcpThreadProfiles: { other: "t3-only" } }, + thread("c", "x"), + ); + assert.include(String(orphan), "parent thread cannot be read"); + const picked = yield* forThread({ mcpThreadProfiles: { c: "t3-only" } }, thread("c", "x")); + assert.deepStrictEqual(picked, []); + }), + ); + + it.effect("a looping lineage is refused, never widened to all", () => + Effect.gen(function* () { + const file = { mcpThreadProfiles: { other: "all" } }; + const looping = yield* forThread(file, thread("a", "b"), store([thread("b", "a")])); + assert.include(String(looping), "repeat a thread"); + }), + ); +}); diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts new file mode 100644 index 0000000000000..6609916851138 --- /dev/null +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -0,0 +1,422 @@ +/** + * Fork: a thread's MCP profile, applied to its Claude session. This applies the outside servers + * only; T3's own tools are filtered in a later PR. A profile that cannot be applied refuses the + * turn instead of starting it with every tool: the owner chose refusing over warning. + */ +import type { + HookCallback, + HookCallbackMatcher, + HookEvent, + McpServerStatus, + Settings as ClaudeSettings, +} from "@anthropic-ai/claude-agent-sdk"; +import { + MCP_PROFILE_ALL, + MCP_SUBAGENT_INHERIT, + type OrchestrationV2AppThread, + type ServerSettings, + type ThreadId, + isDelegatedAppThread, +} from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as ServerConfig from "../config.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import { + MCP_PROFILE_MAX_LINEAGE, + type McpProfileSet, + type McpProfileThread, + resolveMcpProfile, +} from "./mcpProfile.ts"; + +export class ClaudeMcpProfileError extends Schema.TaggedError()( + "ClaudeMcpProfileError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +const isRefusal = Schema.is(ClaudeMcpProfileError); + +/** + * The SDK options a profile adds, and the outside servers the session may then show. `hooks` holds + * the call-time guard; ClaudeAdapterV2 merges it into its own hooks. + */ +export interface ClaudeMcpProfilePlan { + readonly name: string; + readonly options: { + readonly strictMcpConfig?: true; + readonly managedSettings?: ClaudeSettings; + readonly hooks?: Partial>>; + }; + readonly servers: McpProfileSet["servers"]; +} + +export type LineageThread = Pick< + OrchestrationV2AppThread, + "id" | "projectId" | "lineage" | "delegatedFrom" +>; + +const ALL_PLAN: ClaudeMcpProfilePlan = { name: MCP_PROFILE_ALL, options: {}, servers: "all" }; +const FIX = `pick "${MCP_PROFILE_ALL}" for this thread, or fix the profile in Settings`; +/** What can make Claude load a server T3's options leave out, at start. */ +const START_LEAKS = + "A managed Claude policy on this machine or --mcp-config in the Claude launch arguments can add servers T3's list does not drop"; +const blank = (value: string | undefined) => value === undefined || value.trim() === ""; + +/** `t3-only` and an empty list ignore every server Claude would load itself; a list keeps those named. */ +export function claudeMcpProfilePlan( + name: string, + profile: McpProfileSet, + t3ServerNames: ReadonlyArray, +): ClaudeMcpProfilePlan | ClaudeMcpProfileError { + if (profile.t3Tools !== "all") { + return new ClaudeMcpProfileError({ + reason: `MCP profile "${name}" limits T3's own tools, which this version cannot apply yet, so this thread cannot start: set its t3Tools to "all", or ${FIX}.`, + }); + } + if (profile.servers === "all") return { ...ALL_PLAN, name }; + const servers = profile.servers; + const hooks = { PreToolUse: [{ hooks: [claudeMcpProfileGuard(name, servers, t3ServerNames)] }] }; + if (servers.length === 0) { + return { name, options: { strictMcpConfig: true, hooks }, servers }; + } + // T3's own servers are listed too, so the allowlist cannot drop them. + const allowed = [...new Set([...t3ServerNames, ...servers])]; + return { + name, + options: { + managedSettings: { allowedMcpServers: allowed.map((serverName) => ({ serverName })) }, + hooks, + }, + servers, + }; +} + +/** A server name as Claude writes it in a tool name (`mcp____`), per its CLI. */ +const toolNameServer = (name: string) => { + const normalized = name.replace(/[^a-zA-Z0-9_-]/g, "_"); + return name.startsWith("claude.ai ") + ? normalized.replace(/_+/g, "_").replace(/^_|_$/g, "") + : normalized; +}; + +/** Claude's own tools that reach an MCP server named in their input. */ +const MCP_RESOURCE_TOOLS: ReadonlySet = new Set([ + "ListMcpResourcesTool", + "ReadMcpResourceTool", +]); + +/** What `claudeMcpCallOutsideProfile` returns for a resource listing of every connected server. */ +export const EVERY_MCP_SERVER = "*"; + +/** + * Claude's tools that run a command by name, and the input holding it. Claude names an MCP + * server's prompt `mcp____`; Claude Code 2.1.326 refuses a plain MCP prompt in + * `Skill`, but runs a skill an MCP server serves, so a name of that form is checked too. + * `SlashCommand` is the older name of `Skill`, whose input holds the whole command line. + */ +const COMMAND_TOOLS: Readonly> = { Skill: "skill", SlashCommand: "command" }; + +const mcpToolServer = (allowed: ReadonlyArray, toolName: string): string | undefined => { + const kept = allowed.some((name) => toolName.startsWith(`mcp__${toolNameServer(name)}__`)); + return kept ? undefined : toolName.slice("mcp__".length).split("__")[0]; +}; + +/** + * The MCP server a tool call reaches that the profile leaves out, or `undefined`. Claude names the + * server it calls (`mcp_server`); an older one does not, so the tool name's prefix is matched. + */ +export function claudeMcpCallOutsideProfile( + servers: ReadonlyArray, + t3ServerNames: ReadonlyArray, + call: { + readonly tool_name: string; + readonly tool_input: unknown; + readonly mcp_server?: { readonly name: string } | undefined; + }, +): string | undefined { + const allowed = [...t3ServerNames, ...servers]; + if (call.mcp_server !== undefined) { + return allowed.includes(call.mcp_server.name) ? undefined : call.mcp_server.name; + } + if (call.tool_name.startsWith("mcp__")) return mcpToolServer(allowed, call.tool_name); + const input = (call.tool_input ?? {}) as Readonly>; + if (MCP_RESOURCE_TOOLS.has(call.tool_name)) { + const server = input.server; + // A listing with no server lists every connected server's, those left out too. + if (call.tool_name === "ListMcpResourcesTool" && (server === undefined || server === "")) { + return EVERY_MCP_SERVER; + } + return typeof server === "string" && !allowed.includes(server) ? server : undefined; + } + const commandKey = Object.hasOwn(COMMAND_TOOLS, call.tool_name) + ? COMMAND_TOOLS[call.tool_name] + : undefined; + const command = commandKey === undefined ? undefined : input[commandKey]; + if (typeof command === "string") { + const name = command.trim().replace(/^\//, "").split(/\s/)[0] ?? ""; + return name.startsWith("mcp__") ? mcpToolServer(allowed, name) : undefined; + } + return undefined; +} + +/** + * Refuses, at the moment of the call, a tool call to an MCP server the profile leaves out. The + * options keep such servers from loading; this covers what loads anyway (a managed policy that + * drops T3's allowlist, an agent file's servers, a server added mid-session). Hooks run in every + * permission mode and inside sub-agents. + */ +const claudeMcpProfileGuard = + ( + name: string, + servers: ReadonlyArray, + t3ServerNames: ReadonlyArray, + ): HookCallback => + async (input) => { + if (input.hook_event_name !== "PreToolUse") return {}; + const server = claudeMcpCallOutsideProfile(servers, t3ServerNames, input); + if (server === undefined) return {}; + return { + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: + server === EVERY_MCP_SERVER + ? `MCP profile "${name}" leaves out some MCP servers, so T3 refused listing every server's resources: name a server in "server", one the profile keeps.` + : `MCP profile "${name}" leaves out the MCP server "${server}", so T3 refused this call. Claude loaded it anyway: a managed Claude policy on this machine, --mcp-config in the Claude launch arguments, or an agent file's servers can add one. To use it, ${FIX} so the profile names it.`, + }, + }; + }; + +/** + * Servers the started session shows that the plan leaves out. An IT-managed policy on the machine + * drops T3's allowlist, and an older Claude may not know strict mode, so the session is checked. + */ +export function claudeMcpServersOutsidePlan( + plan: ClaudeMcpProfilePlan, + t3ServerNames: ReadonlyArray, + statuses: ReadonlyArray>, +): ReadonlyArray { + const kept = plan.servers; + if (kept === "all") return []; + return statuses + .filter( + (server) => + server.status !== "disabled" && + !t3ServerNames.includes(server.name) && + !kept.includes(server.name), + ) + .map((server) => server.name); +} + +/** With no thread picks, project values or sub-agent rule, every thread in a lineage gets `mcpProfile`. */ +const needsLineage = (settings: ServerSettings) => + Object.keys(settings.mcpThreadProfiles).length > 0 || + !( + blank(settings.mcpSubagentProfile) || + settings.mcpSubagentProfile.trim() === MCP_SUBAGENT_INHERIT + ) || + Object.values(settings.projectSettingsOverrides).some( + (project) => !blank(project.mcpProfile) || !blank(project.mcpSubagentProfile), + ); + +const profileThread = (settings: ServerSettings, thread: LineageThread): McpProfileThread => { + const project = settings.projectSettingsOverrides[thread.projectId]; + return { + threadId: thread.id, + delegated: isDelegatedAppThread(thread), + project: { mcpProfile: project?.mcpProfile, mcpSubagentProfile: project?.mcpSubagentProfile }, + }; +}; + +/** The thread's profile as a Claude plan. `findThread` is `undefined` when no store is wired. */ +export const claudeMcpProfileForThread = Effect.fn("ClaudeMcpProfile.forThread")(function* ( + settings: ServerSettings, + thread: LineageThread, + t3ServerNames: ReadonlyArray, + findThread: ((threadId: ThreadId) => Effect.Effect) | undefined, +) { + const lineage: Array = [thread]; + let parentMissing = false; + let parentId = needsLineage(settings) ? thread.lineage.parentThreadId : null; + // One past the limit, or a repeat, is kept so the resolver refuses it. + while (parentId !== null && lineage.length <= MCP_PROFILE_MAX_LINEAGE) { + const repeated = lineage.find((entry) => entry.id === parentId); + const parent = repeated ?? (findThread === undefined ? null : yield* findThread(parentId)); + parentMissing = parent === null; + if (parent === null) break; + lineage.push(parent); + parentId = repeated === undefined ? parent.lineage.parentThreadId : null; + } + const resolved = resolveMcpProfile( + settings, + lineage.map((entry) => profileThread(settings, entry)), + ); + if (resolved._tag === "CannotApply") { + return yield* new ClaudeMcpProfileError({ reason: resolved.message }); + } + // A local parent that is gone cannot cut the profile down, so the thread refuses. A task delegated + // from another machine has no parent here (`parentThreadId` is null): it never reaches this check + // and gets this machine's profile for its role, not its remote parent's (docs/fork/README.md). + if (parentMissing && resolved.source !== "thread-pick") { + return yield* new ClaudeMcpProfileError({ + reason: `This thread's parent thread cannot be read, so its MCP profile cannot be worked out: ${FIX}.`, + }); + } + const plan = claudeMcpProfilePlan(resolved.name, resolved.profile, t3ServerNames); + return isRefusal(plan) ? yield* plan : plan; +}); + +const PLAN_KEYS = new WeakMap(); +let unplanned = 0; + +/** + * The plan's part of the live-query key (`undefined` for `all`), found by the turn's MCP overrides, + * the only input of upstream's key line. Overrides with no plan get a key no other turn has, so + * such a turn opens a new process instead of reusing one a wider profile started. + */ +export const planKeyFor = (mcpOverrides: object): string | undefined => + (PLAN_KEYS.get(mcpOverrides) ?? { key: `unplanned\u0000${++unplanned}` }).key; + +/** The plan's key part, or `undefined` for `all`. NUL keeps the joined names apart. */ +const planKey = (plan: ClaudeMcpProfilePlan): string | undefined => + plan.servers === "all" ? undefined : ["mcp", ...plan.servers].join("\u0000"); + +/** + * The settings as a load decodes them from settings.json, without reading provider secrets: the + * MCP profile keys hold none. `undefined` when this server has no settings file to read here. + * As the load: no file means the policy's defaults, a file that does not decode loads as them too + * (upstream's rule), and the policy's locks are laid over either. A file that cannot be read fails. + */ +const settingsFileReader = Effect.gen(function* () { + const config = yield* Effect.serviceOption(ServerConfig.ServerConfig); + const fileSystem = yield* Effect.serviceOption(FileSystem.FileSystem); + const policy = yield* Effect.serviceOption(ManagedPolicy.ManagedPolicy); + if (Option.isNone(config) || Option.isNone(fileSystem) || Option.isNone(policy)) { + return undefined; + } + const { settingsPath } = config.value; + const fs = fileSystem.value; + const managed = policy.value.settings; + return Effect.gen(function* () { + if (!(yield* fs.exists(settingsPath))) return managed.applyLocks(managed.defaults); + const raw = yield* fs.readFileString(settingsPath); + const decoded = ServerSettingsService.decodeSettingsFileText(raw, managed.withDefaults); + const readable = + Exit.isSuccess(decoded) && !ServerSettingsService.settingsFileLegacyKeysUnreadable(raw); + return managed.applyLocks(readable ? decoded.value : managed.defaults); + }); +}); + +type McpOverrides = { readonly mcpServers?: Readonly> | undefined }; + +/** + * The thread's plan, or a refusal; without the settings service (tests), `all`. A settings read + * that fails (it reads provider secrets too) falls back to settings.json alone, which holds every + * MCP profile key; if that cannot be read either, the turn is refused, never widened to `all`. + */ +export const makeClaudeMcpProfiles = Effect.gen(function* () { + const settingsService = yield* Effect.serviceOption(ServerSettingsService.ServerSettingsService); + if (Option.isNone(settingsService)) { + yield* Effect.logWarning( + "MCP profiles: no settings service here, so every Claude thread gets the all profile", + ); + } + const sql = yield* Effect.serviceOption(SqlClient.SqlClient); + const store = Option.isSome(sql) + ? yield* ProjectionStore.ProjectionStoreV2.pipe( + Effect.provide(ProjectionStore.layer), + Effect.provideService(SqlClient.SqlClient, sql.value), + ) + : undefined; + // A parent that cannot be read refuses the thread, as a missing one does. + const findThread = + store && ((id: ThreadId) => store.findThread(id).pipe(Effect.orElseSucceed(() => null))); + const readSettingsFile = yield* settingsFileReader; + const readSettings = Effect.fn("ClaudeMcpProfile.readSettings")(function* ( + service: ServerSettingsService.ServerSettingsService["Service"], + ) { + const read = yield* service.getSettings.pipe(Effect.result); + if (read._tag === "Success") return read.success; + const file = + readSettingsFile === undefined + ? undefined + : yield* readSettingsFile.pipe(Effect.option, Effect.map(Option.getOrUndefined)); + if (file === undefined) { + yield* Effect.logWarning( + "MCP profiles: neither the settings nor settings.json could be read", + { + cause: read.failure, + }, + ); + return yield* new ClaudeMcpProfileError({ + reason: `T3 could not read this thread's MCP profile settings, so this thread cannot start: retry, or check that T3's settings.json can be read.`, + }); + } + yield* Effect.logWarning( + "MCP profiles: settings could not be read in full, so this Claude thread's profile comes from settings.json alone", + { cause: read.failure }, + ); + return file; + }); + const planFor = Effect.fn("ClaudeMcpProfile.planFor")(function* ( + thread: LineageThread, + overrides: McpOverrides, + ) { + if (Option.isNone(settingsService)) return ALL_PLAN; + const settings = yield* readSettings(settingsService.value); + const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); + return yield* claudeMcpProfileForThread(settings, thread, t3ServerNames, findThread); + }); + + return Effect.fn("ClaudeMcpProfile.plan")(function* ( + thread: LineageThread, + overrides: McpOverrides, + ) { + const plan = yield* planFor(thread, overrides); + PLAN_KEYS.set(overrides, { key: planKey(plan) }); + return plan; + }); +}); + +/** How long the started session may take to list its servers; Claude's own boot is bounded alike. */ +export const CHECK_SESSION_TIMEOUT = Duration.minutes(5); + +/** + * Refuses and closes a started session that shows a server the plan leaves out, or that does not + * list its servers in time: with a profile set, an unchecked session never starts the turn. + */ +export const checkClaudeSession = + (plan: ClaudeMcpProfilePlan, overrides: McpOverrides) => + (session: { + readonly mcpServerStatus: Effect.Effect, E>; + readonly close: Effect.Effect; + }): Effect.Effect => + Effect.gen(function* () { + if (plan.servers === "all") return; + const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); + const outside = yield* session.mcpServerStatus.pipe( + Effect.map((statuses) => claudeMcpServersOutsidePlan(plan, t3ServerNames, statuses)), + Effect.timeout(CHECK_SESSION_TIMEOUT), + Effect.orElseSucceed(() => undefined), + ); + if (outside?.length === 0) return; + yield* session.close.pipe(Effect.ignore); + return yield* new ClaudeMcpProfileError({ + reason: + outside === undefined + ? `T3 could not check which MCP servers Claude loaded for profile "${plan.name}", so this thread cannot start: retry, or ${FIX}.` + : `MCP profile "${plan.name}" could not be applied: Claude still loaded ${outside.join(", ")}, so this thread cannot start. ${START_LEAKS}; check them, or ${FIX}.`, + }); + }).pipe(Effect.withSpan("ClaudeMcpProfile.checkSession")); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1941620cd8b01..13ead43e6a33c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -184,6 +184,7 @@ import * as ServerConfig from "../../config.ts"; import * as PortScanner from "../../preview/PortScanner.ts"; import * as ProcessRunner from "../../processRunner.ts"; import * as ServerSettings from "../../serverSettings.ts"; +import * as ClaudeMcpProfile from "../../fork/claudeMcpProfile.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; @@ -2179,6 +2180,7 @@ export function makeClaudeQueryOptions(input: { readonly sdkSettings?: string | ClaudeSdkSettings; readonly environment?: NodeJS.ProcessEnv; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + readonly mcpProfileOptions?: ClaudeMcpProfile.ClaudeMcpProfilePlan["options"]; /** The thread's T3 MCP session holds the `device` capability. */ readonly deviceToolsAvailable?: boolean; readonly tools?: ClaudeAgentSdkQueryTools; @@ -2326,6 +2328,7 @@ export function makeClaudeQueryOptions(input: { ? { pathToClaudeCodeExecutable: input.settings.binaryPath } : {}), ...(input.environment === undefined ? {} : { env: input.environment }), + ...input.mcpProfileOptions, ...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }), systemPrompt: { type: "preset" as const, @@ -2346,6 +2349,7 @@ export function makeClaudeQueryOptions(input: { ...(deviceInstructions || input.onStop !== undefined ? { hooks: { + ...input.mcpProfileOptions?.hooks, ...(deviceInstructions ? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } : {}), @@ -3556,6 +3560,7 @@ export function claudeEffectiveQueryPolicyKey( : { allowedTools: mcpOverrides.allowedTools }), }), mcpServers: mcpOverrides.mcpServers, + mcpProfile: ClaudeMcpProfile.planKeyFor(mcpOverrides), }); } @@ -5588,6 +5593,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService); + const mcpProfiles = yield* ClaudeMcpProfile.makeClaudeMcpProfiles; const { attachmentsDir, fileSystem, path, random, idAllocator, queryRunner } = adapterOptions; const loadModelCatalog = ( adapterOptions.modelCatalog ?? Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG) @@ -12776,6 +12782,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? {} : { allowedTools: queryPolicy.allowedTools }), }); + // Fork: a profile that cannot apply refuses here, before the live process is replaced. + const mcpProfile = yield* mcpProfiles(turnInput.appThread, mcpOverrides); + const checkMcpProfile = ClaudeMcpProfile.checkClaudeSession(mcpProfile, mcpOverrides); const queryPolicyKey = claudeEffectiveQueryPolicyKey(queryPolicy, mcpOverrides); const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread); const existing = yield* Ref.get(queryContext); @@ -12933,6 +12942,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? {} : { mcpServers: mcpOverrides.mcpServers }), deviceToolsAvailable: mcpSession?.capabilities?.has("device") === true, + mcpProfileOptions: mcpProfile.options, permissionMode: queryPolicy.permissionMode, ...(queryPolicy.allowDangerouslySkipPermissions === undefined ? {} @@ -12962,6 +12972,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? openQueryRuntime : adapterOptions.installationGate.execute(adapterOptions.instanceId, openQueryRuntime) ).pipe( + Effect.tap(checkMcpProfile), Effect.onError(() => closedExistingNativeThreadId === nativeThreadId ? Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index bb5701d337d0d..0f864c25299b1 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -111,6 +111,7 @@ const PROMPT_REFUSAL_TAGS = [ "ClaudeAppendSystemPromptMissingValueError", "ClaudeSettingsLaunchArgError", "ClaudeMcpRegistrationTimeoutError", + "ClaudeMcpProfileError", ] as const; const refusedBeforePrompt = (error: unknown): boolean => diff --git a/docs/fork/README.md b/docs/fork/README.md index f13411580574b..4abaf70f93d9e 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -261,8 +261,35 @@ Named MCP profiles. A profile says which outside MCP servers (`servers`) and whi own tools (`t3Tools`) a thread gets; each is `"all"` or a list. Two profiles are built in: `all` (everything, today's behaviour) and `t3-only` (no outside servers, every T3 tool); a profile cannot take their names, and one written in by hand makes that built-in refuse threads until it is removed -(a save may send `null` under a built-in name to remove it) or renamed. Nothing applies a profile -yet: the provider adapters and the T3 tool filter come in later pull requests. +(a save may send `null` under a built-in name to remove it) or renamed. + +A Claude thread applies the profile's `servers`: `[]` (and `t3-only`) starts Claude without any MCP +server of its own (its config files, plugins and claude.ai connectors), and a list keeps only the +servers it names, written as Claude lists them (`claude.ai Calendar`). T3's own tools stay. A Claude +thread whose profile cannot be applied does not start its turn and says why: a missing or broken +profile, a parent thread that cannot be read, a `settings.json` T3 cannot read (when only a +provider secret cannot be read, the profile comes from `settings.json` alone and the server log +says so; with no profile set there, the thread gets `all` as before), a profile whose +`t3Tools` is not `"all"` (the T3 tool filter comes in a later pull request), or a session that +still shows a server the profile leaves out, or does not list its servers within 5 minutes. A +managed Claude policy on the machine or `--mcp-config` in the Claude launch arguments can make +Claude load a server T3's list leaves out. Other providers do not apply profiles yet. + +Each tool call is checked too: a call to an MCP server the profile leaves out (also one an agent +file declares, or one added while the session runs) is refused at the moment of the call: Claude +gets the reason as the call's result, and the turn goes on. That covers its tools, its resources +(a resource listing that names no server is refused, as it would list every server's), and a +`Skill` call naming `mcp____…`, the form of a skill an MCP server serves. Where Claude does +not name the server it calls, the tool name's prefix is matched, so a server named like +`docs__x`, or `my_docs` under a profile that names `my.docs`, passes. With the `all` profile +nothing is checked. A +profile change applies from the thread's next turn: a running turn, and a message sent into it, +keep the session it started with. + +A task delegated to another machine has no parent thread there, so it gets that machine's profile +for its role (`mcpSubagentProfile`, else `mcpProfile`), not the delegating thread's: server names on +two machines need not mean the same servers. Carrying the parent's profile along is +[#532](https://github.com/scuttletoby/t3code/issues/532). ```json { "mcpProfiles": { "lean": { "servers": [], "t3Tools": ["orchestration", "threads"] } } } @@ -279,7 +306,8 @@ one (for example after a hand edit) is refused instead of getting `all`. ### `server.mcpSubagentProfile` The profile a delegated child gets when nobody picked one for it. `inherit` (the default) gives it -its parent's profile. A child never gets more than its parent. +its parent's profile. A child on the same machine never gets more than its parent; a task +delegated from another machine gets this machine's profile (see `server.mcpProfiles`). ### `server.mcpThreadProfiles` diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index c416596dd45d2..eba37d37acca0 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -121,6 +121,7 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeAppendSystemPromptMissingValueError": case "ClaudeSettingsLaunchArgError": case "ClaudeMcpRegistrationTimeoutError": + case "ClaudeMcpProfileError": case "ClaudeCodeRootRefusalError": case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError":