diff --git a/.github/fork-seams.json b/.github/fork-seams.json index c734f19ef72c..bf5e4c169b6f 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -259,14 +259,10 @@ }, "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.", - "added": [], - "announced": { - "since": "2026-11-21", - "added": [ - "import { searchableT3Tool } from \"../fork/mcpT3ToolFilter.ts\"; // Fork: MCP profile T3 tool groups", - ".filter(searchableT3Tool) // Fork: MCP profile T3 tool groups" - ] - } + "added": [ + "import { searchableT3Tool } from \"../fork/mcpT3ToolFilter.ts\"; // Fork: MCP profile T3 tool groups", + ".filter(searchableT3Tool) // Fork: MCP profile T3 tool groups" + ] }, "apps/server/src/mcp/toolkits/project/handlers.ts": { "why": "t3_thread_launch from a thread whose MCP profile is narrower than \"all\" is refused when the new thread would get more than the launcher's profile (fork/launchMcpProfile.ts, #681); a launch that starts a run takes a slot from the agent slot gate, or is refused slots_full (fork/agentSlotRoutes.ts, #706). An agent's t3_thread_launch (from a calling thread) is checked against the model policy once its model is known, before the slot gate: refused in enforce when the launch names no model, a model in no row, or an effort off its row (fork/modelPolicyCheck.ts, #731).", diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index a36f77c2a81b..e4514aab309b 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -33,7 +33,7 @@ setting is missing here or a setting named here does not exist. | A local, read-only "is T3 busy?" answer: `GET /api/fork/activity` on loopback, and `t3 __fork-report --base-dir --activity`, which asks it and exits 0 only when nothing is working. | A host quiet check reads T3's own turns and approvals instead of guessing from processes. | `server.activityProbe` | off | [#547](https://github.com/scuttletoby/t3code/pull/547) | | `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work and T3 Connect held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | | Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | -| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude and Codex apply the outside servers (Codex per thread on its shared app-server, as `mcp_servers..enabled = false`) and refuse a turn when its profile cannot. A task delegated to another machine carries its parent's profile, and a narrower one goes only to a Claude instance on a machine that applies it (one can refuse such tasks). Only Claude and Codex apply profiles: a turn on any other provider whose profile is narrower than `all` is refused as it starts. Settings → Fork lists, adds, edits and deletes profiles, sets the default and the sub-agent rule (also per project) and each thread's pick. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `server.mcpCarriedProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528), [#640](https://github.com/scuttletoby/t3code/issues/640), [#672](https://github.com/scuttletoby/t3code/issues/672) | +| MCP profiles: named profiles (which outside MCP servers and T3 tool groups a thread gets), a default, a sub-agent rule, a pick per thread and the rules that pick one. Claude and Codex apply the outside servers (Codex per thread, as `mcp_servers..enabled = false`) and refuse a turn when they cannot; any other provider refuses a turn whose profile leaves one out. T3's MCP server applies the T3 tool groups on every provider, fixed as each turn starts: a tool outside them is hidden and refused. A delegated task carries its parent's profile; a narrower one goes only to a Claude instance on a machine that applies it. Settings → Fork edits profiles, the default, the sub-agent rule (also per project) and each thread's pick. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `server.mcpCarriedProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227), [#528](https://github.com/scuttletoby/t3code/pull/528), [#640](https://github.com/scuttletoby/t3code/issues/640), [#672](https://github.com/scuttletoby/t3code/issues/672) | | Playtest mode, part 1: settings for a project's playtest adapter (claim, renew, push and release steps only the person sets) and the contract those steps follow. Nothing starts a session yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#260](https://github.com/scuttletoby/t3code/pull/260) | | Playtest mode, part 2: the session store and service: start (claim), rounds of push steps, end (release), kept across restarts. A session keeps the steps it started with. No tool calls it yet. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#261](https://github.com/scuttletoby/t3code/pull/261) | | Playtest mode, part 3: the worker renews claims, ends idle, too-long and gone-thread sessions, finishes what a restart cut, and tells the thread once when T3 ended a session. | A person tries an agent's unfinished work on a test target, round after round, no PR per round. | `server.playtest`, `projectOverride.playtest` | off | [#262](https://github.com/scuttletoby/t3code/pull/262) | diff --git a/apps/server/src/fork/claudeMcpProfile.test.ts b/apps/server/src/fork/claudeMcpProfile.test.ts index 4ed7d184e7fb..7c189e94894f 100644 --- a/apps/server/src/fork/claudeMcpProfile.test.ts +++ b/apps/server/src/fork/claudeMcpProfile.test.ts @@ -23,7 +23,6 @@ import { CHECK_SESSION_TIMEOUT, ClaudeMcpProfileError, EVERY_MCP_SERVER, - type ClaudeMcpProfilePlan, type FindThread, type LineageThread, checkClaudeSession, @@ -35,6 +34,7 @@ import { planKeyFor, } from "./claudeMcpProfile.ts"; import { type McpProfileCarried } from "./mcpProfile.ts"; +import * as T3ToolSets from "./mcpT3ToolSets.ts"; const fromFile = Schema.decodeSync(ServerSettings); const policyDocument = Schema.decodeUnknownSync(ManagedPolicyDocument); @@ -54,13 +54,18 @@ const store = (threads: ReadonlyArray) => (threadId: ThreadId) => Effect.succeed(threads.find((entry) => entry.id === threadId) ?? null); const noReads = () => Effect.die("read a parent thread"); -const outcome = (result: ClaudeMcpProfilePlan | ClaudeMcpProfileError) => - isRefusal(result) ? result.message : result.options; - describe("claudeMcpProfilePlan", () => { - it("refuses a profile that limits T3's own tools, which nothing applies yet", () => { - const result = claudeMcpProfilePlan("lean", { servers: [], t3Tools: ["threads"] }, T3); - assert.include(String(outcome(result)), 'MCP profile "lean" limits T3\'s own tools'); + it("takes a profile that limits T3's own tools: no Claude option, T3's server cuts them", () => { + const result = claudeMcpProfilePlan("lean", { servers: "all", t3Tools: ["threads"] }, T3); + assert.isFalse(isRefusal(result)); + assert.deepStrictEqual(result, { + name: "lean", + options: {}, + servers: "all", + t3Tools: ["threads"], + }); + const none = claudeMcpProfilePlan("bare", { servers: [], t3Tools: [] }, T3); + assert.deepStrictEqual(isRefusal(none) ? none.message : none.t3Tools, []); }); }); @@ -76,7 +81,7 @@ describe("claudeMcpServersOutsidePlan", () => { { servers: [], outside: ["docs", "claude.ai Calendar"] }, { servers: ["docs"], outside: ["claude.ai Calendar"] }, ])("names what $servers leaves out, at any status but disabled", ({ servers, outside }) => { - const plan = { name: "p", options: {}, servers }; + const plan = { name: "p", options: {}, servers, t3Tools: "all" as const }; assert.deepStrictEqual(claudeMcpServersOutsidePlan(plan, T3, statuses), outside); }); }); @@ -222,6 +227,93 @@ describe("makeClaudeMcpProfiles", () => { ), ); + it.effect( + "fixes the thread's T3 tool groups as each query opens; a group change changes the key", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const lean = (t3Tools: unknown) => ({ + mcpProfile: "lean", + mcpProfiles: { lean: { servers: "all", t3Tools } }, + }); + const reads = [lean(["threads"]), lean(["threads"]), lean(["threads", "orchestration"])]; + const service = yield* ServerSettingsService.ServerSettingsService; + let next = 0; + const plan = yield* makeClaudeMcpProfiles.pipe( + Effect.provideService(ServerSettingsService.ServerSettingsService, { + ...service, + getSettings: Effect.suspend(() => Effect.succeed(fromFile(reads[next++] ?? {}))), + }), + ); + const self = thread("t"); + const keys: Array = []; + const sets: Array = []; + for (const _ of reads) { + const overrides = {}; + yield* plan(self, overrides); + keys.push(planKeyFor(overrides)); + const set = T3ToolSets.t3ToolSetFor(self.id); + sets.push(set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set); + } + assert.deepStrictEqual(sets, [["threads"], ["threads"], ["threads", "orchestration"]]); + // Same groups, same process; changed groups, a fresh process that lists T3's tools again. + assert.isDefined(keys[0]); + assert.strictEqual(keys[1], keys[0]); + assert.notStrictEqual(keys[2], keys[1]); + }).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(); + T3ToolSets.fixT3ToolSet("t", { _tag: "Groups", name: "all", groups: "all" }); + // The thread names a profile that is gone: the turn refuses, and the old `all` set is gone. + assert.include( + (yield* plansFor([{ mcpProfile: "gone" }]))[0], + 'MCP profile "gone" is not set up', + ); + assert.strictEqual(T3ToolSets.t3ToolSetFor("t")?._tag, "Refused"); + }), + ); + + it.effect( + "stopped half-way: a query whose profile read is interrupted leaves no T3 tool set", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + T3ToolSets.fixT3ToolSet("t", { _tag: "Groups", name: "all", groups: "all" }); + const reading = yield* Deferred.make(); + const service = yield* ServerSettingsService.ServerSettingsService; + const plan = yield* makeClaudeMcpProfiles.pipe( + Effect.provideService(ServerSettingsService.ServerSettingsService, { + ...service, + getSettings: Deferred.succeed(reading, undefined).pipe(Effect.andThen(Effect.never)), + }), + ); + 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")); + }).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("with no profile anywhere, a failed settings read gives all instead of refusing", () => Effect.gen(function* () { assert.deepStrictEqual(yield* plansFor(["fails", {}, "fails"]), ["all", "all", "all"]); @@ -836,7 +928,7 @@ describe("checkClaudeSession", () => { it.effect("refuses and closes a session that does not list its servers in time", () => Effect.gen(function* () { let closed = 0; - const plan = { name: "t3-only", options: {}, servers: [] }; + const plan = { name: "t3-only", options: {}, servers: [], t3Tools: "all" as const }; const check = yield* checkClaudeSession( plan, {}, diff --git a/apps/server/src/fork/claudeMcpProfile.ts b/apps/server/src/fork/claudeMcpProfile.ts index 1d0517bc5541..fa1e7fb1cdff 100644 --- a/apps/server/src/fork/claudeMcpProfile.ts +++ b/apps/server/src/fork/claudeMcpProfile.ts @@ -1,7 +1,8 @@ /** - * Fork: a thread's MCP profile, applied to its Claude session. This applies the outside servers - * only; T3's own tools are filtered in a later PR. A profile that cannot be applied refuses the - * turn instead of starting it with every tool: the owner chose refusing over warning. + * 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 + * 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. */ import type { HookCallback, @@ -39,6 +40,7 @@ import { type McpProfileThread, resolveMcpProfile, } from "./mcpProfile.ts"; +import { fixT3ToolSet, forgetT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; import { type McpProfileFileKeys, mcpProfileFileKeysOf, @@ -69,6 +71,8 @@ export interface ClaudeMcpProfilePlan { readonly hooks?: Partial>>; }; readonly servers: McpProfileSet["servers"]; + /** T3's own tool groups; the T3 MCP server applies them (mcpT3ToolFilter.ts). */ + readonly t3Tools: McpProfileSet["t3Tools"]; } export type LineageThread = Pick< @@ -76,28 +80,32 @@ export type LineageThread = Pick< "id" | "projectId" | "lineage" | "delegatedFrom" >; -const ALL_PLAN: ClaudeMcpProfilePlan = { name: MCP_PROFILE_ALL, options: {}, servers: "all" }; +const ALL_PLAN: ClaudeMcpProfilePlan = { + name: MCP_PROFILE_ALL, + options: {}, + servers: "all", + t3Tools: "all", +}; const FIX = `pick "${MCP_PROFILE_ALL}" for this thread, or fix the profile in Settings`; /** What can make Claude load a server T3's options leave out, at start. */ const START_LEAKS = "A managed Claude policy on this machine or --mcp-config in the Claude launch arguments can add servers T3's list does not drop"; -/** `t3-only` and an empty list ignore every server Claude would load itself; a list keeps those named. */ +/** + * `t3-only` and an empty list ignore every server Claude would load itself; a list keeps those named. + * `t3Tools` adds no option: T3's own server hides and refuses the tools it leaves out. + */ export function claudeMcpProfilePlan( name: string, profile: McpProfileSet, t3ServerNames: ReadonlyArray, ): ClaudeMcpProfilePlan | ClaudeMcpProfileError { - if (profile.t3Tools !== "all") { - return new ClaudeMcpProfileError({ - reason: `MCP profile "${name}" limits T3's own tools, which this version cannot apply yet, so this thread cannot start: set its t3Tools to "all", or ${FIX}.`, - }); - } - if (profile.servers === "all") return { ...ALL_PLAN, name }; + const t3Tools = profile.t3Tools; + if (profile.servers === "all") return { ...ALL_PLAN, name, t3Tools }; const servers = profile.servers; const hooks = { PreToolUse: [{ hooks: [claudeMcpProfileGuard(name, servers, t3ServerNames)] }] }; if (servers.length === 0) { - return { name, options: { strictMcpConfig: true, hooks }, servers }; + return { name, options: { strictMcpConfig: true, hooks }, servers, t3Tools }; } // T3's own servers are listed too, so the allowlist cannot drop them. const allowed = [...new Set([...t3ServerNames, ...servers])]; @@ -108,6 +116,7 @@ export function claudeMcpProfilePlan( hooks, }, servers, + t3Tools, }; } @@ -324,9 +333,18 @@ const PLAN_KEYS = new WeakMap(); export const planKeyFor = (mcpOverrides: object): string | undefined => (PLAN_KEYS.get(mcpOverrides) ?? { key: "unplanned" }).key; -/** The plan's key part, or `undefined` for `all`. NUL keeps the joined names apart. */ +/** + * The plan's key part, or `undefined` for `all`. NUL keeps the joined names apart. A change of T3 + * tool groups changes it too, so the next turn's fresh process lists T3's tools again. + */ const planKey = (plan: ClaudeMcpProfilePlan): string | undefined => - plan.servers === "all" ? undefined : ["mcp", ...plan.servers].join("\u0000"); + plan.servers === "all" && plan.t3Tools === "all" + ? undefined + : [ + "mcp", + ...(plan.servers === "all" ? ["*"] : plan.servers), + ...(plan.t3Tools === "all" ? [] : ["\u0001t3", ...plan.t3Tools]), + ].join("\u0000"); /** settings.json as this read found it. */ type SettingsFileRead = @@ -617,7 +635,16 @@ export const makeClaudeMcpProfiles = Effect.gen(function* () { thread: LineageThread, overrides: McpOverrides, ) { - const resolved: McpProfileResolved = yield* profileFor(thread); + // 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. + 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; diff --git a/apps/server/src/fork/codexMcpProfile.test.ts b/apps/server/src/fork/codexMcpProfile.test.ts index 9d392ef8cb61..ebc062f320b1 100644 --- a/apps/server/src/fork/codexMcpProfile.test.ts +++ b/apps/server/src/fork/codexMcpProfile.test.ts @@ -48,6 +48,13 @@ import { type ProfileById, } from "./codexMcpProfile.ts"; import type { McpProfileResolved, McpProfileSet } from "./mcpProfile.ts"; +import * as T3ToolSets from "./mcpT3ToolSets.ts"; + +/** The groups the thread's set holds now, or its tag when it is not a list. */ +const groupsOf = (threadId: string) => { + const set = T3ToolSets.t3ToolSetFor(threadId); + return set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set?._tag; +}; type Client = CodexClient.CodexAppServerClient["Service"]; type Json = Record; @@ -432,10 +439,18 @@ describe("codexMcpProfile helpers", () => { ); }); + it("a profile that limits T3's tools adds no Codex config: T3's own server cuts them", () => { + assert.deepStrictEqual( + codexMcpProfileConfig("lean", { servers: "all", t3Tools: ["threads"] }, ["alpha"]), + {}, + ); + assert.deepStrictEqual( + codexMcpProfileConfig("lean", { servers: ["alpha"], t3Tools: [] }, ["alpha", "beta"]), + codexMcpProfileConfig("lean", { servers: ["alpha"], t3Tools: "all" }, ["alpha", "beta"]), + ); + }); + it("refuses a profile it cannot apply, with the fix", () => { - const tools = codexMcpProfileConfig("lean", { servers: "all", t3Tools: ["threads"] }, []); - assert.isTrue(isRefusal(tools)); - assert.include((tools as ClaudeMcpProfileError).reason, 'set its t3Tools to "all"'); const named = codexMcpProfileConfig("mine", { servers: [], t3Tools: "all" }, ["a.b"]); assert.isTrue(isRefusal(named)); assert.include((named as ClaudeMcpProfileError).reason, '"a.b"'); @@ -604,20 +619,28 @@ describe("withCodexMcpProfiles", () => { }), ); - it.effect("a profile that limits T3's tools, or a server name Codex cannot take, refuses", () => - Effect.gen(function* () { - const fake = makeFakeCodex({ servers: ["alpha", "my server"] }); - const { profileFor } = makeProfiles({ - tools: resolved("lean", "all", ["threads"]), - named: resolved("none", []), - }); - const client = yield* withCodexMcpProfiles(fake.client, profileFor); - assert.include(yield* outcome(start(client, "tools")), 'set its t3Tools to "all"'); - const named = yield* outcome(start(client, "named")); - assert.include(named, '"my server"'); - assert.include(named, FIX); - assert.deepStrictEqual(fake.sent("thread/start"), []); - }), + it.effect( + "a server name Codex cannot take refuses; a profile that limits only T3's tools loads", + () => + Effect.gen(function* () { + const fake = makeFakeCodex({ servers: ["alpha", "my server"] }); + const { profileFor } = makeProfiles({ + tools: resolved("lean", "all", ["threads"]), + named: resolved("none", []), + }); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const named = yield* outcome(start(client, "named")); + assert.include(named, '"my server"'); + assert.include(named, FIX); + assert.deepStrictEqual(fake.sent("thread/start"), []); + // Every outside server kept: nothing extra is asked of Codex or sent to it. + const reads = fake.sent("config/read").length; + assert.strictEqual(yield* outcome(start(client, "tools")), "ok"); + assert.strictEqual(fake.sent("thread/start").length, 1); + assert.strictEqual(fake.sent("config/read").length, reads); + const sent = fake.sent("thread/start")[0]!.params as { readonly config: Json }; + assert.deepStrictEqual(offKeys(sent.config), []); + }), ); it.effect.each([ @@ -847,19 +870,32 @@ describe("withCodexMcpProfiles", () => { }), ); - it.effect("T3's tools narrowed after the thread loaded on all: its next turn is refused", () => - Effect.gen(function* () { - const fake = makeFakeCodex({ servers: ["alpha"] }); - const { profiles, profileFor } = makeProfiles(); - const client = yield* withCodexMcpProfiles(fake.client, profileFor); - const id = (yield* start(client, "t")).thread.id; - // Every server kept, only T3's tools limited: no server is outside the profile. - profiles.set("t", resolved("lean", "all", ["threads"])); - const message = yield* outcome(turn(client, id)); - assert.include(message, 'MCP profile "lean" limits T3\'s own tools'); - assert.include(message, 'set its t3Tools to "all"'); - assert.deepStrictEqual(fake.sent("turn/start"), []); - }), + it.effect( + "T3's tools narrowed after the thread loaded on all: its next turn runs with exactly that set", + () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const fake = makeFakeCodex({ servers: ["alpha"] }); + const { profiles, profileFor } = makeProfiles(); + const client = yield* withCodexMcpProfiles(fake.client, profileFor); + const id = (yield* start(client, "t")).thread.id; + // Every server kept, only T3's tools limited: no server is outside the profile. + profiles.set("t", resolved("lean", "all", ["threads"])); + assert.strictEqual(yield* outcome(turn(client, id)), "ok"); + assert.strictEqual(fake.sent("turn/start").length, 1); + assert.deepStrictEqual(groupsOf("t"), ["threads"]); + // A turn Codex starts on its own (a goal's next turn) fixes the set as it starts too. + profiles.set("t", resolved("lean", ["alpha"], ["threads", "waits"])); + const reads = fake.sent("mcpServerStatus/list").length; + yield* fake.emit("turn/started", turnStarted(id, "goal-2")); + yield* fake.reached("mcpServerStatus/list", reads + 1); + assert.deepStrictEqual(groupsOf("t"), ["threads", "waits"]); + assert.deepStrictEqual(fake.sent("turn/interrupt"), []); + // A profile that cannot be worked out keeps only the tools every profile keeps. + profiles.set("t", new ClaudeMcpProfileError({ reason: "gone" })); + assert.include(yield* outcome(turn(client, id)), "gone"); + assert.strictEqual(T3ToolSets.t3ToolSetFor("t")?._tag, "Refused"); + }), ); it.effect( diff --git a/apps/server/src/fork/codexMcpProfile.ts b/apps/server/src/fork/codexMcpProfile.ts index 91963694ec31..0bc7faa9df24 100644 --- a/apps/server/src/fork/codexMcpProfile.ts +++ b/apps/server/src/fork/codexMcpProfile.ts @@ -1,7 +1,8 @@ /** - * Fork: MCP profiles on Codex (design part 5). Each thread T3 loads on the shared app-server gets - * `mcp_servers..enabled = false` in its own config for every server Codex's config/read lists - * that its profile leaves out; each turn first checks the thread's live servers, and refuses. + * 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. */ import { MCP_PROFILE_ALL, ThreadId } from "@t3tools/contracts"; import type * as CodexClient from "effect-codex-app-server/client"; @@ -13,7 +14,8 @@ 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 { isEveryMcpTool, type McpProfileResolved, type McpProfileSet } from "./mcpProfile.ts"; +import type { McpProfileResolved, McpProfileSet } from "./mcpProfile.ts"; +import { fixT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; type Client = CodexClient.CodexAppServerClient["Service"]; type Send = ( @@ -66,18 +68,14 @@ export function codexConfiguredMcpServers(config: unknown): ReadonlyArray, ): Readonly> | ClaudeMcpProfileError { - if (profile.t3Tools !== "all") { - return new ClaudeMcpProfileError({ - reason: `MCP profile "${name}" limits T3's own tools, which this version cannot apply yet, so this thread cannot start: set its t3Tools to "all", or ${FIX}.`, - }); - } const kept = profile.servers; if (kept === "all") return {}; const off = configured.filter( @@ -151,7 +149,7 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* * start of such a thread is refused too, once, so a passing hiccup cannot cost the history. */ const refusedResumes = new Map(); - /** Set once a thread here got a profile narrower than `all`. */ + /** Set once a thread here got a profile that leaves out an outside server. */ let narrowed = false; const read = (method: string, params: unknown) => (client.raw.request as unknown as Send)(method, params).pipe( @@ -247,7 +245,7 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* ) { const resolved = yield* profileOf(method, threadId); let off: Readonly> = {}; - if (!isEveryMcpTool(resolved.profile)) { + if (resolved.profile.servers !== "all") { const cwd = yield* workspaceOf(method, request); const configured = yield* read("config/read", { ...(cwd === undefined ? {} : { cwd }), @@ -280,11 +278,17 @@ export const withCodexMcpProfiles = Effect.fn("CodexMcpProfile.wrap")(function* }), ); } - const resolved = yield* profileOf(method, threadId); + // 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( + Effect.tapError((cause) => + Effect.sync(() => fixT3ToolSet(threadId, refusedT3ToolSet(cause.reason))), + ), + Effect.mapError((cause) => refusal(method, cause)), + ); + fixT3ToolSet(threadId, t3ToolSetOf(resolved)); // A thread loaded narrower than its profile is now stays narrower until Codex reloads it. - if (isEveryMcpTool(resolved.profile)) return; - const planned = codexMcpProfileConfig(resolved.name, resolved.profile, []); - if (isRefusal(planned)) return yield* refusal(method, planned); + if (resolved.profile.servers === "all") return; const statuses: Array<{ readonly name: string; readonly runtimeStatus?: string | null }> = []; let cursor: string | undefined; for (let page = 0; ; page++) { diff --git a/apps/server/src/fork/forkLayers.ts b/apps/server/src/fork/forkLayers.ts index e5dfdd9e8bea..9d236fb0e4f8 100644 --- a/apps/server/src/fork/forkLayers.ts +++ b/apps/server/src/fork/forkLayers.ts @@ -72,10 +72,9 @@ export const handoffThreadsSkipIdleCompaction = PullRequestWatchSlot.layer.pipe( ); /** - * Right below upstream's orchestration layer in server.ts, so every turn reads its adapter from it: - * upstream's provider instance registry, except that a provider that cannot apply MCP profiles - * refuses a turn whose profile is narrower than `all` (fork/mcpProfileTurnCheck.ts). The real boot - * test (holdWork.boot.test.ts) checks that the orchestration layer's reads go through it. + * Right below upstream's orchestration layer in server.ts, so every turn reads its adapter from it + * (fork/mcpProfileTurnCheck.ts): off Claude it refuses a profile that leaves out an outside server + * and fixes the turn's T3 tool groups. holdWork.boot.test.ts checks the reads go through it. */ export const mcpProfileTurnCheck = McpProfileTurnCheck.layer; diff --git a/apps/server/src/fork/mcpProfile.ts b/apps/server/src/fork/mcpProfile.ts index d67f7cbb0aa2..c140cc066854 100644 --- a/apps/server/src/fork/mcpProfile.ts +++ b/apps/server/src/fork/mcpProfile.ts @@ -1,8 +1,8 @@ /** * Fork: which MCP profile a thread gets. The pure resolver lives in - * packages/contracts/src/mcpProfileResolve.ts, so the app reads profiles by the same rules; it is - * re-exported here. This file keeps what only the server needs: each T3 toolkit's group and the - * drivers that apply a profile. + * 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. */ import { MCP_T3_UNGROUPED_TOOLS, @@ -31,8 +31,8 @@ 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 (a later PR) uses it. The test in - * personOnlySettings.test.ts fails when a toolkit or tool maps to nothing. + * only tools of `MCP_T3_UNGROUPED_TOOLS`. The T3 tool filter (mcpT3ToolFilter.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> = { orchestrator: "orchestration", @@ -107,10 +107,10 @@ export function mcpT3ToolGroup( } /** - * The drivers whose threads apply an MCP profile: Claude (fork/claudeMcpProfile.ts) and Codex - * (fork/codexMcpProfile.ts). Any other provider would give a thread every MCP server and T3 tool, - * so a turn there whose profile is narrower than `all` is refused as it starts - * (fork/mcpProfileTurnCheck.ts). + * 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). */ 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 29d53b557bd4..319dc6f51829 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.test.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.test.ts @@ -1,8 +1,8 @@ /** - * Fork: a turn on a provider that cannot apply MCP profiles (all but Claude and Codex) refuses when its - * thread's profile is narrower than `all`. The check wraps upstream's provider instance - * registry as server.ts wires it, over upstream's settings test service and a real thread store - * (SQLite in memory), so each route a thread takes to such a provider meets it at turn start. + * Fork: every turn but Claude's fixes its thread's T3 tool groups; outside Claude and Codex a turn + * whose profile leaves out an outside server also refuses. The check wraps upstream's provider + * instance registry as server.ts wires it, over upstream's settings test service and a real + * thread store (SQLite in memory), so each route a thread takes meets it at turn start. */ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; @@ -40,6 +40,13 @@ import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry. 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"; + +/** The groups the thread's set holds now, or its tag when it is not a list. */ +const groupsOf = (threadId: string) => { + const set = T3ToolSets.t3ToolSetFor(threadId); + return set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set?._tag; +}; const CLAUDE = ProviderInstanceId.make("claudeAgent"); const CODEX = ProviderInstanceId.make("codex"); @@ -242,9 +249,9 @@ const withCheck = ( }; const CUT = - /MCP profile \("all", cut down to its parent thread's\) is narrower than "all", and opencode/; + /MCP profile \("all", cut down to its parent thread's\) leaves out some outside MCP servers, and opencode/; const REFUSED = - /MCP profile "t3-only" is narrower than "all", and opencode \(provider instance opencode-work\) does not apply MCP profiles/; + /MCP profile "t3-only" leaves out some outside MCP servers, and opencode \(provider instance opencode-work\) does not apply a profile's outside servers/; describe("mcpProfileTurnCheck", () => { it("checks every driver but those that apply profiles", () => { @@ -271,11 +278,12 @@ describe("mcpProfileTurnCheck", () => { withCheck({ mcpProfile: "t3-only" }, [], ({ calls, raw, start }) => Effect.gen(function* () { const own = appThread("switched"); - // Claude and Codex apply the profile themselves: their instances are upstream's, untouched. + // Claude applies the whole profile itself: its instance is upstream's, untouched. Codex + // applies the outside servers itself: its turns only get their T3 tool groups fixed here. const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; assert.strictEqual(yield* registry.getInstance(CLAUDE), raw[0]); assert.strictEqual(yield* start(own, CLAUDE), "ok"); - assert.strictEqual(yield* registry.getInstance(CODEX), raw[1]); + assert.notStrictEqual(yield* registry.getInstance(CODEX), raw[1]); assert.strictEqual(yield* start(own, CODEX), "ok"); // The same thread, switched to a provider that does not apply profiles. assert.match(yield* start(own, OPENCODE), REFUSED); @@ -306,26 +314,129 @@ describe("mcpProfileTurnCheck", () => { ), ); - it.effect("every outside server but fewer T3 tools is narrower than all: it refuses", () => + it.effect( + "every outside server but fewer T3 tools runs on every provider, its groups fixed", + () => + withCheck( + { + mcpProfiles: { "servers-only": { servers: "all", t3Tools: ["threads"] } }, + mcpProfile: "servers-only", + } as Mcp, + [], + ({ calls, start }) => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const own = appThread("own"); + assert.strictEqual(yield* start(own, OPENCODE), "ok"); + assert.deepStrictEqual(groupsOf(own.id), ["threads"]); + assert.strictEqual(yield* start(own, CODEX), "ok"); + assert.strictEqual(yield* start(own, CLAUDE), "ok"); + assert.deepStrictEqual(calls, [ + "start:opencode-work:own", + "start:codex:own", + "start:claudeAgent:own", + ]); + }), + ), + ); + + it.effect( + "Codex (in MCP_PROFILE_DRIVERS): a narrowed t3Tools gets exactly that set, and outside servers are left to Codex", + () => + withCheck( + { + mcpProfiles: { lean: { servers: [], t3Tools: ["threads", "waits"] } }, + mcpProfile: "lean", + } as Mcp, + [], + ({ calls, start }) => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const own = appThread("own"); + // Every outside server left out: OpenCode cannot apply that, Codex does it itself. + assert.match(yield* start(own, OPENCODE), /"lean" leaves out some outside MCP servers/); + T3ToolSets.__testing.clear(); + for (const how of ["start", "resume", "compact"] as const) { + T3ToolSets.fixT3ToolSet(own.id, { _tag: "Groups", name: "all", groups: "all" }); + assert.strictEqual(yield* start(own, CODEX, how), "ok"); + assert.deepStrictEqual(groupsOf(own.id), ["threads", "waits"]); + } + assert.deepStrictEqual(calls, [ + "start:codex:own", + "resume:codex:own", + "compact:codex:own", + ]); + }), + ), + ); + + it.effect( + "Claude is unchanged: its turns are upstream's, its set fixed where its query opens", + () => + withCheck( + { + mcpProfiles: { lean: { servers: [], t3Tools: ["threads"] } }, + mcpProfile: "lean", + } as Mcp, + [], + ({ calls, start }) => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + const own = appThread("own"); + assert.strictEqual(yield* start(own, CLAUDE), "ok"); + // Not fixed here: claudeMcpProfile.ts fixes it as the query opens. + assert.isUndefined(T3ToolSets.t3ToolSetFor(own.id)); + assert.deepStrictEqual(calls, ["start:claudeAgent:own"]); + }), + ), + ); + + it.effect("a profile change applies from the next turn: the running one keeps its set", () => withCheck( { - mcpProfiles: { "servers-only": { servers: "all", t3Tools: ["threads"] } }, - mcpProfile: "servers-only", + mcpProfiles: { lean: { servers: "all", t3Tools: ["threads"] } }, + mcpProfile: "lean", } as Mcp, [], - ({ calls, start }) => + ({ start }) => Effect.gen(function* () { + T3ToolSets.__testing.clear(); const own = appThread("own"); - assert.include( - yield* start(own, OPENCODE), - 'MCP profile "servers-only" is narrower than "all", and opencode', - ); - assert.strictEqual(yield* start(own, CLAUDE), "ok"); - assert.deepStrictEqual(calls, ["start:claudeAgent:own"]); + for (const id of [CODEX, OPENCODE]) { + assert.strictEqual(yield* start(own, id), "ok"); + const settings = yield* ServerSettingsService.ServerSettingsService; + yield* settings.updateSettings({ + mcpProfiles: { lean: { servers: "all", t3Tools: ["threads", "orchestration"] } }, + } as never); + // No turn started since: the set stays what the running turn started with. + assert.deepStrictEqual(groupsOf(own.id), ["threads"]); + assert.strictEqual(yield* start(own, id, "resume"), "ok"); + assert.deepStrictEqual(groupsOf(own.id), ["threads", "orchestration"]); + yield* settings.updateSettings({ + mcpProfiles: { lean: { servers: "all", t3Tools: ["threads"] } }, + } as never); + assert.strictEqual(yield* start(own, id), "ok"); + } }), ), ); + it.effect( + "a profile that is gone refuses the turn on Codex and OpenCode and keeps only the ungrouped", + () => + withCheck({ mcpProfile: "gone" }, [], ({ calls, start }) => + Effect.gen(function* () { + const own = appThread("own"); + for (const id of [CODEX, OPENCODE]) { + T3ToolSets.fixT3ToolSet(own.id, { _tag: "Groups", name: "all", groups: "all" }); + assert.include(yield* start(own, id, "compact"), 'MCP profile "gone" is not set up'); + assert.strictEqual(T3ToolSets.t3ToolSetFor(own.id)?._tag, "Refused"); + } + assert.deepStrictEqual(calls, []); + }), + ), + ); + it.effect("a thread made by t3_thread_launch in a narrowed project refuses on OpenCode", () => withCheck( { projectSettingsOverrides: { [PROJECT]: { mcpProfile: "t3-only" } } }, @@ -466,10 +577,13 @@ describe("mcpProfileTurnCheck", () => { ({ calls, start }) => Effect.gen(function* () { const own = appThread("own"); + T3ToolSets.fixT3ToolSet(own.id, { _tag: "Groups", name: "all", groups: "all" }); const fiber = yield* Effect.forkChild(start(own, OPENCODE)); yield* Deferred.await(reading); yield* Fiber.interrupt(fiber); assert.deepStrictEqual(calls, []); + // No set stands for a turn that never started: the next request works it out again. + assert.isUndefined(T3ToolSets.t3ToolSetFor(own.id)); // The next turn reads again and starts. assert.strictEqual(yield* start(own, OPENCODE), "ok"); assert.deepStrictEqual(calls, ["start:opencode-work:own"]); diff --git a/apps/server/src/fork/mcpProfileTurnCheck.ts b/apps/server/src/fork/mcpProfileTurnCheck.ts index 443bb8c22d87..4985e063498d 100644 --- a/apps/server/src/fork/mcpProfileTurnCheck.ts +++ b/apps/server/src/fork/mcpProfileTurnCheck.ts @@ -1,10 +1,10 @@ /** - * Fork: a turn on a provider outside `MCP_PROFILE_DRIVERS` would get every MCP server and T3 tool, - * so it refuses at start when its thread's profile is narrower than `all` or cannot be worked out. - * Checked where the turn runs, so every route is covered; so is compaction (a `/compact` prompt on - * some providers). A steer joins a turn that was checked as it started. + * Fork: every turn start (also resume, compaction) fixes its thread's T3 tool groups for + * mcpT3ToolFilter.ts, on every driver but Claude (claudeMcpProfile.ts fixes its own). Outside + * `MCP_PROFILE_DRIVERS` the turn also refuses when its profile leaves out an outside server. + * A profile that cannot be worked out refuses on every wrapped driver. */ -import { MCP_PROFILE_ALL, type ProviderDriverKind } from "@t3tools/contracts"; +import { MCP_PROFILE_ALL, ProviderDriverKind } from "@t3tools/contracts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import * as Effect from "effect/Effect"; @@ -18,7 +18,8 @@ import { type LineageThread, makeThreadMcpProfiles, } from "./claudeMcpProfile.ts"; -import { isEveryMcpTool, MCP_PROFILE_DRIVERS, type McpProfileResolved } from "./mcpProfile.ts"; +import { MCP_PROFILE_DRIVERS, type McpProfileResolved } from "./mcpProfile.ts"; +import { fixT3ToolSet, forgetT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts"; type ProfileFor = Effect.Success; /** What a turn start, and a resume, are given that the check reads. */ @@ -52,28 +53,45 @@ const withOverrides = (source: T, overrides: Partial): T => }); }; -/** Whether threads on this driver apply MCP profiles; any other is checked at each turn start. */ +/** Whether threads on this driver apply a profile's outside servers themselves. */ const appliesMcpProfiles = (driver: ProviderDriverKind): boolean => MCP_PROFILE_DRIVERS.has(driver); +/** + * Drivers that fix their threads' T3 tool groups themselves, as each query opens + * (claudeMcpProfile.ts), and so are not wrapped here. Every other driver's turns are. + */ +const FIXES_OWN_T3_TOOL_SETS: ReadonlySet = new Set([ + ProviderDriverKind.make("claudeAgent"), +]); + const refusalReason = (resolved: McpProfileResolved, instance: ProviderInstance): string => { // A parent's profile (here, or the one another machine carried) can cut even `all` down. const profile = resolved.narrowedByParent ? `("${resolved.name}", cut down to its parent thread's)` : `"${resolved.name}"`; - return `This thread's MCP profile ${profile} is narrower than "${MCP_PROFILE_ALL}", and ${instance.driverKind} (provider instance ${instance.instanceId}) does not apply MCP profiles (only Claude and Codex do), so this turn was not started: it would get every MCP server and T3 tool. Switch the thread to a Claude or Codex instance, or pick "${MCP_PROFILE_ALL}" for this thread in Settings.`; + return `This thread's MCP profile ${profile} leaves out some outside MCP servers, and ${instance.driverKind} (provider instance ${instance.instanceId}) does not apply a profile's outside servers (only Claude and Codex do), so this turn was not started: it would get every outside MCP server. Switch the thread to a Claude or Codex instance, or pick "${MCP_PROFILE_ALL}" (or a profile whose servers are "all") for this thread in Settings.`; }; /** - * Nothing when the thread's profile is `all`; otherwise the refusal. A profile that cannot be - * worked out refuses with the resolver's reason, as it does on Claude. + * 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. */ const checkTurnProfile = Effect.fn("McpProfileTurnCheck.check")(function* ( profileFor: ProfileFor, instance: ProviderInstance, thread: LineageThread, ) { - const resolved = yield* profileFor(thread); - if (isEveryMcpTool(resolved.profile)) return; + const resolved = 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)); + if (appliesMcpProfiles(instance.driverKind) || resolved.profile.servers === "all") return; return yield* new ClaudeMcpProfileError({ reason: refusalReason(resolved, instance) }); }); @@ -100,7 +118,7 @@ const makeWrap = (profileFor: ProfileFor) => { Effect.andThen(run(input)), ); return (instance: ProviderInstance): ProviderInstance => { - if (appliesMcpProfiles(instance.driverKind)) return instance; + if (FIXES_OWN_T3_TOOL_SETS.has(instance.driverKind)) return instance; const known = wrapped.get(instance); if (known !== undefined) return known; const adapter = instance.orchestrationAdapter; @@ -127,7 +145,7 @@ const makeWrap = (profileFor: ProfileFor) => { }; /** - * Upstream's registry with every instance outside `MCP_PROFILE_DRIVERS` checked at turn start. + * Upstream's registry with every instance but Claude's checked at turn start. * Asks for the thread store and the settings service, so a server wired without them is a type * error, not a check that reads every thread as `all`. */ diff --git a/apps/server/src/fork/mcpT3ToolFilter.test.ts b/apps/server/src/fork/mcpT3ToolFilter.test.ts new file mode 100644 index 000000000000..e7a750d37f79 --- /dev/null +++ b/apps/server/src/fork/mcpT3ToolFilter.test.ts @@ -0,0 +1,552 @@ +/** + * Fork: the MCP profile's T3 tool groups over the real `/mcp` transport, a real thread store and + * upstream's settings test service: `tools/list`, `tools/call` (by any name, or in a batch) and + * `tool_search`, the ways an agent reaches a T3 tool. + */ +import { NodeHttpServer } from "@effect/platform-node"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + EventId, + type OrchestrationV2AppThread, + ProjectId, + ProviderInstanceId, + ProviderThreadId, + ThreadId, +} from "@t3tools/contracts"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpBody, HttpClient, HttpRouter } from "effect/http"; +import { describe } from "vite-plus/test"; + +import * as GitManager from "../git/GitManager.ts"; +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import * as McpToolAccessTestkit from "../mcp/McpToolAccess.testkit.ts"; +import { makeTurnInput } from "../orchestration-v2/Adapters/AcpAdapterV2.testkit.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as PeerForwarding from "../peer/PeerForwarding.ts"; +import { Playtest } from "../playtest/PlaytestLayer.ts"; +import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +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 T3ToolSets from "./mcpT3ToolSets.ts"; + +const ENVIRONMENT = EnvironmentId.make("environment-t3-tool-groups"); +const PROJECT = ProjectId.make("project-t3-tool-groups"); +const NOW = DateTime.makeUnsafe("2026-11-21T00:00:00.000Z"); +const CODEX = ProviderInstanceId.make("codex"); + +const WAIT_TOOLS = ["wait_for", "wait_list", "wait_cancel", "task_list"]; +const PR_TOOL = "list_thread_pull_requests"; + +/** The wait tools list only while waits are on. */ +const WAITS_ON = { waitFor: { enabled: true } }; + +const SETTINGS = { + ...WAITS_ON, + mcpProfiles: { + prs: { servers: "all", t3Tools: ["pull-requests"] }, + waits: { servers: "all", t3Tools: ["waits"] }, + none: { servers: "all", t3Tools: [] }, + }, + mcpSubagentProfile: "waits", + mcpThreadProfiles: { + "thread-prs": "prs", + "thread-waits": "waits", + "thread-none": "none", + "thread-gone": "gone", + }, +}; + +const appThread = (id: string, parent?: string): OrchestrationV2AppThread => { + const threadId = ThreadId.make(id); + const base = makeTurnInput({ + threadId, + instanceId: CODEX, + providerThread: { + id: ProviderThreadId.make(`provider-thread:${id}`), + threadId, + providerInstanceId: CODEX, + } as never, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + }), + now: NOW, + }).appThread; + return { + ...base, + projectId: PROJECT, + lineage: { + parentThreadId: parent === undefined ? null : ThreadId.make(parent), + relationshipToParent: parent === undefined ? null : "subagent", + rootThreadId: ThreadId.make(parent ?? id), + }, + }; +}; + +/** Threads in the store. `thread-deleted` has a credential but no row. */ +const STORED = [ + appThread("thread-all"), + appThread("thread-prs"), + appThread("thread-waits"), + appThread("thread-none"), + appThread("thread-gone"), + // Its own role default is `waits` (mcpSubagentProfile), cut down to its parent's `prs`. + appThread("thread-child", "thread-prs"), +]; + +const scopeFor = (token: string): McpInvocationContext.McpThreadInvocationScope => ({ + environmentId: ENVIRONMENT, + requestNamespace: token, + thread: { + threadId: ThreadId.make(`thread-${token}`), + providerSessionId: `session-${token}`, + providerInstanceId: CODEX, + subagent: token === "child", + }, + client: undefined, + capabilities: new Set(["orchestration", "pull-requests", "issues", "worktree"]), + issuedAt: 1, +}); + +const TOKENS = ["all", "prs", "waits", "none", "gone", "child", "deleted"]; + +/** Every `waits.list` the server ran: a call that reached the handler. */ +let listed = 0; + +const serverLayer = (shared: Layer.Layer) => { + const scopes = new Map( + TOKENS.map((token) => [token, scopeFor(token)]), + ); + // An outside MCP client of this machine: no thread, so no profile. + scopes.set("outside", { ...scopeFor("outside"), thread: undefined }); + return McpHttpServer.layerMcpTransport( + Layer.mergeAll( + McpHttpServer.layerPullRequestsToolkit, + McpHttpServer.layerForkTools, + McpHttpServer.layerToolSearch, + McpT3ToolFilter.layer, + ), + ).pipe( + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: (token) => Effect.succeed(scopes.get(token) as never), + }), + ), + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (threadId) => + Effect.succeed({ + ...McpToolAccessTestkit.liveThreadShell(threadId), + projectId: PROJECT, + }), + }), + Layer.mock(Waits)({ + list: () => + Effect.sync(() => { + listed += 1; + return { enabled: false, waits: [], checks: [] }; + }), + }), + Layer.mock(Playtest)({ filePath: "unused" }), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(PeerForwarding.PeerForwarding)({}), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), + Layer.mock(PullRequestService.PullRequestService)({ + servesProject: () => Effect.succeed(true), + }), + Layer.mock(GitManager.GitManager)({}), + Layer.mock(Orchestrator.OrchestratorV2)({}), + ), + ), + Layer.provide(shared), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ); +}; + +/** The settings and the thread store, shared by the server and the test. */ +const sharedLayer = (settings: object) => + Layer.mergeAll( + ServerSettingsService.ServerSettingsService.layerTest(settings as never), + ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), + ).pipe(Layer.provideMerge(NodeServices.layer)); + +interface RpcReply { + readonly id?: number; + readonly result?: { + readonly tools?: ReadonlyArray<{ readonly name: string }>; + readonly isError?: boolean; + readonly structuredContent?: unknown; + }; + readonly error?: { readonly code: number; readonly message: string }; +} + +/** Starts the server with `settings` and the threads stored, then runs `body` against it. */ +const withServer = ( + body: (mcp: { + readonly rpc: (token: string, payload: unknown) => Effect.Effect; + readonly list: (token: string) => Effect.Effect>; + readonly call: (token: string, name: string, args?: object) => Effect.Effect; + }) => Effect.Effect, + settings: object = SETTINGS, +) => + Effect.scoped( + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + listed = 0; + const shared = yield* Layer.build(sharedLayer(settings)); + const store = yield* ProjectionStore.ProjectionStoreV2.pipe(Effect.provide(shared)); + for (const thread of STORED) { + yield* store.apply({ + id: EventId.make(`seed:${thread.id}`), + type: "thread.created", + threadId: thread.id, + occurredAt: NOW, + payload: thread, + } as never); + } + yield* HttpRouter.serve(serverLayer(Layer.succeedContext(shared)), { + disableListenLog: true, + disableLogger: true, + }).pipe(Layer.build); + const http = yield* HttpClient.HttpClient; + const sessions = new Map(); + const rpc = (token: string, payload: unknown) => + Effect.gen(function* () { + const headers = { + accept: "application/json, text/event-stream", + authorization: `Bearer ${token}`, + }; + let session = sessions.get(token); + if (session === undefined) { + const initialize = yield* http.post("/mcp", { + headers, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`, + "application/json", + ), + }); + session = initialize.headers["mcp-session-id"]!; + sessions.set(token, session); + } + const reply = yield* http.post("/mcp", { + headers: { + ...headers, + "mcp-session-id": session, + "mcp-protocol-version": "2025-06-18", + }, + body: HttpBody.text(JSON.stringify(payload), "application/json"), + }); + const text = yield* reply.text; + if (text === "") return { status: reply.status }; + // A reply that also sends a notification (tool_search's list change) comes as events. + if (!text.startsWith("data:")) return JSON.parse(text) as unknown; + const messages = text + .split("\n") + .filter((line) => line.startsWith("data:")) + .map((line) => JSON.parse(line.slice("data:".length)) as { readonly id?: unknown }); + return messages.find((message) => message.id !== undefined) ?? messages; + }).pipe(Effect.orDie); + const list = (token: string) => + rpc(token, { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }).pipe( + Effect.map((reply) => ((reply as RpcReply).result?.tools ?? []).map((tool) => tool.name)), + ); + const call = (token: string, name: string, args: object = {}) => + rpc(token, { + jsonrpc: "2.0", + id: 3, + method: "tools/call", + params: { name, arguments: args }, + }) as Effect.Effect; + return yield* body({ rpc, list, call }).pipe(Effect.provide(shared)); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)); + +const grouped = (names: ReadonlyArray) => ({ + waits: WAIT_TOOLS.filter((name) => names.includes(name)), + prs: names.includes(PR_TOOL), +}); + +describe("the T3 tool filter on /mcp", () => { + it.effect("tools/list: a tool outside the thread's groups is absent, one inside unchanged", () => + withServer(({ list }) => + Effect.gen(function* () { + const all = yield* list("all"); + expect(grouped(all)).toEqual({ waits: WAIT_TOOLS, prs: true }); + // Inside the groups: the same entries as with `all`. + expect(grouped(yield* list("prs"))).toEqual({ waits: [], prs: true }); + 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) ?? ""); + 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(all).toContain("playtest"); + expect(waits).not.toContain("playtest"); + expect(grouped(yield* list("none"))).toEqual({ waits: [], prs: false }); + // An outside client of this machine has no profile: only upstream's own rules apply (the + // wait tools that act as the calling thread are hidden from a client with none). + expect(grouped(yield* list("outside"))).toEqual({ waits: ["wait_cancel"], prs: true }); + }), + ), + ); + + it.effect("tools/call: refused by exact name, with a plain reason and the fix", () => + withServer(({ call }) => + Effect.gen(function* () { + const refused = yield* call("prs", "wait_list"); + expect(refused.result).toBeUndefined(); + expect(refused.error?.code).toBe(-32001); + expect(refused.error?.message).toBe( + 'T3 refused "wait_list": it is in the "waits" T3 tool group, which this thread\'s MCP profile "prs" leaves out. Ask the user to add "waits" 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.', + ); + expect(listed).toBe(0); + // Inside the groups the call runs as before. + const ran = yield* call("waits", "wait_list"); + expect(ran.error).toBeUndefined(); + expect(ran.result?.isError).not.toBe(true); + expect(listed).toBe(1); + }), + ), + ); + + it.effect("tools/call: no other name, and no batch, reaches a tool outside the groups", () => + withServer(({ call, rpc }) => + Effect.gen(function* () { + // The names a provider shows its model, and case changes: the server knows none of them. + for (const alias of [ + "mcp__t3-code__wait_list", + "t3-code__wait_list", + "WAIT_LIST", + " wait_list", + ]) { + const reply = yield* call("prs", alias); + expect([alias, reply.result?.isError === true || reply.error !== undefined]).toEqual([ + alias, + true, + ]); + } + // A name the server does not have: upstream's lookup refuses it, before the group rule. + expect((yield* call("prs", "no_such_tool")).error?.code).toBe(-32602); + // A JSON-RPC batch: the transport (MCP 2025-06-18) refuses it whole, so no call in it runs. + const batch = yield* rpc("prs", [ + { + jsonrpc: "2.0", + id: 10, + method: "tools/call", + params: { name: "wait_list", arguments: {} }, + }, + { + jsonrpc: "2.0", + id: 11, + method: "tools/call", + params: { name: "task_list", arguments: {} }, + }, + ]); + expect(batch).toEqual({ status: 400 }); + expect(listed).toBe(0); + }), + ), + ); + + it.effect("tool_search: a tool outside the groups is not found, nor loaded", () => + withServer(({ call }) => + Effect.gen(function* () { + const found = (reply: RpcReply) => + ( + (reply.result?.structuredContent as { tools?: ReadonlyArray<{ name: string }> }) + ?.tools ?? [] + ).map((tool) => tool.name); + expect(found(yield* call("all", "tool_search", { query: "wait_list waits" }))).toContain( + "wait_list", + ); + const prs = found(yield* call("prs", "tool_search", { query: "wait_list waits" })); + expect(prs.filter((name) => WAIT_TOOLS.includes(name))).toEqual([]); + expect(found(yield* call("prs", "tool_search", { query: PR_TOOL }))).toContain(PR_TOOL); + // A profile that cannot apply finds no grouped tool. + expect(found(yield* call("gone", "tool_search", { query: "wait_list pull" }))).toEqual([]); + }), + ), + ); + + it.effect("a child is never wider than its parent: its own default is cut to the parent's", () => + withServer(({ list, call }) => + Effect.gen(function* () { + // Its own role default (`waits`) and its parent's (`prs`) share no group: it gets none. + expect(grouped(yield* list("child"))).toEqual({ waits: [], prs: false }); + expect((yield* call("child", "wait_list")).error?.code).toBe(-32001); + expect((yield* call("child", PR_TOOL)).error?.code).toBe(-32001); + }), + ), + ); + + it.effect("fail closed: a profile that is gone, or a thread T3 cannot read, keeps no group", () => + withServer(({ list, call }) => + Effect.gen(function* () { + for (const token of ["gone", "deleted"]) { + expect(grouped(yield* list(token))).toEqual({ waits: [], prs: false }); + const refused = yield* call(token, "wait_list"); + expect(refused.error?.code).toBe(-32001); + expect(refused.error?.message).toContain("this thread's MCP profile cannot be applied"); + } + expect((yield* call("gone", "wait_list")).error?.message).toContain( + 'MCP profile "gone" is not set up', + ); + expect((yield* call("deleted", "wait_list")).error?.message).toContain( + "T3 cannot read this thread", + ); + // The tools every profile keeps stay: tool_search answers (with nothing grouped). + expect((yield* call("gone", "tool_search", { query: "x" })).error).toBeUndefined(); + expect(listed).toBe(0); + }), + ), + ); + + it.effect("old or empty state: no profile set anywhere, every thread sees every tool", () => + withServer( + ({ list }) => + Effect.gen(function* () { + for (const token of ["all", "prs", "child"]) { + expect(grouped(yield* list(token))).toEqual({ waits: WAIT_TOOLS, prs: true }); + } + }), + WAITS_ON, + ), + ); + + it.effect( + "a change mid-thread applies from the next turn; a restart works the set out again", + () => + withServer(({ list }) => + Effect.gen(function* () { + expect(grouped(yield* list("prs"))).toEqual({ waits: [], prs: true }); + const settings = yield* ServerSettingsService.ServerSettingsService; + yield* settings.updateSettings({ + mcpThreadProfiles: { "thread-prs": "waits" }, + } as never); + // The running turn keeps the set it started with. + 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]!, {}); + 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]!, {}); + 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); + T3ToolSets.__testing.clear(); + expect(grouped(yield* list("prs"))).toEqual({ waits: [], prs: true }); + }), + ), + ); +}); + +describe("tool_search's filter", () => { + const searchable = (name: string) => + Effect.sync(() => McpT3ToolFilter.searchableT3Tool({ name })).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scopeFor("prs")), + ); + + it.effect("with the rule on the server, a thread with no set finds only the ungrouped", () => + withServer(() => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + expect(yield* searchable("wait_list")).toBe(false); + expect(yield* searchable("request_secret")).toBe(true); + }), + ), + ); + + it.effect("on a server without the rule (upstream's tests), it searches as upstream does", () => + Effect.gen(function* () { + T3ToolSets.__testing.clear(); + expect(yield* searchable("wait_list")).toBe(true); + }), + ); +}); + +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( + ([, 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"); + }), + ); +}); + +describe("the refusal of a tool in no group", () => { + it.effect("names the real cause (a T3 bug), not a setting that cannot fix it", () => + 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); + 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( + 'Ask the user to add "pull-requests" to that profile\'s t3Tools', + ); + }), + ); +}); + +describe("the T3 tool sets in memory", () => { + const groups = (name: string): T3ToolSets.T3ToolSet => ({ + _tag: "Groups", + name, + groups: new Set(["threads"]), + }); + + it.effect("a set worked out for a request never replaces one a turn fixed", () => + Effect.sync(() => { + T3ToolSets.__testing.clear(); + T3ToolSets.fixT3ToolSet("t", groups("turn")); + expect(T3ToolSets.rememberT3ToolSet("t", groups("request"))).toEqual(groups("turn")); + expect(T3ToolSets.rememberT3ToolSet("u", groups("request"))).toEqual(groups("request")); + // A later turn start does replace it. + T3ToolSets.fixT3ToolSet("u", groups("turn")); + expect(T3ToolSets.t3ToolSetFor("u")).toEqual(groups("turn")); + }), + ); + + it.effect("keeps at most MAX_T3_TOOL_SETS threads, dropping the oldest", () => + Effect.sync(() => { + T3ToolSets.__testing.clear(); + for (let index = 0; index <= T3ToolSets.MAX_T3_TOOL_SETS; index += 1) { + T3ToolSets.fixT3ToolSet(`thread-${index}`, groups("p")); + } + expect(T3ToolSets.__testing.size()).toBe(T3ToolSets.MAX_T3_TOOL_SETS); + // The dropped thread has no set: its next request works it out again, never `all`. + expect(T3ToolSets.t3ToolSetFor("thread-0")).toBeUndefined(); + expect(T3ToolSets.t3ToolSetFor(`thread-${T3ToolSets.MAX_T3_TOOL_SETS}`)).toBeDefined(); + }), + ); +}); diff --git a/apps/server/src/fork/mcpT3ToolFilter.ts b/apps/server/src/fork/mcpT3ToolFilter.ts new file mode 100644 index 000000000000..619b56b641ec --- /dev/null +++ b/apps/server/src/fork/mcpT3ToolFilter.ts @@ -0,0 +1,188 @@ +/** + * 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). + */ +import { MCP_T3_UNGROUPED_TOOLS, type McpT3ToolGroup, type ThreadId } from "@t3tools/contracts"; +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], +]; + +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; + +/** Servers in this process the rule is installed on; `tool_search` follows it only there. */ +let installed = 0; + +/** + * `tool_search`'s filter: false for a tool the calling thread's set leaves out (none set: only the + * ungrouped). Reads the caller from the request fiber, like upstream's `EnabledWhen`, so call it only + * 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 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); +}; + +/** + * 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/mcpT3ToolSets.ts b/apps/server/src/fork/mcpT3ToolSets.ts new file mode 100644 index 000000000000..1ff95e607426 --- /dev/null +++ b/apps/server/src/fork/mcpT3ToolSets.ts @@ -0,0 +1,70 @@ +/** + * 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). + */ +import type { McpT3ToolGroup } from "@t3tools/contracts"; + +import type { McpProfileResolved } from "./mcpProfile.ts"; + +/** What a thread's T3 tools may be: its profile's groups, or none when the profile cannot apply. */ +export type T3ToolSet = + | { + readonly _tag: "Groups"; + /** The profile's name, for refusals. */ + readonly name: string; + readonly groups: "all" | ReadonlySet; + } + | { + /** The profile cannot be worked out: only the tools every profile keeps. Never `all`. */ + readonly _tag: "Refused"; + /** The resolver's plain reason, with its fix. */ + readonly reason: string; + }; + +export const t3ToolSetOf = (resolved: McpProfileResolved): T3ToolSet => ({ + _tag: "Groups", + name: resolved.name, + groups: resolved.profile.t3Tools === "all" ? "all" : new Set(resolved.profile.t3Tools), +}); + +export const refusedT3ToolSet = (reason: string): T3ToolSet => ({ _tag: "Refused", reason }); + +/** + * Threads kept; the oldest beyond this is dropped, and its next request works its set out again + * from the settings then (never wider than they allow). + */ +export const MAX_T3_TOOL_SETS = 4096; + +const sets = new Map(); + +const keep = (threadId: string, set: T3ToolSet) => { + sets.delete(threadId); + sets.set(threadId, set); + for (const oldest of sets.keys()) { + if (sets.size <= MAX_T3_TOOL_SETS) break; + sets.delete(oldest); + } +}; + +/** A turn of the thread starts: its set from now until the next turn starts. */ +export const fixT3ToolSet = (threadId: string, set: T3ToolSet): void => keep(threadId, set); + +/** A turn start stopped half-way: no set stands, so the next request works it out again. */ +export const forgetT3ToolSet = (threadId: string): void => void sets.delete(threadId); + +export const t3ToolSetFor = (threadId: string): T3ToolSet | undefined => sets.get(threadId); + +/** + * A set worked out for a request before any turn fixed one (a provider that lists tools as its + * session opens). Kept only if no turn fixed one meanwhile, so it never replaces a turn's set. + */ +export const rememberT3ToolSet = (threadId: string, set: T3ToolSet): T3ToolSet => { + const fixed = sets.get(threadId); + if (fixed !== undefined) return fixed; + keep(threadId, set); + return set; +}; + +export const __testing = { clear: () => sets.clear(), size: () => sets.size }; diff --git a/apps/server/src/fork/personOnlySettings.test.ts b/apps/server/src/fork/personOnlySettings.test.ts index ab948888565b..f5b0c59b4379 100644 --- a/apps/server/src/fork/personOnlySettings.test.ts +++ b/apps/server/src/fork/personOnlySettings.test.ts @@ -19,6 +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 { MCP_T3_TOOLKIT_GROUPS, MCP_T3_TOOL_NOT_ALLOWED, @@ -393,6 +394,29 @@ describe("MCP profile T3 tool groups", () => { expect(mcpT3ToolGroup("toolSearch", "send_to_user")).toBe(MCP_T3_TOOL_NOT_ALLOWED); }); + 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 + // 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) { + for (const name of names) { + const group = mcpT3ToolGroup(folder, name); + const known = fromFolders.get(name); + fromFolders.set(name, known === undefined || known === group ? group : "two groups"); + } + } + const sorted = (table: ReadonlyMap) => + [...table].toSorted(([a], [b]) => a.localeCompare(b)); + expect(sorted(T3_TOOL_GROUPS)).toEqual(sorted(fromFolders)); + }); + + it("gives every group of MCP_T3_TOOL_GROUPS a tool in the T3 tool filter's table", () => { + // A group added to the contracts (a new toolkit, or tools moved) with no toolkit behind it in the + // filter would be offered in Settings and keep nothing. + const used = new Set(T3_TOOL_GROUPS.values()); + expect(MCP_T3_TOOL_GROUPS.filter((group) => !used.has(group))).toEqual([]); + }); + it("does not allow a tool this build does not know", () => { expect(mcpT3ToolGroup("someNewToolkit", "anything")).toBe(MCP_T3_TOOL_NOT_ALLOWED); expect(mcpT3ToolGroup("someNewToolkit", "send_to_user")).toBe(MCP_T3_TOOL_NOT_ALLOWED); diff --git a/apps/server/src/holdWork.boot.test.ts b/apps/server/src/holdWork.boot.test.ts index b6b244fbdbf8..4f40f8d7b5c2 100644 --- a/apps/server/src/holdWork.boot.test.ts +++ b/apps/server/src/holdWork.boot.test.ts @@ -388,6 +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 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 8fbcbfdb07db..c350b9918c7e 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -96,6 +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 MessageHandlers from "./toolkits/message/handlers.ts"; import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts"; import { MCP_HTTP_PATH } from "../httpCors.ts"; @@ -1471,12 +1472,11 @@ export const layerToolSearch = Layer.mergeAll( layerDeferredListing, ).pipe(Layer.provide(layerToolExposure)); -/** - * Fork: every tool the fork adds. Advertised like `layerTools`, but measured by - * ForkAgentContextBudget.test.ts, so upstream's budget file stays upstream's. - */ +// Fork: the fork's tools. ForkAgentContextBudget.test.ts measures them, not upstream's budget. export const layerForkTools = Layer.mergeAll( toolkitRegistration(WaitsToolkit, WaitsHandlers.layer), ); -export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerForkTools, layerToolSearch)); +export const layer = layerMcpTransport( + Layer.mergeAll(layerTools, layerForkTools, layerToolSearch, McpT3ToolFilter.layer), +); diff --git a/apps/server/src/mcp/McpToolExposure.ts b/apps/server/src/mcp/McpToolExposure.ts index cb1ff850717d..ea16d778e5c1 100644 --- a/apps/server/src/mcp/McpToolExposure.ts +++ b/apps/server/src/mcp/McpToolExposure.ts @@ -1,5 +1,6 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import { searchableT3Tool } from "../fork/mcpT3ToolFilter.ts"; // Fork: MCP profile T3 tool groups export const TOOL_SEARCH = "tool_search"; @@ -67,6 +68,7 @@ export const make = ( .filter(Boolean); const found = tools() .filter((tool) => tool.name !== TOOL_SEARCH) + .filter(searchableT3Tool) // Fork: MCP profile T3 tool groups .map((tool) => ({ tool, score: score(tool, terms) })) .filter((match) => match.score > 0) .sort((a, b) => b.score - a.score) diff --git a/docs/fork/README.md b/docs/fork/README.md index 418c78f7797b..6f73a85baaf1 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -779,12 +779,40 @@ servers it names, written as Claude lists them (`claude.ai Calendar`). T3's own thread whose profile cannot be applied does not start its turn and says why: a missing or broken profile, a parent thread that cannot be read, a `settings.json` T3 cannot read (when only a provider secret cannot be read, the profile comes from `settings.json` alone and the server log -says so; with no profile set there, the thread gets `all` as before), a profile whose -`t3Tools` is not `"all"` (the T3 tool filter comes in a later pull request), or a session that +says so; with no profile set there, the thread gets `all` as before), or a session that still shows a server the profile leaves out, or does not list its servers within 5 minutes. A managed Claude policy on the machine or `--mcp-config` in the Claude launch arguments can make Claude load a server T3's list leaves out. +Every thread applies the profile's `t3Tools`, on any provider: T3's own MCP server judges each +request of the thread's MCP credential. A T3 tool outside the profile's groups is left out of +`tools/list`, left out of `tool_search`'s results, and refused when called, with a plain reason and +its fix (the call gets a JSON-RPC error: ask the owner to add the group to the profile, or to pick +a profile that has it). The server matches a call by the tool's exact name, and refuses a JSON-RPC +batch whole, so no other way reaches it. `request_secret`, `send_to_user` and `tool_search` stay in +every profile, and `[]` keeps only them. A tool in no group is refused by any profile but `all`, +and the refusal says that is a T3 bug to report (no setting fixes it); a test keeps every T3 tool +in exactly one group, and every group with a toolkit. The groups are fixed as each turn starts (as a Claude query opens, or as a turn +on another provider starts, also a resumed turn and a compaction): a running turn, and a message +sent into it, keep the set it started with, and a change applies from the thread's next turn. A +Claude thread whose groups changed starts a fresh Claude process for its next turn (resumed), so +Claude lists T3's tools again; that costs one prompt-cache miss. Another provider may keep the +list it read before: a tool it still shows is refused when called, and one newly kept is there the +next time it lists. The sets live in the server's memory, one per thread, not per credential (a +credential reused after a change gets the thread's new set from its next turn): after a restart, or for a thread +whose session lists its tools before its first turn, the set is worked out from the settings at +the first request. A thread whose profile cannot be worked out (a missing or broken profile, a +parent that cannot be read, settings that cannot be read, a thread T3 cannot read because it was +deleted) keeps only the tools every profile keeps and is told why, never `all`. A delegated child +is cut down to its parent's groups like its servers, so it never gets more. Clients from outside +a thread (signed in with OAuth) have no profile. + +Profiles are not a sandbox. Only requests that come from a thread are filtered: a request with no +thread (an OAuth client, the `t3 thread` CLI, a script run from a shell with the owner's access) +gets every T3 tool. So a profile limits what an agent is offered and may call as its thread, not +what an agent with a shell can reach. A thread that keeps the `orchestration` group can also ask a +wider thread to act for it (`t3_thread_send`). + A thread whose profile is narrower than `all` cannot start a top-level thread on this machine that gets more than its own profile ([#681](https://github.com/scuttletoby/t3code/issues/681)). `t3_thread_launch` and `create_threads` from it are refused, before any thread is made, when the new @@ -859,9 +887,9 @@ forwards it. A thread bound while a save is being made (the task's first run bin made, or another thread binding the task to itself) is kept by that save and not checked against it ([#719](https://github.com/scuttletoby/t3code/issues/719)): the first run's thread gets the project's profile the save was checked on, and a thread that binds the task to itself is one a -narrowed thread can already send words to (`t3_thread_send`, as T3's own tools cannot be cut yet). -A change that lets profiles cut T3's own tools (today `claudeMcpProfile.ts` refuses `t3Tools` -other than `all`) must revisit this: then such a bind is a way to a wider run. +narrowed thread can already send words to: `schedule_task` and `t3_thread_send` are both in the +`orchestration` T3 tool group, so a profile that keeps one keeps the other, and a profile without +it can do neither. An owner-made task that a narrowed thread changed runs as the owner's again if its entry is dropped from the file, which takes owner-level access to the state folder. Entries of deleted tasks are dropped at each start. @@ -888,8 +916,7 @@ fails is stopped, the goal is paused, and the turn ends failed with the reason. check when the profile was narrowed while Codex had the thread loaded (Codex reads a thread's config only as it loads it, so the change counts once it loads the thread again: after it has been idle a while, or after T3 restarts) and for a server a Codex plugin adds, which T3 cannot switch off -this way. A turn is also refused when the profile is missing or broken, its `t3Tools` is not -`"all"`, Codex's servers cannot be listed, a server's name cannot be written as a config key, the +this way. A turn is also refused when the profile is missing or broken, Codex's servers cannot be listed, a server's name cannot be written as a config key, the thread is not in T3's store, or (once any thread on that app-server has a narrower profile) Codex asks to load or run a thread T3 cannot match to one of its own. Codex answers the server list only once the thread's servers have started, and T3 waits up to 30 seconds for each read: a kept server @@ -898,14 +925,18 @@ refused (for example a read failed once), T3 does not move the thread to a fresh which would lose its history: the turn fails, and sending it again resumes the thread. A thread on `all` sends Codex nothing extra, but T3 still works out its profile from the settings and the thread store at each load and turn, so a thread missing from the store refuses there too. A turn already running when the profile is narrowed keeps its servers -until it ends. - -Only Claude and Codex threads apply profiles. A thread on any other provider would get every -MCP server and every T3 tool whatever its profile says. So its turn is not started when its profile -is narrower than `all` ([#672](https://github.com/scuttletoby/t3code/issues/672)): the machine that +until it ends. A Codex thread's T3 tool groups are cut on T3's own server, as on every provider +(above); each Codex turn fixes them as it starts, also one Codex starts on its own (a goal's next +turn, a sub-agent's turn, which uses its parent's T3 thread). + +Only Claude and Codex threads apply a profile's outside servers. A thread on any other provider +would get every outside MCP server whatever its profile says (T3's own tool groups apply on every +provider, above). So its turn is not started when its profile leaves out any outside server +([#672](https://github.com/scuttletoby/t3code/issues/672)): the machine that runs the turn checks the thread's profile as the turn starts (also a resumed turn, and a compaction, which some providers run as a `/compact` prompt) and refuses it, saying why and how to go on (switch -the thread to a Claude or Codex instance, or pick `all` for it). That covers every way a thread gets there: a +the thread to a Claude or Codex instance, or pick `all`, or a profile whose servers are `"all"`, for +it). A profile whose `servers` is `"all"` and whose `t3Tools` is a list runs on every provider. That covers every way a thread gets there: a thread switched to another provider (`t3_thread_configure`, or in the app), a thread made by `t3_thread_launch` in a project whose profile is narrower, a task delegated on this machine (a child gets its parent's profile, or `mcpSubagentProfile`), and a task another machine sent, also one from @@ -918,7 +949,8 @@ reads as the provider keeps it (its status and capabilities stay live). One chan thread: a turn on another provider refuses when the profile cannot be worked out (the cases above), where it used to run, and the settings are read for each such turn. A delegation also refuses, before anything is sent, a narrower profile to a Codex (or other non-Claude) instance on another -machine (see below), so the task is not made only to be refused there. +machine (see below), so the task is not made only to be refused there; that holds also for a +profile that only cuts T3 tools, as the other machine may run a T3 from before the T3 tool filter. Each tool call is checked too: a call to an MCP server the profile leaves out (also one an agent file declares, or one added while the session runs) is refused at the moment of the call: Claude diff --git a/packages/contracts/src/mcpProfile.ts b/packages/contracts/src/mcpProfile.ts index acf409878a70..b584ff72515c 100644 --- a/packages/contracts/src/mcpProfile.ts +++ b/packages/contracts/src/mcpProfile.ts @@ -66,8 +66,8 @@ export type McpT3ToolGroup = (typeof MCP_T3_TOOL_GROUPS)[number]; /** * T3 tools every profile keeps, in no group: the two message tools, and `tool_search`, which only - * finds tools the thread may already use (the T3 tool filter, a later PR, leaves the others out of - * its results). + * finds tools the thread may already use (the server's T3 tool filter leaves the others out of its + * results). */ export const MCP_T3_UNGROUPED_TOOLS: ReadonlyArray = [ "request_secret",