From b8373685b5717eb0d927460576fb3c383e2e05a9 Mon Sep 17 00:00:00 2001 From: scuttletoby Date: Thu, 19 Nov 2026 12:30:17 +0100 Subject: [PATCH 1/4] feat(server): Claude threads apply their MCP profile's outside servers MCP profiles part 2. A Claude thread's profile now reaches its session: t3-only and an empty server list open Claude in strict MCP mode, and a named list passes an allowlist of those servers (plus T3's own). A profile that cannot be applied refuses the turn with a message that says why and how to fix it, and a started session that still shows a server the profile leaves out is closed and refused. With no profile set, nothing changes. Co-Authored-By: Claude Opus 5.5 --- .github/fork-seams.json | 23 ++ FORK_CHANGES.md | 2 +- .../src/fork/claudeMcpProfile.adapter.test.ts | 179 ++++++++++++++ apps/server/src/fork/claudeMcpProfile.test.ts | 102 ++++++++ apps/server/src/fork/claudeMcpProfile.ts | 228 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 10 + .../ProviderTurnStartService.ts | 1 + docs/fork/README.md | 12 +- packages/provider-core/src/server/failure.ts | 1 + 9 files changed, 555 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/fork/claudeMcpProfile.adapter.test.ts create mode 100644 apps/server/src/fork/claudeMcpProfile.test.ts create mode 100644 apps/server/src/fork/claudeMcpProfile.ts diff --git a/.github/fork-seams.json b/.github/fork-seams.json index 45ff09bec6965..d344da47fedd6 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -131,6 +131,29 @@ "// Fork: the tile shows while the image still compresses, and that Enter sends nothing.", "await expect.element(page.getByRole(\"button\", { name: \"Preview shot.png\" })).toBeEnabled();" ] + }, + "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, and refuses the turn when it cannot be applied. Additions only; tested in apps/server/src/fork/claudeMcpProfile.adapter.test.ts.", + "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)," + ] + }, + "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": ["\"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": ["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 c81c9924867f0..489a8a6ce73a2 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. | 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) | | 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..00d3f9c67727a --- /dev/null +++ b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts @@ -0,0 +1,179 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import { + ClaudeSettings, + 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 * 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 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"; + +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", +}); + +/** Starts one Claude turn with these server settings; records the open and the session's close. */ +const startTurn = ( + settings: Partial>, + statuses: ReadonlyArray<{ readonly name: string; readonly status: "connected" }> | "unexpected", +) => + Effect.gen(function* () { + const opened: 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-mcp-profile"), + open: (input) => + Effect.sync(() => { + opened.push(input.options); + return { + messages: Stream.never, + 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 started = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId: MODEL.instanceId, + runtimePolicy: POLICY, + now: yield* DateTime.now, + modelSelection: MODEL, + }), + ) + .pipe(Effect.exit); + const refusal = + started._tag === "Failure" + ? makeProviderFailure({ cause: started.cause, class: "provider_error" }).message + : undefined; + return { opened, closed, refusal }; + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ServerSettingsService.layerTest(settings), + ), + ), + ); + +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* startTurn({}, "unexpected"); + assert.isUndefined(refusal); + assert.lengthOf(opened, 1); + assert.notProperty(opened[0], "strictMcpConfig"); + assert.notProperty(opened[0], "managedSettings"); + }), + ); + + it.effect("t3-only opens Claude in strict MCP mode", () => + Effect.gen(function* () { + const { opened, refusal } = yield* startTurn({ 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* startTurn( + { 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 the turn, without opening Claude, when the profile is missing", () => + Effect.gen(function* () { + const { opened, refusal } = yield* startTurn({ 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* startTurn({ mcpProfile: "t3-only" }, [ + { name: "claude.ai Calendar", status: "connected" }, + ]); + assert.equal(closed, 1); + assert.include(refusal, "Claude still loaded claude.ai Calendar"); + }), + ); +}); diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts new file mode 100644 index 0000000000000..22020d9f8d515 --- /dev/null +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -0,0 +1,102 @@ +import { ProjectId, ServerSettings, ThreadId } from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { + ClaudeMcpProfileError, + type ClaudeMcpProfilePlan, + type LineageThread, + claudeMcpProfileForThread, + claudeMcpProfilePlan, + claudeMcpServersOutsidePlan, +} from "./claudeMcpProfile.ts"; + +const fromFile = Schema.decodeSync(ServerSettings); +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("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.options }), + ); + + it.effect("with no profile set, a child gets all and no parent is read", () => + Effect.gen(function* () { + assert.deepStrictEqual(yield* forThread({}, thread("child", "gone"), noReads), {}); + }), + ); + + 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, { strictMcpConfig: true }); + }), + ); + + 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, { strictMcpConfig: true }); + }), + ); + + 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..daf7e05bf34d1 --- /dev/null +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -0,0 +1,228 @@ +/** + * 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 { 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 Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.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. */ +export interface ClaudeMcpProfilePlan { + readonly name: string; + readonly options: { + readonly strictMcpConfig?: true; + readonly managedSettings?: ClaudeSettings; + }; + 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`; +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 }; + if (profile.servers.length === 0) { + return { name, options: { strictMcpConfig: true }, servers: [] }; + } + // T3's own servers are listed too, so the allowlist cannot drop them. + const allowed = [...new Set([...t3ServerNames, ...profile.servers])]; + return { + name, + options: { + managedSettings: { allowedMcpServers: allowed.map((serverName) => ({ serverName })) }, + }, + servers: profile.servers, + }; +} + +/** + * 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 parent that is gone (or on another machine) cannot cut the profile down. + 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(); + +/** + * The plan's part of the live-query key, by the turn's MCP overrides object, so a profile change + * opens a new Claude process. `undefined` for `all`, which leaves the key as it was. + */ +export const planKeyFor = (mcpOverrides: object): string | undefined => PLAN_KEYS.get(mcpOverrides); + +type McpOverrides = { readonly mcpServers?: Readonly> | undefined }; + +/** The thread's plan, or a refusal. Without the settings service (tests), every thread gets `all`. */ +export const makeClaudeMcpProfiles = Effect.gen(function* () { + const settingsService = yield* Effect.serviceOption(ServerSettingsService.ServerSettingsService); + 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))); + return Effect.fn("ClaudeMcpProfile.plan")(function* ( + thread: LineageThread, + overrides: McpOverrides, + ) { + if (Option.isNone(settingsService)) return ALL_PLAN; + const settings = yield* settingsService.value.getSettings.pipe( + Effect.mapError( + () => + new ClaudeMcpProfileError({ + reason: `T3 could not read this thread's MCP profile settings, so this thread cannot start: retry, or ${FIX}.`, + }), + ), + ); + const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); + const plan = yield* claudeMcpProfileForThread(settings, thread, t3ServerNames, findThread); + // NUL keeps the joined names apart. + if (plan.servers !== "all") PLAN_KEYS.set(overrides, ["mcp", ...plan.servers].join("\u0000")); + return plan; + }); +}); + +/** Refuses and closes a started session that shows a server the plan leaves out. */ +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.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. A managed Claude policy on this machine can override T3's server list; check it, 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..da4910ae2da3c 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, @@ -3556,6 +3559,7 @@ export function claudeEffectiveQueryPolicyKey( : { allowedTools: mcpOverrides.allowedTools }), }), mcpServers: mcpOverrides.mcpServers, + mcpProfile: ClaudeMcpProfile.planKeyFor(mcpOverrides), }); } @@ -5588,6 +5592,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 +12781,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 +12941,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 +12971,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 4084019e26a9d..01fa434359442 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -253,8 +253,16 @@ 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 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 +(a managed Claude policy on the machine can override T3's list). Other providers do not apply +profiles yet. ```json { "mcpProfiles": { "lean": { "servers": [], "t3Tools": ["orchestration", "threads"] } } } 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": From 5790ff3c75758a1e82bc4cb8a5b7f1361878c3ec Mon Sep 17 00:00:00 2001 From: scuttletoby Date: Thu, 19 Nov 2026 12:32:56 +0100 Subject: [PATCH 2/4] docs(fork): link the MCP profile row to #528 Co-Authored-By: Claude Opus 5.5 --- FORK_CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index 489a8a6ce73a2..f5c64255cddcf 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. | 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: 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) | +| 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) | From 421630934302af3165b539226d963e40dc7e2095 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:17:09 +0100 Subject: [PATCH 3/4] fix(server): MCP profiles refuse outside servers at call time Fix round for the two reviews of PR 528: - Call-time guard: a profile other than all adds a PreToolUse hook that refuses a tool call (or an MCP resource read) to a server outside the profile, in every permission mode and inside sub-agents. Covers a managed policy that drops T3's allowlist, agent-file servers and servers added mid-session. The adapter merges it into its own hooks (one seam line, announced in PR 533). - No-profile path: a failed settings read (it reads provider secrets too) refuses only when the settings last read had a profile set; otherwise the thread gets all, with a warning, as upstream's own reads fall back. - Reuse key: overrides with no worked-out plan get a key no other turn has, so a reordered or rebuilt key line opens a new process instead of reusing a wider one; a two-turn test locks reuse and replacement. - The start-time server check times out after 5 minutes and then refuses. - The leaked-server refusal names --mcp-config in the Claude launch arguments; a missing settings service is logged. - A task delegated from another machine keeps this machine's profile for its role: comment and docs say so; carrying the parent's profile is #532. Co-Authored-By: Claude Opus 5.5 --- .github/fork-seams.json | 5 +- .../src/fork/claudeMcpProfile.adapter.test.ts | 162 +++++++++++++--- apps/server/src/fork/claudeMcpProfile.test.ts | 126 +++++++++++- apps/server/src/fork/claudeMcpProfile.ts | 183 +++++++++++++++--- .../Adapters/ClaudeAdapterV2.ts | 1 + docs/fork/README.md | 24 ++- 6 files changed, 436 insertions(+), 65 deletions(-) diff --git a/.github/fork-seams.json b/.github/fork-seams.json index ac6b7425f3b73..54598a1fb648c 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -141,7 +141,7 @@ ] }, "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, and refuses the turn when it cannot be applied. Additions only; tested in apps/server/src/fork/claudeMcpProfile.adapter.test.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": [ "import * as ClaudeMcpProfile from \"../../fork/claudeMcpProfile.ts\";", "readonly mcpProfileOptions?: ClaudeMcpProfile.ClaudeMcpProfilePlan[\"options\"];", @@ -152,7 +152,8 @@ "const mcpProfile = yield* mcpProfiles(turnInput.appThread, mcpOverrides);", "const checkMcpProfile = ClaudeMcpProfile.checkClaudeSession(mcpProfile, mcpOverrides);", "mcpProfileOptions: mcpProfile.options,", - "Effect.tap(checkMcpProfile)," + "Effect.tap(checkMcpProfile),", + "...input.mcpProfileOptions?.hooks," ] }, "apps/server/src/orchestration-v2/ProviderTurnStartService.ts": { diff --git a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts index 00d3f9c67727a..41da3cdfbd29a 100644 --- a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts @@ -1,5 +1,6 @@ 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, @@ -18,6 +19,7 @@ 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"; @@ -36,13 +38,21 @@ const POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ cwd: "/workspace", }); -/** Starts one Claude turn with these server settings; records the open and the session's close. */ -const startTurn = ( - settings: Partial>, +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, @@ -54,12 +64,14 @@ const startTurn = ( random: yield* SecureRandom.SecureRandom, idAllocator: yield* IdAllocator.IdAllocatorV2, queryRunner: { - allocateSessionId: Effect.succeed("native-thread-mcp-profile"), + allocateSessionId: Effect.succeed(NATIVE_THREAD), open: (input) => - Effect.sync(() => { + Effect.gen(function* () { + const messages = yield* Queue.unbounded(); + processes.push(messages); opened.push(input.options); return { - messages: Stream.never, + messages: Stream.fromQueue(messages), offer: () => Effect.void, setModel: () => Effect.void, applyFlagSettings: () => Effect.void, @@ -96,24 +108,41 @@ const startTurn = ( modelSelection: MODEL, runtimePolicy: POLICY, }); - const started = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId: MODEL.instanceId, - runtimePolicy: POLICY, - now: yield* DateTime.now, - modelSelection: MODEL, - }), - ) - .pipe(Effect.exit); - const refusal = - started._tag === "Failure" - ? makeProviderFailure({ cause: started.cause, class: "provider_error" }).message - : undefined; + 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, @@ -125,20 +154,69 @@ const startTurn = ( ), ); +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* startTurn({}, "unexpected"); + 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* startTurn({ mcpProfile: "t3-only" }, []); + const { opened, refusal } = yield* runTurns({ mcpProfile: "t3-only" }, []); assert.isUndefined(refusal); assert.isTrue(opened[0]?.strictMcpConfig); }), @@ -146,7 +224,7 @@ describe("ClaudeAdapterV2 MCP profile", () => { it.effect("a list opens Claude with only those servers allowed", () => Effect.gen(function* () { - const { opened, refusal } = yield* startTurn( + const { opened, refusal } = yield* runTurns( { mcpProfile: "docs", mcpProfiles: { docs: { servers: ["docs"], t3Tools: "all" } } }, [{ name: "docs", status: "connected" }], ); @@ -157,9 +235,39 @@ describe("ClaudeAdapterV2 MCP profile", () => { }), ); + 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* startTurn({ mcpProfile: "lean" }, []); + 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'); }), @@ -169,7 +277,7 @@ describe("ClaudeAdapterV2 MCP profile", () => { "refuses the turn and closes Claude when it still loads a server the profile leaves out", () => Effect.gen(function* () { - const { closed, refusal } = yield* startTurn({ mcpProfile: "t3-only" }, [ + const { closed, refusal } = yield* runTurns({ mcpProfile: "t3-only" }, [ { name: "claude.ai Calendar", status: "connected" }, ]); assert.equal(closed, 1); diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts index 22020d9f8d515..29e2cbebf8288 100644 --- a/apps/server/src/fork/claudeMcpProfile.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -1,15 +1,23 @@ -import { ProjectId, ServerSettings, ThreadId } from "@t3tools/contracts"; +import { 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 Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; +import * as ServerSettingsService from "../serverSettings.ts"; import { + CHECK_SESSION_TIMEOUT, ClaudeMcpProfileError, type ClaudeMcpProfilePlan, type LineageThread, + checkClaudeSession, + claudeMcpCallOutsideProfile, claudeMcpProfileForThread, claudeMcpProfilePlan, claudeMcpServersOutsidePlan, + makeClaudeMcpProfiles, + planKeyFor, } from "./claudeMcpProfile.ts"; const fromFile = Schema.decodeSync(ServerSettings); @@ -56,6 +64,114 @@ describe("claudeMcpServersOutsidePlan", () => { }); }); +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 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"), + }); + /** Plans a thread once per entry: a settings file, or a failed read (it reads secrets too). */ + const plansFor = (reads: ReadonlyArray | "fails">) => + Effect.gen(function* () { + 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(ServerSettingsService.ServerSettingsService.layerTest())); + + it.effect("with no profile set, a failed settings read gives all instead of refusing", () => + Effect.gen(function* () { + assert.deepStrictEqual(yield* plansFor(["fails", {}, "fails"]), ["all", "all", "all"]); + }), + ); + + it.effect("with a profile set when last read, a failed settings read refuses", () => + Effect.gen(function* () { + const [first, second] = yield* plansFor([{ mcpProfile: "t3-only" }, "fails"]); + assert.strictEqual(first, "t3-only"); + 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, @@ -63,12 +179,12 @@ describe("claudeMcpProfileForThread", () => { findThread?: (threadId: ThreadId) => Effect.Effect, ) => claudeMcpProfileForThread(fromFile(file), self, T3, findThread).pipe( - Effect.match({ onFailure: (refusal) => refusal.message, onSuccess: (plan) => plan.options }), + 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.deepStrictEqual(yield* forThread({}, thread("child", "gone"), noReads), {}); + assert.strictEqual(yield* forThread({}, thread("child", "gone"), noReads), "all"); }), ); @@ -76,7 +192,7 @@ describe("claudeMcpProfileForThread", () => { Effect.gen(function* () { const file = { mcpThreadProfiles: { parent: "t3-only" } }; const child = yield* forThread(file, thread("child", "parent"), store([thread("parent")])); - assert.deepStrictEqual(child, { strictMcpConfig: true }); + assert.deepStrictEqual(child, []); }), ); @@ -88,7 +204,7 @@ describe("claudeMcpProfileForThread", () => { ); assert.include(String(orphan), "parent thread cannot be read"); const picked = yield* forThread({ mcpThreadProfiles: { c: "t3-only" } }, thread("c", "x")); - assert.deepStrictEqual(picked, { strictMcpConfig: true }); + assert.deepStrictEqual(picked, []); }), ); diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index daf7e05bf34d1..b689149b99ee6 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -3,7 +3,13 @@ * 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 { McpServerStatus, Settings as ClaudeSettings } from "@anthropic-ai/claude-agent-sdk"; +import type { + HookCallback, + HookCallbackMatcher, + HookEvent, + McpServerStatus, + Settings as ClaudeSettings, +} from "@anthropic-ai/claude-agent-sdk"; import { MCP_PROFILE_ALL, MCP_SUBAGENT_INHERIT, @@ -12,6 +18,7 @@ import { type ThreadId, isDelegatedAppThread, } from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -37,12 +44,16 @@ export class ClaudeMcpProfileError extends Schema.TaggedError>>; }; readonly servers: McpProfileSet["servers"]; } @@ -54,6 +65,9 @@ export type LineageThread = Pick< 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. */ @@ -68,20 +82,92 @@ export function claudeMcpProfilePlan( }); } if (profile.servers === "all") return { ...ALL_PLAN, name }; - if (profile.servers.length === 0) { - return { name, options: { strictMcpConfig: true }, servers: [] }; + 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, ...profile.servers])]; + const allowed = [...new Set([...t3ServerNames, ...servers])]; return { name, options: { managedSettings: { allowedMcpServers: allowed.map((serverName) => ({ serverName })) }, + hooks, }, - servers: profile.servers, + 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", +]); + +/** + * 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__")) { + const kept = allowed.some((name) => + call.tool_name.startsWith(`mcp__${toolNameServer(name)}__`), + ); + return kept ? undefined : call.tool_name.slice("mcp__".length).split("__")[0]; + } + if (MCP_RESOURCE_TOOLS.has(call.tool_name)) { + const server = (call.tool_input as { readonly server?: unknown } | null)?.server; + return typeof server === "string" && !allowed.includes(server) ? server : 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: `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. @@ -149,7 +235,9 @@ export const claudeMcpProfileForThread = Effect.fn("ClaudeMcpProfile.forThread") if (resolved._tag === "CannotApply") { return yield* new ClaudeMcpProfileError({ reason: resolved.message }); } - // A parent that is gone (or on another machine) cannot cut the profile down. + // 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}.`, @@ -159,19 +247,41 @@ export const claudeMcpProfileForThread = Effect.fn("ClaudeMcpProfile.forThread") return isRefusal(plan) ? yield* plan : plan; }); -const PLAN_KEYS = new WeakMap(); +const PLAN_KEYS = new WeakMap(); +let unplanned = 0; /** - * The plan's part of the live-query key, by the turn's MCP overrides object, so a profile change - * opens a new Claude process. `undefined` for `all`, which leaves the key as it was. + * 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); +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"); + +/** Something set that can narrow a thread's profile: a default other than `all`, or any rule. */ +const profileConfigured = (settings: ServerSettings) => + !(blank(settings.mcpProfile) || settings.mcpProfile.trim() === MCP_PROFILE_ALL) || + needsLineage(settings); type McpOverrides = { readonly mcpServers?: Readonly> | undefined }; -/** The thread's plan, or a refusal. Without the settings service (tests), every thread gets `all`. */ +/** + * The thread's plan, or a refusal. Without the settings service (tests), every thread gets `all`. + * A settings read that fails (it also reads provider secrets) refuses only when the settings last + * read had a profile set; with none set it falls back to `all` with a warning, as upstream's + * own reads in the adapter fall back, so an owner who never set a profile sees no change. + */ 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( @@ -182,28 +292,48 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () { // 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))); - return Effect.fn("ClaudeMcpProfile.plan")(function* ( + // Whether the settings last read could narrow a profile; `false` until one read succeeds. + let lastConfigured = false; + const planFor = Effect.fn("ClaudeMcpProfile.planFor")(function* ( thread: LineageThread, overrides: McpOverrides, ) { if (Option.isNone(settingsService)) return ALL_PLAN; - const settings = yield* settingsService.value.getSettings.pipe( - Effect.mapError( - () => - new ClaudeMcpProfileError({ - reason: `T3 could not read this thread's MCP profile settings, so this thread cannot start: retry, or ${FIX}.`, - }), - ), - ); + const read = yield* settingsService.value.getSettings.pipe(Effect.result); + if (read._tag === "Failure") { + if (lastConfigured) { + return yield* new ClaudeMcpProfileError({ + reason: `T3 could not read this thread's MCP profile settings, so this thread cannot start: retry, or ${FIX}.`, + }); + } + yield* Effect.logWarning( + "MCP profiles: settings could not be read and no profile was set when last read, so this Claude thread gets the all profile", + { cause: read.failure }, + ); + return ALL_PLAN; + } + lastConfigured = profileConfigured(read.success); const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); - const plan = yield* claudeMcpProfileForThread(settings, thread, t3ServerNames, findThread); - // NUL keeps the joined names apart. - if (plan.servers !== "all") PLAN_KEYS.set(overrides, ["mcp", ...plan.servers].join("\u0000")); + return yield* claudeMcpProfileForThread(read.success, 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; }); }); -/** Refuses and closes a started session that shows a server the plan leaves out. */ +/** 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: { @@ -215,6 +345,7 @@ export const checkClaudeSession = 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; @@ -223,6 +354,6 @@ export const checkClaudeSession = 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. A managed Claude policy on this machine can override T3's server list; check it, 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 da4910ae2da3c..13ead43e6a33c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2349,6 +2349,7 @@ export function makeClaudeQueryOptions(input: { ...(deviceInstructions || input.onStop !== undefined ? { hooks: { + ...input.mcpProfileOptions?.hooks, ...(deviceInstructions ? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } : {}), diff --git a/docs/fork/README.md b/docs/fork/README.md index 2b7228d50c890..1af9601c739c3 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -261,10 +261,23 @@ A Claude thread applies the profile's `servers`: `[]` (and `t3-only`) starts Cla 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 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 -(a managed Claude policy on the machine can override T3's list). Other providers do not apply -profiles yet. +profile, a parent thread that cannot be read, settings T3 cannot read while a profile is set (with +none set when last read, the thread gets `all` and the server log says so), 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. 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"] } } } @@ -281,7 +294,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` From a668ce01543278336fd0136d5a0d83bc24b6b708 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:16:42 +0100 Subject: [PATCH 4/4] fix(server): MCP profiles never widen after a restart; guard Skill and resource listings - A settings read that fails (it reads provider secrets too) now works the profile out from settings.json alone, decoded as the load does (managed defaults and locks applied). Only when that file cannot be read either is the turn refused. Nothing remembered from an earlier read decides, so a server restart or a Claude adapter rebuild no longer turns a set profile into all. - The PreToolUse guard refuses a Skill (or older SlashCommand) call naming mcp____... for a server the profile leaves out, and a ListMcpResourcesTool call that names no server. - A fork test keys planned turns, so dropping the MCP credentials from the live-query key fails it (upstream's rotation test keys unplanned turns, which now always differ). - Docs: the failed-read rule, the Skill and listing checks, and the my.docs / my_docs prefix collision. Co-Authored-By: Claude Opus 5.5 --- .../src/fork/claudeMcpProfile.adapter.test.ts | 48 +++++++ apps/server/src/fork/claudeMcpProfile.test.ts | 103 ++++++++++++-- apps/server/src/fork/claudeMcpProfile.ts | 129 +++++++++++++----- docs/fork/README.md | 12 +- 4 files changed, 248 insertions(+), 44 deletions(-) diff --git a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts index 41da3cdfbd29a..f2999ab234ae9 100644 --- a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts @@ -4,6 +4,8 @@ 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, @@ -13,6 +15,7 @@ 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"; @@ -26,6 +29,7 @@ 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), @@ -284,4 +288,48 @@ describe("ClaudeAdapterV2 MCP profile", () => { 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 index 29e2cbebf8288..ab040fdadf18e 100644 --- a/apps/server/src/fork/claudeMcpProfile.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -1,14 +1,26 @@ -import { ProjectId, ServerSettings, ServerSettingsError, ThreadId } from "@t3tools/contracts"; +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, @@ -21,6 +33,7 @@ import { } from "./claudeMcpProfile.ts"; const fromFile = Schema.decodeSync(ServerSettings); +const policyDocument = Schema.decodeUnknownSync(ManagedPolicyDocument); const isRefusal = Schema.is(ClaudeMcpProfileError); const T3 = ["t3-code"]; @@ -85,6 +98,36 @@ describe("claudeMcpCallOutsideProfile", () => { 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( @@ -108,9 +151,21 @@ describe("makeClaudeMcpProfiles", () => { operation: "read-secret", cause: new Error("secret store unreadable"), }); - /** Plans a thread once per entry: a settings file, or a failed read (it reads secrets too). */ - const plansFor = (reads: ReadonlyArray | "fails">) => + /** + * 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(() => { @@ -135,18 +190,50 @@ describe("makeClaudeMcpProfiles", () => { ); } return outcomes; - }).pipe(Effect.provide(ServerSettingsService.ServerSettingsService.layerTest())); + }).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 set, a failed settings read gives all instead of refusing", () => + 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("with a profile set when last read, a failed settings read refuses", () => + it.effect("refuses when settings.json cannot be read either, even after a read with none", () => Effect.gen(function* () { - const [first, second] = yield* plansFor([{ mcpProfile: "t3-only" }, "fails"]); - assert.strictEqual(first, "t3-only"); + const [first, second] = yield* plansFor([{}, "fails"], "unreadable"); + assert.strictEqual(first, "all"); assert.include(second, "could not read this thread's MCP profile settings"); }), ); diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index b689149b99ee6..6609916851138 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -20,11 +20,15 @@ import { } 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, @@ -113,6 +117,22 @@ const MCP_RESOURCE_TOOLS: ReadonlySet = new Set([ "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. @@ -130,16 +150,24 @@ export function claudeMcpCallOutsideProfile( if (call.mcp_server !== undefined) { return allowed.includes(call.mcp_server.name) ? undefined : call.mcp_server.name; } - if (call.tool_name.startsWith("mcp__")) { - const kept = allowed.some((name) => - call.tool_name.startsWith(`mcp__${toolNameServer(name)}__`), - ); - return kept ? undefined : call.tool_name.slice("mcp__".length).split("__")[0]; - } + 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 = (call.tool_input as { readonly server?: unknown } | null)?.server; + 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; } @@ -163,7 +191,10 @@ const claudeMcpProfileGuard = hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", - permissionDecisionReason: `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.`, + 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.`, }, }; }; @@ -262,18 +293,38 @@ export const planKeyFor = (mcpOverrides: object): string | undefined => const planKey = (plan: ClaudeMcpProfilePlan): string | undefined => plan.servers === "all" ? undefined : ["mcp", ...plan.servers].join("\u0000"); -/** Something set that can narrow a thread's profile: a default other than `all`, or any rule. */ -const profileConfigured = (settings: ServerSettings) => - !(blank(settings.mcpProfile) || settings.mcpProfile.trim() === MCP_PROFILE_ALL) || - needsLineage(settings); +/** + * 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), every thread gets `all`. - * A settings read that fails (it also reads provider secrets) refuses only when the settings last - * read had a profile set; with none set it falls back to `all` with a warning, as upstream's - * own reads in the adapter fall back, so an owner who never set a profile sees no change. + * 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); @@ -292,29 +343,41 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () { // 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))); - // Whether the settings last read could narrow a profile; `false` until one read succeeds. - let lastConfigured = false; + 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 read = yield* settingsService.value.getSettings.pipe(Effect.result); - if (read._tag === "Failure") { - if (lastConfigured) { - return yield* new ClaudeMcpProfileError({ - reason: `T3 could not read this thread's MCP profile settings, so this thread cannot start: retry, or ${FIX}.`, - }); - } - yield* Effect.logWarning( - "MCP profiles: settings could not be read and no profile was set when last read, so this Claude thread gets the all profile", - { cause: read.failure }, - ); - return ALL_PLAN; - } - lastConfigured = profileConfigured(read.success); + const settings = yield* readSettings(settingsService.value); const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); - return yield* claudeMcpProfileForThread(read.success, thread, t3ServerNames, findThread); + return yield* claudeMcpProfileForThread(settings, thread, t3ServerNames, findThread); }); return Effect.fn("ClaudeMcpProfile.plan")(function* ( diff --git a/docs/fork/README.md b/docs/fork/README.md index 1af9601c739c3..b4530f0504ab6 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -261,8 +261,9 @@ A Claude thread applies the profile's `servers`: `[]` (and `t3-only`) starts Cla 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, settings T3 cannot read while a profile is set (with -none set when last read, the thread gets `all` and the server log says so), a profile whose +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 @@ -270,7 +271,12 @@ Claude load a server T3's list leaves out. Other providers do not apply profiles 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. With the `all` profile nothing is checked. A +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.