diff --git a/.github/fork-seams.json b/.github/fork-seams.json index 3b278c248741a..f198c28c28e9f 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -270,7 +270,7 @@ ] }, "apps/server/src/mcp/McpToolExposure.ts": { - "why": "MCP profile design PR 4 (T3 tool groups): tool_search leaves out the T3 tools the calling thread's MCP profile leaves out (its t3Tools groups), before it ranks them, so a search never finds or loads a tool the thread cannot call. The filter and the global rule that hides those tools from tools/list and refuses them on tools/call are in fork/mcpT3ToolFilter.ts; the rule is installed in McpHttpServer's production `layer` (a pending file, no new line). A server without the rule (upstream's tests) searches as upstream does. Tested in apps/server/src/fork/mcpT3ToolFilter.test.ts.", + "why": "MCP profile design PR 4 (T3 tool groups): tool_search leaves out the T3 tools the calling thread's MCP profile leaves out (its t3Tools groups), before it ranks them, so a search never finds or loads a tool the thread cannot call. The filter is in fork/mcpT3ToolFilter.ts, which imports no toolkit, profile resolver or store (fork issue #812); the global rule that hides those tools from tools/list, refuses them on tools/call and installs the filter's check is in fork/mcpT3ToolRule.ts, installed in McpHttpServer's production `layer` (a pending file, no new line; its import names the rule's module). A server without the rule (upstream's tests) searches as upstream does. Tested in apps/server/src/fork/mcpT3ToolFilter.test.ts.", "added": [ "import { searchableT3Tool } from \"../fork/mcpT3ToolFilter.ts\"; // Fork: MCP profile T3 tool groups", ".filter(searchableT3Tool) // Fork: MCP profile T3 tool groups" diff --git a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts index 23f7b63fa6efb..a7b17dbe9b756 100644 --- a/apps/server/src/fork/claudeMcpProfile.adapter.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.adapter.test.ts @@ -9,6 +9,7 @@ import { ProviderInstanceId, ProviderSessionId, type ServerSettings, + ServerSettingsError, ThreadId, } from "@t3tools/contracts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -30,6 +31,7 @@ import { makeTurnInput } from "../orchestration-v2/Adapters/AcpAdapterV2.testkit import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import * as ServerSettingsService from "../serverSettings.ts"; import { type LineageThread, makeClaudeMcpProfiles } from "./claudeMcpProfile.ts"; +import * as T3ToolSets from "./mcpT3ToolSets.ts"; const MODEL = { instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER), @@ -47,14 +49,18 @@ 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. + * next turn; records each open, the sessions' closes and the thread's T3 tool set after each turn. + * Stops at the first refused turn, unless `pastRefusals`. */ const runTurns = ( settings: McpSettings, statuses: ReadonlyArray<{ readonly name: string; readonly status: "connected" }> | "unexpected", - saves: ReadonlyArray = [], -) => - Effect.gen(function* () { + saves: ReadonlyArray = [], + pastRefusals = false, +) => { + /** True for a turn whose settings read fails (`"unreadable"`): only that one. */ + let unreadable = false; + return Effect.gen(function* () { const opened: Array = []; const processes: Array> = []; let closed = 0; @@ -123,8 +129,10 @@ const runTurns = ( ); const settingsService = yield* ServerSettingsService.ServerSettingsService; let refusal: string | undefined; + const sets: Array = []; for (const [index, save] of [undefined, ...saves].entries()) { - if (save !== undefined) yield* settingsService.updateSettings(save); + unreadable = save === "unreadable"; + if (save !== undefined && save !== "unreadable") yield* settingsService.updateSettings(save); const started = yield* runtime .startTurn( makeTurnInput({ @@ -138,8 +146,10 @@ const runTurns = ( }), ) .pipe(Effect.exit); + sets.push(T3ToolSets.t3ToolSetFor(threadId)); if (started._tag === "Failure") { - refusal = makeProviderFailure({ cause: started.cause, class: "provider_error" }).message; + refusal ??= makeProviderFailure({ cause: started.cause, class: "provider_error" }).message; + if (pastRefusals) continue; break; } if (index === saves.length) break; @@ -147,7 +157,7 @@ const runTurns = ( yield* Queue.offer(processes.at(-1)!, resultFrame(index + 1)); yield* Queue.take(terminals); } - return { opened, closed, refusal }; + return { opened, closed, refusal, sets }; }).pipe( Effect.scoped, Effect.provide( @@ -156,10 +166,29 @@ const runTurns = ( McpProviderSessions.layer, NodeServices.layer, NodeCrypto.layer, - ServerSettingsService.layerTest(settings), + Layer.effect( + ServerSettingsService.ServerSettingsService, + Effect.map(ServerSettingsService.ServerSettingsService, (service) => + ServerSettingsService.ServerSettingsService.of({ + ...service, + getSettings: Effect.suspend(() => + unreadable + ? Effect.fail( + new ServerSettingsError({ + settingsPath: "settings.json", + operation: "read-secret", + cause: new Error("secret store unreadable"), + }), + ) + : service.getSettings, + ), + }), + ), + ).pipe(Layer.provideMerge(ServerSettingsService.layerTest(settings))), ), ), ); +}; const resultFrame = (ordinal: number) => ({ @@ -274,6 +303,31 @@ describe("ClaudeAdapterV2 MCP profile", () => { }), ); + it.effect( + "runs again after a refused turn: the next good turn on the same process gets its set back", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const lean = { servers: "all", t3Tools: ["waits"] } as const; + // Turn 2's settings read fails once, so it is refused and the live process stays; turn 3 + // reads them again: the same plan as the process opened with, so it reuses that process. + const { opened, refusal, sets } = yield* runTurns( + { mcpProfile: "lean", mcpProfiles: { lean } }, + [], + ["unreadable", {}], + true, + ); + assert.isDefined(refusal); + assert.lengthOf(opened, 1); + assert.deepStrictEqual( + sets.map((set) => + set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set?._tag, + ), + [["waits"], "Refused", ["waits"]], + ); + }), + ); + it.effect( 'builtinTools "none" opens Claude with no built-in tools and refuses any at the call', () => diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts index 7c189e94894fb..cb31c20f01671 100644 --- a/apps/server/src/fork/claudeMcpProfile.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -250,7 +250,8 @@ describe("makeClaudeMcpProfiles", () => { const sets: Array = []; for (const _ of reads) { const overrides = {}; - yield* plan(self, overrides); + // The adapter reads the options only as it opens the query's process. + void (yield* plan(self, overrides)).options; keys.push(planKeyFor(overrides)); const set = T3ToolSets.t3ToolSetFor(self.id); sets.push(set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set); @@ -271,6 +272,41 @@ describe("makeClaudeMcpProfiles", () => { ), ); + it.effect( + "the set is fixed only once the plan opens a process: a turn that keeps the old one keeps its set", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const lean = { mcpProfile: "lean", mcpProfiles: { lean: { servers: "all", t3Tools: [] } } }; + const service = yield* ServerSettingsService.ServerSettingsService; + const plan = yield* makeClaudeMcpProfiles.pipe( + Effect.provideService(ServerSettingsService.ServerSettingsService, { + ...service, + getSettings: Effect.succeed(fromFile(lean)), + }), + ); + const before: T3ToolSets.T3ToolSet = { _tag: "Groups", name: "all", groups: "all" }; + T3ToolSets.fixT3ToolSet("t", before); + const planned = yield* plan(thread("t"), {}); + // Planned, not opened (a continuation, or background work blocks the replacement). + assert.strictEqual(planned.name, "lean"); + assert.deepStrictEqual(planned.servers, "all"); + assert.strictEqual(T3ToolSets.t3ToolSetFor("t"), before); + // The new process opens: its options are read, and the new set applies from then. + assert.deepStrictEqual(planned.options, {}); + const set = T3ToolSets.t3ToolSetFor("t"); + assert.deepStrictEqual(set?._tag === "Groups" ? [...(set.groups as Set)] : set, []); + }).pipe( + Effect.provide( + Layer.mergeAll( + ServerSettingsService.ServerSettingsService.layerTest(), + ManagedPolicy.layerTest(), + Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-mcp-profile-" })), + ).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ), + ); + it.effect("a profile that cannot be worked out fixes no T3 tool but the ungrouped ones", () => Effect.gen(function* () { T3ToolSets.__testing.clear(); @@ -285,7 +321,7 @@ describe("makeClaudeMcpProfiles", () => { ); it.effect( - "stopped half-way: a query whose profile read is interrupted leaves no T3 tool set", + "stopped half-way: a query whose profile read is interrupted leaves the set as it was", () => Effect.gen(function* () { T3ToolSets.__testing.clear(); @@ -301,8 +337,12 @@ describe("makeClaudeMcpProfiles", () => { const fiber = yield* Effect.forkChild(plan(thread("t"), {})); yield* Deferred.await(reading); yield* Fiber.interrupt(fiber); - // The next request works the set out again from the settings, rather than the old turn's. - assert.isUndefined(T3ToolSets.t3ToolSetFor("t")); + // No process opened: the last turn's set stands until one does. + assert.deepStrictEqual(T3ToolSets.t3ToolSetFor("t"), { + _tag: "Groups", + name: "all", + groups: "all", + }); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index 757a5337e885b..2b7e3c724bcd6 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -1,6 +1,6 @@ /** * Fork: a thread's MCP profile, applied to its Claude session. This applies the outside servers; - * T3's own tools are filtered on the T3 MCP server for every provider (mcpT3ToolFilter.ts), with + * T3's own tools are filtered on the T3 MCP server for every provider (mcpT3ToolRule.ts), with * the groups fixed as each query opens. A profile that cannot be applied refuses the turn instead * of starting it with every tool: the owner chose refusing over warning. */ @@ -42,7 +42,13 @@ import { type McpProfileThread, resolveMcpProfile, } from "./mcpProfile.ts"; -import { fixT3ToolSet, forgetT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; +import { + MAX_T3_TOOL_SETS, + type T3ToolSet, + fixT3ToolSet, + refusedT3ToolSet, + t3ToolSetOf, +} from "./mcpT3ToolSets.ts"; import { type McpProfileFileKeys, mcpProfileFileKeysOf, @@ -76,7 +82,7 @@ export interface ClaudeMcpProfilePlan { readonly disallowedTools?: Array; }; readonly servers: McpProfileSet["servers"]; - /** T3's own tool groups; the T3 MCP server applies them (mcpT3ToolFilter.ts). */ + /** T3's own tool groups; the T3 MCP server applies them (mcpT3ToolRule.ts). */ readonly t3Tools: McpProfileSet["t3Tools"]; readonly builtinTools?: McpProfileSet["builtinTools"]; } @@ -669,6 +675,14 @@ export const makeThreadMcpProfiles = Effect.gen(function* () { }); }); +const NOT_IN_STORE = `T3 cannot read this thread from its store, so its MCP profile cannot be worked out and it cannot start: retry, or ${FIX}.`; + +/** {@link makeThreadMcpProfilesById}'s refusal of a thread the store did not give. */ +export const threadNotInStore = () => new ClaudeMcpProfileError({ reason: NOT_IN_STORE }); +/** True for {@link threadNotInStore}'s refusal. */ +export const isNotInStore = (error: ClaudeMcpProfileError): boolean => + error.reason === NOT_IN_STORE; + /** * A thread's resolved profile, or a refusal, found by its id alone (a Codex thread request carries * only the id). A thread the store cannot give refuses, as an unreadable parent does. With no store @@ -686,15 +700,49 @@ export const makeThreadMcpProfilesById = Effect.gen(function* () { } as LineageThread); } const thread = yield* findThread(threadId); - if (thread === null) { - return yield* new ClaudeMcpProfileError({ - reason: `T3 cannot read this thread from its store, so its MCP profile cannot be worked out and it cannot start: retry, or ${FIX}.`, - }); - } + if (thread === null) return yield* threadNotInStore(); return yield* read(thread); }); }); +/** + * The plan key each thread's Claude process last opened with. Its T3 tool groups are part of the + * key, so a later plan with the same key has the same set as that process. Memory only, bounded + * like the sets: a thread dropped here just waits for its next process to fix its set. + */ +const openedPlanKeys = new Map(); + +const keepOpenedPlanKey = (threadId: ThreadId, key: string | undefined) => { + openedPlanKeys.delete(threadId); + openedPlanKeys.set(threadId, key); + for (const oldest of openedPlanKeys.keys()) { + if (openedPlanKeys.size <= MAX_T3_TOOL_SETS) break; + openedPlanKeys.delete(oldest); + } +}; + +/** + * The plan with its T3 tool set fixed when its `options` are first read: ClaudeAdapterV2 reads + * them only to open a new process, after the old one closed. A turn that keeps the live process (a + * continuation, the same plan) or is refused before replacing it (background work still runs) + * leaves that process's set as its turn fixed it, so a running turn keeps its set. + */ +const fixedWhenOpened = ( + plan: ClaudeMcpProfilePlan, + threadId: ThreadId, + set: T3ToolSet, +): ClaudeMcpProfilePlan => { + const { options, ...rest } = plan; + return Object.defineProperty({ ...rest }, "options", { + enumerable: true, + get: () => { + fixT3ToolSet(threadId, set); + keepOpenedPlanKey(threadId, planKey(plan)); + return options; + }, + }) as ClaudeMcpProfilePlan; +}; + /** The thread's Claude plan, or a refusal, from {@link makeThreadMcpProfiles}. */ export const makeClaudeMcpProfiles = Effect.gen(function* () { const profileFor = yield* makeThreadMcpProfiles; @@ -702,19 +750,27 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () { thread: LineageThread, overrides: McpOverrides, ) { - // The query opens for a turn: its T3 tool groups are fixed here until the next one opens, and - // a profile that cannot be worked out keeps only the tools every profile keeps. + // A profile that cannot apply refuses the turn and keeps only the tools every profile keeps, + // at once: narrowing never waits. A profile that applies is fixed as its process opens. const resolved: McpProfileResolved = yield* profileFor(thread).pipe( Effect.tapError((refusal) => Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason))), ), - // Stopped half-way: no set stands, so the next request works it out again. - Effect.onInterrupt(() => Effect.sync(() => forgetT3ToolSet(thread.id))), ); - fixT3ToolSet(thread.id, t3ToolSetOf(resolved)); const t3ServerNames = Object.keys(overrides.mcpServers ?? {}); const plan = claudeMcpProfilePlan(resolved.name, resolved.profile, t3ServerNames); - return isRefusal(plan) ? yield* plan : plan; + if (isRefusal(plan)) { + fixT3ToolSet(thread.id, refusedT3ToolSet(plan.reason)); + return yield* plan; + } + const set = t3ToolSetOf(resolved); + // The same plan as the thread's process opened with: the adapter keeps that process without + // reading the options, so its set is fixed here, the one that process has (never wider). This + // is how a good turn after a refused one gets its set back on the process the refusal kept. + if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === planKey(plan)) { + fixT3ToolSet(thread.id, set); + } + return fixedWhenOpened(plan, thread.id, set); }); return Effect.fn("ClaudeMcpProfile.plan")(function* ( diff --git a/apps/server/src/fork/codexMcpProfile.test.ts b/apps/server/src/fork/codexMcpProfile.test.ts index 43b022ce73357..0cd3af2c257f7 100644 --- a/apps/server/src/fork/codexMcpProfile.test.ts +++ b/apps/server/src/fork/codexMcpProfile.test.ts @@ -28,7 +28,10 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Exit from "effect/Exit"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as TestClock from "effect/testing/TestClock"; import { makeTurnInput } from "../orchestration-v2/Adapters/AcpAdapterV2.testkit.ts"; import * as CodexAdapterV2 from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; @@ -38,8 +41,11 @@ import * as ServerConfig from "../config.ts"; import * as PortScanner from "../preview/PortScanner.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ServerSettingsService from "../serverSettings.ts"; -import { ClaudeMcpProfileError } from "./claudeMcpProfile.ts"; +import { ClaudeMcpProfileError, threadNotInStore } from "./claudeMcpProfile.ts"; import { + CODEX_ADOPT_WAIT_MS, + afterStoreLag, + codexCarriedT3McpServers, codexConfiguredMcpServers, codexMcpProfileConfig, codexMcpServersOutsideProfile, @@ -49,6 +55,7 @@ import { } from "./codexMcpProfile.ts"; import type { McpProfileResolved, McpProfileSet } from "./mcpProfile.ts"; import * as T3ToolSets from "./mcpT3ToolSets.ts"; +import { CurrentTurnMcpProfile } from "./mcpTurnProfile.ts"; /** The groups the thread's set holds now, or its tag when it is not a list. */ const groupsOf = (threadId: string) => { @@ -109,6 +116,8 @@ interface FakeThread { readonly cwd: string; config: Json; loaded: boolean; + /** The thread that spawned it, for a Codex sub-agent. */ + readonly parent?: string; } /** @@ -183,7 +192,19 @@ const makeFakeCodex = ( const found = thread(params.threadId); return found === undefined ? Effect.fail(fail(method)) - : Effect.succeed({ thread: { id: found.id, cwd: found.cwd } }); + : Effect.succeed({ + thread: { + id: found.id, + cwd: found.cwd, + ...(found.parent === undefined + ? {} + : { + source: { + subAgent: { thread_spawn: { parent_thread_id: found.parent, depth: 1 } }, + }, + }), + }, + }); } case "config/read": { const cwd = typeof params.cwd === "string" ? params.cwd : ""; @@ -251,12 +272,20 @@ const makeFakeCodex = ( string, Array<(payload: unknown) => Effect.Effect> >(); + /** Server-request handlers (the last one added for a method, as the real client keeps them). */ + const serverRequests = new Map< + string, + (payload: unknown) => Effect.Effect + >(); const client = { request, raw: { request, requests: undefined as never }, notify: () => Effect.void, awaitTermination: Effect.never, - handleServerRequest: () => Effect.void, + handleServerRequest: ( + method: string, + handler: (payload: unknown) => Effect.Effect, + ) => Effect.sync(() => void serverRequests.set(method, handler)), handleServerNotification: ( method: string, handler: (payload: unknown) => Effect.Effect, @@ -284,6 +313,8 @@ const makeFakeCodex = ( Effect.forEach(handlers.get(method) ?? [], (handler) => handler(payload), { discard: true, }).pipe(Effect.orDie), + /** Codex asks the client (a server request): the handler's answer. */ + ask: (method: string, payload: unknown) => serverRequests.get(method)!(payload), setPageSize: (size: number) => void (pageSize = size), setEndlessPages: () => void (endlessPages = true), /** @@ -293,7 +324,7 @@ const makeFakeCodex = ( spawnChild: (parent: string) => { const source = threads.get(parent)!; const id = `native-${++next}`; - threads.set(id, { id, cwd: source.cwd, config: { ...source.config }, loaded: true }); + threads.set(id, { id, cwd: source.cwd, config: { ...source.config }, loaded: true, parent }); return id; }, /** Codex lets the thread go (idle): its next resume loads it with the config sent then. */ @@ -1173,6 +1204,280 @@ describe("withCodexMcpProfiles", () => { ); }); +describe("follow-ups: holds, sub-agents, unknown threads, per-call checks (fork issues #814, #918)", () => { + it.effect("a turn Codex starts holds T3's requests until its set is fixed", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const gate = yield* Deferred.make(); + let gated = false; + const profileFor: ProfileById = () => + gated + ? Deferred.await(gate).pipe(Effect.as(resolved("lean", "all", ["waits"]))) + : Effect.succeed(ALL); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + gated = true; + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + // Held from the notification on, before the profile is read: no request sees the old set. + assert.isDefined(T3ToolSets.__testing.asked("t")); + yield* Deferred.succeed(gate, undefined); + yield* TestClock.withLive(Effect.sleep("20 millis")); + assert.isUndefined(T3ToolSets.__testing.asked("t")); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + }), + ); + + it.effect("stopped half-way: a turn Codex starts as the client closes leaves no hold", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const clientScope = yield* Scope.make(); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("lean", "all", ["waits"]) }).profileFor, + ).pipe(Scope.provide(clientScope)); + const id = (yield* start(client, "t")).thread.id; + // The session shuts down, then Codex's turn/started for the thread still arrives: the check + // never runs, and it must not leave the thread's T3 requests held. + yield* Scope.close(clientScope, Exit.void); + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + assert.isUndefined(T3ToolSets.__testing.asked("t")); + }), + ); + + it.effect("stopped half-way: a turn's check interrupted mid-way releases its hold", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const reading = yield* Deferred.make(); + let gated = false; + const profileFor: ProfileById = () => + gated + ? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Effect.never)) + : Effect.succeed(ALL); + const clientScope = yield* Scope.make(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor).pipe( + Scope.provide(clientScope), + ); + const id = (yield* start(client, "t")).thread.id; + gated = true; + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* Deferred.await(reading); + assert.isDefined(T3ToolSets.__testing.asked("t")); + // The session closes while the check reads the profile: the check is interrupted. + yield* Scope.close(clientScope, Exit.void); + assert.isUndefined(T3ToolSets.__testing.asked("t")); + }), + ); + + it.effect("a sub-agent's turn, or a goal set active, checks but leaves the parent's set", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profiles, profileFor } = makeProfiles({ t: resolved("a", "all", ["threads"]) }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + yield* turn(client, id); + assert.deepStrictEqual(groupsOf("t"), ["threads"]); + const child = fake.spawnChild(id); + yield* fake.emit("item/completed", spawned(id, [child])); + // The parent's turn still runs with its set; a change reaches its next turn only. + profiles.set("t", resolved("a", "all", ["waits"])); + yield* fake.emit("turn/started", turnStarted(child, "child-1")); + yield* TestClock.withLive(Effect.sleep("20 millis")); + assert.deepStrictEqual(groupsOf("t"), ["threads"]); + assert.strictEqual( + yield* outcome( + client.request("thread/goal/set", { threadId: id, status: "active" } as never), + ), + "ok", + ); + assert.deepStrictEqual(groupsOf("t"), ["threads"]); + // The goal's own turn, which Codex starts, fixes it. + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* TestClock.withLive(Effect.sleep("20 millis")); + assert.deepStrictEqual(groupsOf("t"), ["waits"]); + }), + ); + + it.effect( + "a turn on a Codex thread T3 has not seen: adopted when Codex names its parent, else stopped", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const { profiles, profileFor } = makeProfiles({ t: resolved("a", ["alpha"]) }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const seen = yield* completions(client); + const id = (yield* start(client, "t")).thread.id; + // A sub-agent whose spawn item T3 has not seen yet: thread/read names its parent. + const child = fake.spawnChild(id); + profiles.set("t", resolved("a", ["alpha", "beta"])); + yield* fake.emit("turn/started", turnStarted(child, "child-1")); + yield* fake.reached("mcpServerStatus/list", 1); + assert.strictEqual(fake.sent("mcpServerStatus/list")[0]!.params.threadId, child); + assert.deepStrictEqual(fake.sent("turn/interrupt"), []); + // A thread Codex names no parent for, and T3 never sees spawned, is stopped after a wait. + const stray = ( + (yield* fake.client.request("thread/start", {} as never)) as { + readonly thread: { readonly id: string }; + } + ).thread.id; + const readsBefore = fake.sent("thread/read").length; + const waited = yield* Effect.forkChild( + Effect.gen(function* () { + yield* fake.emit("turn/started", turnStarted(stray, "stray-1")); + yield* fake.reached("turn/interrupt", 1); + }), + ); + // Codex names no parent for it; then T3 waits for the spawn to show. + yield* fake.reached("thread/read", readsBefore + 1); + yield* drive(waited, CODEX_ADOPT_WAIT_MS); + assert.deepStrictEqual(fake.sent("turn/interrupt")[0]!.params, { + threadId: stray, + turnId: "stray-1", + }); + yield* fake.emit("turn/completed", turnCompleted(stray, "stray-1")); + assert.include( + (seen.at(-1)!.error as { readonly message: string }).message, + "did not load this Codex thread", + ); + }), + ); + + it.effect("T3's own turn reads the profile the turn check worked out, once per turn", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + let reads = 0; + const profileFor: ProfileById = () => + Effect.sync(() => void (reads += 1)).pipe(Effect.as(resolved("a", ["alpha"]))); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + reads = 0; + const response = (yield* turn(client, id).pipe( + Effect.provideService(CurrentTurnMcpProfile, { + threadId: ThreadId.make("t"), + resolved: resolved("a", ["alpha"]), + }), + )) as { readonly turn: { readonly id: string } }; + const listed = fake.sent("mcpServerStatus/list").length; + assert.isAbove(listed, 0); + // Codex reports T3's own turn started: it was checked before it was sent. + yield* fake.emit("turn/started", turnStarted(id, response.turn.id)); + yield* TestClock.withLive(Effect.sleep("20 millis")); + assert.strictEqual(reads, 0); + assert.strictEqual(fake.sent("mcpServerStatus/list").length, listed); + }), + ); + + it.effect("MCP Apps calls and elicitations to a server outside the profile are refused", () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "beta"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + let asked = 0; + yield* client.handleServerRequest("mcpServer/elicitation/request", () => + Effect.sync(() => void (asked += 1)).pipe(Effect.as({ action: "accept" as const })), + ); + const id = (yield* start(client, "t")).thread.id; + const call = (server: string) => + outcome( + client.request("mcpServer/tool/call", { threadId: id, server, tool: "x" } as never), + ); + assert.include(yield* call("beta"), 'MCP server "beta" is not in this thread\'s MCP profile'); + assert.include( + yield* outcome( + client.request("mcpServer/resource/read", { + threadId: id, + server: "beta", + uri: "ui://x", + } as never), + ), + "not in this thread's MCP profile", + ); + assert.strictEqual(yield* call("alpha"), "ok"); + assert.strictEqual(yield* call("t3-code"), "ok"); + assert.deepStrictEqual( + fake.sent("mcpServer/tool/call").map((sent) => sent.params.server), + ["alpha", "t3-code"], + ); + const elicit = (serverName: string) => + fake.ask("mcpServer/elicitation/request", { + threadId: id, + serverName, + message: "ok?", + mode: "form", + requestedSchema: { type: "object", properties: {} }, + }); + assert.deepStrictEqual(yield* elicit("beta"), { action: "decline" }); + assert.strictEqual(asked, 0); + assert.deepStrictEqual(yield* elicit("alpha"), { action: "accept" }); + assert.strictEqual(asked, 1); + }), + ); + + it.effect("a server of the user's named like T3's is switched off unless T3 carries it", () => + Effect.gen(function* () { + assert.deepStrictEqual([...codexCarriedT3McpServers(threadConfig("t"))].sort(), [ + "t3-code", + "t3-code-direct", + ]); + const fake = makeFakeCodex({ servers: ["alpha", "t3-code"] }); + const client = yield* withCodexMcpProfiles( + fake.client, + makeProfiles({ t: resolved("a", ["alpha"]) }).profileFor, + ); + // A load with no T3 server of its own (T3's MCP session was not set up). + const { + "mcp_servers.t3-code": _, + "mcp_servers.t3-code-direct": __, + ...bare + } = threadConfig("t"); + const id = ( + (yield* client.request("thread/start", { cwd: "/workspace", config: bare } as never)) as { + readonly thread: { readonly id: string }; + } + ).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(id)!.config), [ + "mcp_servers.t3-code.enabled", + ]); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + // One T3 does carry stays on. + const own = (yield* start(client, "t")).thread.id; + assert.deepStrictEqual(offKeys(fake.threads.get(own)!.config), []); + }), + ); + + it.effect("a thread the store does not have yet is read again before it is refused", () => + Effect.gen(function* () { + let reads = 0; + const lagging = afterStoreLag(() => + Effect.suspend(() => + ++reads < 3 ? Effect.fail(threadNotInStore()) : Effect.succeed(resolved("a", "all")), + ), + ); + const found = yield* drive(yield* Effect.forkChild(lagging(ThreadId.make("t"))), 1_750); + assert.strictEqual(found.name, "a"); + assert.strictEqual(reads, 3); + // Any other refusal stands at once. + reads = 0; + const refused = afterStoreLag(() => + Effect.sync(() => void (reads += 1)).pipe( + Effect.andThen(Effect.fail(new ClaudeMcpProfileError({ reason: "gone" }))), + ), + ); + assert.include(yield* outcome(refused(ThreadId.make("t"))), "gone"); + assert.strictEqual(reads, 1); + }), + ); +}); + +/** Moves test time on by `millis` (each sleep in turn wakes), then joins the fiber. */ +const drive = (fiber: Fiber.Fiber, millis: number) => + TestClock.adjust(millis).pipe(Effect.andThen(Fiber.join(fiber))); + describe("profiledClientFactory (settings and thread store)", () => { const NOW = DateTime.makeUnsafe("2026-11-21T00:00:00.000Z"); const PROJECT = ProjectId.make("project"); @@ -1288,7 +1593,11 @@ describe("profiledClientFactory (settings and thread store)", () => { Effect.gen(function* () { const lost = yield* outcome(start(client, "lost")); assert.include(lost, '"gone"'); - const unknown = yield* outcome(start(client, "not-stored")); + // Read again three times over 1.75 s (the store may lag a new thread), then refused. + const unknown = yield* drive( + yield* Effect.forkChild(outcome(start(client, "not-stored"))), + 1_750, + ); assert.include(unknown, "cannot read this thread from its store"); assert.include(unknown, FIX); assert.deepStrictEqual(fake.sent("thread/start"), []); diff --git a/apps/server/src/fork/codexMcpProfile.ts b/apps/server/src/fork/codexMcpProfile.ts index 0cba7e1da5518..626abccf4fe12 100644 --- a/apps/server/src/fork/codexMcpProfile.ts +++ b/apps/server/src/fork/codexMcpProfile.ts @@ -1,25 +1,30 @@ /** - * Fork: MCP profiles on Codex (design part 5). Each thread on the shared app-server gets - * `mcp_servers..enabled = false` for every listed server its profile leaves out; each turn - * checks the thread's live servers, refuses on a mismatch, and fixes its T3 tool groups (cut on - * T3's MCP server, mcpT3ToolFilter.ts), also on a turn Codex starts itself. + * Fork: MCP profiles on Codex. Each thread on the shared app-server gets `enabled = false` for + * each server its profile leaves out (T3's own only when the load carries them); each turn is + * checked and fixes its T3 tool groups (mcpT3ToolRule.ts). MCP Apps calls are checked too. */ import { MCP_BUILTIN_TOOLS_NONE, MCP_PROFILE_ALL, ThreadId } from "@t3tools/contracts"; import type * as CodexClient from "effect-codex-app-server/client"; import * as CodexError from "effect-codex-app-server/errors"; import type * as CodexSchema from "effect-codex-app-server/schema"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import type { CodexAppServerClientFactoryShape } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; import { AGENT_THREAD_ENV } from "../preview/PortScanner.ts"; -import { ClaudeMcpProfileError, makeThreadMcpProfilesById } from "./claudeMcpProfile.ts"; +import { + ClaudeMcpProfileError, + isNotInStore, + makeThreadMcpProfilesById, +} from "./claudeMcpProfile.ts"; import { type McpProfileResolved, type McpProfileSet, builtinToolsNoneRefusal, } from "./mcpProfile.ts"; -import { fixT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; +import { fixT3ToolSet, holdT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; +import { CurrentTurnMcpProfile } from "./mcpTurnProfile.ts"; type Client = CodexClient.CodexAppServerClient["Service"]; type Send = ( @@ -69,22 +74,32 @@ export function codexConfiguredMcpServers(config: unknown): ReadonlyArray`). + * Only those are T3's: a server of the user's that has one of their names is not. + */ +export function codexCarriedT3McpServers(config: unknown): ReadonlySet { + if (!isRecord(config)) return new Set(); + return new Set( + [...CODEX_T3_MCP_SERVERS].filter((name) => isRecord(config[`mcp_servers.${name}`])), + ); +} + /** * The per-thread config that turns off every configured server the profile does not keep (and * Codex's connectors server, see {@link CODEX_APPS_MCP_SERVER}), or the refusal. T3's own servers - * stay; a kept name that is not configured keeps nothing (design §9). `t3Tools` adds no config: - * T3's own server hides and refuses the tools it leaves out. + * the thread carries stay; a kept name that is not configured keeps nothing (design §9). `t3Tools` + * adds no config: T3's own server hides and refuses the tools it leaves out. */ export function codexMcpProfileConfig( name: string, profile: McpProfileSet, configured: ReadonlyArray, + carried: ReadonlySet = CODEX_T3_MCP_SERVERS, ): Readonly> | ClaudeMcpProfileError { const kept = profile.servers; if (kept === "all") return {}; - const off = configured.filter( - (server) => !CODEX_T3_MCP_SERVERS.has(server) && !kept.includes(server), - ); + const off = configured.filter((server) => !carried.has(server) && !kept.includes(server)); const unnamed = off.filter((server) => !SERVER_NAME.test(server)); if (unnamed.length > 0) { return new ClaudeMcpProfileError({ @@ -101,13 +116,14 @@ export function codexMcpProfileConfig( export function codexMcpServersOutsideProfile( kept: McpProfileSet["servers"], statuses: ReadonlyArray<{ readonly name: string; readonly runtimeStatus?: string | null }>, + carried: ReadonlySet = CODEX_T3_MCP_SERVERS, ): ReadonlyArray { if (kept === "all") return []; return statuses .filter( (server) => server.runtimeStatus !== "disabled" && - !CODEX_T3_MCP_SERVERS.has(server.name) && + !carried.has(server.name) && !kept.includes(server.name), ) .map((server) => server.name); @@ -129,6 +145,28 @@ const refusal = (method: string, cause: ClaudeMcpProfileError) => }); const LOADS: ReadonlySet = new Set(["thread/start", "thread/resume", "thread/fork"]); +/** Requests the UI sends to one MCP server of a thread (MCP Apps); checked like a tool call. */ +const SERVER_CALLS: ReadonlySet = new Set([ + "mcpServer/tool/call", + "mcpServer/resource/read", +]); +const ELICITATION = "mcpServer/elicitation/request"; +/** How long a turn on a Codex thread T3 has not seen waits to be counted as a sub-agent's. */ +export const CODEX_ADOPT_WAIT_MS = 5_000; +const ADOPT_POLL_MS = 250; +/** T3-started turns remembered as checked, until Codex reports them started. */ +const MAX_OWN_TURNS = 256; + +/** The Codex thread's parent, from a thread/read answer (a sub-agent's spawn source). */ +const parentOf = (response: unknown): string | undefined => { + const thread = isRecord(response) ? response.thread : undefined; + const direct = stringField(thread, "parentThreadId"); + if (direct !== undefined) return direct; + const source = isRecord(thread) ? thread.source : undefined; + const subAgent = isRecord(source) ? source.subAgent : undefined; + const spawn = isRecord(subAgent) ? subAgent.thread_spawn : undefined; + return stringField(spawn, "parent_thread_id"); +}; /** * The client with the thread's profile applied to each thread it loads and checked before each @@ -145,6 +183,16 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* * each Codex sub-agent of such a thread (its parent's T3 thread). */ const known = new Map(); + /** Codex sub-agents in `known`: their turns are checked but never fix their parent's T3 set. */ + const children = new Set(); + /** T3's own servers each Codex thread was loaded with; a sub-agent's are its parent's. */ + const carried = new Map>(); + const carriedBy = (nativeId: string | undefined) => + (nativeId === undefined ? undefined : carried.get(nativeId)) ?? CODEX_T3_MCP_SERVERS; + /** Codex threads with a T3 `turn/start` sent and not yet answered (its turn is checked). */ + const starting = new Set(); + /** Turns T3 started itself and checked before sending, until Codex reports them started. */ + const ownTurns = new Set(); /** Turns stopped here because their profile was narrower, by Codex turn id: the reason. */ const stoppedTurns = new Map(); /** @@ -160,8 +208,32 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* Effect.timeout(CODEX_READ_TIMEOUT), ); + /** The thread's profile: the one the turn check worked out for this turn, else worked out now. */ + const workedOut = Effect.fn("CodexMcpProfile.workedOut")(function* (threadId: ThreadId) { + const current = yield* CurrentTurnMcpProfile; + if (current?.threadId === threadId) return current.resolved; + return yield* profileFor(threadId); + }); const profileOf = (method: string, threadId: ThreadId) => - profileFor(threadId).pipe(Effect.mapError((cause) => refusal(method, cause))); + workedOut(threadId).pipe(Effect.mapError((cause) => refusal(method, cause))); + + /** Counts a Codex sub-agent as its parent's T3 thread, with the parent's servers. */ + const adopt = (child: string, parent: string) => { + const threadId = known.get(parent); + if (threadId === undefined || known.has(child)) return; + known.set(child, threadId); + children.add(child); + carried.set(child, carriedBy(parent)); + }; + /** Adopts the Codex thread when Codex says it is a sub-agent of a thread T3 knows. */ + const adoptByRead = (nativeId: string) => + read("thread/read", { threadId: nativeId, includeTurns: false }).pipe( + Effect.map((response) => { + const parent = parentOf(response); + if (parent !== undefined) adopt(nativeId, parent); + }), + Effect.ignore, + ); /** The workspace Codex loads the thread in: the request's, else the stored thread's. */ const workspaceOf = (method: string, params: Readonly>) => { @@ -195,6 +267,10 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* const config = isRecord(request.config) ? request.config : {}; const nativeId = method === "thread/resume" ? stringField(request, "threadId") : undefined; const fromConfig = stringField(config, THREAD_ID_KEY); + // A sub-agent T3 did not see spawned (one from before an app-server restart) is its parent's. + if (fromConfig === undefined && nativeId !== undefined && !known.has(nativeId) && narrowed) { + yield* adoptByRead(nativeId); + } const threadId = fromConfig === undefined ? nativeId === undefined @@ -202,8 +278,8 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* : known.get(nativeId) : ThreadId.make(fromConfig); if (threadId === undefined) { - // A Codex thread T3 did not load and saw no parent spawn (e.g. a sub-agent from before an - // app-server restart): its T3 thread is not known, so with a profile in use it is not loaded. + // A Codex thread T3 did not load and whose parent it does not know: its T3 thread is not + // known, so with a profile in use it is not loaded. if (narrowed) { return yield* refusal( method, @@ -224,7 +300,12 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* }), ); } - const off = yield* offFor(method, threadId, request).pipe( + // A resume without T3's servers (an adopted sub-agent's) keeps the ones it was loaded with. + const carriedHere = + fromConfig === undefined && nativeId !== undefined + ? carriedBy(nativeId) + : codexCarriedT3McpServers(config); + const off = yield* offFor(method, threadId, request, carriedHere).pipe( Effect.tapError((error) => method === "thread/resume" ? Effect.sync(() => void refusedResumes.set(threadId, reasonOf(error))) @@ -237,7 +318,10 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* ); refusedResumes.delete(threadId); const loaded = stringField(isRecord(response) ? response.thread : undefined, "id"); - if (loaded !== undefined) known.set(loaded, threadId); + if (loaded !== undefined) { + known.set(loaded, threadId); + carried.set(loaded, carriedHere); + } return response; }); @@ -246,6 +330,7 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* method: string, threadId: ThreadId, request: Readonly>, + carriedHere: ReadonlySet, ) { const resolved = yield* profileOf(method, threadId); let off: Readonly> = {}; @@ -261,7 +346,12 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* Effect.orElseSucceed(() => undefined), ); if (configured === undefined) return yield* cannotList(method, resolved.name); - const planned = codexMcpProfileConfig(resolved.name, resolved.profile, configured); + const planned = codexMcpProfileConfig( + resolved.name, + resolved.profile, + configured, + carriedHere, + ); if (isRefusal(planned)) return yield* refusal(method, planned); off = planned; narrowed = true; @@ -269,28 +359,30 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* return off; }); - /** Refuses a turn on a thread whose live servers include one its profile leaves out. */ - const check = Effect.fn("CodexMcpProfile.check")(function* (method: string, params: unknown) { - const nativeId = stringField(params, "threadId"); - const threadId = nativeId === undefined ? undefined : known.get(nativeId); - if (threadId === undefined) { - if (!narrowed) return; - return yield* refusal( - method, - new ClaudeMcpProfileError({ - reason: `T3 did not load this Codex thread itself, so it cannot tell which MCP servers the thread has, and runs no turn on it: ${FIX}.`, - }), - ); - } - // The turn's T3 tool groups, also for a turn Codex started itself (`turn/started`): fixed - // until the next turn, and only the tools every profile keeps when the profile cannot apply. - const resolved = yield* profileFor(threadId).pipe( + /** + * The thread's profile, with its T3 tool groups fixed when `fix` (a turn of the thread itself, + * not of a sub-agent, and not a goal set while a turn may run): fixed until the next turn, and + * only the tools every profile keeps when the profile cannot apply. + */ + const profileStep = (method: string, threadId: ThreadId, fix: boolean) => + workedOut(threadId).pipe( + Effect.tap((resolved) => + fix ? Effect.sync(() => fixT3ToolSet(threadId, t3ToolSetOf(resolved))) : Effect.void, + ), Effect.tapError((cause) => - Effect.sync(() => fixT3ToolSet(threadId, refusedT3ToolSet(cause.reason))), + fix + ? Effect.sync(() => fixT3ToolSet(threadId, refusedT3ToolSet(cause.reason))) + : Effect.void, ), Effect.mapError((cause) => refusal(method, cause)), ); - fixT3ToolSet(threadId, t3ToolSetOf(resolved)); + + /** Refuses a turn on a thread whose live servers include one its profile leaves out. */ + const serverStep = Effect.fn("CodexMcpProfile.servers")(function* ( + method: string, + nativeId: string, + resolved: McpProfileResolved, + ) { // Codex cannot run a thread without its shell and file tools; also a turn it starts itself. if (resolved.profile.builtinTools === MCP_BUILTIN_TOOLS_NONE) { const reason = builtinToolsNoneRefusal(resolved.name, "codex"); @@ -317,7 +409,11 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* cursor = isRecord(response) ? stringField(response, "nextCursor") : undefined; if (cursor === undefined) break; } - const outside = codexMcpServersOutsideProfile(resolved.profile.servers, statuses); + const outside = codexMcpServersOutsideProfile( + resolved.profile.servers, + statuses, + carriedBy(nativeId), + ); if (outside.length === 0) return; return yield* refusal( method, @@ -327,41 +423,167 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* ); }); + const notLoadedHere = (method: string) => + refusal( + method, + new ClaudeMcpProfileError({ + reason: `T3 did not load this Codex thread itself, so it cannot tell which MCP servers the thread has, and runs no turn on it: ${FIX}.`, + }), + ); + + /** The turn's checks: its profile (`fix`: see {@link profileStep}), then its live servers. */ + const check = Effect.fn("CodexMcpProfile.check")(function* ( + method: string, + nativeId: string | undefined, + fix: boolean, + ) { + const threadId = nativeId === undefined ? undefined : known.get(nativeId); + if (nativeId === undefined || threadId === undefined) { + if (!narrowed) return; + return yield* notLoadedHere(method); + } + const resolved = yield* profileStep(method, threadId, fix && !children.has(nativeId)); + yield* serverStep(method, nativeId, resolved); + }); + + /** T3's own turn: checked, then remembered so its `turn/started` is not checked again. */ + const turnStart = Effect.fn("CodexMcpProfile.turnStart")(function* (send: Send, params: unknown) { + const nativeId = stringField(params, "threadId"); + yield* check("turn/start", nativeId, true); + if (nativeId === undefined) return yield* send("turn/start", params); + starting.add(nativeId); + const response = yield* send("turn/start", params).pipe( + Effect.ensuring(Effect.sync(() => starting.delete(nativeId))), + ); + const turnId = stringField(isRecord(response) ? response.turn : undefined, "id"); + if (turnId !== undefined) { + ownTurns.add(turnId); + for (const oldest of ownTurns) { + if (ownTurns.size <= MAX_OWN_TURNS) break; + ownTurns.delete(oldest); + } + } + return response; + }); + + /** + * A UI call to one of the thread's MCP servers (MCP Apps), or an elicitation one asks for: refused + * when the thread's profile leaves the server out, or when T3 cannot tell the thread's profile + * while a narrower one is in use. Read now, not at the turn: no turn runs it. + */ + const guardServer = Effect.fn("CodexMcpProfile.guardServer")(function* ( + method: string, + nativeId: string | undefined, + server: string | undefined, + ) { + const threadId = nativeId === undefined ? undefined : known.get(nativeId); + const named = server === undefined ? "an MCP server" : `MCP server "${server}"`; + if (threadId === undefined) { + if (!narrowed) return; + return yield* refusal( + method, + new ClaudeMcpProfileError({ + reason: `T3 did not load this Codex thread itself, so it cannot tell which MCP servers the thread may use, and refused this request to ${named}: ${FIX}.`, + }), + ); + } + const resolved = yield* profileOf(method, threadId); + const kept = resolved.profile.servers; + if (kept === "all") return; + if (server !== undefined && (carriedBy(nativeId).has(server) || kept.includes(server))) return; + return yield* refusal( + method, + new ClaudeMcpProfileError({ + reason: `${named[0]!.toUpperCase()}${named.slice(1)} is not in this thread's MCP profile "${resolved.name}", so T3 refused this request to it: ${FIX}.`, + }), + ); + }); + /** Model work Codex starts on a thread at this request; a paused goal starts none. */ - const startsWork = (method: string, params: unknown) => - method === "turn/start" || - (method === "thread/goal/set" && stringField(params, "status") !== "paused"); + const setsGoal = (method: string, params: unknown) => + method === "thread/goal/set" && stringField(params, "status") !== "paused"; const intercept = (send: Send): Send => (method, params) => LOADS.has(method) ? load(send, method, params) - : startsWork(method, params) - ? check(method, params).pipe(Effect.andThen(send(method, params))) - : send(method, params); + : method === "turn/start" + ? turnStart(send, params) + : setsGoal(method, params) + ? // The goal's turn fixes the set as it starts; a turn may still be running now. + check(method, stringField(params, "threadId"), false).pipe( + Effect.andThen(send(method, params)), + ) + : SERVER_CALLS.has(method) + ? guardServer( + method, + stringField(params, "threadId") ?? undefined, + stringField(params, "server"), + ).pipe(Effect.andThen(send(method, params))) + : send(method, params); + + /** A refused turn Codex started is stopped: its goal paused, then the turn interrupted. */ + const stop = (nativeId: string, turnId: string) => (error: CodexError.CodexAppServerError) => + Effect.gen(function* () { + stoppedTurns.set(turnId, `${STOPPED}. ${reasonOf(error)}`); + const raw = client.raw.request as unknown as Send; + yield* raw("thread/goal/set", { threadId: nativeId, status: "paused" }).pipe(Effect.ignore); + yield* raw("turn/interrupt", { threadId: nativeId, turnId }).pipe(Effect.ignore); + }); /** - * A turn Codex started on its own (a goal's next turn) never passed `turn/start`, so every turn - * that starts is checked again; one the check refuses is stopped: its goal is paused (so Codex - * starts no next one) and the turn interrupted, and it ends failed with the reason. + * A turn on a Codex thread T3 has not seen, while a narrower profile is in use: counted as a + * sub-agent's when Codex names a parent T3 knows, or T3 sees the spawn within a short wait, and + * checked as one; otherwise stopped. */ - const watchTurn = (threadId: string, turnId: string) => - (known.has(threadId) - ? check("turn/started", { threadId }).pipe(Effect.asVoid) - : Effect.void - ).pipe( - Effect.catch((error) => - Effect.gen(function* () { - stoppedTurns.set(turnId, `${STOPPED}. ${reasonOf(error)}`); - const raw = client.raw.request as unknown as Send; - yield* raw("thread/goal/set", { threadId, status: "paused" }).pipe(Effect.ignore); - yield* raw("turn/interrupt", { threadId, turnId }).pipe(Effect.ignore); - }), - ), - Effect.forkIn(scope, { startImmediately: true }), - Effect.asVoid, - ); + const adoptOrStop = Effect.fn("CodexMcpProfile.adoptOrStop")(function* (nativeId: string) { + yield* adoptByRead(nativeId); + for (let waited = 0; !known.has(nativeId) && waited < CODEX_ADOPT_WAIT_MS;) { + yield* Effect.sleep(ADOPT_POLL_MS); + waited += ADOPT_POLL_MS; + } + if (!known.has(nativeId)) return yield* notLoadedHere("turn/started"); + yield* check("turn/started", nativeId, false); + }); + + /** + * A turn Codex started itself (a goal's, a sub-agent's) is checked as it starts; a refused one is + * stopped (goal paused, turn interrupted). While a thread's own such turn fixes its set, T3's MCP + * server holds the thread's requests (mcpT3ToolRule.ts), so its first T3 tool call has that set. + */ + const watchTurn = (nativeId: string, turnId: string) => + Effect.suspend(() => { + if (ownTurns.delete(turnId) || starting.has(nativeId)) return Effect.void; + const threadId = known.get(nativeId); + if (threadId === undefined) { + if (!narrowed) return Effect.void; + return adoptOrStop(nativeId).pipe( + Effect.catch(stop(nativeId, turnId)), + Effect.forkIn(scope, { startImmediately: true }), + Effect.asVoid, + ); + } + const own = !children.has(nativeId); + // Held inside the check, which starts before this handler returns, and released however it + // ends: a closed scope never starts it, so no hold is left. Only the profile step is held; + // T3's tools carry the new set while the server step runs. + const held = own + ? Effect.acquireUseRelease( + Effect.flatMap(Clock.currentTimeMillis, (now) => + Effect.sync(() => holdT3ToolSet(threadId, now)), + ), + () => profileStep("turn/started", threadId, own), + (release) => Effect.sync(release), + ) + : profileStep("turn/started", threadId, own); + return held.pipe( + Effect.flatMap((resolved) => serverStep("turn/started", nativeId, resolved)), + Effect.catch(stop(nativeId, turnId)), + Effect.forkIn(scope, { startImmediately: true }), + Effect.asVoid, + ); + }); yield* client.handleServerNotification("turn/started", (payload) => watchTurn(payload.threadId, payload.turn.id), ); @@ -377,15 +599,13 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* | CodexSchema.V2ItemCompletedNotification["item"], parent: string, ) => { - const threadId = known.get(parent); - if (threadId === undefined) return; - const children = + const found = payload.type === "collabAgentToolCall" ? payload.receiverThreadIds : payload.type === "subAgentActivity" ? [payload.agentThreadId] : []; - for (const child of children) if (!known.has(child)) known.set(child, threadId); + for (const child of found) adopt(child, parent); }; yield* client.handleServerNotification("item/started", (payload) => Effect.sync(() => adoptChildren(payload.item, payload.threadId)), @@ -404,6 +624,35 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* return { ...payload, turn: { ...payload.turn, status: "failed", error: { message: reason } } }; }; + /** + * Codex asks before an MCP server's elicitation (also its approval of an MCP tool call, when the + * approval policy asks): one from a server outside the thread's profile is declined. + */ + const declineOutside = + ( + handler: ( + payload: CodexSchema.McpServerElicitationRequestParams, + ) => Effect.Effect< + CodexSchema.McpServerElicitationRequestResponse, + CodexError.CodexAppServerError + >, + ) => + (payload: CodexSchema.McpServerElicitationRequestParams) => + guardServer(ELICITATION, payload.threadId, payload.serverName).pipe( + Effect.matchEffect({ + onFailure: (error) => + Effect.logWarning("MCP profiles: declined an MCP elicitation", { + serverName: payload.serverName, + reason: reasonOf(error), + }).pipe( + Effect.as({ + action: "decline", + } satisfies CodexSchema.McpServerElicitationRequestResponse), + ), + onSuccess: () => handler(payload), + }), + ); + const wrapped: Client = { ...client, request: intercept(client.request as unknown as Send) as unknown as Client["request"], @@ -413,6 +662,10 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* client.raw.request as unknown as Send, ) as unknown as Client["raw"]["request"], }, + handleServerRequest: ((method: string, handler: never) => + method === ELICITATION + ? client.handleServerRequest(ELICITATION, declineOutside(handler)) + : client.handleServerRequest(method as never, handler)) as Client["handleServerRequest"], handleServerNotification: (method, handler) => method === "turn/completed" ? client.handleServerNotification("turn/completed", (payload) => @@ -425,6 +678,29 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* return wrapped; }); +/** Waits between reads of a thread the store did not give yet (a projection still catching up). */ +const STORE_LAG_WAITS = ["250 millis", "500 millis", "1 second"] as const; + +/** + * `profileFor` that reads a thread the store does not have again a few times before it refuses: + * Codex asks for a thread's profile as T3 creates it, which can be before the store has the row. + * Any other refusal, and the last, stands. + */ +export const afterStoreLag = + (profileFor: ProfileById): ProfileById => + (threadId) => { + const attempt = ( + waits: ReadonlyArray<(typeof STORE_LAG_WAITS)[number]>, + ): ReturnType => + profileFor(threadId).pipe( + Effect.catchIf( + (error) => waits.length > 0 && isNotInStore(error), + () => Effect.sleep(waits[0]!).pipe(Effect.andThen(attempt(waits.slice(1)))), + ), + ); + return attempt(STORE_LAG_WAITS); + }; + /** * CodexAdapterV2's client factory with each app-server's client wrapped in * {@link withCodexMcpProfiles}; spread over the adapter's options, so its key replaces theirs. @@ -434,7 +710,7 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* export const profiledClientFactory = Effect.fn("CodexMcpProfile.clientFactory")(function* ( factory: CodexAppServerClientFactoryShape, ) { - const profileFor = yield* makeThreadMcpProfilesById; + const profileFor = afterStoreLag(yield* makeThreadMcpProfilesById); const clientFactory: CodexAppServerClientFactoryShape = { open: (input) => factory diff --git a/apps/server/src/fork/mcpProfile.ts b/apps/server/src/fork/mcpProfile.ts index 8f2e2a993f83c..b5f3221492021 100644 --- a/apps/server/src/fork/mcpProfile.ts +++ b/apps/server/src/fork/mcpProfile.ts @@ -2,7 +2,7 @@ * Fork: which MCP profile a thread gets. The pure resolver lives in * packages/contracts/src/mcpProfileResolve.ts (re-exported here). This file keeps what only the * server needs: each T3 toolkit's group and the drivers that apply a profile's outside servers. - * The adapters, the turn check and the T3 tool filter (mcpT3ToolFilter.ts) use it. + * The adapters, the turn check and the T3 tool filter (mcpT3ToolRule.ts) use it. */ import { MCP_BUILTIN_TOOLS_NONE, @@ -34,7 +34,7 @@ export { /** * Each T3 toolkit's group, by its folder under src/mcp/toolkits; `null` for a toolkit that holds - * only tools of `MCP_T3_UNGROUPED_TOOLS`. The T3 tool filter (mcpT3ToolFilter.ts) uses it. The test + * only tools of `MCP_T3_UNGROUPED_TOOLS`. The T3 tool filter (mcpT3ToolRule.ts) uses it. The test * in personOnlySettings.test.ts fails when a toolkit or tool maps to nothing. */ export const MCP_T3_TOOLKIT_GROUPS: Readonly> = { @@ -113,7 +113,7 @@ export function mcpT3ToolGroup( * The drivers that apply a profile's outside servers: Claude (fork/claudeMcpProfile.ts) and Codex * (fork/codexMcpProfile.ts). Any other provider would give a thread every outside MCP server, so a * turn there whose profile leaves one out is refused as it starts (fork/mcpProfileTurnCheck.ts). - * T3 tool groups apply on every driver (mcpT3ToolFilter.ts). + * T3 tool groups apply on every driver (mcpT3ToolRule.ts). */ export const MCP_PROFILE_DRIVERS: ReadonlySet = new Set([ ProviderDriverKind.make("claudeAgent"), diff --git a/apps/server/src/fork/mcpProfileTurnCheck.test.ts b/apps/server/src/fork/mcpProfileTurnCheck.test.ts index deda7cd259c9f..8253c040d84d7 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.test.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.test.ts @@ -41,6 +41,7 @@ import * as ServerSettingsService from "../serverSettings.ts"; import * as ForkLayers from "./forkLayers.ts"; import { MCP_PROFILE_DRIVERS } from "./mcpProfile.ts"; import * as T3ToolSets from "./mcpT3ToolSets.ts"; +import { CurrentTurnMcpProfile } from "./mcpTurnProfile.ts"; /** The groups the thread's set holds now, or its tag when it is not a list. */ const groupsOf = (threadId: string) => { @@ -74,11 +75,20 @@ type Mcp = Partial< /** What each provider's session was asked to do, in order: `start:thread`, `resume:…`, `compact:…`. */ type Calls = Array; +/** The profile each recorded call was given to read (`thread:name`), in order. */ +const turnProfiles: Array = []; + /** A provider instance whose sessions only record their calls; enough for the check. */ const fakeInstance = (instanceId: ProviderInstanceId, calls: Calls): ProviderInstance => { const driver = DRIVERS[instanceId]!; const record = (kind: string) => (input: { readonly threadId: ThreadId }) => - Effect.sync(() => void calls.push(`${kind}:${instanceId}:${input.threadId}`)); + Effect.gen(function* () { + calls.push(`${kind}:${instanceId}:${input.threadId}`); + const current = yield* CurrentTurnMcpProfile; + turnProfiles.push( + current === undefined ? undefined : `${current.threadId}:${current.resolved.name}`, + ); + }); return { instanceId, driverKind: driver, @@ -366,6 +376,8 @@ describe("mcpProfileTurnCheck", () => { "resume:codex:own", "compact:codex:own", ]); + // Codex's own checks read this profile, not work it out again. + assert.deepStrictEqual(turnProfiles.slice(-3), ["own:lean", "own:lean", "own:lean"]); }), ), ); diff --git a/apps/server/src/fork/mcpProfileTurnCheck.ts b/apps/server/src/fork/mcpProfileTurnCheck.ts index 850c133c3b71c..3f5f895f36fcc 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.ts @@ -1,5 +1,5 @@ /** - * Fork: each turn start fixes the thread's T3 tool groups (mcpT3ToolFilter.ts) on every driver but + * Fork: each turn start fixes the thread's T3 tool groups (mcpT3ToolRule.ts) on every driver but * Claude. It refuses outside `MCP_PROFILE_DRIVERS` when the profile leaves out an outside server, and * on every wrapped driver for `builtinTools: "none"` or a profile that cannot be worked out. */ @@ -23,6 +23,7 @@ import { builtinToolsNoneRefusal, } from "./mcpProfile.ts"; import { fixT3ToolSet, forgetT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; +import { CurrentTurnMcpProfile } from "./mcpTurnProfile.ts"; type ProfileFor = Effect.Success; /** What a turn start, and a resume, are given that the check reads. */ @@ -79,7 +80,7 @@ const refusalReason = (resolved: McpProfileResolved, instance: ProviderInstance) * Fixes the thread's T3 tool groups for this turn, then nothing when the driver applies outside * servers itself (Codex) or the profile keeps every one; otherwise the refusal. A profile that * cannot be worked out refuses with the resolver's reason, as it does on Claude, and keeps only the - * tools every profile keeps. + * tools every profile keeps. Returns the profile, so the turn reads it once. */ const checkTurnProfile = Effect.fn("McpProfileTurnCheck.check")(function* ( profileFor: ProfileFor, @@ -99,7 +100,9 @@ const checkTurnProfile = Effect.fn("McpProfileTurnCheck.check")(function* ( reason: builtinToolsNoneRefusal(resolved.name, instance.driverKind), }); } - if (appliesMcpProfiles(instance.driverKind) || resolved.profile.servers === "all") return; + if (appliesMcpProfiles(instance.driverKind) || resolved.profile.servers === "all") { + return resolved; + } return yield* new ClaudeMcpProfileError({ reason: refusalReason(resolved, instance) }); }); @@ -123,7 +126,18 @@ const makeWrap = (profileFor: ProfileFor) => { cause, }), ), - Effect.andThen(run(input)), + // The driver's own checks (Codex's) read this profile rather than work it out again. It is + // keyed by thread, not turn, so it assumes nothing forked here outlives this turn start: + // a fiber that did would hand this turn's profile to a later turn of the thread (wider, + // after a narrowing). Fork long-lived work from the session (openSession), never here. + Effect.flatMap((resolved) => + run(input).pipe( + Effect.provideService(CurrentTurnMcpProfile, { + threadId: input.appThread.id, + resolved, + }), + ), + ), ); return (instance: ProviderInstance): ProviderInstance => { if (FIXES_OWN_T3_TOOL_SETS.has(instance.driverKind)) return instance; diff --git a/apps/server/src/fork/mcpT3ToolFilter.test.ts b/apps/server/src/fork/mcpT3ToolFilter.test.ts index e7a750d37f79b..01a04c3092dc6 100644 --- a/apps/server/src/fork/mcpT3ToolFilter.test.ts +++ b/apps/server/src/fork/mcpT3ToolFilter.test.ts @@ -17,9 +17,13 @@ import { ThreadId, } from "@t3tools/contracts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import { HttpBody, HttpClient, HttpRouter } from "effect/http"; import { describe } from "vite-plus/test"; @@ -43,6 +47,7 @@ import * as ServerSettingsService from "../serverSettings.ts"; import { Waits } from "../waits/WaitWorker.ts"; import { makeClaudeMcpProfiles } from "./claudeMcpProfile.ts"; import * as McpT3ToolFilter from "./mcpT3ToolFilter.ts"; +import * as McpT3ToolRule from "./mcpT3ToolRule.ts"; import * as T3ToolSets from "./mcpT3ToolSets.ts"; const ENVIRONMENT = EnvironmentId.make("environment-t3-tool-groups"); @@ -141,7 +146,7 @@ const serverLayer = (shared: Layer.Layer) => { McpHttpServer.layerPullRequestsToolkit, McpHttpServer.layerForkTools, McpHttpServer.layerToolSearch, - McpT3ToolFilter.layer, + McpT3ToolRule.layer, ), ).pipe( Layer.provide( @@ -211,6 +216,7 @@ const withServer = ( Effect.scoped( Effect.gen(function* () { T3ToolSets.__testing.clear(); + McpT3ToolRule.__testing.clearRefused(); listed = 0; const shared = yield* Layer.build(sharedLayer(settings)); const store = yield* ProjectionStore.ProjectionStoreV2.pipe(Effect.provide(shared)); @@ -296,10 +302,10 @@ describe("the T3 tool filter on /mcp", () => { const waits = yield* list("waits"); expect(grouped(waits)).toEqual({ waits: WAIT_TOOLS, prs: false }); const inWaits = (name: string) => - ["waits", "ungrouped"].includes(McpT3ToolFilter.T3_TOOL_GROUPS.get(name) ?? ""); + ["waits", "ungrouped"].includes(McpT3ToolRule.T3_TOOL_GROUPS.get(name) ?? ""); expect(waits).toEqual(all.filter(inWaits)); // `playtest` lives in the waits toolkit but has its own group: keeping `waits` hides it. - expect(McpT3ToolFilter.T3_TOOL_GROUPS.get("playtest")).toBe("playtest"); + expect(McpT3ToolRule.T3_TOOL_GROUPS.get("playtest")).toBe("playtest"); expect(all).toContain("playtest"); expect(waits).not.toContain("playtest"); expect(grouped(yield* list("none"))).toEqual({ waits: [], prs: false }); @@ -447,10 +453,10 @@ describe("the T3 tool filter on /mcp", () => { expect(grouped(yield* list("prs"))).toEqual({ waits: [], prs: true }); // The next turn starts (Claude's query opens): the new set from then on. const plan = yield* makeClaudeMcpProfiles; - yield* plan(STORED[1]!, {}); + void (yield* plan(STORED[1]!, {})).options; expect(grouped(yield* list("prs"))).toEqual({ waits: WAIT_TOOLS, prs: false }); // Runs again: a second turn start with the same settings gives the same set. - yield* plan(STORED[1]!, {}); + void (yield* plan(STORED[1]!, {})).options; expect(grouped(yield* list("prs"))).toEqual({ waits: WAIT_TOOLS, prs: false }); // A restart loses the memory: the set is worked out again from the settings as they are. yield* settings.updateSettings({ mcpThreadProfiles: { "thread-prs": "prs" } } as never); @@ -461,6 +467,84 @@ describe("the T3 tool filter on /mcp", () => { ); }); +/** Moves test time on by `millis` (each sleep in turn wakes), then joins the fiber. */ +const drive = (fiber: Fiber.Fiber, millis: number) => + TestClock.adjust(millis).pipe(Effect.andThen(Fiber.join(fiber))); + +describe("a set worked out by a request, not a turn (fork issues #812, #918)", () => { + it.effect("a refused set is not remembered: it is reused briefly, then worked out again", () => + withServer(({ list }) => + Effect.gen(function* () { + expect(grouped(yield* list("gone"))).toEqual({ waits: [], prs: false }); + // Not the thread's set: the next turn, or the next request after a moment, works it out. + expect(T3ToolSets.t3ToolSetFor("thread-gone")).toBeUndefined(); + const settings = yield* ServerSettingsService.ServerSettingsService; + yield* settings.updateSettings({ + mcpProfiles: { ...SETTINGS.mcpProfiles, gone: { servers: "all", t3Tools: ["waits"] } }, + } as never); + // Reused for a moment, so a list request does not read the settings once per tool. + expect(grouped(yield* list("gone"))).toEqual({ waits: [], prs: false }); + yield* TestClock.adjust(McpT3ToolRule.REFUSED_SET_REUSE_MS + 1); + expect(grouped(yield* list("gone"))).toEqual({ waits: WAIT_TOOLS, prs: false }); + }), + ), + ); + + it.effect("while a turn's set is being fixed, a request waits for it", () => + withServer(({ list }) => + Effect.gen(function* () { + const release = T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + const listing = yield* Effect.forkChild(list("prs")); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + expect(listing.pollUnsafe()).toBeUndefined(); + // The turn's check fixes the thread's new set, then releases: the request gets that one. + T3ToolSets.fixT3ToolSet("thread-prs", { + _tag: "Groups", + name: "waits", + groups: new Set(["waits"]), + }); + release(); + release(); + expect(grouped(yield* Fiber.join(listing))).toEqual({ waits: WAIT_TOOLS, prs: false }); + expect(T3ToolSets.__testing.asked("thread-prs")).toBeUndefined(); + }), + ), + ); + + it.effect("a hold never released: the request is refused, not given the set before", () => + withServer(({ call }) => + Effect.gen(function* () { + T3ToolSets.fixT3ToolSet("thread-all", { _tag: "Groups", name: "all", groups: "all" }); + T3ToolSets.holdT3ToolSet("thread-all", yield* Clock.currentTimeMillis); + const calling = yield* Effect.forkChild(call("all", "wait_list")); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-all")!); + const refused = yield* drive(calling, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS); + expect(refused.error?.code).toBe(-32001); + expect(refused.error?.message).toContain("still working out this thread's MCP profile"); + expect(listed).toBe(0); + }), + ), + ); +}); + +describe("the module upstream's tool_search imports (fork issue #812)", () => { + it.effect("imports no toolkit, profile resolver or store", () => + Effect.promise(async () => { + const { readFile } = await import("node:fs/promises"); + const text = await readFile(new URL("./mcpT3ToolFilter.ts", import.meta.url), "utf8"); + const specifiers = [...text.matchAll(/^import[^;]*?from "([^"]+)";/gms)].map( + (match) => match[1], + ); + expect(specifiers).toEqual([ + "effect/Context", + "effect/Effect", + "effect/Fiber", + "../mcp/McpInvocationContext.ts", + ]); + }), + ); +}); + describe("tool_search's filter", () => { const searchable = (name: string) => Effect.sync(() => McpT3ToolFilter.searchableT3Tool({ name })).pipe( @@ -488,14 +572,14 @@ describe("tool_search's filter", () => { describe("the T3 tool table", () => { it.effect("names every tool the server registers, each in one group", () => Effect.sync(() => { - const unknown = [...McpT3ToolFilter.T3_TOOL_GROUPS].filter( + const unknown = [...McpT3ToolRule.T3_TOOL_GROUPS].filter( ([, group]) => group === "not-allowed", ); expect(unknown).toEqual([]); - expect(McpT3ToolFilter.T3_TOOL_GROUPS.get("wait_list")).toBe("waits"); - expect(McpT3ToolFilter.T3_TOOL_GROUPS.get("request_secret")).toBe("ungrouped"); - expect(McpT3ToolFilter.T3_TOOL_GROUPS.get("send_to_user")).toBe("ungrouped"); - expect(McpT3ToolFilter.T3_TOOL_GROUPS.get("tool_search")).toBe("ungrouped"); + expect(McpT3ToolRule.T3_TOOL_GROUPS.get("wait_list")).toBe("waits"); + expect(McpT3ToolRule.T3_TOOL_GROUPS.get("request_secret")).toBe("ungrouped"); + expect(McpT3ToolRule.T3_TOOL_GROUPS.get("send_to_user")).toBe("ungrouped"); + expect(McpT3ToolRule.T3_TOOL_GROUPS.get("tool_search")).toBe("ungrouped"); }), ); }); @@ -505,13 +589,13 @@ describe("the refusal of a tool in no group", () => { Effect.sync(() => { const set: T3ToolSets.T3ToolSet = { _tag: "Groups", name: "prs", groups: new Set(["waits"]) }; for (const name of ["orphan_tool", "send_to_user_in_a_new_toolkit"]) { - const message = McpT3ToolFilter.__testing.t3ToolRefusal(set, name); + const message = McpT3ToolRule.__testing.t3ToolRefusal(set, name); expect(message).toBe( `T3 refused "${name}": this tool has no T3 tool group, so MCP profile "prs" cannot keep it. This is a T3 bug, not a setting to change: report it.`, ); } // A tool in a group still gets the group and its fix. - expect(McpT3ToolFilter.__testing.t3ToolRefusal(set, "list_thread_pull_requests")).toContain( + expect(McpT3ToolRule.__testing.t3ToolRefusal(set, "list_thread_pull_requests")).toContain( 'Ask the user to add "pull-requests" to that profile\'s t3Tools', ); }), @@ -550,3 +634,76 @@ describe("the T3 tool sets in memory", () => { }), ); }); + +describe("the hold bound, without a socket (fork issue #918)", () => { + /** The rule's check of `targets`, one after another as upstream's list filter runs it. */ + const checkAll = ( + token: string, + method: "tools/list" | "tools/call", + targets: ReadonlyArray, + ) => + Effect.gen(function* () { + const visible = yield* McpT3ToolRule.__testing.makeVisible; + return yield* Effect.forEach(targets, (target) => + visible({ method, target } as never).pipe( + Effect.orElseSucceed(() => false), + Effect.map((shown) => [target, shown] as const), + ), + ); + }).pipe(Effect.provideService(McpInvocationContext.McpInvocationContext, scopeFor(token))); + + const prs: T3ToolSets.T3ToolSet = { + _tag: "Groups", + name: "prs", + groups: new Set(["pull-requests"]), + }; + + it.effect("tools/list waits once for the hold, not once per tool", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + McpT3ToolRule.__testing.clearRefused(); + T3ToolSets.fixT3ToolSet("thread-prs", prs); + expect(yield* checkAll("prs", "tools/list", [PR_TOOL])).toEqual([[PR_TOOL, true]]); + T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + const listing = yield* Effect.forkChild( + checkAll("prs", "tools/list", [...WAIT_TOOLS, PR_TOOL]), + ); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + yield* TestClock.adjust(McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS); + for (let turn = 0; turn < 10; turn += 1) yield* Effect.yieldNow; + // One wait for the whole list, then it is refused: never the set from before the hold. + const done = listing.pollUnsafe(); + expect(done).toBeDefined(); + expect(yield* Fiber.join(listing)).toEqual( + [...WAIT_TOOLS, PR_TOOL].map((name) => [name, false]), + ); + }), + ); + + it.effect( + "a hold past its bound is dropped: later requests do not wait, later turns start fresh", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + McpT3ToolRule.__testing.clearRefused(); + T3ToolSets.fixT3ToolSet("thread-prs", prs); + T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + const first = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + expect(yield* drive(first, McpT3ToolRule.T3_TOOL_SET_HOLD_WAIT_MS)).toEqual([ + [PR_TOOL, false], + ]); + // Dropped: the next request does not wait 10 s again, and it keeps only the ungrouped tools + // (never the set from before the hold) until a turn fixes the thread's set. + expect(T3ToolSets.__testing.asked("thread-prs")).toBeUndefined(); + expect(yield* checkAll("prs", "tools/call", [PR_TOOL])).toEqual([[PR_TOOL, false]]); + // The next turn's hold starts fresh, and its check's set applies once it releases. + const release = T3ToolSets.holdT3ToolSet("thread-prs", yield* Clock.currentTimeMillis); + const second = yield* Effect.forkChild(checkAll("prs", "tools/call", [PR_TOOL])); + yield* Deferred.await(T3ToolSets.__testing.asked("thread-prs")!); + T3ToolSets.fixT3ToolSet("thread-prs", prs); + release(); + expect(yield* Fiber.join(second)).toEqual([[PR_TOOL, true]]); + }), + ); +}); diff --git a/apps/server/src/fork/mcpT3ToolFilter.ts b/apps/server/src/fork/mcpT3ToolFilter.ts index 619b56b641ec1..e0fe801cefd48 100644 --- a/apps/server/src/fork/mcpT3ToolFilter.ts +++ b/apps/server/src/fork/mcpT3ToolFilter.ts @@ -1,127 +1,38 @@ /** - * Fork: the MCP profile's T3 tool groups on T3's own MCP server, so for every provider. One global - * rule hides a T3 tool outside the calling thread's groups from `tools/list`, refuses it on - * `tools/call` and keeps it out of `tool_search`; like upstream's `requiresCapability` (open PR). + * Fork: `tool_search`'s MCP profile filter, the one name McpToolExposure.ts imports. Kept light on + * purpose: it imports no toolkit, profile resolver or store, so the upstream + * module that imports it pulls in none of them. The global rule (mcpT3ToolRule.ts, installed in + * McpHttpServer's `layer`) installs the check this filter asks. */ -import { MCP_T3_UNGROUPED_TOOLS, type McpT3ToolGroup, type ThreadId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as Context from "effect/Context"; -import * as SqlClient from "effect/sql/SqlClient"; -// oxlint-disable-next-line t3code/no-raw-mcp-registration -- A visibility rule registers no tool: it only narrows what McpHttpServer registered. -import { McpSchema, McpServer } from "effect/ai"; import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; -import * as ServerSettingsService from "../serverSettings.ts"; -import { AttachmentToolkit } from "../mcp/toolkits/attachment/tools.ts"; -import { DeviceToolkit } from "../mcp/toolkits/device/tools.ts"; -import { EnvironmentToolkit } from "../mcp/toolkits/environment/tools.ts"; -import { HtmlToolkit } from "../mcp/toolkits/html/tools.ts"; -import { IssuesToolkit } from "../mcp/toolkits/issues/tools.ts"; -import { MessageToolkit } from "../mcp/toolkits/message/tools.ts"; -import { OrchestratorToolkit } from "../mcp/toolkits/orchestrator/tools.ts"; -import { PreviewToolkit } from "../mcp/toolkits/preview/tools.ts"; -import { PreviewControlsToolkit } from "../mcp/toolkits/previewControls/tools.ts"; -import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; -import { PullRequestsToolkit } from "../mcp/toolkits/pullRequests/tools.ts"; -import { ThemeToolkit } from "../mcp/toolkits/theme/tools.ts"; -import { ThreadToolkit } from "../mcp/toolkits/thread/tools.ts"; -import { WaitsToolkit } from "../mcp/toolkits/waits/tools.ts"; -import { WorktreeToolkit } from "../mcp/toolkits/worktree/tools.ts"; -import { makeThreadMcpProfilesById } from "./claudeMcpProfile.ts"; -import { MCP_T3_TOOL_NOT_ALLOWED, mcpT3ToolGroup } from "./mcpProfile.ts"; -import { - type T3ToolSet, - refusedT3ToolSet, - rememberT3ToolSet, - t3ToolSetFor, - t3ToolSetOf, -} from "./mcpT3ToolSets.ts"; -type ToolGroup = McpT3ToolGroup | "ungrouped" | typeof MCP_T3_TOOL_NOT_ALLOWED; - -/** - * Each toolkit the server registers, by its folder under src/mcp/toolkits (`toolSearch`'s one tool - * is ungrouped by name: importing it would loop through McpToolExposure). Kept by hand, so - * personOnlySettings.test.ts fails when the table differs from the folders' toolkits by one tool. - */ -const TOOLKITS: ReadonlyArray = [ - ["attachment", AttachmentToolkit], - ["device", DeviceToolkit], - ["environment", EnvironmentToolkit], - ["html", HtmlToolkit], - ["issues", IssuesToolkit], - ["message", MessageToolkit], - ["orchestrator", OrchestratorToolkit], - ["preview", PreviewToolkit], - ["previewControls", PreviewControlsToolkit], - ["project", ProjectToolkit], - ["pullRequests", PullRequestsToolkit], - ["theme", ThemeToolkit], - ["thread", ThreadToolkit], - ["waits", WaitsToolkit], - ["worktree", WorktreeToolkit], -]; +/** True when the thread may see and call the T3 tool `name`. */ +export type T3ToolSearchCheck = (threadId: string, name: string) => boolean; -const TOOL_SEARCH = "tool_search"; +/** The check the rule installed, and on how many servers; none installed: every tool passes. */ +let check: T3ToolSearchCheck | undefined; +let installed = 0; /** - * Every T3 tool's group, by its name. A name two toolkits give different groups is in none this - * version knows, so a profile narrower than `all` refuses it (the test keeps there being none). + * Installs the rule's check for the scope's life: one per server the rule is on (every one installs + * the same check). The filter passes every tool again once the last one is gone. */ -export const T3_TOOL_GROUPS: ReadonlyMap = (() => { - const groups = new Map([ - [TOOL_SEARCH, mcpT3ToolGroup("toolSearch", TOOL_SEARCH)], - ]); - for (const [folder, toolkit] of TOOLKITS) { - for (const name of Object.keys(toolkit.tools)) { - const group = mcpT3ToolGroup(folder, name); - const known = groups.get(name); - groups.set(name, known === undefined || known === group ? group : MCP_T3_TOOL_NOT_ALLOWED); - } - } - return groups; -})(); - -/** True when the set lets the thread see and call the T3 tool `name`. */ -function t3ToolAllowed(set: T3ToolSet, name: string): boolean { - // `all` is today's behaviour: every tool, also one this table does not know. - if (set._tag === "Groups" && set.groups === "all") return true; - const group = T3_TOOL_GROUPS.get(name); - // The tools every profile keeps, matched by name and by the toolkit they are in. - if (group === "ungrouped") return MCP_T3_UNGROUPED_TOOLS.includes(name); - if (set._tag === "Refused" || set.groups === "all") return false; - return group !== undefined && group !== MCP_T3_TOOL_NOT_ALLOWED && set.groups.has(group); -} - -/** Why the call was refused, in plain words, with what fixes it. */ -function t3ToolRefusal(set: T3ToolSet, name: string): string { - const group = T3_TOOL_GROUPS.get(name); - if (set._tag === "Refused") { - return `T3 refused "${name}": this thread's MCP profile cannot be applied, so it keeps only the T3 tools every profile keeps (${MCP_T3_UNGROUPED_TOOLS.join(", ")}). The reason: ${set.reason}`; - } - if (group === undefined || group === "ungrouped" || group === MCP_T3_TOOL_NOT_ALLOWED) { - // Fail closed, but name the real cause: no profile setting can add a tool with no group. (A - // name the server does not have never gets here: upstream refuses it before this rule.) - return `T3 refused "${name}": this tool has no T3 tool group, so MCP profile "${set.name}" cannot keep it. This is a T3 bug, not a setting to change: report it.`; - } - return `T3 refused "${name}": it is in the "${group}" T3 tool group, which this thread's MCP profile "${set.name}" leaves out. Ask the user to add "${group}" to that profile's t3Tools in Settings, or to pick a profile that has it for this thread; it applies from the thread's next turn.`; -} - -/** The JSON-RPC error a refused call gets; its message is the plain reason. */ -class T3ToolOutsideProfile extends Schema.Error("T3ToolOutsideProfile")({ - ...McpSchema.McpErrorBase.fields, - _tag: Schema.tag("T3ToolOutsideProfile"), - code: Schema.tag(-32001), -}) {} - -const callerThread = (scope: Option.Option) => - Option.getOrUndefined(scope)?.thread; - -/** Servers in this process the rule is installed on; `tool_search` follows it only there. */ -let installed = 0; +export const installT3ToolSearchCheck = (allowed: T3ToolSearchCheck) => + Effect.acquireRelease( + Effect.sync(() => { + installed += 1; + check = allowed; + }), + () => + Effect.sync(() => { + installed -= 1; + if (installed === 0) check = undefined; + }), + ); /** * `tool_search`'s filter: false for a tool the calling thread's set leaves out (none set: only the @@ -129,60 +40,12 @@ let installed = 0; * inside a request: outside one, and on a server without the rule, it lets every tool through. */ export const searchableT3Tool = (tool: { readonly name: string }): boolean => { - if (installed === 0) return true; + const allowed = check; + if (allowed === undefined) return true; const fiber = Fiber.getCurrent(); const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext.McpInvocationContext); const thread = scope?.thread; if (thread === undefined) return true; - const set = - t3ToolSetFor(thread.threadId) ?? - refusedT3ToolSet("no MCP profile was worked out for this thread yet."); - return t3ToolAllowed(set, tool.name); + return allowed(thread.threadId, tool.name); }; - -/** - * The global rule: on `tools/list` it hides, on `tools/call` it refuses, a T3 tool the calling - * thread's set leaves out. Other methods (T3 serves no resources or prompts) pass. - */ -export const layer = McpServer.visibility( - Effect.gen(function* () { - // Asked for, so a server wired without them is a type error, not a rule that refuses every - // thread (no store) or reads every thread as `all` (no settings). - yield* SqlClient.SqlClient; - yield* ServerSettingsService.ServerSettingsService; - const profileById = yield* makeThreadMcpProfilesById; - yield* Effect.acquireRelease( - Effect.sync(() => void (installed += 1)), - () => Effect.sync(() => void (installed -= 1)), - ); - /** The thread's set: the one its turn fixed, else worked out now from the settings. */ - const setFor = (threadId: ThreadId) => - Effect.suspend(() => { - const fixed = t3ToolSetFor(threadId); - if (fixed !== undefined) return Effect.succeed(fixed); - return profileById(threadId).pipe( - Effect.map(t3ToolSetOf), - Effect.catchTags({ - ClaudeMcpProfileError: (refusal) => Effect.succeed(refusedT3ToolSet(refusal.reason)), - }), - Effect.map((set) => rememberT3ToolSet(threadId, set)), - ); - }); - // Untraced: it runs once per tool on every list request. - return Effect.fnUntraced(function* ({ method, target }: McpServer.MiddlewareOptions) { - if (method !== "tools/list" && method !== "tools/call") return true; - const thread = callerThread( - yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext), - ); - if (thread === undefined) return true; - const set = yield* setFor(thread.threadId); - if (t3ToolAllowed(set, target)) return true; - if (method === "tools/list") return false; - return yield* new T3ToolOutsideProfile({ message: t3ToolRefusal(set, target) }); - }); - }).pipe(Effect.withSpan("McpT3ToolFilter.make")), - { global: true }, -); - -export const __testing = { t3ToolRefusal }; diff --git a/apps/server/src/fork/mcpT3ToolRule.ts b/apps/server/src/fork/mcpT3ToolRule.ts new file mode 100644 index 0000000000000..9370c98a03661 --- /dev/null +++ b/apps/server/src/fork/mcpT3ToolRule.ts @@ -0,0 +1,236 @@ +/** + * Fork: the MCP profile's T3 tool groups, for every provider. One global rule on T3's MCP server + * hides a T3 tool outside the calling thread's groups from `tools/list`, refuses it on `tools/call` + * and keeps it out of `tool_search` (through the light filter in mcpT3ToolFilter.ts). + */ +import { MCP_T3_UNGROUPED_TOOLS, type McpT3ToolGroup, type ThreadId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Deferred from "effect/Deferred"; +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"; +// oxlint-disable-next-line t3code/no-raw-mcp-registration -- A visibility rule registers no tool: it only narrows what McpHttpServer registered. +import { McpSchema, McpServer } from "effect/ai"; + +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import * as ServerSettingsService from "../serverSettings.ts"; +import { AttachmentToolkit } from "../mcp/toolkits/attachment/tools.ts"; +import { DeviceToolkit } from "../mcp/toolkits/device/tools.ts"; +import { EnvironmentToolkit } from "../mcp/toolkits/environment/tools.ts"; +import { HtmlToolkit } from "../mcp/toolkits/html/tools.ts"; +import { IssuesToolkit } from "../mcp/toolkits/issues/tools.ts"; +import { MessageToolkit } from "../mcp/toolkits/message/tools.ts"; +import { OrchestratorToolkit } from "../mcp/toolkits/orchestrator/tools.ts"; +import { PreviewToolkit } from "../mcp/toolkits/preview/tools.ts"; +import { PreviewControlsToolkit } from "../mcp/toolkits/previewControls/tools.ts"; +import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; +import { PullRequestsToolkit } from "../mcp/toolkits/pullRequests/tools.ts"; +import { ThemeToolkit } from "../mcp/toolkits/theme/tools.ts"; +import { ThreadToolkit } from "../mcp/toolkits/thread/tools.ts"; +import { WaitsToolkit } from "../mcp/toolkits/waits/tools.ts"; +import { WorktreeToolkit } from "../mcp/toolkits/worktree/tools.ts"; +import { makeThreadMcpProfilesById } from "./claudeMcpProfile.ts"; +import { MCP_T3_TOOL_NOT_ALLOWED, mcpT3ToolGroup } from "./mcpProfile.ts"; +import { installT3ToolSearchCheck } from "./mcpT3ToolFilter.ts"; +import { + type T3ToolSet, + T3_TOOL_SET_HOLD_WAIT_MS as HOLD_WAIT_MS, + dropT3ToolSetHold, + refusedT3ToolSet, + rememberT3ToolSet, + t3ToolSetFor, + t3ToolSetHold, + t3ToolSetOf, +} from "./mcpT3ToolSets.ts"; + +type ToolGroup = McpT3ToolGroup | "ungrouped" | typeof MCP_T3_TOOL_NOT_ALLOWED; + +/** + * Each toolkit the server registers, by its folder under src/mcp/toolkits (`toolSearch`'s one tool + * is ungrouped by name: importing it would loop through McpToolExposure). Kept by hand, so + * personOnlySettings.test.ts fails when the table differs from the folders' toolkits by one tool. + */ +const TOOLKITS: ReadonlyArray = [ + ["attachment", AttachmentToolkit], + ["device", DeviceToolkit], + ["environment", EnvironmentToolkit], + ["html", HtmlToolkit], + ["issues", IssuesToolkit], + ["message", MessageToolkit], + ["orchestrator", OrchestratorToolkit], + ["preview", PreviewToolkit], + ["previewControls", PreviewControlsToolkit], + ["project", ProjectToolkit], + ["pullRequests", PullRequestsToolkit], + ["theme", ThemeToolkit], + ["thread", ThreadToolkit], + ["waits", WaitsToolkit], + ["worktree", WorktreeToolkit], +]; + +const TOOL_SEARCH = "tool_search"; + +/** + * Every T3 tool's group, by its name. A name two toolkits give different groups is in none this + * version knows, so a profile narrower than `all` refuses it (the test keeps there being none). + */ +export const T3_TOOL_GROUPS: ReadonlyMap = (() => { + const groups = new Map([ + [TOOL_SEARCH, mcpT3ToolGroup("toolSearch", TOOL_SEARCH)], + ]); + for (const [folder, toolkit] of TOOLKITS) { + for (const name of Object.keys(toolkit.tools)) { + const group = mcpT3ToolGroup(folder, name); + const known = groups.get(name); + groups.set(name, known === undefined || known === group ? group : MCP_T3_TOOL_NOT_ALLOWED); + } + } + return groups; +})(); + +/** True when the set lets the thread see and call the T3 tool `name`. */ +function t3ToolAllowed(set: T3ToolSet, name: string): boolean { + // `all` is today's behaviour: every tool, also one this table does not know. + if (set._tag === "Groups" && set.groups === "all") return true; + const group = T3_TOOL_GROUPS.get(name); + // The tools every profile keeps, matched by name and by the toolkit they are in. + if (group === "ungrouped") return MCP_T3_UNGROUPED_TOOLS.includes(name); + if (set._tag === "Refused" || set.groups === "all") return false; + return group !== undefined && group !== MCP_T3_TOOL_NOT_ALLOWED && set.groups.has(group); +} + +/** Why the call was refused, in plain words, with what fixes it. */ +function t3ToolRefusal(set: T3ToolSet, name: string): string { + const group = T3_TOOL_GROUPS.get(name); + if (set._tag === "Refused") { + return `T3 refused "${name}": this thread's MCP profile cannot be applied, so it keeps only the T3 tools every profile keeps (${MCP_T3_UNGROUPED_TOOLS.join(", ")}). The reason: ${set.reason}`; + } + if (group === undefined || group === "ungrouped" || group === MCP_T3_TOOL_NOT_ALLOWED) { + // Fail closed, but name the real cause: no profile setting can add a tool with no group. (A + // name the server does not have never gets here: upstream refuses it before this rule.) + return `T3 refused "${name}": this tool has no T3 tool group, so MCP profile "${set.name}" cannot keep it. This is a T3 bug, not a setting to change: report it.`; + } + return `T3 refused "${name}": it is in the "${group}" T3 tool group, which this thread's MCP profile "${set.name}" leaves out. Ask the user to add "${group}" to that profile's t3Tools in Settings, or to pick a profile that has it for this thread; it applies from the thread's next turn.`; +} + +/** The JSON-RPC error a refused call gets; its message is the plain reason. */ +class T3ToolOutsideProfile extends Schema.Error("T3ToolOutsideProfile")({ + ...McpSchema.McpErrorBase.fields, + _tag: Schema.tag("T3ToolOutsideProfile"), + code: Schema.tag(-32001), +}) {} + +const callerThread = (scope: Option.Option) => + Option.getOrUndefined(scope)?.thread; + +const NO_SET_YET = "no MCP profile was worked out for this thread yet."; + +/** + * How long a refused set worked out by a request (not a turn) is reused: long enough that a list + * request does not read the settings once per tool, short enough that a one-off read error does not + * last the turn. Never remembered as the thread's set. + */ +export const REFUSED_SET_REUSE_MS = 5_000; +/** Threads whose refused set is reused at once; the oldest beyond this is worked out again. */ +const MAX_REFUSED_SETS = 1024; +/** How long a turn Codex started may hold the thread's requests while its set is fixed. */ +export const T3_TOOL_SET_HOLD_WAIT_MS = HOLD_WAIT_MS; +const HOLD_TIMED_OUT = + "T3 is still working out this thread's MCP profile for the turn that just started, or that check stopped; the profile applies again once it ends or the thread's next turn starts. Try again in a moment."; + +/** Recent refused sets, by thread, with when each stops being reused. */ +const refused = new Map(); + +/** True when the set lets the thread see and call the T3 tool `name`; no fixed set: the ungrouped. */ +const searchable = (threadId: string, name: string) => + t3ToolAllowed( + t3ToolSetFor(threadId) ?? refused.get(threadId)?.set ?? refusedT3ToolSet(NO_SET_YET), + name, + ); + +/** The rule's check of one tool for one request, as {@link layer} runs it. */ +const makeVisible = Effect.gen(function* () { + const profileById = yield* makeThreadMcpProfilesById; + /** Worked out now from the settings: kept when it applies, reused briefly when refused. */ + const workedOut = Effect.fnUntraced(function* (threadId: ThreadId) { + const now = yield* Clock.currentTimeMillis; + const recent = refused.get(threadId); + if (recent !== undefined && recent.until > now) return recent.set; + const resolved = yield* profileById(threadId).pipe( + Effect.map(t3ToolSetOf), + Effect.catchTags({ + ClaudeMcpProfileError: (refusal) => Effect.succeed(refusedT3ToolSet(refusal.reason)), + }), + ); + if (resolved._tag === "Groups") { + refused.delete(threadId); + return rememberT3ToolSet(threadId, resolved); + } + // A turn may have fixed a set while this read ran: that one stands. + const fixed = t3ToolSetFor(threadId); + if (fixed !== undefined) return fixed; + refused.delete(threadId); + refused.set(threadId, { set: resolved, until: now + REFUSED_SET_REUSE_MS }); + for (const oldest of refused.keys()) { + if (refused.size <= MAX_REFUSED_SETS) break; + refused.delete(oldest); + } + return resolved; + }); + /** + * The thread's set: the one its turn fixed, else worked out now from the settings. While a turn + * Codex started is having its set fixed, wait for that set rather than use the one before. + */ + const setFor: (threadId: ThreadId) => Effect.Effect = Effect.fnUntraced(function* ( + threadId: ThreadId, + ) { + const hold = t3ToolSetHold(threadId, yield* Clock.currentTimeMillis); + if (hold !== undefined) { + // At most until the hold's bound, whichever request asks: a list request checks each tool + // in turn and only its first waits, so a hold never released costs one wait, not one per + // tool. It is then dropped, so the thread's later requests do not wait on it again. + const released = + hold.waitMs > 0 + ? yield* Deferred.await(hold.done).pipe(Effect.timeoutOption(hold.waitMs)) + : Option.none(); + if (Option.isNone(released)) { + const timedOut = refusedT3ToolSet(HOLD_TIMED_OUT); + if (dropT3ToolSetHold(threadId, hold, timedOut)) return timedOut; + // Released, or a later turn's hold took its place, as the wait ended: look again. + return yield* setFor(threadId); + } + } + return t3ToolSetFor(threadId) ?? (yield* workedOut(threadId)); + }); + // Untraced: it runs once per tool on every list request. + return Effect.fnUntraced(function* ({ method, target }: McpServer.MiddlewareOptions) { + if (method !== "tools/list" && method !== "tools/call") return true; + const thread = callerThread( + yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext), + ); + if (thread === undefined) return true; + const set = yield* setFor(thread.threadId); + if (t3ToolAllowed(set, target)) return true; + if (method === "tools/list") return false; + return yield* new T3ToolOutsideProfile({ message: t3ToolRefusal(set, target) }); + }); +}); + +/** + * The global rule: on `tools/list` it hides, on `tools/call` it refuses, a T3 tool the calling + * thread's set leaves out. Other methods (T3 serves no resources or prompts) pass. + */ +export const layer = McpServer.visibility( + Effect.gen(function* () { + // Asked for, so a server wired without them is a type error, not a rule that refuses every + // thread (no store) or reads every thread as `all` (no settings). + yield* SqlClient.SqlClient; + yield* ServerSettingsService.ServerSettingsService; + yield* installT3ToolSearchCheck(searchable); + return yield* makeVisible; + }).pipe(Effect.withSpan("McpT3ToolRule.make")), + { global: true }, +); + +export const __testing = { t3ToolRefusal, clearRefused: () => refused.clear(), makeVisible }; diff --git a/apps/server/src/fork/mcpT3ToolSets.ts b/apps/server/src/fork/mcpT3ToolSets.ts index 1ff95e607426e..73ade63125f1d 100644 --- a/apps/server/src/fork/mcpT3ToolSets.ts +++ b/apps/server/src/fork/mcpT3ToolSets.ts @@ -2,9 +2,11 @@ * Fork: the T3 tool groups each thread's MCP credential may use, fixed as each of its turns starts * (MCP profile design PR 4). A running turn keeps the set it started with, and a profile change * applies from the thread's next turn. Memory only, like the credentials it goes with: after a - * restart each thread's set is worked out again from the settings (mcpT3ToolFilter.ts). + * restart each thread's set is worked out again from the settings (mcpT3ToolRule.ts). */ import type { McpT3ToolGroup } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; import type { McpProfileResolved } from "./mcpProfile.ts"; @@ -67,4 +69,91 @@ export const rememberT3ToolSet = (threadId: string, set: T3ToolSet): T3ToolSet = return set; }; -export const __testing = { clear: () => sets.clear(), size: () => sets.size }; +/** + * How long a hold lasts: a request waits for it at most until then, and a hold still there after + * that is dropped (mcpT3ToolRule.ts), so one that is never released holds the thread's requests + * once, not until a restart. + */ +export const T3_TOOL_SET_HOLD_WAIT_MS = 10_000; + +/** Threads whose next set is being worked out right now, as a turn Codex started begins. */ +const holds = new Map< + string, + { + readonly done: Deferred.Deferred; + /** Done once a request waits on this hold (a milestone tests await). */ + readonly asked: Deferred.Deferred; + /** When the hold stops holding: requests then stop waiting, and it is dropped. */ + readonly until: number; + count: number; + } +>(); + +/** + * Holds the thread's T3 requests (mcpT3ToolRule.ts) until the returned release runs, so a turn + * Codex started gets the set its check fixes. Release always; a second release does nothing. A hold + * taken while one is in force joins it; one taken after the last one's bound starts afresh. + */ +export const holdT3ToolSet = (threadId: string, now: number): (() => void) => { + let hold = holds.get(threadId); + if (hold === undefined || hold.until <= now) { + hold = { + done: Deferred.makeUnsafe(), + asked: Deferred.makeUnsafe(), + until: now + T3_TOOL_SET_HOLD_WAIT_MS, + count: 0, + }; + holds.set(threadId, hold); + } + const held = hold; + held.count += 1; + let released = false; + return () => { + if (released) return; + released = true; + held.count -= 1; + if (held.count > 0) return; + if (holds.get(threadId) === held) holds.delete(threadId); + Deferred.doneUnsafe(held.done, Effect.void); + }; +}; + +/** The thread's hold: done once every hold on it is released; wait for it at most `waitMs`. */ +export interface T3ToolSetHold { + readonly done: Deferred.Deferred; + readonly waitMs: number; +} + +/** The hold on the thread's set; `undefined` when none is held. */ +export const t3ToolSetHold = (threadId: string, now: number): T3ToolSetHold | undefined => { + const hold = holds.get(threadId); + if (hold === undefined) return undefined; + Deferred.doneUnsafe(hold.asked, Effect.void); + return { done: hold.done, waitMs: Math.max(0, hold.until - now) }; +}; + +/** + * A hold its bound passed: dropped, and the thread keeps `set` (never the one before the hold) + * until a turn, or the late check, fixes one. False when it was released meanwhile: the set its + * check fixed stands. + */ +export const dropT3ToolSetHold = ( + threadId: string, + hold: T3ToolSetHold, + set: T3ToolSet, +): boolean => { + if (holds.get(threadId)?.done !== hold.done) return false; + holds.delete(threadId); + keep(threadId, set); + return true; +}; + +export const __testing = { + clear: () => { + sets.clear(); + holds.clear(); + }, + size: () => sets.size, + /** Done once a request waits on the thread's hold; `undefined` when none is held. */ + asked: (threadId: string) => holds.get(threadId)?.asked, +}; diff --git a/apps/server/src/fork/mcpTurnProfile.ts b/apps/server/src/fork/mcpTurnProfile.ts new file mode 100644 index 0000000000000..71eee3d44754a --- /dev/null +++ b/apps/server/src/fork/mcpTurnProfile.ts @@ -0,0 +1,19 @@ +/** + * Fork: the profile the turn check (mcpProfileTurnCheck.ts) worked out for the turn it starts, read + * by the Codex wrapper (codexMcpProfile.ts). Keyed by thread, not turn: never fork work inside a turn + * start that outlives it (it would hand this turn's profile to a later turn); fork from the session. + */ +import type { ThreadId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; + +import type { McpProfileResolved } from "./mcpProfile.ts"; + +export interface TurnMcpProfile { + readonly threadId: ThreadId; + readonly resolved: McpProfileResolved; +} + +export const CurrentTurnMcpProfile = Context.Reference( + "t3/fork/mcpTurnProfile/CurrentTurnMcpProfile", + { defaultValue: () => undefined }, +); diff --git a/apps/server/src/fork/personOnlySettings.test.ts b/apps/server/src/fork/personOnlySettings.test.ts index 92bf9119fa729..9546028be5173 100644 --- a/apps/server/src/fork/personOnlySettings.test.ts +++ b/apps/server/src/fork/personOnlySettings.test.ts @@ -19,7 +19,7 @@ import * as Schema from "effect/Schema"; import { beforeAll, describe, expect, it } from "vite-plus/test"; import { withoutMachineOnlyFields } from "./advertisedMachineFields.ts"; -import { T3_TOOL_GROUPS } from "./mcpT3ToolFilter.ts"; +import { T3_TOOL_GROUPS } from "./mcpT3ToolRule.ts"; import { MCP_T3_TOOLKIT_GROUPS, MCP_T3_TOOL_NOT_ALLOWED, @@ -520,7 +520,7 @@ describe("MCP profile T3 tool groups", () => { }); it("gives the T3 tool filter's table exactly the toolkit folders' tools, each in its group", () => { - // The filter (mcpT3ToolFilter.ts) lists its toolkits by hand. A toolkit it leaves out would have + // The filter (mcpT3ToolRule.ts) lists its toolkits by hand. A toolkit it leaves out would have // every tool refused by any profile but `all`, and no profile setting could fix that. const fromFolders = new Map(); for (const [folder, names] of toolsByFolder) { diff --git a/apps/server/src/holdWork.boot.test.ts b/apps/server/src/holdWork.boot.test.ts index 4f40f8d7b5c2f..54e1de70b9469 100644 --- a/apps/server/src/holdWork.boot.test.ts +++ b/apps/server/src/holdWork.boot.test.ts @@ -388,8 +388,8 @@ const FORK_LAYER_SPANS = [ "HeadlessUsageRefresher.make", "cloud.auto_update.make", "McpProfileTurnCheck.make", - // The MCP profile's T3 tool filter on /mcp: `McpT3ToolFilter.layer` in McpHttpServer's `layer`. - "McpT3ToolFilter.make", + // The MCP profile's T3 tool rule on /mcp (fork/mcpT3ToolRule.ts) in McpHttpServer's `layer`. + "McpT3ToolRule.make", // The agent slot gate on scheduled runs: `Layer.provide(SlotGate.layer)` in runtimeLayer.ts. "AgentSlotRoutes.scheduledRunsGated", // The record of who saved each scheduled task, which needs the server's state folder. diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index c350b9918c7ec..bae1a41944517 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -96,7 +96,7 @@ import * as HtmlHandlers from "./toolkits/html/handlers.ts"; import { MessageToolkit } from "./toolkits/message/tools.ts"; import * as WaitsHandlers from "./toolkits/waits/handlers.ts"; import { WaitsToolkit } from "./toolkits/waits/tools.ts"; -import * as McpT3ToolFilter from "../fork/mcpT3ToolFilter.ts"; +import * as McpT3ToolRule from "../fork/mcpT3ToolRule.ts"; import * as MessageHandlers from "./toolkits/message/handlers.ts"; import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts"; import { MCP_HTTP_PATH } from "../httpCors.ts"; @@ -1478,5 +1478,5 @@ export const layerForkTools = Layer.mergeAll( ); export const layer = layerMcpTransport( - Layer.mergeAll(layerTools, layerForkTools, layerToolSearch, McpT3ToolFilter.layer), + Layer.mergeAll(layerTools, layerForkTools, layerToolSearch, McpT3ToolRule.layer), ); diff --git a/apps/web/src/components/settings/fork/McpProfileSettings.browser.test.tsx b/apps/web/src/components/settings/fork/McpProfileSettings.browser.test.tsx index a249c877efa6a..5a9b912806d31 100644 --- a/apps/web/src/components/settings/fork/McpProfileSettings.browser.test.tsx +++ b/apps/web/src/components/settings/fork/McpProfileSettings.browser.test.tsx @@ -127,6 +127,16 @@ describe("McpProfileSettings", () => { expect(state.update).not.toHaveBeenCalled(); }); + it("says under the T3 tool groups that a profile is not a sandbox", async () => { + setup({}); + await using screen = await render(); + await userEvent.click(screen.getByRole("button", { name: "Add profile" })); + await expect + .element(screen.getByText(/^Profiles are not a sandbox: only requests/)) + .toBeVisible(); + await expect.element(screen.getByText(/the `t3 thread` CLI/)).toBeVisible(); + }); + it("shows an entry from a newer build as broken, with no Edit", async () => { setup({ mcpProfiles: { newer: { servers: "all", t3Tools: "all", hosts: ["a"] } } }); await using screen = await render(); diff --git a/apps/web/src/components/settings/fork/McpProfileSettings.tsx b/apps/web/src/components/settings/fork/McpProfileSettings.tsx index bb70b4fffd13f..665f3a150a271 100644 --- a/apps/web/src/components/settings/fork/McpProfileSettings.tsx +++ b/apps/web/src/components/settings/fork/McpProfileSettings.tsx @@ -32,6 +32,7 @@ import { import { ForkRow, useForkRowLock } from "./ForkRow"; import { MCP_ALWAYS_KEPT_NOTE, + MCP_NOT_A_SANDBOX_NOTE, MCP_BLANK_PICK_ISSUE, MCP_PICK_APPLIES_NOTE, type McpProfileDraft, @@ -228,6 +229,7 @@ function ProfileEditor({ onChange={(next) => setDraft({ ...draft, t3Tools: next })} />

{MCP_ALWAYS_KEPT_NOTE}

+

{MCP_NOT_A_SANDBOX_NOTE}