From ac0d1bd2c5b728baa7c6fd14e751a8448497bd69 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:22:07 +0000 Subject: [PATCH 1/6] Fork: MCP profile settings and resolver (MCP1, off by default) Adds the four MCP profile settings keys (mcpProfiles, mcpProfile, mcpSubagentProfile, mcpThreadProfiles) to the fork settings seam, their schemas in packages/contracts/src/mcpProfile.ts, a replaceEntries patch rule (per-entry replace, keep the 500 newest thread picks), and the pure resolver in apps/server/src/fork/mcpProfile.ts. Nothing calls the resolver yet, so behaviour is unchanged: every thread resolves to "all". FORK_PERSON_ONLY_KEYS (every fork key not agent-writable) replaces the hand-written PERSON_ONLY_KEYS test with one that loads every T3 toolkit and fails if any tool input names a person-only key in any spelling. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/fork/mcpProfile.test.ts | 327 ++++++++++++++++++ apps/server/src/fork/mcpProfile.ts | 286 +++++++++++++++ .../src/fork/personOnlySettings.test.ts | 143 ++++++++ .../environment/waitForSettings.test.ts | 27 -- packages/contracts/src/forkDefaults.ts | 48 +++ packages/contracts/src/forkSettings.ts | 63 +++- packages/contracts/src/mcpProfile.test.ts | 92 +++++ packages/contracts/src/mcpProfile.ts | 136 ++++++++ packages/shared/src/forkSettingsPatch.test.ts | 73 ++++ packages/shared/src/forkSettingsPatch.ts | 14 + 10 files changed, 1178 insertions(+), 31 deletions(-) create mode 100644 apps/server/src/fork/mcpProfile.test.ts create mode 100644 apps/server/src/fork/mcpProfile.ts create mode 100644 apps/server/src/fork/personOnlySettings.test.ts delete mode 100644 apps/server/src/mcp/toolkits/environment/waitForSettings.test.ts create mode 100644 packages/contracts/src/mcpProfile.test.ts create mode 100644 packages/contracts/src/mcpProfile.ts diff --git a/apps/server/src/fork/mcpProfile.test.ts b/apps/server/src/fork/mcpProfile.test.ts new file mode 100644 index 0000000000000..e92adfab2752f --- /dev/null +++ b/apps/server/src/fork/mcpProfile.test.ts @@ -0,0 +1,327 @@ +import { ServerSettings } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { + MCP_PROFILE_MAX_LINEAGE, + type McpProfileResolution, + type McpProfileThread, + isEveryMcpTool, + resolveMcpProfile, +} from "./mcpProfile.ts"; + +/** The settings as a load decodes them from a settings file's JSON. */ +const decodeSettingsFile = Schema.decodeSync(ServerSettings); +const fromFile = (file: Record) => decodeSettingsFile(file); + +const top = (threadId: string, project?: McpProfileThread["project"]): McpProfileThread => ({ + threadId, + delegated: false, + ...(project === undefined ? {} : { project }), +}); +const child = (threadId: string, project?: McpProfileThread["project"]): McpProfileThread => ({ + ...top(threadId, project), + delegated: true, +}); + +const PROFILES = { + lean: { servers: [], t3Tools: ["orchestration", "threads", "pull-requests"] }, + review: { servers: ["docs"], t3Tools: ["threads"] }, + docs: { servers: ["docs", "game"], t3Tools: "all" }, +}; + +const resolved = (result: McpProfileResolution) => { + if (result._tag !== "Resolved") throw new Error(`expected Resolved, got ${result.message}`); + return result; +}; +const refused = (result: McpProfileResolution) => { + if (result._tag !== "CannotApply") throw new Error(`expected CannotApply, got ${result.name}`); + return result; +}; + +describe("MCP profile resolver: old and empty state", () => { + it.each([ + ["no settings file (no keys)", {}], + [ + "empty values", + { mcpProfiles: {}, mcpProfile: "", mcpSubagentProfile: "", mcpThreadProfiles: {} }, + ], + ["the defaults written out", { mcpProfile: "all", mcpSubagentProfile: "inherit" }], + ])("%s: every thread gets everything, as today", (_name, file) => { + const settings = fromFile(file); + for (const lineage of [[top("t1")], [child("c1"), top("t1")], [top("f1"), top("t1")]]) { + const result = resolved(resolveMcpProfile(settings, lineage)); + expect(result.name).toBe("all"); + expect(isEveryMcpTool(result.profile)).toBe(true); + expect(result.narrowedByParent).toBe(false); + } + }); + + it("knows the built-ins with no profiles defined", () => { + const settings = fromFile({ mcpProfile: "t3-only" }); + expect(resolved(resolveMcpProfile(settings, [top("t1")])).profile).toEqual({ + servers: [], + t3Tools: "all", + }); + }); + + it("reads an empty keep-list as none, not as all", () => { + const settings = fromFile({ + mcpProfiles: { bare: { servers: [], t3Tools: [] } }, + mcpProfile: "bare", + }); + expect(resolved(resolveMcpProfile(settings, [top("t1")])).profile).toEqual({ + servers: [], + t3Tools: [], + }); + }); + + it("ignores a profile in the file that redefines a built-in", () => { + const settings = fromFile({ mcpProfiles: { all: { servers: [], t3Tools: [] } } }); + expect(isEveryMcpTool(resolved(resolveMcpProfile(settings, [top("t1")])).profile)).toBe(true); + }); +}); + +describe("MCP profile resolver: who decides", () => { + const settings = fromFile({ + mcpProfiles: PROFILES, + mcpProfile: "docs", + mcpSubagentProfile: "review", + mcpThreadProfiles: { picked: "lean", blank: " " }, + }); + + it.each([ + ["the environment default", [top("t1")], "docs", "environment"], + ["a project's override", [top("t1", { mcpProfile: "lean" })], "lean", "project"], + ["an empty project override", [top("t1", { mcpProfile: "" })], "docs", "environment"], + [ + "the sub-agent rule for a delegated child", + [child("c1"), top("t1")], + "review", + "subagent-rule", + ], + [ + "a project's sub-agent rule", + [child("c1", { mcpSubagentProfile: "lean" }), top("t1")], + "lean", + "subagent-rule", + ], + [ + "a project's `inherit` over the server's rule", + [child("c1", { mcpSubagentProfile: "inherit", mcpProfile: "docs" }), top("t1")], + "docs", + "project", + ], + ["the owner's pick", [top("picked")], "lean", "thread-pick"], + [ + "the owner's pick over the sub-agent rule", + [child("picked"), top("t1")], + "lean", + "thread-pick", + ], + ["a blank pick as no pick", [top("blank")], "docs", "environment"], + ] as const)("%s", (_name, lineage, name, source) => { + const result = resolved(resolveMcpProfile(settings, lineage)); + expect([result.name, result.source]).toEqual([name, source]); + }); + + it("does not apply the sub-agent rule to a fork", () => { + // A fork has a parent but is not delegated: its role default is `mcpProfile`. + expect(resolved(resolveMcpProfile(settings, [top("f1"), top("t1")])).name).toBe("docs"); + }); +}); + +describe("MCP profile resolver: a child is never wider than its parent", () => { + const settings = fromFile({ + mcpProfiles: PROFILES, + mcpProfile: "all", + mcpThreadProfiles: { "lean-parent": "lean", "review-parent": "review", "wide-child": "all" }, + }); + + it("cuts an inheriting child down to its parent", () => { + const result = resolved(resolveMcpProfile(settings, [child("c1"), top("lean-parent")])); + expect(result.name).toBe("all"); + expect(result.profile).toEqual(PROFILES.lean); + expect(result.narrowedByParent).toBe(true); + }); + + it("cuts both keep-lists to what both keep", () => { + const narrow = fromFile({ + mcpProfiles: PROFILES, + mcpSubagentProfile: "docs", + mcpThreadProfiles: { "review-parent": "review" }, + }); + const result = resolved(resolveMcpProfile(narrow, [child("c1"), top("review-parent")])); + expect(result.profile).toEqual({ servers: ["docs"], t3Tools: ["threads"] }); + }); + + it("cuts a fork down like a child", () => { + const result = resolved(resolveMcpProfile(settings, [top("f1"), top("review-parent")])); + expect(result.profile).toEqual(PROFILES.review); + }); + + it("cuts across every generation", () => { + const result = resolved( + resolveMcpProfile(settings, [child("grandchild"), child("c1"), top("review-parent")]), + ); + expect(result.profile).toEqual(PROFILES.review); + }); + + it("lets the owner's pick for the child stand", () => { + const result = resolved(resolveMcpProfile(settings, [child("wide-child"), top("lean-parent")])); + expect(isEveryMcpTool(result.profile)).toBe(true); + expect(result.narrowedByParent).toBe(false); + }); + + it("grows a child back to its own default when the parent widens, not beyond", () => { + const lineage = [child("c1"), top("p1")]; + const narrowSettings = fromFile({ + mcpProfiles: PROFILES, + mcpSubagentProfile: "docs", + mcpThreadProfiles: { p1: "lean" }, + }); + expect(resolved(resolveMcpProfile(narrowSettings, lineage)).profile).toEqual({ + servers: [], + t3Tools: ["orchestration", "threads", "pull-requests"], + }); + // The owner widens the parent to `all`: the child gets its own default, `docs`, not `all`. + const widened = fromFile({ + mcpProfiles: PROFILES, + mcpSubagentProfile: "docs", + mcpThreadProfiles: { p1: "all" }, + }); + expect(resolved(resolveMcpProfile(widened, lineage)).profile).toEqual(PROFILES.docs); + }); +}); + +describe("MCP profile resolver: never falls back to all", () => { + it.each([ + ["the environment names a missing profile", { mcpProfile: "gone" }, [top("t1")], "gone"], + ["a project names a missing profile", {}, [top("t1", { mcpProfile: "renamed" })], "renamed"], + [ + "the sub-agent rule names a missing profile", + { mcpSubagentProfile: "gone" }, + [child("c1"), top("t1")], + "gone", + ], + [ + "a thread pick names a missing profile", + { mcpThreadProfiles: { t1: "gone" } }, + [top("t1")], + "gone", + ], + ["a name no profile may have", { mcpProfile: "Not A Name" }, [top("t1")], "Not A Name"], + ["`inherit` as a thread's profile", { mcpProfile: "inherit" }, [top("t1")], "inherit"], + // Plain-object keys must not resolve to Object.prototype's members. + ["a prototype key", { mcpProfile: "constructor" }, [top("t1")], "constructor"], + ] as const)("%s: refuses and names it", (_name, file, lineage, name) => { + const result = refused( + resolveMcpProfile(fromFile({ mcpProfiles: PROFILES, ...file }), lineage), + ); + expect(result.problem).toBe("missing"); + expect(result.profileName).toBe(name); + expect(result.message).toContain(`"${name}"`); + expect(result.message).toContain('pick "all" for this thread'); + }); + + it.each([ + [ + "an unknown field (written by a newer build)", + { servers: [], t3Tools: [], builtinTools: "none" }, + ], + ["a missing field", { servers: [] }], + ["a wrong servers value", { servers: "docs", t3Tools: "all" }], + ["a blank server name", { servers: [" "], t3Tools: "all" }], + ["a non-string group", { servers: "all", t3Tools: [1] }], + ["not an object", ["docs"]], + ["null", null], + ])("a profile with %s is broken, never wider", (_name, entry) => { + const settings = fromFile({ mcpProfiles: { odd: entry }, mcpProfile: "odd" }); + const result = refused(resolveMcpProfile(settings, [top("t1")])); + expect(result.problem).toBe("broken"); + expect(result.profileName).toBe("odd"); + }); + + it("keeps one broken profile from touching the others", () => { + const settings = fromFile({ + mcpProfiles: { ...PROFILES, odd: { servers: [], t3Tools: [], future: true } }, + mcpProfile: "lean", + }); + expect(resolved(resolveMcpProfile(settings, [top("t1")])).profile).toEqual(PROFILES.lean); + }); + + it("refuses a child whose parent's profile cannot be applied", () => { + const settings = fromFile({ mcpProfiles: PROFILES, mcpThreadProfiles: { p1: "gone" } }); + const result = refused(resolveMcpProfile(settings, [child("c1"), top("p1")])); + expect([result.problem, result.profileName, result.threadId]).toEqual(["parent", "gone", "c1"]); + }); + + it("still starts a child the owner picked for, whatever the parent has", () => { + const settings = fromFile({ + mcpProfiles: PROFILES, + mcpThreadProfiles: { p1: "gone", c1: "lean" }, + }); + expect(resolved(resolveMcpProfile(settings, [child("c1"), top("p1")])).name).toBe("lean"); + }); + + it.each([ + ["repeats a thread", [child("c1"), top("p1"), child("c1")]], + [ + "is too deep", + Array.from({ length: MCP_PROFILE_MAX_LINEAGE + 1 }, (_, index) => child(`t${index}`)), + ], + ])("refuses a lineage that %s", (_name, lineage) => { + expect(refused(resolveMcpProfile(fromFile({}), lineage)).problem).toBe("lineage"); + }); +}); + +describe("MCP profile resolver: names that match nothing", () => { + it("keeps a T3 tool group this build does not know as nothing, and says so", () => { + const settings = fromFile({ + mcpProfiles: { future: { servers: [], t3Tools: ["threads", "mail", "threads"] } }, + mcpProfile: "future", + }); + const result = resolved(resolveMcpProfile(settings, [top("t1")])); + expect(result.profile.t3Tools).toEqual(["threads"]); + expect(result.unknownToolGroups).toEqual(["mail"]); + }); + + it("keeps a server name as written; whether it is set up is the provider's question", () => { + const settings = fromFile({ + mcpProfiles: { one: { servers: [" docs ", "docs", "not-set-up"], t3Tools: "all" } }, + mcpProfile: "one", + }); + expect(resolved(resolveMcpProfile(settings, [top("t1")])).profile.servers).toEqual([ + "docs", + "not-set-up", + ]); + }); + + it("ignores a stale pick for a thread that no longer exists", () => { + const settings = fromFile({ mcpProfiles: PROFILES, mcpThreadProfiles: { deleted: "lean" } }); + expect(resolved(resolveMcpProfile(settings, [top("t1")])).name).toBe("all"); + }); +}); + +describe("MCP profile resolver: runs again", () => { + it("gives the same answer for the same input and changes nothing", () => { + const file = { + mcpProfiles: PROFILES, + mcpSubagentProfile: "docs", + mcpThreadProfiles: { p1: "review" }, + }; + const settings = fromFile(structuredClone(file)); + const lineage = [child("c1"), top("p1")]; + const mcpKeys = () => ({ + mcpProfiles: settings.mcpProfiles, + mcpProfile: settings.mcpProfile, + mcpSubagentProfile: settings.mcpSubagentProfile, + mcpThreadProfiles: settings.mcpThreadProfiles, + }); + const before = structuredClone({ settings: mcpKeys(), lineage }); + const first = resolveMcpProfile(settings, lineage); + const second = resolveMcpProfile(settings, lineage); + expect(second).toEqual(first); + expect({ settings: mcpKeys(), lineage }).toEqual(before); + }); +}); diff --git a/apps/server/src/fork/mcpProfile.ts b/apps/server/src/fork/mcpProfile.ts new file mode 100644 index 0000000000000..f005ebf86fb4c --- /dev/null +++ b/apps/server/src/fork/mcpProfile.ts @@ -0,0 +1,286 @@ +/** + * Fork: which MCP profile a thread gets. Pure: the same settings and lineage give the same answer. + * A missing or unreadable profile is never replaced by `all`: the result says it cannot apply. + * Nothing calls it yet; the provider adapters and the T3 tool filter use it in later PRs. + */ +import { + MCP_PROFILE_ALL, + MCP_PROFILE_T3_ONLY, + MCP_SUBAGENT_INHERIT, + MCP_T3_TOOL_GROUPS, + type McpT3ToolGroup, + type ServerSettings, + isDefinableMcpProfileName, +} from "@t3tools/contracts"; + +/** The settings the resolver reads: the server's four MCP profile keys. */ +export type McpProfileSettings = Pick< + ServerSettings, + "mcpProfiles" | "mcpProfile" | "mcpSubagentProfile" | "mcpThreadProfiles" +>; + +/** One thread of a lineage, as the resolver needs it. */ +export interface McpProfileThread { + readonly threadId: string; + /** The thread's project's overrides; absent or empty fields use the server's. */ + readonly project?: { + readonly mcpProfile?: string | undefined; + readonly mcpSubagentProfile?: string | undefined; + }; + /** True for a delegated child thread (a `delegate_task` sub-agent or a task from a linked environment). */ + readonly delegated: boolean; +} + +/** A profile this build can apply: `"all"` or a keep-list, for servers and for T3 tool groups. */ +export interface McpProfileSet { + readonly servers: "all" | ReadonlyArray; + readonly t3Tools: "all" | ReadonlyArray; +} + +/** Where a thread's profile came from. */ +export type McpProfileSource = "thread-pick" | "subagent-rule" | "project" | "environment"; + +export interface McpProfileResolved { + readonly _tag: "Resolved"; + /** The profile's name, before any cut to the parent's. */ + readonly name: string; + readonly source: McpProfileSource; + /** What the thread gets. */ + readonly profile: McpProfileSet; + /** True when the parent's profile took something away from the named one. */ + readonly narrowedByParent: boolean; + /** T3 tool groups the profile names that this build does not know; they keep nothing. */ + readonly unknownToolGroups: ReadonlyArray; +} + +export type McpProfileProblem = + /** No profile has this name (or the name is not one a profile may have). */ + | "missing" + /** The profile is there, but this build cannot read it (a typo, or a newer build wrote it). */ + | "broken" + /** The parent thread's own profile cannot be applied, so the child's cannot be cut down. */ + | "parent" + /** The lineage repeats a thread or is too deep. */ + | "lineage"; + +export interface McpProfileCannotApply { + readonly _tag: "CannotApply"; + readonly problem: McpProfileProblem; + /** The profile name at fault (the parent's for `parent`); empty for `lineage`. */ + readonly profileName: string; + /** The thread whose setting is at fault. */ + readonly threadId: string; + /** One plain sentence on what is wrong and how to fix it, for the thread. */ + readonly message: string; +} + +export type McpProfileResolution = McpProfileResolved | McpProfileCannotApply; + +/** Longer lineages are refused; real delegation chains are a few threads deep. */ +export const MCP_PROFILE_MAX_LINEAGE = 64; + +const BUILT_IN_PROFILES: Readonly> = { + [MCP_PROFILE_ALL]: { servers: "all", t3Tools: "all" }, + [MCP_PROFILE_T3_ONLY]: { servers: [], t3Tools: "all" }, +}; + +const KNOWN_GROUPS: ReadonlySet = new Set(MCP_T3_TOOL_GROUPS); +const PROFILE_FIELDS: ReadonlySet = new Set(["servers", "t3Tools"]); + +/** True when the profile is today's behaviour: every outside server and every T3 tool. */ +export const isEveryMcpTool = (profile: McpProfileSet): boolean => + profile.servers === "all" && profile.t3Tools === "all"; + +const isRecord = (value: unknown): value is Readonly> => + typeof value === "object" && value !== null && !Array.isArray(value); + +const unique = (values: ReadonlyArray): ReadonlyArray => [...new Set(values)]; + +type Parsed = { readonly ok: true; readonly value: A } | { readonly ok: false; issue: string }; + +function parseServers(value: unknown): Parsed { + if (value === "all") return { ok: true, value }; + if (!Array.isArray(value)) return { ok: false, issue: '`servers` must be "all" or a list' }; + const names: Array = []; + for (const entry of value) { + const name = typeof entry === "string" ? entry.trim() : ""; + if (name === "") return { ok: false, issue: "`servers` holds an entry that is not a name" }; + names.push(name); + } + return { ok: true, value: unique(names) }; +} + +function parseT3Tools( + value: unknown, +): Parsed<{ readonly groups: McpProfileSet["t3Tools"]; readonly unknown: ReadonlyArray }> { + if (value === "all") return { ok: true, value: { groups: "all", unknown: [] } }; + if (!Array.isArray(value)) return { ok: false, issue: '`t3Tools` must be "all" or a list' }; + const groups: Array = []; + const unknown: Array = []; + for (const entry of value) { + if (typeof entry !== "string") { + return { ok: false, issue: "`t3Tools` holds an entry that is not a group name" }; + } + // A group this build does not know keeps nothing, like a server that is not set up. + if (KNOWN_GROUPS.has(entry)) groups.push(entry as McpT3ToolGroup); + else unknown.push(entry); + } + return { ok: true, value: { groups: unique(groups), unknown: unique(unknown) } }; +} + +type Lookup = + | { readonly ok: true; readonly profile: McpProfileSet; readonly unknown: ReadonlyArray } + | { readonly ok: false; readonly problem: "missing" | "broken"; readonly issue: string }; + +/** A named profile: a built-in, or an entry of `mcpProfiles` checked now. */ +function lookUp(settings: McpProfileSettings, name: string): Lookup { + const builtIn = Object.hasOwn(BUILT_IN_PROFILES, name) ? BUILT_IN_PROFILES[name] : undefined; + // Built-ins win over an entry of the same name, which a save never writes. + if (builtIn !== undefined) return { ok: true, profile: builtIn, unknown: [] }; + const profiles: unknown = settings.mcpProfiles; + if (!isDefinableMcpProfileName(name) || !isRecord(profiles) || !Object.hasOwn(profiles, name)) { + return { ok: false, problem: "missing", issue: "" }; + } + const entry = profiles[name]; + if (!isRecord(entry)) return { ok: false, problem: "broken", issue: "it is not an object" }; + const extra = Object.keys(entry).filter((field) => !PROFILE_FIELDS.has(field)); + if (extra.length > 0) { + return { + ok: false, + problem: "broken", + issue: `it has fields this version does not know (${extra.join(", ")})`, + }; + } + const servers = parseServers(entry.servers); + if (!servers.ok) return { ok: false, problem: "broken", issue: servers.issue }; + const t3Tools = parseT3Tools(entry.t3Tools); + if (!t3Tools.ok) return { ok: false, problem: "broken", issue: t3Tools.issue }; + return { + ok: true, + profile: { servers: servers.value, t3Tools: t3Tools.value.groups }, + unknown: t3Tools.value.unknown, + }; +} + +/** A set value; empty or absent means "not set". */ +const nonEmpty = (value: string | undefined): string | undefined => { + const trimmed = value?.trim(); + return trimmed === undefined || trimmed === "" ? undefined : trimmed; +}; + +/** The profile name a thread asks for on its own, before any cut to its parent's. */ +function ownChoice( + settings: McpProfileSettings, + thread: McpProfileThread, +): { readonly name: string; readonly source: McpProfileSource } { + const picks: unknown = settings.mcpThreadProfiles; + const pick = + isRecord(picks) && Object.hasOwn(picks, thread.threadId) ? picks[thread.threadId] : undefined; + if (typeof pick === "string" && nonEmpty(pick) !== undefined) { + return { name: pick.trim(), source: "thread-pick" }; + } + if (thread.delegated) { + const rule = + nonEmpty(thread.project?.mcpSubagentProfile) ?? + nonEmpty(settings.mcpSubagentProfile) ?? + MCP_SUBAGENT_INHERIT; + if (rule !== MCP_SUBAGENT_INHERIT) return { name: rule, source: "subagent-rule" }; + } + const project = nonEmpty(thread.project?.mcpProfile); + if (project !== undefined) return { name: project, source: "project" }; + return { name: nonEmpty(settings.mcpProfile) ?? MCP_PROFILE_ALL, source: "environment" }; +} + +/** `child` cut down to `parent`: a keep-list keeps only what both keep. */ +function cutTo(child: McpProfileSet, parent: McpProfileSet): McpProfileSet { + const servers = + parent.servers === "all" + ? child.servers + : child.servers === "all" + ? parent.servers + : child.servers.filter((name) => parent.servers.includes(name)); + const t3Tools = + parent.t3Tools === "all" + ? child.t3Tools + : child.t3Tools === "all" + ? parent.t3Tools + : child.t3Tools.filter((group) => parent.t3Tools.includes(group)); + return { servers, t3Tools }; +} + +const sameList = (a: "all" | ReadonlyArray, b: "all" | ReadonlyArray) => + a === "all" || b === "all" + ? a === b + : a.length === b.length && a.every((value) => b.includes(value)); + +const FIX = `pick "${MCP_PROFILE_ALL}" for this thread, or fix the profile in Settings`; + +function cannotApply( + problem: McpProfileProblem, + thread: McpProfileThread, + profileName: string, + issue: string, +): McpProfileCannotApply { + const message = + problem === "missing" + ? `MCP profile "${profileName}" is not set up, so this thread cannot start: ${FIX}.` + : problem === "broken" + ? `MCP profile "${profileName}" cannot be read by this version (${issue}), so this thread cannot start: ${FIX}.` + : problem === "parent" + ? `The parent thread's MCP profile "${profileName}" cannot be applied, so this thread cannot start: ${FIX}.` + : `This thread's parent threads ${issue}, so its MCP profile cannot be worked out: ${FIX}.`; + return { _tag: "CannotApply", problem, profileName, threadId: thread.threadId, message }; +} + +function resolveAt( + settings: McpProfileSettings, + lineage: ReadonlyArray, + index: number, +): McpProfileResolution { + const thread = lineage[index]!; + const choice = ownChoice(settings, thread); + const found = lookUp(settings, choice.name); + if (!found.ok) return cannotApply(found.problem, thread, choice.name, found.issue); + const own: McpProfileResolved = { + _tag: "Resolved", + name: choice.name, + source: choice.source, + profile: found.profile, + narrowedByParent: false, + unknownToolGroups: found.unknown, + }; + // The owner's pick is final; a thread without a parent has nothing to be cut to. + if (choice.source === "thread-pick" || index === lineage.length - 1) return own; + const parent = resolveAt(settings, lineage, index + 1); + if (parent._tag === "CannotApply") { + return cannotApply("parent", thread, parent.profileName, parent.message); + } + const profile = cutTo(own.profile, parent.profile); + return { + ...own, + profile, + narrowedByParent: + !sameList(profile.servers, own.profile.servers) || + !sameList(profile.t3Tools, own.profile.t3Tools), + }; +} + +/** + * The MCP profile of `lineage[0]`; `lineage` goes up through parents (a fork's source counts). + * Order: the owner's pick is final; else the role default (`mcpSubagentProfile` for a delegated + * child unless `inherit`, else `mcpProfile`; a project's override wins), cut down to the parent's. + */ +export function resolveMcpProfile( + settings: McpProfileSettings, + lineage: ReadonlyArray, +): McpProfileResolution { + const self = lineage[0]; + if (self === undefined) throw new Error("resolveMcpProfile needs the thread itself"); + if (lineage.length > MCP_PROFILE_MAX_LINEAGE) { + return cannotApply("lineage", self, "", `are more than ${MCP_PROFILE_MAX_LINEAGE} deep`); + } + if (new Set(lineage.map((thread) => thread.threadId)).size !== lineage.length) { + return cannotApply("lineage", self, "", "repeat a thread"); + } + return resolveAt(settings, lineage, 0); +} diff --git a/apps/server/src/fork/personOnlySettings.test.ts b/apps/server/src/fork/personOnlySettings.test.ts new file mode 100644 index 0000000000000..0e15e4c01b0e2 --- /dev/null +++ b/apps/server/src/fork/personOnlySettings.test.ts @@ -0,0 +1,143 @@ +// @effect-diagnostics nodeBuiltinImport:off - Lists the server sources and toolkit modules to find every T3 tool. +/** + * Fork: only a person changes fork settings. No T3 tool's input may name a fork setting + * (`FORK_PERSON_ONLY_KEYS`: every fork key not in `FORK_AGENT_WRITABLE_KEYS`), so an agent has no + * tool path to write one. The list is derived from forkSettings.ts, so a new fork setting is + * covered without a row here. + */ +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { FORK_AGENT_WRITABLE_KEYS, FORK_PERSON_ONLY_KEYS } from "@t3tools/contracts"; +import { Tool, Toolkit } from "effect/ai"; +import * as Schema from "effect/Schema"; +import { beforeAll, describe, expect, it } from "vite-plus/test"; + +const TOOLKITS_DIR = NodePath.resolve(import.meta.dirname, "../mcp/toolkits"); +/** Every toolkit module; each defines its tools with `Tool.make` and exports its toolkits. */ +const loadToolkitModules = (): Promise>> => + Promise.all( + NodeFS.readdirSync(TOOLKITS_DIR, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => NodePath.join(TOOLKITS_DIR, entry.name, "tools.ts")) + .filter((path) => NodeFS.existsSync(path)) + .map((path) => import(path) as Promise>), + ); +/** Server sources (relative to src/) that call `Tool.make` outside the toolkit modules. */ +const toolsDefinedElsewhere = (): ReadonlyArray => { + const root = NodePath.resolve(import.meta.dirname, ".."); + return NodeFS.readdirSync(root, { recursive: true, encoding: "utf8" }) + .filter((path) => path.endsWith(".ts") && !path.endsWith(".test.ts")) + .map((path) => path.split(NodePath.sep).join("/")) + .filter((path) => !/^mcp\/toolkits\/[^/]+\/tools\.ts$/.test(path)) + .filter((path) => + /\bTool\.make\(/.test(NodeFS.readFileSync(NodePath.join(root, path), "utf8")), + ); +}; +/** Files that call `Tool.make` but advertise nothing: each with the reason. */ +const NOT_ADVERTISED: Readonly> = { + // Describes the linked environment's `orchestrator_capabilities` to call it there. + "peer/RemoteDelegation.ts": "a client of another environment's tool", +}; + +// A toolkit: an object whose `tools` are all `Tool`s (Toolkit exports no type guard). +const isToolkit = (value: unknown): value is Toolkit.Toolkit> => { + if ((typeof value !== "object" && typeof value !== "function") || value === null) return false; + if (!("tools" in value)) return false; + const toolsOf: unknown = value.tools; + return ( + typeof toolsOf === "object" && + toolsOf !== null && + Object.values(toolsOf).every( + (tool: unknown) => typeof tool === "object" && tool !== null && Tool.TypeId in tool, + ) + ); +}; + +const tools = new Map(); +beforeAll(async () => { + for (const module of await loadToolkitModules()) { + for (const value of Object.values(module)) { + if (!isToolkit(value)) continue; + for (const tool of Object.values(value.tools)) tools.set(tool.name, tool); + } + } +}); + +/** Lower case without separators, so `mcp_profile` or `MCP-Profile` still count as `mcpProfile`. */ +const normalize = (name: string) => name.toLowerCase().replaceAll(/[^a-z0-9]/g, ""); +const PERSON_ONLY = new Map(FORK_PERSON_ONLY_KEYS.map((key) => [normalize(key), key])); + +/** Every property name anywhere in a JSON schema. */ +const propertyNames = (schema: unknown): ReadonlyArray => { + if (schema === null || typeof schema !== "object") return []; + const record = schema as Record; + const own = + record.properties !== null && typeof record.properties === "object" + ? Object.keys(record.properties) + : []; + return [...own, ...Object.values(record).flatMap(propertyNames)]; +}; + +/** The person-only settings a tool's input names. */ +const personOnlyKeysIn = (tool: Tool.Any): ReadonlyArray => + propertyNames(Tool.getJsonSchema(tool)).flatMap((name) => { + const key = PERSON_ONLY.get(normalize(name)); + return key === undefined ? [] : [key]; + }); + +describe("person-only fork settings", () => { + it("lists every fork setting but the agent-writable ones", () => { + expect(FORK_PERSON_ONLY_KEYS).toEqual( + expect.arrayContaining([ + "automaticUpdates", + "waitFor", + "waitChecks", + "agentSlots", + "mcpProfiles", + "mcpProfile", + "mcpSubagentProfile", + "mcpThreadProfiles", + ]), + ); + for (const key of FORK_AGENT_WRITABLE_KEYS) expect(FORK_PERSON_ONLY_KEYS).not.toContain(key); + }); + + it("finds every T3 tool", () => { + // Spot checks across toolkits, upstream's and the fork's, plus the always-loaded ones. + for (const name of [ + "delegate_task", + "t3_environment_preferences_update", + "t3_project_update", + "t3_thread_configure", + "wait_for", + "tool_search", + "request_secret", + "send_to_user", + ]) { + expect(tools.has(name), name).toBe(true); + } + expect(tools.size).toBeGreaterThanOrEqual(70); + // A tool defined outside the toolkit modules would be missed above. + expect(toolsDefinedElsewhere().toSorted()).toEqual(Object.keys(NOT_ADVERTISED).toSorted()); + }); + + it("finds no person-only setting in any T3 tool's input", () => { + const found = [...tools.values()].flatMap((tool) => + personOnlyKeysIn(tool).map((key) => `${tool.name}: ${key}`), + ); + expect(found).toEqual([]); + }); + + it("catches a tool whose input names one, in any spelling or depth", () => { + for (const field of ["mcpProfile", "mcp_profile", "MCP-PROFILE"]) { + const tool = Tool.make("fake_settings_update", { + parameters: Schema.Struct({ + projectId: Schema.String, + patch: Schema.Struct({ [field]: Schema.optionalKey(Schema.String) }), + }), + }); + expect(personOnlyKeysIn(tool), field).toEqual(["mcpProfile"]); + } + }); +}); diff --git a/apps/server/src/mcp/toolkits/environment/waitForSettings.test.ts b/apps/server/src/mcp/toolkits/environment/waitForSettings.test.ts deleted file mode 100644 index 907645bc325b5..0000000000000 --- a/apps/server/src/mcp/toolkits/environment/waitForSettings.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { expect, it } from "@effect/vitest"; -import { Tool } from "effect/ai"; - -import { ProjectToolkit } from "../project/tools.ts"; -import { EnvironmentToolkit } from "./tools.ts"; - -// Fork: waits run commands and hold agent slots, so only a person may change these settings. -const PERSON_ONLY_KEYS = ["waitFor", "waitChecks", "agentSlots"]; - -const propertyNames = (schema: unknown): ReadonlyArray => { - if (schema === null || typeof schema !== "object") return []; - const record = schema as Record; - const own = - record.properties !== null && typeof record.properties === "object" - ? Object.keys(record.properties) - : []; - return [...own, ...Object.values(record).flatMap(propertyNames)]; -}; - -it.each([ - ["t3_environment_preferences_update", EnvironmentToolkit.tools.t3_environment_preferences_update], - ["t3_project_update", ProjectToolkit.tools.t3_project_update], -] as const)("%s cannot write wait or agent slot settings", (_name, tool) => { - const names = propertyNames(Tool.getJsonSchema(tool)); - expect(names.length).toBeGreaterThan(0); - for (const key of PERSON_ONLY_KEYS) expect(names).not.toContain(key); -}); diff --git a/packages/contracts/src/forkDefaults.ts b/packages/contracts/src/forkDefaults.ts index 051fd5ee8149a..c8fac9e58cee1 100644 --- a/packages/contracts/src/forkDefaults.ts +++ b/packages/contracts/src/forkDefaults.ts @@ -107,6 +107,54 @@ export const FORK_SETTING_DEFAULTS: ReadonlyArray = [ "On by default: usage limits are read every 10 minutes while no client watches, so pacing has current numbers. Read-only: it changes no thread, setting or install. 0 turns it off.", decidedIn: "#42", }, + { + scope: "server", + key: "mcpProfiles", + default: {}, + off: true, + reason: "No named MCP profiles; only the built-in `all` and `t3-only` exist.", + decidedIn: "#145", + }, + { + scope: "server", + key: "mcpProfile", + default: "all", + off: true, + reason: "Every thread gets every outside MCP server and every T3 tool, as upstream's does.", + decidedIn: "#145", + }, + { + scope: "server", + key: "mcpSubagentProfile", + default: "inherit", + off: true, + reason: "A delegated child follows `mcpProfile` like any other thread.", + decidedIn: "#145", + }, + { + scope: "server", + key: "mcpThreadProfiles", + default: {}, + off: true, + reason: "No thread has its own MCP profile pick.", + decidedIn: "#145", + }, + { + scope: "projectOverride", + key: "mcpProfile", + default: undefined, + off: true, + reason: "A project without its own MCP profile uses the server's.", + decidedIn: "#145", + }, + { + scope: "projectOverride", + key: "mcpSubagentProfile", + default: undefined, + off: true, + reason: "A project without its own sub-agent rule uses the server's.", + decidedIn: "#145", + }, { scope: "projectOverride", key: "waitChecks", diff --git a/packages/contracts/src/forkSettings.ts b/packages/contracts/src/forkSettings.ts index 2c8c43b132f95..10b29ee51ea26 100644 --- a/packages/contracts/src/forkSettings.ts +++ b/packages/contracts/src/forkSettings.ts @@ -8,6 +8,17 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import { TrimmedString } from "./baseSchemas.ts"; +import { + MCP_PROFILE_ALL, + MCP_SUBAGENT_INHERIT, + MCP_THREAD_PROFILES_KEEP_NEWEST, + McpProfileName, + McpProfileRef, + McpProfilesFromSettingsFile, + McpProfilesPatch, + McpThreadProfiles, + McpThreadProfilesPatch, +} from "./mcpProfile.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; import { DEFAULT_USAGE_PACING_INSTANCE_SETTINGS, @@ -25,6 +36,7 @@ import { WaitForSettingsPatch, } from "./waitFor.ts"; +export * from "./mcpProfile.ts"; export * from "./usagePacing.ts"; /** How often usage limits refresh while no client watches; 0 turns it off. */ @@ -60,6 +72,16 @@ export const ForkServerSettingsFields = { Effect.succeed(Duration.toMillis(DEFAULT_HEADLESS_USAGE_REFRESH_INTERVAL)), ), ), + /** Named MCP profiles besides the built-in `all` and `t3-only`; each checked when used. */ + mcpProfiles: McpProfilesFromSettingsFile, + /** The MCP profile a thread gets; `all` (or empty) is today's behaviour. */ + mcpProfile: McpProfileRef.pipe(Schema.withDecodingDefault(Effect.succeed(MCP_PROFILE_ALL))), + /** The MCP profile of a delegated child thread; `inherit` (or empty) follows `mcpProfile`. */ + mcpSubagentProfile: McpProfileRef.pipe( + Schema.withDecodingDefault(Effect.succeed(MCP_SUBAGENT_INHERIT)), + ), + /** The owner's MCP profile pick per thread; it wins over the defaults above. */ + mcpThreadProfiles: McpThreadProfiles, }; /** A key of {@link ForkServerSettingsFields}. */ @@ -78,17 +100,23 @@ export const ForkServerSettingsPatchFields = { waitChecks: Schema.optionalKey(WaitChecks), agentSlots: Schema.optionalKey(AgentSlotsSettingsPatch), headlessUsageRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis), + /** Strict: a save refuses a bad profile or a built-in name (reading the file keeps it as is). */ + mcpProfiles: Schema.optionalKey(McpProfilesPatch), + mcpProfile: Schema.optionalKey(McpProfileName), + mcpSubagentProfile: Schema.optionalKey(McpProfileName), + mcpThreadProfiles: Schema.optionalKey(McpThreadProfilesPatch), } satisfies Record; /** - * How a patch field changes the stored value: `replace` whole; `merge-fields` replaces only the - * named fields; `{ mergeEntries }` per entry: `null` removes it, else the fields merge into the - * stored entry, and a new entry starts from `mergeEntries` (its defaults). + * How a patch field changes the stored value: `replace` whole; `merge-fields` only the named fields. + * Per entry (`null` removes it): `mergeEntries` merges fields, a new entry starting from its + * defaults; `replaceEntries` replaces the entry whole, makes it newest and keeps `keepNewest`. */ export type ForkPatchRule = | "replace" | "merge-fields" - | { readonly mergeEntries: Readonly> }; + | { readonly mergeEntries: Readonly> } + | { readonly replaceEntries: { readonly keepNewest?: number } }; /** One rule per fork patch field. */ export const FORK_PATCH_RULES: { readonly [K in ForkServerSettingKey]: ForkPatchRule } = { @@ -103,6 +131,12 @@ export const FORK_PATCH_RULES: { readonly [K in ForkServerSettingKey]: ForkPatch // `maxPerAccount` is one field, so a patch that names it replaces the whole map. agentSlots: "merge-fields", headlessUsageRefreshInterval: "replace", + // One profile per entry, so two people editing different profiles keep both. + mcpProfiles: { replaceEntries: {} }, + mcpProfile: "replace", + mcpSubagentProfile: "replace", + // One pick per thread, so two picks at once keep both; old picks go beyond the cap. + mcpThreadProfiles: { replaceEntries: { keepNewest: MCP_THREAD_PROFILES_KEEP_NEWEST } }, }; /** The client settings' fork fields (stored in the browser); none yet. */ @@ -112,18 +146,26 @@ export const ForkClientSettingsFields = {}; export const FORK_PROJECT_SCOPED_KEYS = [ // A project lists every check it uses; its map replaces the server's. "waitChecks", + "mcpProfile", + "mcpSubagentProfile", ] as const satisfies ReadonlyArray; /** A project's overrides of fork settings, as the settings file holds them. */ export const ForkProjectOverrideFields = { /** Bad entries are dropped on read; the settings patch refuses them. */ waitChecks: Schema.optionalKey(WaitChecksFromSettingsFile), + /** Absent or empty: the server's `mcpProfile`. */ + mcpProfile: Schema.optionalKey(McpProfileRef), + /** Absent or empty: the server's `mcpSubagentProfile`. */ + mcpSubagentProfile: Schema.optionalKey(McpProfileRef), } satisfies Record<(typeof FORK_PROJECT_SCOPED_KEYS)[number], unknown>; /** A project's overrides of fork settings in a patch (each project's set is replaced whole). */ export const ForkProjectOverridePatchFields = { /** A save refuses a bad check. */ waitChecks: Schema.optionalKey(WaitChecks), + mcpProfile: Schema.optionalKey(McpProfileName), + mcpSubagentProfile: Schema.optionalKey(McpProfileName), } satisfies Record; /** @@ -143,3 +185,16 @@ export const FORK_SERVER_SETTING_KEYS: ReadonlyArray = [ ...FORK_INLINE_SERVER_KEYS, ...Object.keys(ForkServerSettingsFields), ]; + +/** + * Every fork setting only a person may change: each server, project and client fork key but those + * in {@link FORK_AGENT_WRITABLE_KEYS}. No T3 tool's input may name one (the server's + * personOnlySettings test). Derived, so a new fork setting is covered without a row. + */ +export const FORK_PERSON_ONLY_KEYS: ReadonlyArray = [ + ...new Set([ + ...FORK_SERVER_SETTING_KEYS, + ...Object.keys(ForkProjectOverrideFields), + ...Object.keys(ForkClientSettingsFields), + ]), +].filter((key) => !(FORK_AGENT_WRITABLE_KEYS as ReadonlyArray).includes(key)); diff --git a/packages/contracts/src/mcpProfile.test.ts b/packages/contracts/src/mcpProfile.test.ts new file mode 100644 index 0000000000000..896d6874cbf16 --- /dev/null +++ b/packages/contracts/src/mcpProfile.test.ts @@ -0,0 +1,92 @@ +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { ProjectId } from "./baseSchemas.ts"; +import { ProjectSettingsOverrides, ServerSettings, ServerSettingsPatch } from "./settings.ts"; + +const decodeFile = Schema.decodeUnknownSync(ServerSettings); +const encodeFile = Schema.encodeSync(ServerSettings); +const decodePatch = Schema.decodeUnknownSync(ServerSettingsPatch); +const PROJECT = ProjectId.make("project-1"); + +const mcpKeys = (settings: ServerSettings) => ({ + mcpProfiles: settings.mcpProfiles, + mcpProfile: settings.mcpProfile, + mcpSubagentProfile: settings.mcpSubagentProfile, + mcpThreadProfiles: settings.mcpThreadProfiles, +}); + +describe("MCP profile settings file", () => { + it("reads an old file (no keys) as off", () => { + expect(mcpKeys(decodeFile({}))).toEqual({ + mcpProfiles: {}, + mcpProfile: "all", + mcpSubagentProfile: "inherit", + mcpThreadProfiles: {}, + }); + }); + + it("loads a file whose profile this build cannot read, and keeps it on save", () => { + // Written by a newer build: an unknown field, an unknown group, a missing field. + const profiles = { + future: { servers: [], t3Tools: ["mail"], builtinTools: "none" }, + half: { servers: ["docs"] }, + odd: "not a profile", + }; + const settings = decodeFile({ mcpProfiles: profiles, mcpProfile: "future" }); + expect(settings.mcpProfiles).toEqual(profiles); + // A save writes what was read: a newer build's profile is not cut or widened. + expect(encodeFile(settings).mcpProfiles).toEqual(profiles); + }); + + it("trims profile references", () => { + expect(decodeFile({ mcpProfile: " lean ", mcpSubagentProfile: " " })).toMatchObject({ + mcpProfile: "lean", + mcpSubagentProfile: "", + }); + }); + + it("reads a project's overrides; absent means the server's", () => { + const decode = Schema.decodeUnknownSync(ProjectSettingsOverrides); + expect(decode({})).toEqual({}); + expect(decode({ mcpProfile: "lean", mcpSubagentProfile: "inherit" })).toEqual({ + mcpProfile: "lean", + mcpSubagentProfile: "inherit", + }); + }); +}); + +describe("MCP profile settings patch", () => { + it("takes good profiles, references and picks", () => { + const patch = decodePatch({ + mcpProfiles: { lean: { servers: ["docs"], t3Tools: ["threads", "waits"] }, gone: null }, + mcpProfile: "lean", + mcpSubagentProfile: "inherit", + mcpThreadProfiles: { "thread-1": "t3-only", "thread-2": null }, + projectSettingsOverrides: { [PROJECT]: { mcpProfile: "all", mcpSubagentProfile: "lean" } }, + }); + expect(patch.mcpProfiles?.lean).toEqual({ servers: ["docs"], t3Tools: ["threads", "waits"] }); + expect(patch.projectSettingsOverrides?.[PROJECT]).toEqual({ + mcpProfile: "all", + mcpSubagentProfile: "lean", + }); + }); + + it.each([ + ["a built-in name", { mcpProfiles: { all: { servers: [], t3Tools: [] } } }], + ["the name `inherit`", { mcpProfiles: { inherit: { servers: [], t3Tools: [] } } }], + ["a bad name", { mcpProfiles: { "Bad Name": { servers: [], t3Tools: [] } } }], + ["an unknown field", { mcpProfiles: { lean: { servers: [], t3Tools: [], extra: 1 } } }], + ["a missing field", { mcpProfiles: { lean: { servers: [] } } }], + ["an unknown group", { mcpProfiles: { lean: { servers: [], t3Tools: ["mail"] } } }], + ["a blank server", { mcpProfiles: { lean: { servers: [" "], t3Tools: [] } } }], + ["a bad reference", { mcpProfile: "Not A Name" }], + ["an empty reference", { mcpSubagentProfile: "" }], + ["a bad pick", { mcpThreadProfiles: { "thread-1": "Not A Name" } }], + ["a blank thread id", { mcpThreadProfiles: { " ": "lean" } }], + ["an untrimmed thread id", { mcpThreadProfiles: { " thread-1": "lean" } }], + ["a bad project reference", { projectSettingsOverrides: { [PROJECT]: { mcpProfile: "" } } }], + ])("refuses %s", (_name, patch) => { + expect(() => decodePatch(patch)).toThrow(); + }); +}); diff --git a/packages/contracts/src/mcpProfile.ts b/packages/contracts/src/mcpProfile.ts new file mode 100644 index 0000000000000..418ac240f1384 --- /dev/null +++ b/packages/contracts/src/mcpProfile.ts @@ -0,0 +1,136 @@ +/** + * Fork: MCP profile settings. A profile names the outside MCP servers and T3 tool groups a thread + * gets. Only a person sets them; no agent tool takes these keys. Off by default: every thread + * resolves to `all`, today's behaviour. The resolver is apps/server/src/fork/mcpProfile.ts. + */ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SchemaTransformation from "effect/SchemaTransformation"; + +import { TrimmedString } from "./baseSchemas.ts"; + +/** Today's behaviour: every outside server and every T3 tool. */ +export const MCP_PROFILE_ALL = "all"; +/** No outside servers, every T3 tool. */ +export const MCP_PROFILE_T3_ONLY = "t3-only"; +/** The two profiles every build knows; `mcpProfiles` cannot redefine them. */ +const MCP_BUILT_IN_PROFILE_NAMES = [MCP_PROFILE_ALL, MCP_PROFILE_T3_ONLY] as const; +/** `mcpSubagentProfile` value: a delegated child follows `mcpProfile` like any other thread. */ +export const MCP_SUBAGENT_INHERIT = "inherit"; + +const MCP_PROFILE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/u; + +/** A profile's name: lower-case letters, digits and dashes, at most 40. */ +export const McpProfileName = Schema.String.check(Schema.isPattern(MCP_PROFILE_NAME_PATTERN)); +export type McpProfileName = typeof McpProfileName.Type; + +/** True for a name a profile in `mcpProfiles` may have: valid, not built in, not `inherit`. */ +export const isDefinableMcpProfileName = (name: string): boolean => + MCP_PROFILE_NAME_PATTERN.test(name) && + name !== MCP_SUBAGENT_INHERIT && + !(MCP_BUILT_IN_PROFILE_NAMES as ReadonlyArray).includes(name); + +/** + * Groups of T3's own tools, one per toolkit. The two message tools (`request_secret`, + * `send_to_user`) are in no group: every profile keeps them. + */ +export const MCP_T3_TOOL_GROUPS = [ + "orchestration", + "preview", + "pull-requests", + "threads", + "projects", + "device", + "worktree", + "attachments", + "environment", + "theme", + "html", + "waits", +] as const; +export const McpT3ToolGroup = Schema.Literals(MCP_T3_TOOL_GROUPS); +export type McpT3ToolGroup = typeof McpT3ToolGroup.Type; + +/** An outside MCP server's name as the provider's config spells it. */ +export const McpServerName = TrimmedString.check(Schema.isNonEmpty()); + +/** + * One profile. `servers` and `t3Tools` are each `"all"` or a keep-list; a keep-list leaves out + * anything not named, so a server added later is left out until the owner adds it. An empty list + * keeps none. + */ +export const McpProfile = Schema.Struct({ + servers: Schema.Union([Schema.Literal("all"), Schema.Array(McpServerName)]), + t3Tools: Schema.Union([Schema.Literal("all"), Schema.Array(McpT3ToolGroup)]), +}); +export type McpProfile = typeof McpProfile.Type; + +/** + * The settings file's profiles. Each entry is kept as written and checked only when a thread uses + * it, so one bad entry (or one written by a newer build, with fields this build does not know) + * never stops the settings file from loading, and a save keeps it as it was. + */ +export const McpProfilesFromSettingsFile = Schema.Record(Schema.String, Schema.Unknown).pipe( + Schema.withDecodingDefault(Effect.succeed({})), +); + +const MCP_PROFILE_FIELDS: ReadonlyArray = ["servers", "t3Tools"]; + +/** + * A profile in a settings patch: a field this build does not know is refused, not dropped, so a + * save never stores a profile cut down from what the person wrote. (Effect strips excess fields + * unless the decode call itself asks for errors, so the check runs on the input first.) + */ +const McpProfileInPatch = Schema.Record(Schema.String, Schema.Unknown) + .check( + Schema.makeFilter( + (fields: { readonly [name: string]: unknown }) => + Object.keys(fields).every((name) => MCP_PROFILE_FIELDS.includes(name)), + { expected: `a profile with only the fields ${MCP_PROFILE_FIELDS.join(", ")}` }, + ), + ) + .pipe(Schema.decodeTo(McpProfile, SchemaTransformation.passthrough({ strict: false }))); + +/** + * Profiles in a settings patch: each entry replaces the stored one whole; `null` removes it. Names + * are checked on the whole map: Effect drops, rather than refuses, a record key its key schema + * rejects. + */ +export const McpProfilesPatch = Schema.Record( + Schema.String, + Schema.NullOr(McpProfileInPatch), +).check( + Schema.makeFilter( + (profiles: { readonly [name: string]: unknown }) => + Object.keys(profiles).every(isDefinableMcpProfileName), + { + expected: `profile names of lower-case letters, digits and dashes (at most 40), other than ${MCP_BUILT_IN_PROFILE_NAMES.join(", ")} and ${MCP_SUBAGENT_INHERIT}`, + }, + ), +); + +/** A profile reference as the settings file holds it; empty means "not set". */ +export const McpProfileRef = TrimmedString; + +/** + * The owner's pick per thread in a settings patch; `null` removes the pick. Thread ids are checked + * on the whole map, as for {@link McpProfilesPatch}. + */ +export const McpThreadProfilesPatch = Schema.Record( + Schema.String, + Schema.NullOr(McpProfileName), +).check( + Schema.makeFilter( + (picks: { readonly [threadId: string]: unknown }) => + Object.keys(picks).every((threadId) => threadId.length > 0 && threadId.trim() === threadId), + { expected: "thread ids (non-blank, no outer spaces) as keys" }, + ), +); + +/** The newest thread picks kept; a write that goes over drops the oldest. */ +export const MCP_THREAD_PROFILES_KEEP_NEWEST = 500; + +/** The settings file's thread picks: thread id to profile name. */ +export const McpThreadProfiles = Schema.Record(Schema.String, Schema.String).pipe( + Schema.withDecodingDefault(Effect.succeed({})), +); diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index 885cbedb23cf0..571228909c4ad 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -2,8 +2,10 @@ import { DEFAULT_SERVER_SETTINGS, + MCP_THREAD_PROFILES_KEEP_NEWEST, ProviderInstanceId, type ServerSettings, + ThreadId, } from "@t3tools/contracts"; import { WaitCheck } from "@t3tools/contracts/waitFor"; import * as Duration from "effect/Duration"; @@ -97,6 +99,77 @@ describe("fork settings patch", () => { expect(next.waitChecks).toBe(current.waitChecks); }); + describe("replaces entries (MCP profiles and thread picks)", () => { + const t = (id: string) => ThreadId.make(id); + const withPicks: ServerSettings = { + ...current, + mcpProfiles: { lean: { servers: [], t3Tools: ["threads"], future: true } }, + mcpThreadProfiles: { a: "lean", b: "lean", c: "all" }, + }; + + it("keeps both of two picks saved at once", () => { + const first = { + ...withPicks, + ...applyForkSettingsPatch(withPicks, { mcpThreadProfiles: { [t("d")]: "lean" } }), + }; + // The second client's patch names only its own thread, so the first pick stays. + const second = applyForkSettingsPatch(first, { mcpThreadProfiles: { [t("e")]: "all" } }); + expect(second.mcpThreadProfiles).toEqual({ + a: "lean", + b: "lean", + c: "all", + d: "lean", + e: "all", + }); + }); + + it("removes a pick on null and moves a changed pick to the newest", () => { + const next = applyForkSettingsPatch(withPicks, { + mcpThreadProfiles: { [t("a")]: "all", [t("b")]: null }, + }); + expect(Object.entries(next.mcpThreadProfiles ?? {})).toEqual([ + ["c", "all"], + ["a", "all"], + ]); + }); + + it(`keeps the ${MCP_THREAD_PROFILES_KEEP_NEWEST} newest picks`, () => { + const many = Object.fromEntries( + Array.from({ length: MCP_THREAD_PROFILES_KEEP_NEWEST }, (_, index) => [ + `old-${index}`, + "lean", + ]), + ); + const full: ServerSettings = { ...current, mcpThreadProfiles: many }; + const next = applyForkSettingsPatch(full, { + mcpThreadProfiles: { [t("old-0")]: "all", [t("new")]: "lean" }, + }).mcpThreadProfiles!; + expect(Object.keys(next)).toHaveLength(MCP_THREAD_PROFILES_KEEP_NEWEST); + // `old-0` was picked again, so `old-1` is now the oldest and goes. + expect(Object.keys(next).slice(0, 1)).toEqual(["old-2"]); + expect(Object.keys(next).slice(-2)).toEqual(["old-0", "new"]); + expect(next).not.toHaveProperty("old-1"); + }); + + it("replaces a profile whole, so a save repairs one this build cannot read", () => { + const next = applyForkSettingsPatch(withPicks, { + mcpProfiles: { lean: { servers: ["docs"], t3Tools: "all" }, review: null }, + }); + expect(next.mcpProfiles).toEqual({ lean: { servers: ["docs"], t3Tools: "all" } }); + }); + + it("goes through applyServerSettingsPatch", () => { + const next = applyServerSettingsPatch(withPicks, { + mcpProfile: "lean", + mcpSubagentProfile: "t3-only", + mcpThreadProfiles: { [t("c")]: null }, + }); + expect([next.mcpProfile, next.mcpSubagentProfile]).toEqual(["lean", "t3-only"]); + expect(next.mcpThreadProfiles).toEqual({ a: "lean", b: "lean" }); + expect(next.mcpProfiles).toBe(withPicks.mcpProfiles); + }); + }); + it("pins the fork's lines in serverSettings.ts", () => { const lines = SERVER_SETTINGS_SOURCE.split("\n"); // The import, the split, the destructuring from the upstream half and one spread. diff --git a/packages/shared/src/forkSettingsPatch.ts b/packages/shared/src/forkSettingsPatch.ts index 3da006a7d1aed..aa6b5e5682ee0 100644 --- a/packages/shared/src/forkSettingsPatch.ts +++ b/packages/shared/src/forkSettingsPatch.ts @@ -41,6 +41,20 @@ function applyRule(rule: ForkPatchRule, stored: unknown, patch: unknown): unknow return next; } const next = new Map(Object.entries(isRecord(stored) ? stored : {})); + if ("replaceEntries" in rule) { + for (const [id, entry] of Object.entries(patch as Record)) { + if (entry === undefined) continue; + // Delete first, so a changed entry moves to the end: the newest. + next.delete(id); + if (entry !== null) next.set(id, entry); + } + const { keepNewest } = rule.replaceEntries; + const ids = [...next.keys()]; + if (keepNewest !== undefined && ids.length > keepNewest) { + for (const id of ids.slice(0, ids.length - keepNewest)) next.delete(id); + } + return Object.fromEntries(next); + } for (const [id, entry] of Object.entries(patch as Record)) { if (entry === null) { next.delete(id); From d913a755cbce3d52be8c7c3586ea2942b23404e6 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:22:16 +0000 Subject: [PATCH 2/6] MCP profiles 1: fix round 1 (lenient read, save check, tool groups, docs) - A bad MCP value in the settings file no longer fails the whole file: it reads as an unreadable marker the resolver refuses; null means not set. - Project references: save accepts what read keeps; only a changed value is checked, so old odd values never block unrelated project saves. - Saves refuse inherit where it means nothing and names with no profile, with a message that names the fix (write-fork-setting save error). - Every T3 tool maps to a group or the ungrouped list; previewControls is in preview; tool_search, request_secret, send_to_user are ungrouped. - Person-only test counts aliased Tool.make and checks every toolkit loads. - Docs rows and sections for the six new settings; FORK_CHANGES line. - Fixes the web typecheck (profiles patch type matches the read type). Co-Authored-By: Claude Opus 5.5 --- FORK_CHANGES.md | 37 ++-- apps/server/src/fork/mcpProfile.test.ts | 20 ++ apps/server/src/fork/mcpProfile.ts | 38 ++++ .../src/fork/personOnlySettings.test.ts | 115 ++++++++++-- .../src/serverSettings.forkSettings.test.ts | 45 +++++ apps/server/src/serverSettings.ts | 22 ++- docs/fork/README.md | 68 +++++-- packages/contracts/src/forkSettings.test.ts | 7 +- packages/contracts/src/forkSettings.ts | 20 +- packages/contracts/src/mcpProfile.test.ts | 54 +++++- packages/contracts/src/mcpProfile.ts | 177 +++++++++++++----- packages/contracts/src/settings.ts | 5 + packages/shared/package.json | 4 + packages/shared/src/forkSettingsPatch.test.ts | 107 ++++++++++- packages/shared/src/forkSettingsPatch.ts | 83 ++++++++ 15 files changed, 700 insertions(+), 102 deletions(-) diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index 83ae5032ac685..75edb4867b0d3 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -12,24 +12,25 @@ is missing here or a setting named here does not exist. ## In T3 Code itself -| Change | Why | Setting | Default | PR | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| The server, the CLI and the desktop app look for updates in this fork's releases, not upstream's. | A fork build must never "update" to an upstream build and lose the fork's changes. | none | always | [#1](https://github.com/scuttletoby/t3code/pull/1) | -| A server installed as a boot service can update itself once no thread is working, after an optional "is it quiet?" command agrees. | Updates without someone watching, and without cutting off running work. | `server.automaticUpdates`, `server.automaticUpdatesQuietCommand` | off | [#5](https://github.com/scuttletoby/t3code/pull/5) | -| Every fork setting has a pinned default, and lives in the fork's own file (`forkSettings.ts`). | An upstream sync can never switch a fork feature on, and a new setting touches no upstream file. | none | always | [#171](https://github.com/scuttletoby/t3code/pull/171), [#185](https://github.com/scuttletoby/t3code/pull/185) | -| The server keeps a history of each provider account's usage-limit readings. | Pacing needs to know how fast a limit is being used, not only where it stands. | none | always (read only) | [#24](https://github.com/scuttletoby/t3code/pull/24) | -| The server reads usage limits every 10 minutes while no app is open. | Pacing has current numbers on a machine nobody is looking at. | `server.headlessUsageRefreshInterval` | on (10 minutes); read only | [#42](https://github.com/scuttletoby/t3code/pull/42) | -| Usage pacing: a reserve of each limit window kept free for the person, and an even pace for agents. | Agents should not use up a subscription before its owner needs it. | `server.usagePacing` | off | [#52](https://github.com/scuttletoby/t3code/pull/52) | -| The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | -| Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | -| Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | -| Settings pages for waits, wait checks and agent slots. | Switch these on without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots` | off | [#104](https://github.com/scuttletoby/t3code/pull/104) | -| The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | -| A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | -| File links in chat open in the files viewer, full size, or in an editor on a remote machine, and can be downloaded, from their menu. | File links were only copyable on remote machines and had no menu on touch screens. | none | always | [#17](https://github.com/scuttletoby/t3code/pull/17) | -| A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | -| `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work 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) | +| Change | Why | Setting | Default | PR | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| The server, the CLI and the desktop app look for updates in this fork's releases, not upstream's. | A fork build must never "update" to an upstream build and lose the fork's changes. | none | always | [#1](https://github.com/scuttletoby/t3code/pull/1) | +| A server installed as a boot service can update itself once no thread is working, after an optional "is it quiet?" command agrees. | Updates without someone watching, and without cutting off running work. | `server.automaticUpdates`, `server.automaticUpdatesQuietCommand` | off | [#5](https://github.com/scuttletoby/t3code/pull/5) | +| Every fork setting has a pinned default, and lives in the fork's own file (`forkSettings.ts`). | An upstream sync can never switch a fork feature on, and a new setting touches no upstream file. | none | always | [#171](https://github.com/scuttletoby/t3code/pull/171), [#185](https://github.com/scuttletoby/t3code/pull/185) | +| The server keeps a history of each provider account's usage-limit readings. | Pacing needs to know how fast a limit is being used, not only where it stands. | none | always (read only) | [#24](https://github.com/scuttletoby/t3code/pull/24) | +| The server reads usage limits every 10 minutes while no app is open. | Pacing has current numbers on a machine nobody is looking at. | `server.headlessUsageRefreshInterval` | on (10 minutes); read only | [#42](https://github.com/scuttletoby/t3code/pull/42) | +| Usage pacing: a reserve of each limit window kept free for the person, and an even pace for agents. | Agents should not use up a subscription before its owner needs it. | `server.usagePacing` | off | [#52](https://github.com/scuttletoby/t3code/pull/52) | +| The pacing gate on `delegate_task`: advise only, or move, lower the effort of, or hold a task on an account that is ahead of pace. | Delegated work follows the pace without the agent having to check. | `server.usagePacingGate`, `server.usagePacingLowerEffort` | off | [#73](https://github.com/scuttletoby/t3code/pull/73) | +| Agent slots: `delegate_task` is refused above a number of running agents per machine or account, or below a memory floor. | Too many agents at once can overload a small machine. | `server.agentSlots` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#89](https://github.com/scuttletoby/t3code/pull/89) | +| Waits: agents can wait for a pull request, a file, a system unit, a named check command or a free agent slot (`wait_for`, `wait_list`, `wait_cancel`), and are woken when it happens. | An agent no longer polls or sleeps while it waits. | `server.waitFor`, `server.waitChecks`, `projectOverride.waitChecks` | off | [#84](https://github.com/scuttletoby/t3code/pull/84), [#90](https://github.com/scuttletoby/t3code/pull/90), [#91](https://github.com/scuttletoby/t3code/pull/91), [#103](https://github.com/scuttletoby/t3code/pull/103), [#106](https://github.com/scuttletoby/t3code/pull/106), [#109](https://github.com/scuttletoby/t3code/pull/109), [#110](https://github.com/scuttletoby/t3code/pull/110), [#116](https://github.com/scuttletoby/t3code/pull/116), [#119](https://github.com/scuttletoby/t3code/pull/119) | +| Settings pages for waits, wait checks and agent slots. | Switch these on without editing a file. | `server.waitFor`, `server.waitChecks`, `server.agentSlots` | off | [#104](https://github.com/scuttletoby/t3code/pull/104) | +| The fork's checks on `delegate_task` (pacing, slots) sit behind one fork module. | Fewer fork lines in upstream's code, so syncs conflict less. No change in behaviour. | none | always | [#174](https://github.com/scuttletoby/t3code/pull/174) | +| A pure capacity rule for "dynamic slots" (one budget per machine), with shared test cases. Not wired into anything yet. | A later step replaces fixed agent counts with what the machine can take. | none | not used | [#203](https://github.com/scuttletoby/t3code/pull/203) | +| File links in chat open in the files viewer, full size, or in an editor on a remote machine, and can be downloaded, from their menu. | File links were only copyable on remote machines and had no menu on touch screens. | none | always | [#17](https://github.com/scuttletoby/t3code/pull/17) | +| A hidden read-only command, `t3 __fork-report --base-dir `, prints what a T3 home holds and which fork features are on. | The go-live kit checks a build and a home before switching, without writing anything. | none | only when run | [#172](https://github.com/scuttletoby/t3code/pull/172), [#184](https://github.com/scuttletoby/t3code/pull/184) | +| `t3 serve --hold-work` starts a server on a copy of a T3 home with all agent work held. | Look at a new build's threads and migrations on a copy before it replaces a running T3. | none | only with the flag | [#175](https://github.com/scuttletoby/t3code/pull/175) | +| Docs: one machine for new work through upstream's load-balancing weights; settings saved with an early draft's client setting for it still load. | Upstream already has the feature, so the fork's own setting was removed. | none | - | [#25](https://github.com/scuttletoby/t3code/pull/25) | +| MCP profiles, part 1: settings for named profiles (which outside MCP servers and which T3 tool groups a thread gets), a default, a sub-agent rule and a pick per thread, and the rules that decide a thread's profile. Nothing applies a profile yet. | Fewer tools per thread saves tokens and keeps agents from tools they should not use. | `server.mcpProfiles`, `server.mcpProfile`, `server.mcpSubagentProfile`, `server.mcpThreadProfiles`, `projectOverride.mcpProfile`, `projectOverride.mcpSubagentProfile` | off | [#227](https://github.com/scuttletoby/t3code/pull/227) | ## Repository, CI and releases diff --git a/apps/server/src/fork/mcpProfile.test.ts b/apps/server/src/fork/mcpProfile.test.ts index e92adfab2752f..30b60bc2bb708 100644 --- a/apps/server/src/fork/mcpProfile.test.ts +++ b/apps/server/src/fork/mcpProfile.test.ts @@ -214,6 +214,26 @@ describe("MCP profile resolver: never falls back to all", () => { ["`inherit` as a thread's profile", { mcpProfile: "inherit" }, [top("t1")], "inherit"], // Plain-object keys must not resolve to Object.prototype's members. ["a prototype key", { mcpProfile: "constructor" }, [top("t1")], "constructor"], + // Values that are not text read as a marker no profile can have, so they never widen to all. + ["a default that is a number", { mcpProfile: 5 }, [top("t1")], "(unreadable number)"], + [ + "a sub-agent rule that is a list", + { mcpSubagentProfile: ["lean"] }, + [child("c1"), top("t1")], + "(unreadable list)", + ], + [ + "a thread pick that is an object", + { mcpThreadProfiles: { t1: { profile: "lean" } } }, + [top("t1")], + "(unreadable object)", + ], + [ + "a project reference that is a number", + {}, + [top("t1", { mcpProfile: "(unreadable number)" })], + "(unreadable number)", + ], ] as const)("%s: refuses and names it", (_name, file, lineage, name) => { const result = refused( resolveMcpProfile(fromFile({ mcpProfiles: PROFILES, ...file }), lineage), diff --git a/apps/server/src/fork/mcpProfile.ts b/apps/server/src/fork/mcpProfile.ts index f005ebf86fb4c..b12968d4a6485 100644 --- a/apps/server/src/fork/mcpProfile.ts +++ b/apps/server/src/fork/mcpProfile.ts @@ -8,6 +8,7 @@ import { MCP_PROFILE_T3_ONLY, MCP_SUBAGENT_INHERIT, MCP_T3_TOOL_GROUPS, + MCP_T3_UNGROUPED_TOOLS, type McpT3ToolGroup, type ServerSettings, isDefinableMcpProfileName, @@ -76,6 +77,43 @@ export interface McpProfileCannotApply { export type McpProfileResolution = McpProfileResolved | McpProfileCannotApply; +/** + * 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. + */ +export const MCP_T3_TOOLKIT_GROUPS: Readonly> = { + orchestrator: "orchestration", + preview: "preview", + previewControls: "preview", + pullRequests: "pull-requests", + thread: "threads", + project: "projects", + device: "device", + worktree: "worktree", + attachment: "attachments", + environment: "environment", + theme: "theme", + html: "html", + waits: "waits", + message: null, + toolSearch: null, +}; + +/** + * A T3 tool's group, or `"ungrouped"` for one every profile keeps; `undefined` when its toolkit + * has no row in {@link MCP_T3_TOOLKIT_GROUPS} or it is an ungrouped toolkit's unlisted tool. + */ +export function mcpT3ToolGroup( + toolkit: string, + tool: string, +): McpT3ToolGroup | "ungrouped" | undefined { + if (MCP_T3_UNGROUPED_TOOLS.includes(tool)) return "ungrouped"; + return Object.hasOwn(MCP_T3_TOOLKIT_GROUPS, toolkit) + ? (MCP_T3_TOOLKIT_GROUPS[toolkit] ?? undefined) + : undefined; +} + /** Longer lineages are refused; real delegation chains are a few threads deep. */ export const MCP_PROFILE_MAX_LINEAGE = 64; diff --git a/apps/server/src/fork/personOnlySettings.test.ts b/apps/server/src/fork/personOnlySettings.test.ts index 0e15e4c01b0e2..c2f35c66094b8 100644 --- a/apps/server/src/fork/personOnlySettings.test.ts +++ b/apps/server/src/fork/personOnlySettings.test.ts @@ -8,20 +8,56 @@ import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; -import { FORK_AGENT_WRITABLE_KEYS, FORK_PERSON_ONLY_KEYS } from "@t3tools/contracts"; +import { + FORK_AGENT_WRITABLE_KEYS, + FORK_PERSON_ONLY_KEYS, + MCP_T3_TOOL_GROUPS, + MCP_T3_UNGROUPED_TOOLS, +} from "@t3tools/contracts"; import { Tool, Toolkit } from "effect/ai"; import * as Schema from "effect/Schema"; import { beforeAll, describe, expect, it } from "vite-plus/test"; +import { MCP_T3_TOOLKIT_GROUPS, mcpT3ToolGroup } from "./mcpProfile.ts"; + const TOOLKITS_DIR = NodePath.resolve(import.meta.dirname, "../mcp/toolkits"); -/** Every toolkit module; each defines its tools with `Tool.make` and exports its toolkits. */ -const loadToolkitModules = (): Promise>> => - Promise.all( - NodeFS.readdirSync(TOOLKITS_DIR, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => NodePath.join(TOOLKITS_DIR, entry.name, "tools.ts")) - .filter((path) => NodeFS.existsSync(path)) - .map((path) => import(path) as Promise>), +/** Every toolkit folder; each must define its tools in `tools.ts` and export its toolkits there. */ +const toolkitFolders = (): ReadonlyArray => + NodeFS.readdirSync(TOOLKITS_DIR, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name); +const toolsFile = (folder: string) => NodePath.join(TOOLKITS_DIR, folder, "tools.ts"); + +const escapeRegExp = (text: string) => text.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&"); +/** + * How a source file can call effect/ai's `Tool.make`, read from its imports so an alias counts: + * `Tool.make`, `T.make` (`{ Tool as T }`), `Ai.Tool.make` (`* as Ai`), or `make` from effect/ai/Tool. + */ +const toolMakeCallees = (source: string): ReadonlyArray => { + const callees: Array = []; + for (const [, names = "", from] of source.matchAll( + /import\s+\{([^}]*)\}\s*from\s*["'](effect\/ai(?:\/Tool)?)["']/g, + )) { + for (const spec of names.split(",")) { + const [imported = "", local = imported] = spec.trim().split(/\s+as\s+/); + if (from === "effect/ai" && imported === "Tool") callees.push(`${local}.make`); + if (from === "effect/ai/Tool" && imported === "make") callees.push(local); + } + } + for (const [, local = "", from] of source.matchAll( + /import\s+\*\s+as\s+(\w+)\s+from\s*["'](effect\/ai(?:\/Tool)?)["']/g, + )) { + callees.push(from === "effect/ai" ? `${local}.Tool.make` : `${local}.make`); + } + return callees; +}; +/** How many times a source file calls `Tool.make`, under any alias. */ +const toolMakeCalls = (source: string): number => + toolMakeCallees(source).reduce( + (count, callee) => + count + + [...source.matchAll(new RegExp(`(? => { @@ -30,9 +66,7 @@ const toolsDefinedElsewhere = (): ReadonlyArray => { .filter((path) => path.endsWith(".ts") && !path.endsWith(".test.ts")) .map((path) => path.split(NodePath.sep).join("/")) .filter((path) => !/^mcp\/toolkits\/[^/]+\/tools\.ts$/.test(path)) - .filter((path) => - /\bTool\.make\(/.test(NodeFS.readFileSync(NodePath.join(root, path), "utf8")), - ); + .filter((path) => toolMakeCalls(NodeFS.readFileSync(NodePath.join(root, path), "utf8")) > 0); }; /** Files that call `Tool.make` but advertise nothing: each with the reason. */ const NOT_ADVERTISED: Readonly> = { @@ -55,12 +89,21 @@ const isToolkit = (value: unknown): value is Toolkit.Toolkit(); +/** Each toolkit folder's tools, as its exported toolkits hold them. */ +const toolsByFolder = new Map>(); beforeAll(async () => { - for (const module of await loadToolkitModules()) { + for (const folder of toolkitFolders()) { + if (!NodeFS.existsSync(toolsFile(folder))) continue; + const module = (await import(toolsFile(folder))) as Record; + const names = new Set(); for (const value of Object.values(module)) { if (!isToolkit(value)) continue; - for (const tool of Object.values(value.tools)) tools.set(tool.name, tool); + for (const tool of Object.values(value.tools)) { + tools.set(tool.name, tool); + names.add(tool.name); + } } + toolsByFolder.set(folder, names); } }); @@ -122,6 +165,30 @@ describe("person-only fork settings", () => { expect(toolsDefinedElsewhere().toSorted()).toEqual(Object.keys(NOT_ADVERTISED).toSorted()); }); + it("loads every toolkit file, and every tool each one makes is in an exported toolkit", () => { + const folders = toolkitFolders(); + expect(folders.filter((folder) => !NodeFS.existsSync(toolsFile(folder)))).toEqual([]); + expect([...toolsByFolder.keys()].toSorted()).toEqual(folders.toSorted()); + // A tool made but left out of every exported toolkit would never be checked. + const counts = (count: (folder: string) => number) => + Object.fromEntries(folders.map((folder) => [folder, count(folder)])); + expect(counts((folder) => toolsByFolder.get(folder)?.size ?? 0)).toEqual( + counts((folder) => toolMakeCalls(NodeFS.readFileSync(toolsFile(folder), "utf8"))), + ); + }); + + it("counts `Tool.make` under any import alias", () => { + const cases: ReadonlyArray = [ + ['import { Tool, Toolkit } from "effect/ai";\nTool.make("a", {});', 1], + ['import { Toolkit, Tool as T } from "effect/ai";\nT.make("a", {}); T.make("b", {});', 2], + ['import * as Ai from "effect/ai";\nAi.Tool.make("a", {});', 1], + ['import * as AiTool from "effect/ai/Tool";\nAiTool.make("a", {});', 1], + ['import { make as makeTool } from "effect/ai/Tool";\nmakeTool("a", {});', 1], + ['import { Schema } from "effect";\nSchema.make(1); Tool.make("a", {});', 0], + ]; + for (const [source, calls] of cases) expect(toolMakeCalls(source), source).toBe(calls); + }); + it("finds no person-only setting in any T3 tool's input", () => { const found = [...tools.values()].flatMap((tool) => personOnlyKeysIn(tool).map((key) => `${tool.name}: ${key}`), @@ -141,3 +208,23 @@ describe("person-only fork settings", () => { } }); }); + +describe("MCP profile T3 tool groups", () => { + it("maps every T3 tool to a group or to the ungrouped list", () => { + const unmapped = [...toolsByFolder].flatMap(([folder, names]) => + [...names].filter((name) => mcpT3ToolGroup(folder, name) === undefined), + ); + expect(unmapped).toEqual([]); + }); + + it("has a row for each toolkit and uses every group", () => { + expect(Object.keys(MCP_T3_TOOLKIT_GROUPS).toSorted()).toEqual(toolkitFolders().toSorted()); + const used = new Set( + [...toolsByFolder].flatMap(([folder, names]) => + [...names].map((name) => mcpT3ToolGroup(folder, name)), + ), + ); + expect(MCP_T3_TOOL_GROUPS.filter((group) => !used.has(group))).toEqual([]); + expect(MCP_T3_UNGROUPED_TOOLS.filter((name) => !tools.has(name))).toEqual([]); + }); +}); diff --git a/apps/server/src/serverSettings.forkSettings.test.ts b/apps/server/src/serverSettings.forkSettings.test.ts index 1eb0eeed87b25..9de8265f46bc0 100644 --- a/apps/server/src/serverSettings.forkSettings.test.ts +++ b/apps/server/src/serverSettings.forkSettings.test.ts @@ -218,3 +218,48 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("fork settings ro }).pipe(Effect.provide(layerServerSettings())), ); }); + +it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("fork MCP profile keys", (it) => { + it.effect("keeps every other setting when an MCP key in the file holds a bad value", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString( + config.settingsPath, + JSON.stringify({ ...FULL_FILE, mcpThreadProfiles: { t1: null }, mcpProfile: 5 }), + ); + const service = yield* ServerSettingsModule.ServerSettingsService; + const settings = yield* service.getSettings; + assert.strictEqual(settings.enableAgentBrowserAccess, false); + assert.strictEqual(settings.usagePacingGate, "advise"); + assert.strictEqual(settings.agentSlots.maxPerMachine, 4); + assert.deepStrictEqual(Object.keys(settings.waitChecks).toSorted(), [ + "build-done", + "ci-green", + ]); + // The unset pick is dropped; the bad default reads as a name no profile can have, so the + // resolver refuses it instead of widening it to "all". + assert.deepStrictEqual(settings.mcpThreadProfiles, {}); + assert.strictEqual(settings.mcpProfile, "(unreadable number)"); + }).pipe(Effect.provide(layerServerSettings())), + ); + + it.effect("refuses a save that names a profile that is not set up, saying how to fix it", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(config.settingsPath, JSON.stringify(FULL_FILE)); + const service = yield* ServerSettingsModule.ServerSettingsService; + const error = yield* service + .updateSettings(decodePatch({ mcpProfile: "lean" })) + .pipe(Effect.flip); + assert.strictEqual( + error.message, + 'mcpProfile names MCP profile "lean", which is not set up: add that profile first, or pick "all" or "t3-only".', + ); + // Nothing was written: the file still has no MCP keys. + const file = (yield* readFile) as Record; + assert.isFalse("mcpProfile" in file); + }).pipe(Effect.provide(layerServerSettings())), + ); +}); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 9f78cfb797b5e..8a02c169a5bf4 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -55,6 +55,7 @@ import { fallbackTextGenerationModelSelection, isModelSelectionProviderEnabled, } from "@t3tools/shared/serverSettings"; +import { forkSettingsWriteProblem } from "@t3tools/shared/forkSettingsPatch"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts"; @@ -231,6 +232,20 @@ function ensureSecretProviderWritesAllowed( return Effect.void; } +// Fork: refuses a fork setting's save that could not apply (forkSettingsPatch.ts says why). +function ensureForkSettingsWriteAllowed( + current: ServerSettings, + next: ServerSettings, + settingsPath: string, +): Effect.Effect { + const detail = forkSettingsWriteProblem(current, next); + return detail === undefined + ? Effect.void + : Effect.fail( + new ServerSettingsError({ settingsPath, operation: "write-fork-setting", detail }), + ); +} + function ensureProviderInstanceMutationAllowed( settings: ServerSettings, mutation: ProviderInstanceMutation, @@ -313,7 +328,11 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( ): Effect.Effect => writeSemaphore.withPermits(1)( Ref.get(currentSettingsRef).pipe( - Effect.flatMap(update), + Effect.flatMap((current) => + update(current).pipe( + Effect.tap((next) => ensureForkSettingsWriteAllowed(current, next, "test settings")), + ), + ), Effect.flatMap(normalizeServerSettings), Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)), Effect.map(resolveTextGenerationProvider), @@ -1226,6 +1245,7 @@ const make = Effect.gen(function* () { // An older client echoes a reference as the redacted marker; restore it before vetting so // a removed provider's reference is cleared below rather than restored by persistence. const updated = withEchoedSecretReferences(current, yield* update(current)); + yield* ensureForkSettingsWriteAllowed(current, updated, settingsPath); // Vet before secrets: a variable the policy hides from clients is not one they removed. const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch); if (vetted._tag === "Locked") { diff --git a/docs/fork/README.md b/docs/fork/README.md index f54dc66bc8859..d68e3d8b86a8d 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -26,18 +26,24 @@ The defaults, "off" and "decided in" below come from one table in the code, (`packages/shared/src/forkDocs.test.ts`) fails when this table and that one differ, or a setting has no section below. "Off" means the default leaves the machine as upstream's would be. -| Setting | Default | Off | Decided in | -| ---------------------------------------------------------------------------- | ------------------- | --- | ------------------------------------------------------ | -| [`server.automaticUpdates`](#serverautomaticupdates) | `false` | yes | [#41](https://github.com/scuttletoby/t3code/issues/41) | -| [`server.automaticUpdatesQuietCommand`](#serverautomaticupdatesquietcommand) | `""` | yes | [#5](https://github.com/scuttletoby/t3code/issues/5) | -| [`server.usagePacing`](#serverusagepacing) | `{}` | yes | [#52](https://github.com/scuttletoby/t3code/issues/52) | -| [`server.usagePacingGate`](#serverusagepacinggate) | `"off"` | yes | [#73](https://github.com/scuttletoby/t3code/issues/73) | -| [`server.usagePacingLowerEffort`](#serverusagepacinglowereffort) | `{}` | yes | [#73](https://github.com/scuttletoby/t3code/issues/73) | -| [`server.waitFor`](#serverwaitfor) | `{"enabled":false}` | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | -| [`server.waitChecks`](#serverwaitchecks) | `{}` | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | -| [`server.agentSlots`](#serveragentslots) | `{"enabled":false}` | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | -| [`server.headlessUsageRefreshInterval`](#serverheadlessusagerefreshinterval) | `600000` | no | [#42](https://github.com/scuttletoby/t3code/issues/42) | -| [`projectOverride.waitChecks`](#projectoverridewaitchecks) | not set | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | +| Setting | Default | Off | Decided in | +| ---------------------------------------------------------------------------- | ------------------- | --- | -------------------------------------------------------- | +| [`server.automaticUpdates`](#serverautomaticupdates) | `false` | yes | [#41](https://github.com/scuttletoby/t3code/issues/41) | +| [`server.automaticUpdatesQuietCommand`](#serverautomaticupdatesquietcommand) | `""` | yes | [#5](https://github.com/scuttletoby/t3code/issues/5) | +| [`server.usagePacing`](#serverusagepacing) | `{}` | yes | [#52](https://github.com/scuttletoby/t3code/issues/52) | +| [`server.usagePacingGate`](#serverusagepacinggate) | `"off"` | yes | [#73](https://github.com/scuttletoby/t3code/issues/73) | +| [`server.usagePacingLowerEffort`](#serverusagepacinglowereffort) | `{}` | yes | [#73](https://github.com/scuttletoby/t3code/issues/73) | +| [`server.waitFor`](#serverwaitfor) | `{"enabled":false}` | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | +| [`server.waitChecks`](#serverwaitchecks) | `{}` | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | +| [`server.agentSlots`](#serveragentslots) | `{"enabled":false}` | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | +| [`server.headlessUsageRefreshInterval`](#serverheadlessusagerefreshinterval) | `600000` | no | [#42](https://github.com/scuttletoby/t3code/issues/42) | +| [`server.mcpProfiles`](#servermcpprofiles) | `{}` | yes | [#145](https://github.com/scuttletoby/t3code/issues/145) | +| [`server.mcpProfile`](#servermcpprofile) | `"all"` | yes | [#145](https://github.com/scuttletoby/t3code/issues/145) | +| [`server.mcpSubagentProfile`](#servermcpsubagentprofile) | `"inherit"` | yes | [#145](https://github.com/scuttletoby/t3code/issues/145) | +| [`server.mcpThreadProfiles`](#servermcpthreadprofiles) | `{}` | yes | [#145](https://github.com/scuttletoby/t3code/issues/145) | +| [`projectOverride.waitChecks`](#projectoverridewaitchecks) | not set | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | +| [`projectOverride.mcpProfile`](#projectoverridemcpprofile) | not set | yes | [#145](https://github.com/scuttletoby/t3code/issues/145) | +| [`projectOverride.mcpSubagentProfile`](#projectoverridemcpsubagentprofile) | not set | yes | [#145](https://github.com/scuttletoby/t3code/issues/145) | For `waitFor` and `agentSlots` only the `enabled` switch is pinned; their other fields are tuning that does nothing while the switch is off. @@ -139,6 +145,35 @@ thread, setting or install. Never more often than the provider status refresh. Switch off in `settings.json`: `"headlessUsageRefreshInterval": 0`. +### `server.mcpProfiles` + +Named MCP profiles. A profile says which outside MCP servers (`servers`) and which groups of T3's +own tools (`t3Tools`) a thread gets; each is `"all"` or a list. Two profiles are built in: `all` +(everything, today's behaviour) and `t3-only` (no outside servers, every T3 tool). Nothing applies +a profile yet: the provider adapters and the T3 tool filter come in later pull requests. + +```json +{ "mcpProfiles": { "lean": { "servers": [], "t3Tools": ["orchestration", "threads"] } } } +``` + +Only the person can change MCP profile settings; agents cannot. + +### `server.mcpProfile` + +The profile a top-level thread gets when nobody picked one for it. `all` (the default) gives every +thread everything, as today. A name with no profile is refused when saved, and a thread that meets +one (for example after a hand edit) is refused instead of getting `all`. + +### `server.mcpSubagentProfile` + +The profile a delegated child gets when nobody picked one for it. `inherit` (the default) gives it +its parent's profile. A child never gets more than its parent. + +### `server.mcpThreadProfiles` + +The person's pick of profile per thread, by thread id. A pick wins over every default. The newest +500 picks are kept; a thread whose pick was dropped falls back to its default. + ### `projectOverride.waitChecks` A project's own list of wait checks. It replaces the server's list for that project as a whole (a @@ -146,6 +181,15 @@ project lists every check it uses). Not set: the project uses the server's check Set: **Settings**, choose the project at the top, then **Wait checks**. +### `projectOverride.mcpProfile` + +A project's own default profile for its top-level threads. Not set: the server's `mcpProfile`. + +### `projectOverride.mcpSubagentProfile` + +A project's own profile rule for delegated children (`inherit` or a profile name). Not set: the +server's `mcpSubagentProfile`. + ### A setting the fork removed An early draft had a client setting for one "anchor machine" for new work. It was removed before it diff --git a/packages/contracts/src/forkSettings.test.ts b/packages/contracts/src/forkSettings.test.ts index 2b3d07eee2a1d..dbb92576405b0 100644 --- a/packages/contracts/src/forkSettings.test.ts +++ b/packages/contracts/src/forkSettings.test.ts @@ -79,8 +79,11 @@ describe("fork settings seam", () => { const lines = SETTINGS_SOURCE.split("\n"); // The import, `export *` and six spreads. expect(lines.filter((line) => /forkSettings|ForkSettings/.test(line))).toHaveLength(8); - // The inline `automaticUpdates`: its comment, its field and its patch field. - expect(lines.filter((line) => line.includes("Fork:"))).toHaveLength(1); + // Three `Fork:` comments: the inline `automaticUpdates`, and the save error for a refused fork + // setting (its operation and its `detail` field). That error's operation, the comment on + // `detail` and the line of `message` that shows the detail name `write-fork-setting`. + expect(lines.filter((line) => line.includes("Fork:"))).toHaveLength(3); + expect(lines.filter((line) => line.includes("write-fork-setting"))).toHaveLength(3); expect(lines.filter((line) => /^ {2}automaticUpdates:/.test(line))).toHaveLength(2); // forkSettings.ts never imports settings.ts, so upstream's file stays the only one with seams. expect(FORK_SOURCE).not.toMatch(/from "\.\/settings(\.ts)?"/); diff --git a/packages/contracts/src/forkSettings.ts b/packages/contracts/src/forkSettings.ts index 10b29ee51ea26..7d0c5a339b41b 100644 --- a/packages/contracts/src/forkSettings.ts +++ b/packages/contracts/src/forkSettings.ts @@ -13,9 +13,11 @@ import { MCP_SUBAGENT_INHERIT, MCP_THREAD_PROFILES_KEEP_NEWEST, McpProfileName, + McpProfilePatch, McpProfileRef, McpProfilesFromSettingsFile, McpProfilesPatch, + McpProjectProfileRefPatch, McpThreadProfiles, McpThreadProfilesPatch, } from "./mcpProfile.ts"; @@ -74,7 +76,7 @@ export const ForkServerSettingsFields = { ), /** Named MCP profiles besides the built-in `all` and `t3-only`; each checked when used. */ mcpProfiles: McpProfilesFromSettingsFile, - /** The MCP profile a thread gets; `all` (or empty) is today's behaviour. */ + /** The MCP profile a thread gets; `all` (or empty) is today's behaviour. Read leniently. */ mcpProfile: McpProfileRef.pipe(Schema.withDecodingDefault(Effect.succeed(MCP_PROFILE_ALL))), /** The MCP profile of a delegated child thread; `inherit` (or empty) follows `mcpProfile`. */ mcpSubagentProfile: McpProfileRef.pipe( @@ -102,7 +104,9 @@ export const ForkServerSettingsPatchFields = { headlessUsageRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis), /** Strict: a save refuses a bad profile or a built-in name (reading the file keeps it as is). */ mcpProfiles: Schema.optionalKey(McpProfilesPatch), - mcpProfile: Schema.optionalKey(McpProfileName), + /** A profile name, not `inherit`; the server also refuses a name no profile has. */ + mcpProfile: Schema.optionalKey(McpProfilePatch), + /** `inherit` or a profile name; the server also refuses a name no profile has. */ mcpSubagentProfile: Schema.optionalKey(McpProfileName), mcpThreadProfiles: Schema.optionalKey(McpThreadProfilesPatch), } satisfies Record; @@ -154,9 +158,9 @@ export const FORK_PROJECT_SCOPED_KEYS = [ export const ForkProjectOverrideFields = { /** Bad entries are dropped on read; the settings patch refuses them. */ waitChecks: Schema.optionalKey(WaitChecksFromSettingsFile), - /** Absent or empty: the server's `mcpProfile`. */ + /** Absent or empty: the server's `mcpProfile`. Read leniently, as the server's. */ mcpProfile: Schema.optionalKey(McpProfileRef), - /** Absent or empty: the server's `mcpSubagentProfile`. */ + /** Absent or empty: the server's `mcpSubagentProfile`. Read leniently, as the server's. */ mcpSubagentProfile: Schema.optionalKey(McpProfileRef), } satisfies Record<(typeof FORK_PROJECT_SCOPED_KEYS)[number], unknown>; @@ -164,8 +168,12 @@ export const ForkProjectOverrideFields = { export const ForkProjectOverridePatchFields = { /** A save refuses a bad check. */ waitChecks: Schema.optionalKey(WaitChecks), - mcpProfile: Schema.optionalKey(McpProfileName), - mcpSubagentProfile: Schema.optionalKey(McpProfileName), + /** + * Any text, as reading keeps it: clients resend a project's whole entry when they save its other + * settings. The server refuses only a changed value that names no profile (forkSettingsPatch.ts). + */ + mcpProfile: Schema.optionalKey(McpProjectProfileRefPatch), + mcpSubagentProfile: Schema.optionalKey(McpProjectProfileRefPatch), } satisfies Record; /** diff --git a/packages/contracts/src/mcpProfile.test.ts b/packages/contracts/src/mcpProfile.test.ts index 896d6874cbf16..e194acbe07fb9 100644 --- a/packages/contracts/src/mcpProfile.test.ts +++ b/packages/contracts/src/mcpProfile.test.ts @@ -39,6 +39,45 @@ describe("MCP profile settings file", () => { expect(encodeFile(settings).mcpProfiles).toEqual(profiles); }); + it("keeps every other setting when an MCP key holds a bad value", () => { + const settings = decodeFile({ + enableAgentBrowserAccess: false, + waitFor: { enabled: true }, + mcpProfile: 5, + mcpSubagentProfile: ["lean"], + mcpThreadProfiles: { t1: null, t2: 7, t3: " lean ", t4: { profile: "lean" } }, + projectSettingsOverrides: { + [PROJECT]: { mcpProfile: 5, mcpSubagentProfile: null, waitChecks: {} }, + }, + }); + expect(settings.enableAgentBrowserAccess).toBe(false); + expect(settings.waitFor.enabled).toBe(true); + expect(settings.projectSettingsOverrides[PROJECT]?.waitChecks).toEqual({}); + // A bad value is kept as a marker no profile has, so a thread that uses it is refused (never + // widened to `all`); `null` means "not set", as an empty value does. + expect(mcpKeys(settings)).toEqual({ + mcpProfiles: {}, + mcpProfile: "(unreadable number)", + mcpSubagentProfile: "(unreadable list)", + mcpThreadProfiles: { t2: "(unreadable number)", t3: "lean", t4: "(unreadable object)" }, + }); + expect(settings.projectSettingsOverrides[PROJECT]).toMatchObject({ + mcpProfile: "(unreadable number)", + mcpSubagentProfile: "", + }); + }); + + it("reads a map that is not an object as empty and keeps every other setting", () => { + const settings = decodeFile({ + enableAgentBrowserAccess: false, + mcpProfiles: "lean", + mcpThreadProfiles: ["t1"], + }); + expect(settings.enableAgentBrowserAccess).toBe(false); + expect(settings.mcpProfiles).toEqual({}); + expect(settings.mcpThreadProfiles).toEqual({}); + }); + it("trims profile references", () => { expect(decodeFile({ mcpProfile: " lean ", mcpSubagentProfile: " " })).toMatchObject({ mcpProfile: "lean", @@ -72,6 +111,16 @@ describe("MCP profile settings patch", () => { }); }); + it("takes a project's reference as reading keeps it, so other project saves still work", () => { + // Clients resend a project's whole entry; the server refuses only a changed reference. + for (const mcpProfile of ["", "Lean", "(unreadable number)", "inherit"]) { + expect( + decodePatch({ projectSettingsOverrides: { [PROJECT]: { mcpProfile } } }) + .projectSettingsOverrides?.[PROJECT]?.mcpProfile, + ).toBe(mcpProfile); + } + }); + it.each([ ["a built-in name", { mcpProfiles: { all: { servers: [], t3Tools: [] } } }], ["the name `inherit`", { mcpProfiles: { inherit: { servers: [], t3Tools: [] } } }], @@ -85,7 +134,10 @@ describe("MCP profile settings patch", () => { ["a bad pick", { mcpThreadProfiles: { "thread-1": "Not A Name" } }], ["a blank thread id", { mcpThreadProfiles: { " ": "lean" } }], ["an untrimmed thread id", { mcpThreadProfiles: { " thread-1": "lean" } }], - ["a bad project reference", { projectSettingsOverrides: { [PROJECT]: { mcpProfile: "" } } }], + ["`inherit` as the default profile", { mcpProfile: "inherit" }], + ["`inherit` as a thread pick", { mcpThreadProfiles: { "thread-1": "inherit" } }], + ["a profile that is not an object", { mcpProfiles: { lean: "all" } }], + ["a server that is not text", { mcpProfiles: { lean: { servers: [1], t3Tools: [] } } }], ])("refuses %s", (_name, patch) => { expect(() => decodePatch(patch)).toThrow(); }); diff --git a/packages/contracts/src/mcpProfile.ts b/packages/contracts/src/mcpProfile.ts index 418ac240f1384..ebd0c68e05246 100644 --- a/packages/contracts/src/mcpProfile.ts +++ b/packages/contracts/src/mcpProfile.ts @@ -14,7 +14,7 @@ export const MCP_PROFILE_ALL = "all"; /** No outside servers, every T3 tool. */ export const MCP_PROFILE_T3_ONLY = "t3-only"; /** The two profiles every build knows; `mcpProfiles` cannot redefine them. */ -const MCP_BUILT_IN_PROFILE_NAMES = [MCP_PROFILE_ALL, MCP_PROFILE_T3_ONLY] as const; +const MCP_BUILT_IN_PROFILE_NAMES: ReadonlyArray = [MCP_PROFILE_ALL, MCP_PROFILE_T3_ONLY]; /** `mcpSubagentProfile` value: a delegated child follows `mcpProfile` like any other thread. */ export const MCP_SUBAGENT_INHERIT = "inherit"; @@ -24,15 +24,27 @@ const MCP_PROFILE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/u; export const McpProfileName = Schema.String.check(Schema.isPattern(MCP_PROFILE_NAME_PATTERN)); export type McpProfileName = typeof McpProfileName.Type; +/** True for `all` and `t3-only`. */ +export const isBuiltInMcpProfileName = (name: string): boolean => + MCP_BUILT_IN_PROFILE_NAMES.includes(name); + /** True for a name a profile in `mcpProfiles` may have: valid, not built in, not `inherit`. */ export const isDefinableMcpProfileName = (name: string): boolean => MCP_PROFILE_NAME_PATTERN.test(name) && name !== MCP_SUBAGENT_INHERIT && - !(MCP_BUILT_IN_PROFILE_NAMES as ReadonlyArray).includes(name); + !isBuiltInMcpProfileName(name); + +/** A profile name a thread can run with: a valid name other than `inherit`. */ +const McpProfileChoice = McpProfileName.check( + Schema.makeFilter((name: string) => name !== MCP_SUBAGENT_INHERIT, { + expected: `a profile name other than ${MCP_SUBAGENT_INHERIT} (only mcpSubagentProfile takes ${MCP_SUBAGENT_INHERIT})`, + }), +); /** - * Groups of T3's own tools, one per toolkit. The two message tools (`request_secret`, - * `send_to_user`) are in no group: every profile keeps them. + * Groups of T3's own tools, one per toolkit (`preview` has the preview and preview-controls + * toolkits). The tools in {@link MCP_T3_UNGROUPED_TOOLS} are in no group. The server's + * apps/server/src/fork/mcpProfile.ts maps every toolkit to its group, and a test checks every tool. */ export const MCP_T3_TOOL_GROUPS = [ "orchestration", @@ -48,77 +60,128 @@ export const MCP_T3_TOOL_GROUPS = [ "html", "waits", ] as const; -export const McpT3ToolGroup = Schema.Literals(MCP_T3_TOOL_GROUPS); -export type McpT3ToolGroup = typeof McpT3ToolGroup.Type; - -/** An outside MCP server's name as the provider's config spells it. */ -export const McpServerName = TrimmedString.check(Schema.isNonEmpty()); +export type McpT3ToolGroup = (typeof MCP_T3_TOOL_GROUPS)[number]; /** - * One profile. `servers` and `t3Tools` are each `"all"` or a keep-list; a keep-list leaves out - * anything not named, so a server added later is left out until the owner adds it. An empty list - * keeps none. + * 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). */ -export const McpProfile = Schema.Struct({ - servers: Schema.Union([Schema.Literal("all"), Schema.Array(McpServerName)]), - t3Tools: Schema.Union([Schema.Literal("all"), Schema.Array(McpT3ToolGroup)]), -}); -export type McpProfile = typeof McpProfile.Type; +export const MCP_T3_UNGROUPED_TOOLS: ReadonlyArray = [ + "request_secret", + "send_to_user", + "tool_search", +]; + +const isRecord = (value: unknown): value is { readonly [key: string]: unknown } => + typeof value === "object" && value !== null && !Array.isArray(value); /** * The settings file's profiles. Each entry is kept as written and checked only when a thread uses * it, so one bad entry (or one written by a newer build, with fields this build does not know) * never stops the settings file from loading, and a save keeps it as it was. */ -export const McpProfilesFromSettingsFile = Schema.Record(Schema.String, Schema.Unknown).pipe( +export const McpProfilesFromSettingsFile = Schema.Unknown.pipe( + Schema.decodeTo( + Schema.Record(Schema.String, Schema.Unknown), + SchemaTransformation.transform({ + // A map that is not an object (a hand edit gone wrong) reads as no profiles; a thread that + // names one is then refused, never widened. + decode: (raw): { readonly [name: string]: unknown } => (isRecord(raw) ? raw : {}), + encode: (profiles) => profiles, + }), + ), Schema.withDecodingDefault(Effect.succeed({})), ); const MCP_PROFILE_FIELDS: ReadonlyArray = ["servers", "t3Tools"]; +const KNOWN_GROUPS: ReadonlyArray = MCP_T3_TOOL_GROUPS; + +const isAllOrListOf = (value: unknown, isEntry: (entry: unknown) => boolean): boolean => + value === "all" || (Array.isArray(value) && value.every(isEntry)); + +/** + * A profile a save may store: exactly `servers` (non-blank names) and `t3Tools` (known groups), each + * `"all"` or a keep-list; a keep-list leaves out anything not named. An unknown field is refused, not + * dropped, so a save never stores a profile cut down from what the person wrote. + */ +const isSavableMcpProfile = (entry: unknown): boolean => + isRecord(entry) && + Object.keys(entry).length === MCP_PROFILE_FIELDS.length && + Object.keys(entry).every((field) => MCP_PROFILE_FIELDS.includes(field)) && + isAllOrListOf(entry.servers, (name) => typeof name === "string" && name.trim() !== "") && + isAllOrListOf( + entry.t3Tools, + (group) => typeof group === "string" && KNOWN_GROUPS.includes(group), + ); /** - * A profile in a settings patch: a field this build does not know is refused, not dropped, so a - * save never stores a profile cut down from what the person wrote. (Effect strips excess fields - * unless the decode call itself asks for errors, so the check runs on the input first.) + * Profiles in a settings patch: each entry replaces the stored one whole; `null` removes it. Typed + * as the settings file's map (each entry `unknown`), so a client may send back what it read; the + * check refuses a bad name or entry. (Effect drops, rather than refuses, a record key its key + * schema rejects, so names are checked on the whole map.) */ -const McpProfileInPatch = Schema.Record(Schema.String, Schema.Unknown) +export const McpProfilesPatch = Schema.Record(Schema.String, Schema.Unknown) .check( Schema.makeFilter( - (fields: { readonly [name: string]: unknown }) => - Object.keys(fields).every((name) => MCP_PROFILE_FIELDS.includes(name)), - { expected: `a profile with only the fields ${MCP_PROFILE_FIELDS.join(", ")}` }, + (profiles: { readonly [name: string]: unknown }) => + Object.keys(profiles).every(isDefinableMcpProfileName), + { + expected: `profile names of lower-case letters, digits and dashes (at most 40), other than ${MCP_BUILT_IN_PROFILE_NAMES.join(", ")} and ${MCP_SUBAGENT_INHERIT}`, + }, ), ) - .pipe(Schema.decodeTo(McpProfile, SchemaTransformation.passthrough({ strict: false }))); + .check( + Schema.makeFilter( + (profiles: { readonly [name: string]: unknown }) => + Object.values(profiles).every((entry) => entry === null || isSavableMcpProfile(entry)), + { + expected: `profiles with only ${MCP_PROFILE_FIELDS.join(" and ")}, each "all" or a list (servers: non-blank names; t3Tools: ${MCP_T3_TOOL_GROUPS.join(", ")}), or null to remove one`, + }, + ), + ); /** - * Profiles in a settings patch: each entry replaces the stored one whole; `null` removes it. Names - * are checked on the whole map: Effect drops, rather than refuses, a record key its key schema - * rejects. + * What a profile reference in the settings file reads as. Text is trimmed (empty means "not set"); + * `null` reads as not set. Any other value (a hand edit gone wrong, or a newer build's) reads as a + * marker no profile can have, so a thread that uses it is refused, never widened, and the rest of + * the file still loads. */ -export const McpProfilesPatch = Schema.Record( - Schema.String, - Schema.NullOr(McpProfileInPatch), -).check( - Schema.makeFilter( - (profiles: { readonly [name: string]: unknown }) => - Object.keys(profiles).every(isDefinableMcpProfileName), - { - expected: `profile names of lower-case letters, digits and dashes (at most 40), other than ${MCP_BUILT_IN_PROFILE_NAMES.join(", ")} and ${MCP_SUBAGENT_INHERIT}`, - }, +const readMcpProfileRef = (value: unknown): string => + typeof value === "string" + ? value.trim() + : value === null || value === undefined + ? "" + : `(unreadable ${Array.isArray(value) ? "list" : typeof value})`; + +/** A profile reference as the settings file holds it; see {@link readMcpProfileRef}. */ +export const McpProfileRef = Schema.Unknown.pipe( + Schema.decodeTo( + Schema.String, + SchemaTransformation.transform({ + decode: readMcpProfileRef, + encode: (ref) => ref, + }), ), ); -/** A profile reference as the settings file holds it; empty means "not set". */ -export const McpProfileRef = TrimmedString; +/** + * A project's profile reference in a settings patch: any text, as reading the file keeps it, so a + * client that saves a project's other settings can send back what it read. The server refuses a + * new value that names no profile when it saves (packages/shared/src/forkSettingsPatch.ts). + */ +export const McpProjectProfileRefPatch = TrimmedString; + +/** The server's default profile in a settings patch: a profile name, not `inherit`. */ +export const McpProfilePatch = McpProfileChoice; /** - * The owner's pick per thread in a settings patch; `null` removes the pick. Thread ids are checked - * on the whole map, as for {@link McpProfilesPatch}. + * The owner's pick per thread in a settings patch; `null` removes the pick. A pick is a profile + * name, not `inherit`. Thread ids are checked on the whole map, as for {@link McpProfilesPatch}. */ export const McpThreadProfilesPatch = Schema.Record( Schema.String, - Schema.NullOr(McpProfileName), + Schema.NullOr(McpProfileChoice), ).check( Schema.makeFilter( (picks: { readonly [threadId: string]: unknown }) => @@ -127,10 +190,30 @@ export const McpThreadProfilesPatch = Schema.Record( ), ); -/** The newest thread picks kept; a write that goes over drops the oldest. */ +/** + * The newest thread picks kept; a write that goes over drops the oldest, which then falls back to + * its role default. Pruning deleted threads' picks comes later. + */ export const MCP_THREAD_PROFILES_KEEP_NEWEST = 500; -/** The settings file's thread picks: thread id to profile name. */ -export const McpThreadProfiles = Schema.Record(Schema.String, Schema.String).pipe( +/** + * The settings file's thread picks: thread id to profile name. Read leniently, like + * {@link McpProfileRef}: a `null` pick is dropped (no pick), any other non-text pick is kept as a + * marker the resolver refuses, and a map that is not an object reads as no picks. One bad pick never + * stops the settings file from loading. + */ +export const McpThreadProfiles = Schema.Unknown.pipe( + Schema.decodeTo( + Schema.Record(Schema.String, Schema.String), + SchemaTransformation.transform({ + decode: (raw): { readonly [threadId: string]: string } => + Object.fromEntries( + Object.entries(isRecord(raw) ? raw : {}) + .filter(([, pick]) => pick !== null && pick !== undefined) + .map(([threadId, pick]) => [threadId, readMcpProfileRef(pick)]), + ), + encode: (picks) => picks, + }), + ), Schema.withDecodingDefault(Effect.succeed({})), ); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 6ca6b5bdebe81..0f0c619b4c577 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1748,6 +1748,8 @@ export const ServerSettingsOperation = Schema.Literals([ "prepare-directory", "write-managed-setting", "use-disallowed-provider", + // Fork: a fork setting's save refused by the fork's save check; `detail` says why. + "write-fork-setting", ]); export type ServerSettingsOperation = typeof ServerSettingsOperation.Type; @@ -1767,10 +1769,13 @@ export class ServerSettingsError extends Schema.TaggedError managedBy: Schema.optional(Schema.String), /** For `use-disallowed-provider`: the provider's name as users know it. */ providerLabel: Schema.optional(Schema.String), + /** Fork: for `write-fork-setting`, what is wrong and how to fix it. */ + detail: Schema.optional(Schema.String), cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { + if (this.operation === "write-fork-setting" && this.detail !== undefined) return this.detail; if (this.operation === "write-managed-setting") { return `${this.managedSetting ?? "This setting"} is managed by ${this.managedBy ?? "your organization"} and cannot be changed.`; } diff --git a/packages/shared/package.json b/packages/shared/package.json index cd67009cb5288..f70a6036eb6bf 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -167,6 +167,10 @@ "types": "./src/serverSettings.ts", "import": "./src/serverSettings.ts" }, + "./forkSettingsPatch": { + "types": "./src/forkSettingsPatch.ts", + "import": "./src/forkSettingsPatch.ts" + }, "./waitFor": { "types": "./src/waitFor.ts", "import": "./src/waitFor.ts" diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index 571228909c4ad..808498eb9207e 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -3,6 +3,7 @@ import { DEFAULT_SERVER_SETTINGS, MCP_THREAD_PROFILES_KEEP_NEWEST, + ProjectId, ProviderInstanceId, type ServerSettings, ThreadId, @@ -12,7 +13,11 @@ import * as Duration from "effect/Duration"; import * as Schema from "effect/Schema"; import { describe, expect, it } from "vite-plus/test"; -import { applyForkSettingsPatch, splitForkSettingsPatch } from "./forkSettingsPatch.ts"; +import { + applyForkSettingsPatch, + forkSettingsWriteProblem, + splitForkSettingsPatch, +} from "./forkSettingsPatch.ts"; import { applyServerSettingsPatch } from "./serverSettings.ts"; // The source text, to pin the fork's lines in upstream's file. import SERVER_SETTINGS_SOURCE from "./serverSettings.ts?raw"; @@ -181,3 +186,103 @@ describe("fork settings patch", () => { expect(lines.filter((line) => /\bFork:/.test(line))).toHaveLength(1); }); }); + +describe("fork settings save check (MCP profile references)", () => { + const project = ProjectId.make("project-1"); + const stored: ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + mcpProfiles: { lean: { servers: [], t3Tools: ["threads"] } }, + mcpThreadProfiles: { "thread-old": "(unreadable number)" }, + // Odd values a hand edit or an older build left; reading keeps them. + projectSettingsOverrides: { + [project]: { mcpProfile: "Lean", mcpSubagentProfile: "" }, + }, + }; + const problemAfter = (patch: Parameters[1]) => + forkSettingsWriteProblem(stored, applyServerSettingsPatch(stored, patch)); + + it("lets a project save its other settings while an odd stored reference stays as it was", () => { + expect( + problemAfter({ + projectSettingsOverrides: { + [project]: { + mcpProfile: "Lean", + mcpSubagentProfile: "", + enableAgentBrowserAccess: true, + }, + }, + }), + ).toBeUndefined(); + expect(problemAfter({ enableAgentBrowserAccess: false })).toBeUndefined(); + // An unreadable pick left as it was does not block another thread's pick. + expect(problemAfter({ mcpThreadProfiles: { "thread-1": "lean" } })).toBeUndefined(); + }); + + it.each([ + ["a default that names a profile", { mcpProfile: "lean" }], + ["a built-in default", { mcpProfile: "t3-only" }], + ["inherit as the sub-agent rule", { mcpSubagentProfile: "inherit" }], + ["a pick of a built-in", { mcpThreadProfiles: { "thread-1": "all" } }], + [ + "a default added in the same save", + { mcpProfiles: { docs: { servers: ["docs"], t3Tools: "all" } }, mcpProfile: "docs" }, + ], + [ + "a project's reference cleared", + { projectSettingsOverrides: { [project]: { mcpProfile: "" } } }, + ], + [ + "inherit as a project's sub-agent rule", + { + projectSettingsOverrides: { + [project]: { mcpProfile: "Lean", mcpSubagentProfile: "inherit" }, + }, + }, + ], + ] as const)("takes %s", (_name, patch) => { + expect(problemAfter(patch)).toBeUndefined(); + }); + + it.each([ + [ + "a default that names no profile", + { mcpProfile: "gone" }, + /^mcpProfile names MCP profile "gone", which is not set up: add that profile first, or pick "all" or "t3-only"\.$/, + ], + ["inherit as the default", { mcpProfile: "inherit" }, /^mcpProfile cannot be "inherit"/], + [ + "a sub-agent rule that names no profile", + { mcpSubagentProfile: "gone" }, + /^mcpSubagentProfile names MCP profile "gone"/, + ], + [ + "a pick that names no profile", + { mcpThreadProfiles: { "thread-1": "gone" } }, + /^The pick for thread thread-1 names MCP profile "gone"/, + ], + [ + "inherit as a pick", + { mcpThreadProfiles: { "thread-1": "inherit" } }, + /^The pick for thread thread-1 cannot be "inherit"/, + ], + [ + "a project's changed reference to no profile", + { projectSettingsOverrides: { [project]: { mcpProfile: "Docs" } } }, + /^Project project-1's mcpProfile names MCP profile "Docs"/, + ], + [ + "inherit as a project's default", + { projectSettingsOverrides: { [project]: { mcpProfile: "inherit" } } }, + /^Project project-1's mcpProfile cannot be "inherit"/, + ], + [ + "a new project's reference to no profile", + { + projectSettingsOverrides: { [ProjectId.make("project-2")]: { mcpSubagentProfile: "gone" } }, + }, + /^Project project-2's mcpSubagentProfile names MCP profile "gone"/, + ], + ] as const)("refuses %s, saying how to fix it", (_name, patch, message) => { + expect(problemAfter(patch)).toMatch(message); + }); +}); diff --git a/packages/shared/src/forkSettingsPatch.ts b/packages/shared/src/forkSettingsPatch.ts index aa6b5e5682ee0..96cfe77671a79 100644 --- a/packages/shared/src/forkSettingsPatch.ts +++ b/packages/shared/src/forkSettingsPatch.ts @@ -4,10 +4,15 @@ */ import { FORK_PATCH_RULES, + MCP_PROFILE_ALL, + MCP_PROFILE_T3_ONLY, + MCP_SUBAGENT_INHERIT, type ForkPatchRule, type ForkServerSettingKey, type ServerSettings, type ServerSettingsPatch, + isBuiltInMcpProfileName, + isDefinableMcpProfileName, } from "@t3tools/contracts"; const FORK_PATCH_KEYS = Object.keys(FORK_PATCH_RULES) as ReadonlyArray; @@ -83,3 +88,81 @@ export function applyForkSettingsPatch( } return next as Partial>; } + +/** + * A profile reference a save sets anew that no thread could run with: `inherit` where only + * `mcpSubagentProfile` takes it, or a name no profile has. A reference the save leaves as it was is + * never refused, so an old or odd stored value does not block saving anything else (a thread that + * uses it is refused when it starts). Empty means "not set" and is always fine. + */ +function mcpProfileRefProblem( + next: ServerSettings, + setting: string, + value: string | undefined, + before: string | undefined, + takesInherit: boolean, +): string | undefined { + const name = value?.trim() ?? ""; + if (name === "" || name === (before?.trim() ?? "")) return undefined; + if (name === MCP_SUBAGENT_INHERIT) { + return takesInherit + ? undefined + : `${setting} cannot be "${MCP_SUBAGENT_INHERIT}" (only a sub-agent rule takes it): pick "${MCP_PROFILE_ALL}", "${MCP_PROFILE_T3_ONLY}" or a profile name.`; + } + if (isBuiltInMcpProfileName(name)) return undefined; + if (isDefinableMcpProfileName(name) && Object.hasOwn(next.mcpProfiles, name)) return undefined; + return `${setting} names MCP profile "${name}", which is not set up: add that profile first, or pick "${MCP_PROFILE_ALL}" or "${MCP_PROFILE_T3_ONLY}".`; +} + +/** + * Why the server must refuse this save of fork settings, or `undefined`. Checks `next` (the + * settings after the patch) against `current`, so it also sees a project's or thread's value that + * a client sent back unchanged. Deleting a profile still in use is not refused yet (a later PR). + */ +export function forkSettingsWriteProblem( + current: ServerSettings, + next: ServerSettings, +): string | undefined { + const problems: Array = [ + mcpProfileRefProblem(next, "mcpProfile", next.mcpProfile, current.mcpProfile, false), + mcpProfileRefProblem( + next, + "mcpSubagentProfile", + next.mcpSubagentProfile, + current.mcpSubagentProfile, + true, + ), + ]; + for (const [threadId, pick] of Object.entries(next.mcpThreadProfiles)) { + const before = Object.hasOwn(current.mcpThreadProfiles, threadId) + ? current.mcpThreadProfiles[threadId] + : undefined; + problems.push( + mcpProfileRefProblem(next, `The pick for thread ${threadId}`, pick, before, false), + ); + } + for (const [projectId, overrides] of Object.entries(next.projectSettingsOverrides)) { + const stored = Object.hasOwn(current.projectSettingsOverrides, projectId) + ? current.projectSettingsOverrides[ + projectId as keyof ServerSettings["projectSettingsOverrides"] + ] + : undefined; + problems.push( + mcpProfileRefProblem( + next, + `Project ${projectId}'s mcpProfile`, + overrides.mcpProfile, + stored?.mcpProfile, + false, + ), + mcpProfileRefProblem( + next, + `Project ${projectId}'s mcpSubagentProfile`, + overrides.mcpSubagentProfile, + stored?.mcpSubagentProfile, + true, + ), + ); + } + return problems.find((problem) => problem !== undefined); +} From b44f1c0a400c5757c71f5e495e80ca652165d71c Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:19:30 +0000 Subject: [PATCH 3/6] fork(mcp-profiles): fix round 2 (cap refuses, built-in names, pinned tools, seam) - forkSettingsPatch: a replaceEntries map never drops a pick to make room; a save past the 500-pick cap is refused by forkSettingsWriteProblem ("remove old picks first"). - The save error moves out of upstream settings.ts: the server fails with upstream's ServerSettingsError (operation "normalize") and a fork ForkSettingsWriteError as its cause, which keeps the reason over the RPC. - mcpProfile: a hand-edited profile named like a built-in makes that built-in "broken" and refused at use, with a clear fix. - Ungrouped T3 tools are pinned to their toolkit; an unknown tool is "not-allowed". Co-Authored-By: Claude Opus 5.5 --- apps/server/src/fork/mcpProfile.test.ts | 28 ++++++- apps/server/src/fork/mcpProfile.ts | 63 ++++++++++++--- .../src/fork/personOnlySettings.test.ts | 33 +++++++- .../src/serverSettings.forkSettings.test.ts | 48 +++++++----- apps/server/src/serverSettings.ts | 17 ++-- docs/fork/README.md | 11 ++- packages/contracts/src/forkSettings.test.ts | 7 +- packages/contracts/src/forkSettings.ts | 11 +-- packages/contracts/src/mcpProfile.ts | 7 +- packages/contracts/src/settings.ts | 5 -- packages/shared/src/forkSettingsPatch.test.ts | 78 +++++++++++++++---- packages/shared/src/forkSettingsPatch.ts | 38 +++++++-- 12 files changed, 262 insertions(+), 84 deletions(-) diff --git a/apps/server/src/fork/mcpProfile.test.ts b/apps/server/src/fork/mcpProfile.test.ts index 30b60bc2bb708..8ec3efcf26f97 100644 --- a/apps/server/src/fork/mcpProfile.test.ts +++ b/apps/server/src/fork/mcpProfile.test.ts @@ -76,10 +76,30 @@ describe("MCP profile resolver: old and empty state", () => { }); }); - it("ignores a profile in the file that redefines a built-in", () => { - const settings = fromFile({ mcpProfiles: { all: { servers: [], t3Tools: [] } } }); - expect(isEveryMcpTool(resolved(resolveMcpProfile(settings, [top("t1")])).profile)).toBe(true); - }); + it.each(["all", "t3-only"])( + "refuses %s when a hand edit put a profile of that name in the file", + (name) => { + const file = { + mcpProfiles: { [name]: { servers: [], t3Tools: [] }, lean: PROFILES.lean }, + mcpProfile: name, + }; + const settings = fromFile(file); + const result = refused(resolveMcpProfile(settings, [top("t1")])); + expect(result.problem).toBe("broken"); + expect(result.profileName).toBe(name); + expect(result.message).toBe( + `MCP profile "${name}" cannot be read by this version (mcpProfiles also has an entry named "${name}", a built-in profile's name), so this thread cannot start: remove or rename that entry in the settings file.`, + ); + // An owner's pick of the same built-in is refused too; another profile still works. + expect( + refused( + resolveMcpProfile(fromFile({ ...file, mcpThreadProfiles: { t2: name } }), [top("t2")]), + ).problem, + ).toBe("broken"); + const lean = fromFile({ ...file, mcpThreadProfiles: { t3: "lean" } }); + expect(resolved(resolveMcpProfile(lean, [top("t3")])).name).toBe("lean"); + }, + ); }); describe("MCP profile resolver: who decides", () => { diff --git a/apps/server/src/fork/mcpProfile.ts b/apps/server/src/fork/mcpProfile.ts index b12968d4a6485..794d4247d7caa 100644 --- a/apps/server/src/fork/mcpProfile.ts +++ b/apps/server/src/fork/mcpProfile.ts @@ -11,6 +11,7 @@ import { MCP_T3_UNGROUPED_TOOLS, type McpT3ToolGroup, type ServerSettings, + isBuiltInMcpProfileName, isDefinableMcpProfileName, } from "@t3tools/contracts"; @@ -57,7 +58,10 @@ export interface McpProfileResolved { export type McpProfileProblem = /** No profile has this name (or the name is not one a profile may have). */ | "missing" - /** The profile is there, but this build cannot read it (a typo, or a newer build wrote it). */ + /** + * The profile is there, but this build cannot read it (a typo, or a newer build wrote it), or a + * hand edit put an entry in `mcpProfiles` under a built-in's name. + */ | "broken" /** The parent thread's own profile cannot be applied, so the child's cannot be cut down. */ | "parent" @@ -101,17 +105,39 @@ export const MCP_T3_TOOLKIT_GROUPS: Readonly> = { + request_secret: "orchestrator", + send_to_user: "message", + tool_search: "toolSearch", +}; + +/** {@link mcpT3ToolGroup}'s answer for a tool no profile may keep. */ +export const MCP_T3_TOOL_NOT_ALLOWED = "not-allowed"; + +/** + * A T3 tool's group; `"ungrouped"` for one of `MCP_T3_UNGROUPED_TOOLS` in its own toolkit, which + * every profile keeps; {@link MCP_T3_TOOL_NOT_ALLOWED} for a tool this build does not know (its + * toolkit has no row in {@link MCP_T3_TOOLKIT_GROUPS}, or it is an ungrouped toolkit's other tool). */ export function mcpT3ToolGroup( toolkit: string, tool: string, -): McpT3ToolGroup | "ungrouped" | undefined { - if (MCP_T3_UNGROUPED_TOOLS.includes(tool)) return "ungrouped"; - return Object.hasOwn(MCP_T3_TOOLKIT_GROUPS, toolkit) - ? (MCP_T3_TOOLKIT_GROUPS[toolkit] ?? undefined) +): McpT3ToolGroup | "ungrouped" | typeof MCP_T3_TOOL_NOT_ALLOWED { + if ( + MCP_T3_UNGROUPED_TOOLS.includes(tool) && + Object.hasOwn(MCP_T3_UNGROUPED_TOOL_KITS, tool) && + MCP_T3_UNGROUPED_TOOL_KITS[tool] === toolkit + ) { + return "ungrouped"; + } + const group = Object.hasOwn(MCP_T3_TOOLKIT_GROUPS, toolkit) + ? MCP_T3_TOOLKIT_GROUPS[toolkit] : undefined; + return group ?? MCP_T3_TOOL_NOT_ALLOWED; } /** Longer lineages are refused; real delegation chains are a few threads deep. */ @@ -172,10 +198,20 @@ type Lookup = /** A named profile: a built-in, or an entry of `mcpProfiles` checked now. */ function lookUp(settings: McpProfileSettings, name: string): Lookup { - const builtIn = Object.hasOwn(BUILT_IN_PROFILES, name) ? BUILT_IN_PROFILES[name] : undefined; - // Built-ins win over an entry of the same name, which a save never writes. - if (builtIn !== undefined) return { ok: true, profile: builtIn, unknown: [] }; const profiles: unknown = settings.mcpProfiles; + const builtIn = Object.hasOwn(BUILT_IN_PROFILES, name) ? BUILT_IN_PROFILES[name] : undefined; + if (builtIn !== undefined) { + // A save never writes an entry under a built-in's name, so one is a hand edit. Which of the + // two the owner meant is unknown, so neither is used. + if (isRecord(profiles) && Object.hasOwn(profiles, name)) { + return { + ok: false, + problem: "broken", + issue: `mcpProfiles also has an entry named "${name}", a built-in profile's name`, + }; + } + return { ok: true, profile: builtIn, unknown: [] }; + } if (!isDefinableMcpProfileName(name) || !isRecord(profiles) || !Object.hasOwn(profiles, name)) { return { ok: false, problem: "missing", issue: "" }; } @@ -263,7 +299,12 @@ function cannotApply( problem === "missing" ? `MCP profile "${profileName}" is not set up, so this thread cannot start: ${FIX}.` : problem === "broken" - ? `MCP profile "${profileName}" cannot be read by this version (${issue}), so this thread cannot start: ${FIX}.` + ? `MCP profile "${profileName}" cannot be read by this version (${issue}), so this thread cannot start: ${ + // Only an entry under its name breaks a built-in; picking it again would not help. + isBuiltInMcpProfileName(profileName) + ? `remove or rename that entry in the settings file` + : FIX + }.` : problem === "parent" ? `The parent thread's MCP profile "${profileName}" cannot be applied, so this thread cannot start: ${FIX}.` : `This thread's parent threads ${issue}, so its MCP profile cannot be worked out: ${FIX}.`; diff --git a/apps/server/src/fork/personOnlySettings.test.ts b/apps/server/src/fork/personOnlySettings.test.ts index c2f35c66094b8..7c868f9a68ff6 100644 --- a/apps/server/src/fork/personOnlySettings.test.ts +++ b/apps/server/src/fork/personOnlySettings.test.ts @@ -18,7 +18,12 @@ import { Tool, Toolkit } from "effect/ai"; import * as Schema from "effect/Schema"; import { beforeAll, describe, expect, it } from "vite-plus/test"; -import { MCP_T3_TOOLKIT_GROUPS, mcpT3ToolGroup } from "./mcpProfile.ts"; +import { + MCP_T3_TOOLKIT_GROUPS, + MCP_T3_TOOL_NOT_ALLOWED, + MCP_T3_UNGROUPED_TOOL_KITS, + mcpT3ToolGroup, +} from "./mcpProfile.ts"; const TOOLKITS_DIR = NodePath.resolve(import.meta.dirname, "../mcp/toolkits"); /** Every toolkit folder; each must define its tools in `tools.ts` and export its toolkits there. */ @@ -212,7 +217,7 @@ describe("person-only fork settings", () => { describe("MCP profile T3 tool groups", () => { it("maps every T3 tool to a group or to the ungrouped list", () => { const unmapped = [...toolsByFolder].flatMap(([folder, names]) => - [...names].filter((name) => mcpT3ToolGroup(folder, name) === undefined), + [...names].filter((name) => mcpT3ToolGroup(folder, name) === MCP_T3_TOOL_NOT_ALLOWED), ); expect(unmapped).toEqual([]); }); @@ -227,4 +232,28 @@ describe("MCP profile T3 tool groups", () => { expect(MCP_T3_TOOL_GROUPS.filter((group) => !used.has(group))).toEqual([]); expect(MCP_T3_UNGROUPED_TOOLS.filter((name) => !tools.has(name))).toEqual([]); }); + + it("pins each ungrouped tool to the toolkit that has it", () => { + expect(Object.keys(MCP_T3_UNGROUPED_TOOL_KITS).toSorted()).toEqual( + [...MCP_T3_UNGROUPED_TOOLS].toSorted(), + ); + for (const [tool, toolkit] of Object.entries(MCP_T3_UNGROUPED_TOOL_KITS)) { + expect(toolsByFolder.get(toolkit)?.has(tool), `${toolkit} has ${tool}`).toBe(true); + expect(mcpT3ToolGroup(toolkit, tool)).toBe("ungrouped"); + } + }); + + it("does not take an ungrouped tool's name in another toolkit as ungrouped", () => { + // Same name, other toolkit: that toolkit's group, or not allowed in a toolkit with no group. + expect(mcpT3ToolGroup("waits", "send_to_user")).toBe("waits"); + expect(mcpT3ToolGroup("orchestrator", "tool_search")).toBe("orchestration"); + expect(mcpT3ToolGroup("message", "request_secret")).toBe(MCP_T3_TOOL_NOT_ALLOWED); + expect(mcpT3ToolGroup("toolSearch", "send_to_user")).toBe(MCP_T3_TOOL_NOT_ALLOWED); + }); + + 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); + expect(mcpT3ToolGroup("message", "new_message_tool")).toBe(MCP_T3_TOOL_NOT_ALLOWED); + }); }); diff --git a/apps/server/src/serverSettings.forkSettings.test.ts b/apps/server/src/serverSettings.forkSettings.test.ts index 9de8265f46bc0..d6ab724672f25 100644 --- a/apps/server/src/serverSettings.forkSettings.test.ts +++ b/apps/server/src/serverSettings.forkSettings.test.ts @@ -4,7 +4,8 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ServerSettingsPatch } from "@t3tools/contracts"; +import { ServerSettingsError, ServerSettingsPatch } from "@t3tools/contracts"; +import { ForkSettingsWriteError } from "@t3tools/shared/forkSettingsPatch"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -244,22 +245,33 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("fork MCP profile }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("refuses a save that names a profile that is not set up, saying how to fix it", () => - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fs = yield* FileSystem.FileSystem; - yield* fs.writeFileString(config.settingsPath, JSON.stringify(FULL_FILE)); - const service = yield* ServerSettingsModule.ServerSettingsService; - const error = yield* service - .updateSettings(decodePatch({ mcpProfile: "lean" })) - .pipe(Effect.flip); - assert.strictEqual( - error.message, - 'mcpProfile names MCP profile "lean", which is not set up: add that profile first, or pick "all" or "t3-only".', - ); - // Nothing was written: the file still has no MCP keys. - const file = (yield* readFile) as Record; - assert.isFalse("mcpProfile" in file); - }).pipe(Effect.provide(layerServerSettings())), + it.effect( + "refuses a save that names a profile that is not set up, with the fix as its cause", + () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(config.settingsPath, JSON.stringify(FULL_FILE)); + const service = yield* ServerSettingsModule.ServerSettingsService; + const error = yield* service + .updateSettings(decodePatch({ mcpProfile: "lean" })) + .pipe(Effect.flip); + const reason = + 'mcpProfile names MCP profile "lean", which is not set up: add that profile first, or pick "all" or "t3-only".'; + // Upstream's error type, unchanged; the reason is its cause. + assert.strictEqual(error.operation, "normalize"); + assert.instanceOf(error.cause, ForkSettingsWriteError); + assert.strictEqual((error.cause as Error).message, reason); + // The reason reaches a client: the error as the RPC sends it and decodes it. + const json = Schema.toCodecJson(ServerSettingsError); + const received = yield* Schema.decodeEffect(json)(yield* Schema.encodeEffect(json)(error)); + assert.deepInclude(received.cause as object, { + name: "ForkSettingsWriteError", + message: reason, + }); + // Nothing was written: the file still has no MCP keys. + const file = (yield* readFile) as Record; + assert.isFalse("mcpProfile" in file); + }).pipe(Effect.provide(layerServerSettings())), ); }); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 8a02c169a5bf4..a3a97a135f55d 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -55,7 +55,10 @@ import { fallbackTextGenerationModelSelection, isModelSelectionProviderEnabled, } from "@t3tools/shared/serverSettings"; -import { forkSettingsWriteProblem } from "@t3tools/shared/forkSettingsPatch"; +import { + ForkSettingsWriteError, + forkSettingsWriteProblem, +} from "@t3tools/shared/forkSettingsPatch"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts"; @@ -232,17 +235,21 @@ function ensureSecretProviderWritesAllowed( return Effect.void; } -// Fork: refuses a fork setting's save that could not apply (forkSettingsPatch.ts says why). +// Fork: refuses a fork setting's save that could not apply; the cause says why and how to fix it. function ensureForkSettingsWriteAllowed( current: ServerSettings, next: ServerSettings, settingsPath: string, ): Effect.Effect { - const detail = forkSettingsWriteProblem(current, next); - return detail === undefined + const problem = forkSettingsWriteProblem(current, next); + return problem === undefined ? Effect.void : Effect.fail( - new ServerSettingsError({ settingsPath, operation: "write-fork-setting", detail }), + new ServerSettingsError({ + settingsPath, + operation: "normalize", + cause: new ForkSettingsWriteError(problem), + }), ); } diff --git a/docs/fork/README.md b/docs/fork/README.md index d68e3d8b86a8d..dcc9db4926f9a 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -149,8 +149,10 @@ Switch off in `settings.json`: `"headlessUsageRefreshInterval": 0`. Named MCP profiles. A profile says which outside MCP servers (`servers`) and which groups of T3's own tools (`t3Tools`) a thread gets; each is `"all"` or a list. Two profiles are built in: `all` -(everything, today's behaviour) and `t3-only` (no outside servers, every T3 tool). Nothing applies -a profile yet: the provider adapters and the T3 tool filter come in later pull requests. +(everything, today's behaviour) and `t3-only` (no outside servers, every T3 tool); a profile cannot +take their names, and one written in by hand makes that built-in refuse threads until it is removed +or renamed. Nothing applies a profile yet: the provider adapters and the T3 tool filter come in later +pull requests. ```json { "mcpProfiles": { "lean": { "servers": [], "t3Tools": ["orchestration", "threads"] } } } @@ -171,8 +173,9 @@ its parent's profile. A child never gets more than its parent. ### `server.mcpThreadProfiles` -The person's pick of profile per thread, by thread id. A pick wins over every default. The newest -500 picks are kept; a thread whose pick was dropped falls back to its default. +The person's pick of profile per thread, by thread id. A pick wins over every default. At most 500 +picks are kept: a save that would add more is refused until old picks are removed. No pick is ever +dropped to make room. ### `projectOverride.waitChecks` diff --git a/packages/contracts/src/forkSettings.test.ts b/packages/contracts/src/forkSettings.test.ts index dbb92576405b0..2b3d07eee2a1d 100644 --- a/packages/contracts/src/forkSettings.test.ts +++ b/packages/contracts/src/forkSettings.test.ts @@ -79,11 +79,8 @@ describe("fork settings seam", () => { const lines = SETTINGS_SOURCE.split("\n"); // The import, `export *` and six spreads. expect(lines.filter((line) => /forkSettings|ForkSettings/.test(line))).toHaveLength(8); - // Three `Fork:` comments: the inline `automaticUpdates`, and the save error for a refused fork - // setting (its operation and its `detail` field). That error's operation, the comment on - // `detail` and the line of `message` that shows the detail name `write-fork-setting`. - expect(lines.filter((line) => line.includes("Fork:"))).toHaveLength(3); - expect(lines.filter((line) => line.includes("write-fork-setting"))).toHaveLength(3); + // The inline `automaticUpdates`: its comment, its field and its patch field. + expect(lines.filter((line) => line.includes("Fork:"))).toHaveLength(1); expect(lines.filter((line) => /^ {2}automaticUpdates:/.test(line))).toHaveLength(2); // forkSettings.ts never imports settings.ts, so upstream's file stays the only one with seams. expect(FORK_SOURCE).not.toMatch(/from "\.\/settings(\.ts)?"/); diff --git a/packages/contracts/src/forkSettings.ts b/packages/contracts/src/forkSettings.ts index 7d0c5a339b41b..21ed07cd2a1c2 100644 --- a/packages/contracts/src/forkSettings.ts +++ b/packages/contracts/src/forkSettings.ts @@ -11,7 +11,7 @@ import { TrimmedString } from "./baseSchemas.ts"; import { MCP_PROFILE_ALL, MCP_SUBAGENT_INHERIT, - MCP_THREAD_PROFILES_KEEP_NEWEST, + MCP_THREAD_PROFILES_MAX, McpProfileName, McpProfilePatch, McpProfileRef, @@ -114,13 +114,14 @@ export const ForkServerSettingsPatchFields = { /** * How a patch field changes the stored value: `replace` whole; `merge-fields` only the named fields. * Per entry (`null` removes it): `mergeEntries` merges fields, a new entry starting from its - * defaults; `replaceEntries` replaces the entry whole, makes it newest and keeps `keepNewest`. + * defaults; `replaceEntries` replaces the entry whole and makes it newest. A save that would leave + * more than `maxEntries` (and more than before) is refused; no entry is dropped to make room. */ export type ForkPatchRule = | "replace" | "merge-fields" | { readonly mergeEntries: Readonly> } - | { readonly replaceEntries: { readonly keepNewest?: number } }; + | { readonly replaceEntries: { readonly maxEntries?: number } }; /** One rule per fork patch field. */ export const FORK_PATCH_RULES: { readonly [K in ForkServerSettingKey]: ForkPatchRule } = { @@ -139,8 +140,8 @@ export const FORK_PATCH_RULES: { readonly [K in ForkServerSettingKey]: ForkPatch mcpProfiles: { replaceEntries: {} }, mcpProfile: "replace", mcpSubagentProfile: "replace", - // One pick per thread, so two picks at once keep both; old picks go beyond the cap. - mcpThreadProfiles: { replaceEntries: { keepNewest: MCP_THREAD_PROFILES_KEEP_NEWEST } }, + // One pick per thread, so two picks at once keep both; a save past the cap is refused. + mcpThreadProfiles: { replaceEntries: { maxEntries: MCP_THREAD_PROFILES_MAX } }, }; /** The client settings' fork fields (stored in the browser); none yet. */ diff --git a/packages/contracts/src/mcpProfile.ts b/packages/contracts/src/mcpProfile.ts index ebd0c68e05246..5b3765450d8cd 100644 --- a/packages/contracts/src/mcpProfile.ts +++ b/packages/contracts/src/mcpProfile.ts @@ -191,10 +191,11 @@ export const McpThreadProfilesPatch = Schema.Record( ); /** - * The newest thread picks kept; a write that goes over drops the oldest, which then falls back to - * its role default. Pruning deleted threads' picks comes later. + * The most thread picks the settings hold. A save that would go over is refused (remove old picks + * first); no pick is ever dropped to make room, since its thread would fall back to a wider role + * default. Pruning deleted threads' picks comes later. */ -export const MCP_THREAD_PROFILES_KEEP_NEWEST = 500; +export const MCP_THREAD_PROFILES_MAX = 500; /** * The settings file's thread picks: thread id to profile name. Read leniently, like diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 0f0c619b4c577..6ca6b5bdebe81 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1748,8 +1748,6 @@ export const ServerSettingsOperation = Schema.Literals([ "prepare-directory", "write-managed-setting", "use-disallowed-provider", - // Fork: a fork setting's save refused by the fork's save check; `detail` says why. - "write-fork-setting", ]); export type ServerSettingsOperation = typeof ServerSettingsOperation.Type; @@ -1769,13 +1767,10 @@ export class ServerSettingsError extends Schema.TaggedError managedBy: Schema.optional(Schema.String), /** For `use-disallowed-provider`: the provider's name as users know it. */ providerLabel: Schema.optional(Schema.String), - /** Fork: for `write-fork-setting`, what is wrong and how to fix it. */ - detail: Schema.optional(Schema.String), cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - if (this.operation === "write-fork-setting" && this.detail !== undefined) return this.detail; if (this.operation === "write-managed-setting") { return `${this.managedSetting ?? "This setting"} is managed by ${this.managedBy ?? "your organization"} and cannot be changed.`; } diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index 808498eb9207e..280d5fddb8036 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -2,7 +2,7 @@ import { DEFAULT_SERVER_SETTINGS, - MCP_THREAD_PROFILES_KEEP_NEWEST, + MCP_THREAD_PROFILES_MAX, ProjectId, ProviderInstanceId, type ServerSettings, @@ -138,22 +138,66 @@ describe("fork settings patch", () => { ]); }); - it(`keeps the ${MCP_THREAD_PROFILES_KEEP_NEWEST} newest picks`, () => { - const many = Object.fromEntries( - Array.from({ length: MCP_THREAD_PROFILES_KEEP_NEWEST }, (_, index) => [ - `old-${index}`, - "lean", - ]), - ); - const full: ServerSettings = { ...current, mcpThreadProfiles: many }; - const next = applyForkSettingsPatch(full, { - mcpThreadProfiles: { [t("old-0")]: "all", [t("new")]: "lean" }, - }).mcpThreadProfiles!; - expect(Object.keys(next)).toHaveLength(MCP_THREAD_PROFILES_KEEP_NEWEST); - // `old-0` was picked again, so `old-1` is now the oldest and goes. - expect(Object.keys(next).slice(0, 1)).toEqual(["old-2"]); - expect(Object.keys(next).slice(-2)).toEqual(["old-0", "new"]); - expect(next).not.toHaveProperty("old-1"); + describe(`the ${MCP_THREAD_PROFILES_MAX}-pick cap`, () => { + const full: ServerSettings = { + ...current, + mcpThreadProfiles: Object.fromEntries( + Array.from({ length: MCP_THREAD_PROFILES_MAX }, (_, i) => [`old-${i}`, "t3-only"]), + ), + }; + const after = (base: ServerSettings, patch: Parameters[1]) => + applyServerSettingsPatch(base, patch); + + it("never widens a live thread to make room", () => { + const next = applyForkSettingsPatch(full, { + mcpThreadProfiles: { [t("new")]: "t3-only" }, + }).mcpThreadProfiles!; + expect(next["old-0"]).toBe("t3-only"); + expect(Object.keys(next)).toHaveLength(MCP_THREAD_PROFILES_MAX + 1); + }); + + it("refuses the save that would go over, saying to remove old picks first", () => { + const patch = { mcpThreadProfiles: { [t("new")]: "t3-only" } }; + expect(forkSettingsWriteProblem(full, after(full, patch))).toBe( + `mcpThreadProfiles would hold ${MCP_THREAD_PROFILES_MAX + 1} entries, more than the ${MCP_THREAD_PROFILES_MAX} allowed: remove old picks first, then save again.`, + ); + }); + + it("takes a save at the cap that replaces or removes picks", () => { + // Replaces an existing pick: still 500. + expect( + forkSettingsWriteProblem( + full, + after(full, { mcpThreadProfiles: { [t("old-0")]: "all" } }), + ), + ).toBeUndefined(); + // Removes one and adds one in the same save: still 500. + expect( + forkSettingsWriteProblem( + full, + after(full, { mcpThreadProfiles: { [t("old-1")]: null, [t("new")]: "all" } }), + ), + ).toBeUndefined(); + }); + + it("lets a map already over the cap (a hand edit) take saves that do not grow it", () => { + const over: ServerSettings = { + ...full, + mcpThreadProfiles: { ...full.mcpThreadProfiles, extra: "t3-only" }, + }; + expect( + forkSettingsWriteProblem(over, after(over, { enableAgentBrowserAccess: false })), + ).toBeUndefined(); + expect( + forkSettingsWriteProblem( + over, + after(over, { mcpThreadProfiles: { [t("old-0")]: null } }), + ), + ).toBeUndefined(); + expect( + forkSettingsWriteProblem(over, after(over, { mcpThreadProfiles: { [t("new")]: "all" } })), + ).toMatch(/remove old picks first/); + }); }); it("replaces a profile whole, so a save repairs one this build cannot read", () => { diff --git a/packages/shared/src/forkSettingsPatch.ts b/packages/shared/src/forkSettingsPatch.ts index 96cfe77671a79..f7ec6b6238dc8 100644 --- a/packages/shared/src/forkSettingsPatch.ts +++ b/packages/shared/src/forkSettingsPatch.ts @@ -53,11 +53,8 @@ function applyRule(rule: ForkPatchRule, stored: unknown, patch: unknown): unknow next.delete(id); if (entry !== null) next.set(id, entry); } - const { keepNewest } = rule.replaceEntries; - const ids = [...next.keys()]; - if (keepNewest !== undefined && ids.length > keepNewest) { - for (const id of ids.slice(0, ids.length - keepNewest)) next.delete(id); - } + // Never trimmed to `maxEntries` here: dropping an entry would quietly change what it set (a + // thread pick's thread would fall back to a wider default). The save check refuses instead. return Object.fromEntries(next); } for (const [id, entry] of Object.entries(patch as Record)) { @@ -89,6 +86,36 @@ export function applyForkSettingsPatch( return next as Partial>; } +/** + * Fork: why the server refused a save of fork settings, with the fix. The server fails the save + * with upstream's `ServerSettingsError` (operation `normalize`, as for a patch that does not decode) + * and this as its `cause`, so upstream's error type stays as it is; the cause's name and message + * travel to the client with it. + */ +export class ForkSettingsWriteError extends Error { + override readonly name = "ForkSettingsWriteError"; +} + +/** + * A save that would leave a `replaceEntries` map with more than its `maxEntries`, and more than it + * had: refused, so no entry is ever dropped to make room. A map already over (a hand edit) still + * takes saves that do not grow it, so it never blocks an unrelated save. + */ +function maxEntriesProblem(current: ServerSettings, next: ServerSettings): string | undefined { + for (const key of FORK_PATCH_KEYS) { + const rule = FORK_PATCH_RULES[key]; + if (typeof rule !== "object" || !("replaceEntries" in rule)) continue; + const max = rule.replaceEntries.maxEntries; + if (max === undefined) continue; + const count = (value: unknown) => (isRecord(value) ? Object.keys(value).length : 0); + const after = count(next[key]); + if (after > max && after > count(current[key])) { + return `${key} would hold ${after} entries, more than the ${max} allowed: remove old picks first, then save again.`; + } + } + return undefined; +} + /** * A profile reference a save sets anew that no thread could run with: `inherit` where only * `mcpSubagentProfile` takes it, or a name no profile has. A reference the save leaves as it was is @@ -124,6 +151,7 @@ export function forkSettingsWriteProblem( next: ServerSettings, ): string | undefined { const problems: Array = [ + maxEntriesProblem(current, next), mcpProfileRefProblem(next, "mcpProfile", next.mcpProfile, current.mcpProfile, false), mcpProfileRefProblem( next, From 6c38d842ebd8892a8fa6a909b299c15e2f70e0f8 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:42:55 +0000 Subject: [PATCH 4/6] fork(mcp-profiles): fix round 3 (tagged error, keep project keys, null built-in, markers) - ForkSettingsWriteError is a Schema.TaggedError (CI: extendsNativeError); its name and message still reach the client as the cause of ServerSettingsError. - A project save that leaves out mcpProfile/mcpSubagentProfile keeps the stored value (an older client would otherwise widen the project); only "" clears it. Applied after upstream's patch by a fork wrapper the server imports under upstream's name, so no shared upstream file changes. - McpProfilesPatch takes null under a built-in name, to remove a hand-edited entry that breaks it; any other value there is still refused. - Fork: markers on the server settings edits; docs updated. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/fork/serverSettingsPatch.ts | 14 ++++ .../src/serverSettings.forkSettings.test.ts | 24 ++++++- apps/server/src/serverSettings.ts | 8 ++- docs/fork/README.md | 8 ++- packages/contracts/src/forkSettings.ts | 11 ++++ packages/contracts/src/mcpProfile.test.ts | 9 +++ packages/contracts/src/mcpProfile.ts | 15 +++-- packages/shared/src/forkSettingsPatch.test.ts | 64 +++++++++++++++++++ packages/shared/src/forkSettingsPatch.ts | 50 +++++++++++++-- 9 files changed, 186 insertions(+), 17 deletions(-) create mode 100644 apps/server/src/fork/serverSettingsPatch.ts diff --git a/apps/server/src/fork/serverSettingsPatch.ts b/apps/server/src/fork/serverSettingsPatch.ts new file mode 100644 index 0000000000000..30188e759221e --- /dev/null +++ b/apps/server/src/fork/serverSettingsPatch.ts @@ -0,0 +1,14 @@ +/** + * Fork: upstream's `applyServerSettingsPatch`, then the fork's project keys a project's entry + * leaves out kept as stored (`keepLeftOutForkProjectKeys`). The server's settings file imports this + * under upstream's name, so every write path (and the test layer) uses it with no other line changed. + */ +import type { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts"; +import { keepLeftOutForkProjectKeys } from "@t3tools/shared/forkSettingsPatch"; +import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; + +export const applyServerSettingsPatchKeepingForkProjectKeys = ( + current: ServerSettings, + patch: ServerSettingsPatch, +): ServerSettings => + keepLeftOutForkProjectKeys(current, patch, applyServerSettingsPatch(current, patch)); diff --git a/apps/server/src/serverSettings.forkSettings.test.ts b/apps/server/src/serverSettings.forkSettings.test.ts index d6ab724672f25..5baab4430ed5d 100644 --- a/apps/server/src/serverSettings.forkSettings.test.ts +++ b/apps/server/src/serverSettings.forkSettings.test.ts @@ -258,9 +258,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("fork MCP profile .pipe(Effect.flip); const reason = 'mcpProfile names MCP profile "lean", which is not set up: add that profile first, or pick "all" or "t3-only".'; - // Upstream's error type, unchanged; the reason is its cause. + // Upstream's error type, unchanged; the reason is its cause, a tagged error. assert.strictEqual(error.operation, "normalize"); assert.instanceOf(error.cause, ForkSettingsWriteError); + assert.strictEqual((error.cause as ForkSettingsWriteError)._tag, "ForkSettingsWriteError"); assert.strictEqual((error.cause as Error).message, reason); // The reason reaches a client: the error as the RPC sends it and decodes it. const json = Schema.toCodecJson(ServerSettingsError); @@ -274,4 +275,25 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("fork MCP profile assert.isFalse("mcpProfile" in file); }).pipe(Effect.provide(layerServerSettings())), ); + + it.effect("keeps a project's MCP profile when an older client saves the project without it", () => + Effect.gen(function* () { + const start = { + ...FULL_FILE, + mcpProfiles: { lean: { servers: [], t3Tools: [] } }, + projectSettingsOverrides: { + [PROJECT]: { mcpProfile: "lean", mcpSubagentProfile: "t3-only" }, + }, + }; + // A client that does not know the MCP keys sends the project's entry without them. + const file = (yield* loadThenPatch(start, { + projectSettingsOverrides: { [PROJECT]: { enableAgentBrowserAccess: true } }, + })) as { projectSettingsOverrides: Record }; + assert.deepStrictEqual(file.projectSettingsOverrides[PROJECT], { + enableAgentBrowserAccess: true, + mcpProfile: "lean", + mcpSubagentProfile: "t3-only", + }); + }).pipe(Effect.provide(layerServerSettings())), + ); }); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index a3a97a135f55d..2960e32710c2a 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -50,15 +50,16 @@ import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct"; import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson"; import { renameRetiredAutoUpdateKeys } from "./cloud/autoUpdateSettings.ts"; import { - applyServerSettingsPatch, deriveLegacyProjectOverrides, fallbackTextGenerationModelSelection, isModelSelectionProviderEnabled, } from "@t3tools/shared/serverSettings"; +// Fork: the save check, and upstream's patch that keeps a project's MCP profile a client left out. import { ForkSettingsWriteError, forkSettingsWriteProblem, } from "@t3tools/shared/forkSettingsPatch"; +import { applyServerSettingsPatchKeepingForkProjectKeys as applyServerSettingsPatch } from "./fork/serverSettingsPatch.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts"; @@ -248,7 +249,7 @@ function ensureForkSettingsWriteAllowed( new ServerSettingsError({ settingsPath, operation: "normalize", - cause: new ForkSettingsWriteError(problem), + cause: new ForkSettingsWriteError({ problem }), }), ); } @@ -335,6 +336,7 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( ): Effect.Effect => writeSemaphore.withPermits(1)( Ref.get(currentSettingsRef).pipe( + // Fork: refuses a fork setting's save that could not apply, as the real layer does. Effect.flatMap((current) => update(current).pipe( Effect.tap((next) => ensureForkSettingsWriteAllowed(current, next, "test settings")), @@ -1252,7 +1254,7 @@ const make = Effect.gen(function* () { // An older client echoes a reference as the redacted marker; restore it before vetting so // a removed provider's reference is cleared below rather than restored by persistence. const updated = withEchoedSecretReferences(current, yield* update(current)); - yield* ensureForkSettingsWriteAllowed(current, updated, settingsPath); + yield* ensureForkSettingsWriteAllowed(current, updated, settingsPath); // Fork: save check // Vet before secrets: a variable the policy hides from clients is not one they removed. const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch); if (vetted._tag === "Locked") { diff --git a/docs/fork/README.md b/docs/fork/README.md index dcc9db4926f9a..5f632934de862 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -151,8 +151,8 @@ Named MCP profiles. A profile says which outside MCP servers (`servers`) and whi own tools (`t3Tools`) a thread gets; each is `"all"` or a list. Two profiles are built in: `all` (everything, today's behaviour) and `t3-only` (no outside servers, every T3 tool); a profile cannot take their names, and one written in by hand makes that built-in refuse threads until it is removed -or renamed. Nothing applies a profile yet: the provider adapters and the T3 tool filter come in later -pull requests. +(a save may send `null` under a built-in name to remove it) or renamed. Nothing applies a profile +yet: the provider adapters and the T3 tool filter come in later pull requests. ```json { "mcpProfiles": { "lean": { "servers": [], "t3Tools": ["orchestration", "threads"] } } } @@ -186,7 +186,9 @@ Set: **Settings**, choose the project at the top, then **Wait checks**. ### `projectOverride.mcpProfile` -A project's own default profile for its top-level threads. Not set: the server's `mcpProfile`. +A project's own default profile for its top-level threads. Not set (absent or `""`): the server's +`mcpProfile`. A project save that leaves this key out (an older client) keeps the stored value; +only `""` clears it. The same holds for `mcpSubagentProfile`. ### `projectOverride.mcpSubagentProfile` diff --git a/packages/contracts/src/forkSettings.ts b/packages/contracts/src/forkSettings.ts index 21ed07cd2a1c2..9cd45a5101b07 100644 --- a/packages/contracts/src/forkSettings.ts +++ b/packages/contracts/src/forkSettings.ts @@ -165,6 +165,17 @@ export const ForkProjectOverrideFields = { mcpSubagentProfile: Schema.optionalKey(McpProfileRef), } satisfies Record<(typeof FORK_PROJECT_SCOPED_KEYS)[number], unknown>; +/** + * Fork project keys a project save keeps when the project's entry leaves them out: upstream replaces + * a project's entry whole, and a client that does not know a key (an older one) leaves it out, which + * would quietly widen that project to the server's profile. `""` clears one. (`waitChecks` keeps + * upstream's rule: left out is removed.) + */ +export const FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT = [ + "mcpProfile", + "mcpSubagentProfile", +] as const satisfies ReadonlyArray; + /** A project's overrides of fork settings in a patch (each project's set is replaced whole). */ export const ForkProjectOverridePatchFields = { /** A save refuses a bad check. */ diff --git a/packages/contracts/src/mcpProfile.test.ts b/packages/contracts/src/mcpProfile.test.ts index e194acbe07fb9..c9af92b27d5dd 100644 --- a/packages/contracts/src/mcpProfile.test.ts +++ b/packages/contracts/src/mcpProfile.test.ts @@ -121,8 +121,17 @@ describe("MCP profile settings patch", () => { } }); + it("takes null under a built-in name, so a hand-edited entry with that name can be removed", () => { + expect(decodePatch({ mcpProfiles: { all: null, "t3-only": null } }).mcpProfiles).toEqual({ + all: null, + "t3-only": null, + }); + }); + it.each([ ["a built-in name", { mcpProfiles: { all: { servers: [], t3Tools: [] } } }], + ["a built-in name with a non-null value", { mcpProfiles: { "t3-only": "all" } }], + ["`inherit` with null", { mcpProfiles: { inherit: null } }], ["the name `inherit`", { mcpProfiles: { inherit: { servers: [], t3Tools: [] } } }], ["a bad name", { mcpProfiles: { "Bad Name": { servers: [], t3Tools: [] } } }], ["an unknown field", { mcpProfiles: { lean: { servers: [], t3Tools: [], extra: 1 } } }], diff --git a/packages/contracts/src/mcpProfile.ts b/packages/contracts/src/mcpProfile.ts index 5b3765450d8cd..428c89dfc645b 100644 --- a/packages/contracts/src/mcpProfile.ts +++ b/packages/contracts/src/mcpProfile.ts @@ -116,18 +116,21 @@ const isSavableMcpProfile = (entry: unknown): boolean => ); /** - * Profiles in a settings patch: each entry replaces the stored one whole; `null` removes it. Typed - * as the settings file's map (each entry `unknown`), so a client may send back what it read; the - * check refuses a bad name or entry. (Effect drops, rather than refuses, a record key its key - * schema rejects, so names are checked on the whole map.) + * Profiles in a settings patch: each entry replaces the stored one whole; `null` removes it (also + * under a built-in name, to remove a hand-edited entry that breaks it). Entries are `unknown`, so a + * client may send back what it read. Names are checked on the whole map: Effect drops, rather than + * refuses, a record key its key schema rejects. */ export const McpProfilesPatch = Schema.Record(Schema.String, Schema.Unknown) .check( Schema.makeFilter( (profiles: { readonly [name: string]: unknown }) => - Object.keys(profiles).every(isDefinableMcpProfileName), + Object.entries(profiles).every( + ([name, entry]) => + isDefinableMcpProfileName(name) || (entry === null && isBuiltInMcpProfileName(name)), + ), { - expected: `profile names of lower-case letters, digits and dashes (at most 40), other than ${MCP_BUILT_IN_PROFILE_NAMES.join(", ")} and ${MCP_SUBAGENT_INHERIT}`, + expected: `profile names of lower-case letters, digits and dashes (at most 40), other than ${MCP_BUILT_IN_PROFILE_NAMES.join(", ")} (null only, to remove one) and ${MCP_SUBAGENT_INHERIT}`, }, ), ) diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index 280d5fddb8036..c1b68ed34141b 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -16,6 +16,7 @@ import { describe, expect, it } from "vite-plus/test"; import { applyForkSettingsPatch, forkSettingsWriteProblem, + keepLeftOutForkProjectKeys, splitForkSettingsPatch, } from "./forkSettingsPatch.ts"; import { applyServerSettingsPatch } from "./serverSettings.ts"; @@ -330,3 +331,66 @@ describe("fork settings save check (MCP profile references)", () => { expect(problemAfter(patch)).toMatch(message); }); }); + +describe("a project save keeps the fork keys its entry leaves out", () => { + const project = ProjectId.make("project-1"); + const other = ProjectId.make("project-2"); + const base: ServerSettings = { + ...current, + mcpProfiles: { lean: { servers: [], t3Tools: [] } }, + projectSettingsOverrides: { + [project]: { mcpProfile: "lean", mcpSubagentProfile: "t3-only", defaultProjectScripts: [] }, + [other]: { defaultAutoPull: true }, + }, + }; + type Patch = Parameters[1]; + // What the server does: upstream's patch, then the kept keys (apps/server/src/fork). + const save = (settings: ServerSettings, patch: Patch) => + keepLeftOutForkProjectKeys(settings, patch, applyServerSettingsPatch(settings, patch)); + + it("an older client's project save keeps the project's MCP profile", () => { + const patch = { projectSettingsOverrides: { [project]: { defaultProjectScripts: [] } } }; + const next = save(base, patch); + expect(next.projectSettingsOverrides[project]).toEqual({ + mcpProfile: "lean", + mcpSubagentProfile: "t3-only", + defaultProjectScripts: [], + }); + expect(next.projectSettingsOverrides[other]).toEqual({ defaultAutoPull: true }); + expect(forkSettingsWriteProblem(base, next)).toBeUndefined(); + // Run again: the same result. + expect(save(next, patch)).toEqual(next); + }); + + it("keeps them when the entry comes back empty (upstream would drop the entry)", () => { + expect( + save(base, { projectSettingsOverrides: { [project]: {} } }).projectSettingsOverrides, + ).toEqual({ + [project]: { mcpProfile: "lean", mcpSubagentProfile: "t3-only" }, + [other]: { defaultAutoPull: true }, + }); + }); + + it("clears a key only on an explicit empty value, and changes one that is sent", () => { + const next = save(base, { + projectSettingsOverrides: { [project]: { mcpProfile: "", mcpSubagentProfile: "lean" } }, + }); + expect(next.projectSettingsOverrides[project]).toEqual({ + mcpProfile: "", + mcpSubagentProfile: "lean", + }); + }); + + it("keeps nothing for a removed project or one that had no keys", () => { + const next = save(base, { + projectSettingsOverrides: { [project]: null, [other]: { defaultAutoPull: false } }, + }); + expect(next.projectSettingsOverrides).toEqual({ [other]: { defaultAutoPull: false } }); + }); + + it("returns the settings untouched when no project entry leaves a stored key out", () => { + const patch = { enableAgentBrowserAccess: false }; + const next = applyServerSettingsPatch(base, patch); + expect(keepLeftOutForkProjectKeys(base, patch, next)).toBe(next); + }); +}); diff --git a/packages/shared/src/forkSettingsPatch.ts b/packages/shared/src/forkSettingsPatch.ts index f7ec6b6238dc8..4d5bbfd32b9c0 100644 --- a/packages/shared/src/forkSettingsPatch.ts +++ b/packages/shared/src/forkSettingsPatch.ts @@ -4,16 +4,19 @@ */ import { FORK_PATCH_RULES, + FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT, MCP_PROFILE_ALL, MCP_PROFILE_T3_ONLY, MCP_SUBAGENT_INHERIT, type ForkPatchRule, type ForkServerSettingKey, + type ProjectId, type ServerSettings, type ServerSettingsPatch, isBuiltInMcpProfileName, isDefinableMcpProfileName, } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; const FORK_PATCH_KEYS = Object.keys(FORK_PATCH_RULES) as ReadonlyArray; @@ -86,14 +89,53 @@ export function applyForkSettingsPatch( return next as Partial>; } +type ProjectOverrides = ServerSettings["projectSettingsOverrides"][ProjectId]; + +/** + * `next` (the settings after `patch`) with each {@link FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT} key a + * project's entry in the patch leaves out kept as stored. Upstream replaces a project's entry whole, + * so without this an older client saving a project's scripts would drop its MCP profile and widen + * it to the server's. A removed project (`null`) keeps nothing; `""` in the entry clears the key. + */ +export function keepLeftOutForkProjectKeys( + current: ServerSettings, + patch: ServerSettingsPatch, + next: ServerSettings, +): ServerSettings { + const storedProjects: Readonly> = + current.projectSettingsOverrides; + let projects: Record | undefined; + for (const [projectId, entry] of Object.entries(patch.projectSettingsOverrides ?? {})) { + if (!isRecord(entry) || !Object.hasOwn(storedProjects, projectId)) continue; + const stored = storedProjects[projectId]; + const kept: Record = {}; + for (const key of FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT) { + const value = stored?.[key]; + if (value !== undefined && !Object.hasOwn(entry, key)) kept[key] = value; + } + if (Object.keys(kept).length === 0) continue; + projects ??= { ...next.projectSettingsOverrides }; + // Upstream drops an entry left empty; a kept key brings it back. + projects[projectId] = { ...projects[projectId], ...kept }; + } + return projects === undefined + ? next + : { ...next, projectSettingsOverrides: projects as ServerSettings["projectSettingsOverrides"] }; +} + /** * Fork: why the server refused a save of fork settings, with the fix. The server fails the save * with upstream's `ServerSettingsError` (operation `normalize`, as for a patch that does not decode) - * and this as its `cause`, so upstream's error type stays as it is; the cause's name and message - * travel to the client with it. + * and this as its `cause`, so upstream's error type stays as it is; the cause's name + * (`ForkSettingsWriteError`) and message (`problem`) travel to the client with it. */ -export class ForkSettingsWriteError extends Error { - override readonly name = "ForkSettingsWriteError"; +export class ForkSettingsWriteError extends Schema.TaggedError()( + "ForkSettingsWriteError", + { problem: Schema.String }, +) { + override get message(): string { + return this.problem; + } } /** From 5227b55633f312414c6af3db34bc8ce58bf36c37 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:32:42 +0000 Subject: [PATCH 5/6] fork(mcp-profiles): fix round 4 (reset to inherited clears MCP keys, PR3 notes) - keepLeftOutForkProjectKeys: an explicit "" for mcpProfile/mcpSubagentProfile now removes the key (an entry left empty is dropped), so the project inherits. - clearProjectSettingsOverridesWithForkKeys: drop-in for upstream's clear helper that sends "" for a cleared MCP key (upstream's leaves it out, which is kept). - Tests: the r3 lens clear case, the real settings layer, parity with upstream's helper, and a pin of upstream's helper keeping the key. - Docs: projectOverride.mcpProfile explains the reset path. Co-Authored-By: Claude Opus 5.5 --- .../src/serverSettings.forkSettings.test.ts | 31 ++++- docs/fork/README.md | 5 +- packages/shared/src/forkSettingsPatch.test.ts | 107 +++++++++++++++++- packages/shared/src/forkSettingsPatch.ts | 50 ++++++-- 4 files changed, 175 insertions(+), 18 deletions(-) diff --git a/apps/server/src/serverSettings.forkSettings.test.ts b/apps/server/src/serverSettings.forkSettings.test.ts index 5baab4430ed5d..f58fdb71dcd7f 100644 --- a/apps/server/src/serverSettings.forkSettings.test.ts +++ b/apps/server/src/serverSettings.forkSettings.test.ts @@ -4,8 +4,11 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ServerSettingsError, ServerSettingsPatch } from "@t3tools/contracts"; -import { ForkSettingsWriteError } from "@t3tools/shared/forkSettingsPatch"; +import { ProjectId, ServerSettingsError, ServerSettingsPatch } from "@t3tools/contracts"; +import { + clearProjectSettingsOverridesWithForkKeys, + ForkSettingsWriteError, +} from "@t3tools/shared/forkSettingsPatch"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -296,4 +299,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("fork MCP profile }); }).pipe(Effect.provide(layerServerSettings())), ); + + it.effect("clears a project's MCP profile when the screen resets it with the fork's helper", () => + Effect.gen(function* () { + const start = { + ...FULL_FILE, + mcpProfile: "t3-only", + projectSettingsOverrides: { [PROJECT]: { mcpProfile: "all", defaultAutoPull: true } }, + }; + const service = yield* ServerSettingsModule.ServerSettingsService; + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString(config.settingsPath, JSON.stringify(start)); + const settings = yield* service.getSettings; + // What the client sends for "reset to inherited" on the project's MCP profile. + const entry = clearProjectSettingsOverridesWithForkKeys(settings, ProjectId.make(PROJECT), [ + "mcpProfile", + ]); + yield* service.updateSettings( + decodePatch({ projectSettingsOverrides: { [PROJECT]: entry } }), + ); + const file = (yield* readFile) as { projectSettingsOverrides: Record }; + assert.deepStrictEqual(file.projectSettingsOverrides[PROJECT], { defaultAutoPull: true }); + }).pipe(Effect.provide(layerServerSettings())), + ); }); diff --git a/docs/fork/README.md b/docs/fork/README.md index 5f632934de862..5d87734fa075a 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -188,7 +188,10 @@ Set: **Settings**, choose the project at the top, then **Wait checks**. A project's own default profile for its top-level threads. Not set (absent or `""`): the server's `mcpProfile`. A project save that leaves this key out (an older client) keeps the stored value; -only `""` clears it. The same holds for `mcpSubagentProfile`. +only `""` clears it (the server then stores nothing, so the project inherits again). Upstream's +"reset to inherited" helper clears by leaving the key out, so it does not clear these two keys; a +screen resets them with the fork's `clearProjectSettingsOverridesWithForkKeys` +(`@t3tools/shared/forkSettingsPatch`), which sends `""`. The same holds for `mcpSubagentProfile`. ### `projectOverride.mcpSubagentProfile` diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index c1b68ed34141b..2c0e3380f117d 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -15,10 +15,12 @@ import { describe, expect, it } from "vite-plus/test"; import { applyForkSettingsPatch, + clearProjectSettingsOverridesWithForkKeys, forkSettingsWriteProblem, keepLeftOutForkProjectKeys, splitForkSettingsPatch, } from "./forkSettingsPatch.ts"; +import { clearProjectSettingsOverrides } from "./projectSettings.ts"; import { applyServerSettingsPatch } from "./serverSettings.ts"; // The source text, to pin the fork's lines in upstream's file. import SERVER_SETTINGS_SOURCE from "./serverSettings.ts?raw"; @@ -372,13 +374,27 @@ describe("a project save keeps the fork keys its entry leaves out", () => { }); it("clears a key only on an explicit empty value, and changes one that is sent", () => { - const next = save(base, { + const patch = { projectSettingsOverrides: { [project]: { mcpProfile: "", mcpSubagentProfile: "lean" } }, - }); - expect(next.projectSettingsOverrides[project]).toEqual({ - mcpProfile: "", - mcpSubagentProfile: "lean", - }); + }; + const next = save(base, patch); + // Cleared means not stored: the project inherits again, as after upstream's clear. + expect(next.projectSettingsOverrides[project]).toEqual({ mcpSubagentProfile: "lean" }); + expect(save(next, patch)).toEqual(next); + }); + + it("drops a project's entry that an explicit empty value leaves with nothing", () => { + const only: ServerSettings = { + ...base, + projectSettingsOverrides: { [project]: { mcpProfile: "lean" } }, + }; + const next = save(only, { projectSettingsOverrides: { [project]: { mcpProfile: "" } } }); + expect(next.projectSettingsOverrides).toEqual({}); + // A new project sent with only an empty value stores nothing either. + expect( + save(base, { projectSettingsOverrides: { [ProjectId.make("new")]: { mcpProfile: "" } } }) + .projectSettingsOverrides, + ).toEqual(base.projectSettingsOverrides); }); it("keeps nothing for a removed project or one that had no keys", () => { @@ -394,3 +410,82 @@ describe("a project save keeps the fork keys its entry leaves out", () => { expect(keepLeftOutForkProjectKeys(base, patch, next)).toBe(next); }); }); + +describe("clearing a project's MCP profile (reset to inherited)", () => { + const p1 = ProjectId.make("project-1"); + const base = { + ...current, + mcpProfile: "t3-only", + projectSettingsOverrides: { [p1]: { mcpProfile: "all", defaultAutoPull: true } }, + } as ServerSettings; + type Patch = Parameters[1]; + const save = (settings: ServerSettings, patch: Patch) => + keepLeftOutForkProjectKeys(settings, patch, applyServerSettingsPatch(settings, patch)); + + it("clearing a project's MCP profile with the fork's clear helper clears it", () => { + const patch = { + projectSettingsOverrides: { + [p1]: clearProjectSettingsOverridesWithForkKeys(base, p1, ["mcpProfile"]), + }, + }; + const next = save(base, patch); + expect(next.projectSettingsOverrides[p1]).toEqual({ defaultAutoPull: true }); + expect(next.projectSettingsOverrides[p1]?.mcpProfile).toBeUndefined(); + expect(forkSettingsWriteProblem(base, next)).toBeUndefined(); + // Run again (a second click, or a retry after a lost reply): the same result. + expect( + save(next, { + projectSettingsOverrides: { + [p1]: clearProjectSettingsOverridesWithForkKeys(next, p1, ["mcpProfile"]), + }, + }), + ).toEqual(next); + }); + + it("clears both MCP keys and other keys at once, and removes an entry left with nothing", () => { + const both = { + ...base, + projectSettingsOverrides: { [p1]: { mcpProfile: "all", mcpSubagentProfile: "all" } }, + } as ServerSettings; + expect(clearProjectSettingsOverridesWithForkKeys(both, p1, ["mcpProfile"])).toEqual({ + mcpProfile: "", + mcpSubagentProfile: "all", + }); + expect( + clearProjectSettingsOverridesWithForkKeys(both, p1, ["mcpProfile", "mcpSubagentProfile"]), + ).toBeNull(); + expect( + save(base, { + projectSettingsOverrides: { + [p1]: clearProjectSettingsOverridesWithForkKeys(base, p1, [ + "mcpProfile", + "defaultAutoPull", + ]), + }, + }).projectSettingsOverrides, + ).toEqual({}); + }); + + it("is upstream's clear helper when no stored MCP key is cleared", () => { + for (const keys of [ + ["defaultAutoPull"], + ["mcpSubagentProfile"], + ["defaultAutoPull", "mcpSubagentProfile"], + ] as const) { + expect(clearProjectSettingsOverridesWithForkKeys(base, p1, keys)).toEqual( + clearProjectSettingsOverrides(base, p1, keys), + ); + } + const missing = ProjectId.make("missing"); + expect(clearProjectSettingsOverridesWithForkKeys(base, missing, ["mcpProfile"])).toBeNull(); + expect(clearProjectSettingsOverrides(base, missing, ["mcpProfile"])).toBeNull(); + }); + + it("pins upstream's helper keeping the profile (it leaves the key out, like an older client)", () => { + // If this turns red, upstream's clear changed: re-check the fork helper and the PR's notes. + const patch = { + projectSettingsOverrides: { [p1]: clearProjectSettingsOverrides(base, p1, ["mcpProfile"]) }, + }; + expect(save(base, patch).projectSettingsOverrides[p1]?.mcpProfile).toBe("all"); + }); +}); diff --git a/packages/shared/src/forkSettingsPatch.ts b/packages/shared/src/forkSettingsPatch.ts index 4d5bbfd32b9c0..eba6ad189a1e0 100644 --- a/packages/shared/src/forkSettingsPatch.ts +++ b/packages/shared/src/forkSettingsPatch.ts @@ -11,6 +11,8 @@ import { type ForkPatchRule, type ForkServerSettingKey, type ProjectId, + type ProjectScopedServerSettingKey, + type ProjectSettingsOverrides, type ServerSettings, type ServerSettingsPatch, isBuiltInMcpProfileName, @@ -90,12 +92,12 @@ export function applyForkSettingsPatch( } type ProjectOverrides = ServerSettings["projectSettingsOverrides"][ProjectId]; +const KEPT_KEYS: ReadonlyArray = FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT; /** - * `next` (the settings after `patch`) with each {@link FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT} key a - * project's entry in the patch leaves out kept as stored. Upstream replaces a project's entry whole, - * so without this an older client saving a project's scripts would drop its MCP profile and widen - * it to the server's. A removed project (`null`) keeps nothing; `""` in the entry clears the key. + * `next` with each {@link FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT} key a patched project entry leaves + * out kept as stored, so an older client's whole-entry save cannot widen the project. A removed + * project keeps nothing; `""` clears the key (not stored; an entry left empty is dropped). */ export function keepLeftOutForkProjectKeys( current: ServerSettings, @@ -106,23 +108,53 @@ export function keepLeftOutForkProjectKeys( current.projectSettingsOverrides; let projects: Record | undefined; for (const [projectId, entry] of Object.entries(patch.projectSettingsOverrides ?? {})) { - if (!isRecord(entry) || !Object.hasOwn(storedProjects, projectId)) continue; - const stored = storedProjects[projectId]; + if (!isRecord(entry)) continue; + const stored = Object.hasOwn(storedProjects, projectId) ? storedProjects[projectId] : undefined; const kept: Record = {}; + const cleared: string[] = []; for (const key of FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT) { const value = stored?.[key]; - if (value !== undefined && !Object.hasOwn(entry, key)) kept[key] = value; + if (!Object.hasOwn(entry, key)) { + if (value !== undefined) kept[key] = value; + } else if (entry[key] === "") { + cleared.push(key); + } } - if (Object.keys(kept).length === 0) continue; + if (Object.keys(kept).length === 0 && cleared.length === 0) continue; projects ??= { ...next.projectSettingsOverrides }; // Upstream drops an entry left empty; a kept key brings it back. - projects[projectId] = { ...projects[projectId], ...kept }; + const merged: Record = { ...projects[projectId], ...kept }; + for (const key of cleared) delete merged[key]; + if (Object.keys(merged).length === 0) delete projects[projectId]; + else projects[projectId] = merged as ProjectOverrides; } return projects === undefined ? next : { ...next, projectSettingsOverrides: projects as ServerSettings["projectSettingsOverrides"] }; } +/** + * Fork: drop-in for upstream's `clearProjectSettingsOverrides` that sends `""` for a cleared MCP + * profile key, since a key left out is kept (above). Any path that can reset an MCP profile key + * must use this; with no such key it returns what upstream's does. + */ +export function clearProjectSettingsOverridesWithForkKeys( + settings: Pick, + projectId: ProjectId, + keys: ReadonlyArray, +): ProjectSettingsOverrides | null { + const current = settings.projectSettingsOverrides[projectId]; + if (current === undefined) return null; + const next: Record = { ...current }; + for (const key of keys) delete next[key]; + // Everything cleared: upstream removes the project's entry (`null`), which keeps nothing. + if (Object.keys(next).length === 0) return null; + for (const key of keys) { + if (KEPT_KEYS.includes(key) && current[key] !== undefined) next[key] = ""; + } + return next as ProjectSettingsOverrides; +} + /** * Fork: why the server refused a save of fork settings, with the fix. The server fails the save * with upstream's `ServerSettingsError` (operation `normalize`, as for a patch that does not decode) From 3d46dc3ff8afad18be8c37790e177b0bdbe09043 Mon Sep 17 00:00:00 2001 From: scuttletoby <123843277+scuttletoby@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:06:07 +0000 Subject: [PATCH 6/6] fork(mcp-profile): seam entry for serverSettings.ts; drop a stored blank MCP key - The save check moves to apps/server/src/fork/serverSettingsWriteCheck.ts, so apps/server/src/serverSettings.ts keeps five fork lines, now pinned in .github/fork-seams.json. - keepLeftOutForkProjectKeys no longer keeps a stored blank mcpProfile or mcpSubagentProfile (a hand edit's "" or null) that a save leaves out, and clearProjectSettingsOverridesWithForkKeys no longer sends "" for one. Co-Authored-By: Claude Opus 5.5 --- .github/fork-seams.json | 10 +++++ .../src/fork/serverSettingsWriteCheck.ts | 39 +++++++++++++++++++ apps/server/src/serverSettings.ts | 34 ++-------------- docs/fork/README.md | 4 +- packages/shared/src/forkSettingsPatch.test.ts | 39 +++++++++++++++++++ packages/shared/src/forkSettingsPatch.ts | 11 ++++-- 6 files changed, 102 insertions(+), 35 deletions(-) create mode 100644 apps/server/src/fork/serverSettingsWriteCheck.ts diff --git a/.github/fork-seams.json b/.github/fork-seams.json index 919e92a0268f9..7153bddbf2fbf 100644 --- a/.github/fork-seams.json +++ b/.github/fork-seams.json @@ -29,6 +29,16 @@ "} = upstreamPatch;", "...applyForkSettingsPatch(current, forkPatch)," ] + }, + "apps/server/src/serverSettings.ts": { + "why": "Every settings write goes through upstream's patch and write paths here. The fork swaps in its patch (fork/serverSettingsPatch.ts, under upstream's name, so a project's MCP profile a client left out is kept) and calls its save check (fork/serverSettingsWriteCheck.ts) once in each write path.", + "added": [ + "// Fork: upstream's patch keeping a project's MCP profile a client left out, and the save check.", + "import { applyServerSettingsPatchKeepingForkProjectKeys as applyServerSettingsPatch } from \"./fork/serverSettingsPatch.ts\";", + "import * as ForkSettingsWrite from \"./fork/serverSettingsWriteCheck.ts\";", + "Effect.flatMap(ForkSettingsWrite.withCheck(update, \"test settings\")), // Fork: save check", + "yield* ForkSettingsWrite.check(current, updated, settingsPath); // Fork: save check" + ] } } } diff --git a/apps/server/src/fork/serverSettingsWriteCheck.ts b/apps/server/src/fork/serverSettingsWriteCheck.ts new file mode 100644 index 0000000000000..106e6f7138dae --- /dev/null +++ b/apps/server/src/fork/serverSettingsWriteCheck.ts @@ -0,0 +1,39 @@ +/** + * Fork: the server's save check for fork settings (`forkSettingsWriteProblem`). A save that could + * not apply fails with upstream's `ServerSettingsError` (operation `normalize`, as for a patch + * that does not decode); its cause, a `ForkSettingsWriteError`, says why and how to fix it. The + * server's settings file calls `check` in its write path and `withCheck` in its test layer. + */ +import { type ServerSettings, ServerSettingsError } from "@t3tools/contracts"; +import { + ForkSettingsWriteError, + forkSettingsWriteProblem, +} from "@t3tools/shared/forkSettingsPatch"; +import { Effect } from "effect"; + +/** Fails when saving `next` over `current` would bring in a fork setting that cannot apply. */ +export function check( + current: ServerSettings, + next: ServerSettings, + settingsPath: string, +): Effect.Effect { + const problem = forkSettingsWriteProblem(current, next); + return problem === undefined + ? Effect.void + : Effect.fail( + new ServerSettingsError({ + settingsPath, + operation: "normalize", + cause: new ForkSettingsWriteError({ problem }), + }), + ); +} + +/** `update`, then {@link check} on what it returns. */ +export const withCheck = + ( + update: (current: ServerSettings) => Effect.Effect, + settingsPath: string, + ) => + (current: ServerSettings): Effect.Effect => + update(current).pipe(Effect.tap((next) => check(current, next, settingsPath))); diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 2960e32710c2a..ac042a2305b49 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -54,12 +54,9 @@ import { fallbackTextGenerationModelSelection, isModelSelectionProviderEnabled, } from "@t3tools/shared/serverSettings"; -// Fork: the save check, and upstream's patch that keeps a project's MCP profile a client left out. -import { - ForkSettingsWriteError, - forkSettingsWriteProblem, -} from "@t3tools/shared/forkSettingsPatch"; +// Fork: upstream's patch keeping a project's MCP profile a client left out, and the save check. import { applyServerSettingsPatchKeepingForkProjectKeys as applyServerSettingsPatch } from "./fork/serverSettingsPatch.ts"; +import * as ForkSettingsWrite from "./fork/serverSettingsWriteCheck.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as ManagedPolicy from "./policy/ManagedPolicy.ts"; import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts"; @@ -236,24 +233,6 @@ function ensureSecretProviderWritesAllowed( return Effect.void; } -// Fork: refuses a fork setting's save that could not apply; the cause says why and how to fix it. -function ensureForkSettingsWriteAllowed( - current: ServerSettings, - next: ServerSettings, - settingsPath: string, -): Effect.Effect { - const problem = forkSettingsWriteProblem(current, next); - return problem === undefined - ? Effect.void - : Effect.fail( - new ServerSettingsError({ - settingsPath, - operation: "normalize", - cause: new ForkSettingsWriteError({ problem }), - }), - ); -} - function ensureProviderInstanceMutationAllowed( settings: ServerSettings, mutation: ProviderInstanceMutation, @@ -336,12 +315,7 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* ( ): Effect.Effect => writeSemaphore.withPermits(1)( Ref.get(currentSettingsRef).pipe( - // Fork: refuses a fork setting's save that could not apply, as the real layer does. - Effect.flatMap((current) => - update(current).pipe( - Effect.tap((next) => ensureForkSettingsWriteAllowed(current, next, "test settings")), - ), - ), + Effect.flatMap(ForkSettingsWrite.withCheck(update, "test settings")), // Fork: save check Effect.flatMap(normalizeServerSettings), Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)), Effect.map(resolveTextGenerationProvider), @@ -1254,7 +1228,7 @@ const make = Effect.gen(function* () { // An older client echoes a reference as the redacted marker; restore it before vetting so // a removed provider's reference is cleared below rather than restored by persistence. const updated = withEchoedSecretReferences(current, yield* update(current)); - yield* ensureForkSettingsWriteAllowed(current, updated, settingsPath); // Fork: save check + yield* ForkSettingsWrite.check(current, updated, settingsPath); // Fork: save check // Vet before secrets: a variable the policy hides from clients is not one they removed. const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch); if (vetted._tag === "Locked") { diff --git a/docs/fork/README.md b/docs/fork/README.md index 5d87734fa075a..25338a50b1980 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -187,8 +187,8 @@ Set: **Settings**, choose the project at the top, then **Wait checks**. ### `projectOverride.mcpProfile` A project's own default profile for its top-level threads. Not set (absent or `""`): the server's -`mcpProfile`. A project save that leaves this key out (an older client) keeps the stored value; -only `""` clears it (the server then stores nothing, so the project inherits again). Upstream's +`mcpProfile`. A project save that leaves this key out (an older client) keeps the stored value +(a blank one, from a hand edit, is dropped instead); only `""` clears it (the server then stores nothing, so the project inherits again). Upstream's "reset to inherited" helper clears by leaving the key out, so it does not clear these two keys; a screen resets them with the fork's `clearProjectSettingsOverridesWithForkKeys` (`@t3tools/shared/forkSettingsPatch`), which sends `""`. The same holds for `mcpSubagentProfile`. diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index 2c0e3380f117d..f4a81ad2de34e 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -404,6 +404,28 @@ describe("a project save keeps the fork keys its entry leaves out", () => { expect(next.projectSettingsOverrides).toEqual({ [other]: { defaultAutoPull: false } }); }); + it("does not keep a stored blank MCP key an older client left out", () => { + // A hand edit's `""` or `null` reads as `""` (not set); it is not carried into the next save. + const s = { + ...base, + projectSettingsOverrides: { [project]: { mcpProfile: "", defaultAutoPull: true } }, + } as ServerSettings; + const patch = { projectSettingsOverrides: { [project]: { defaultAutoPull: false } } }; + const next = save(s, patch); + expect(next.projectSettingsOverrides[project]).toEqual({ defaultAutoPull: false }); + expect(save(next, patch)).toEqual(next); + // Only the blank key goes: a set one beside it is still kept. + const mixed = { + ...base, + projectSettingsOverrides: { [project]: { mcpProfile: "", mcpSubagentProfile: "lean" } }, + } as ServerSettings; + expect( + save(mixed, { projectSettingsOverrides: { [project]: {} } }).projectSettingsOverrides[ + project + ], + ).toEqual({ mcpSubagentProfile: "lean" }); + }); + it("returns the settings untouched when no project entry leaves a stored key out", () => { const patch = { enableAgentBrowserAccess: false }; const next = applyServerSettingsPatch(base, patch); @@ -466,6 +488,23 @@ describe("clearing a project's MCP profile (reset to inherited)", () => { ).toEqual({}); }); + it("does not send a stored blank MCP key back when clearing it", () => { + const blank = { + ...base, + projectSettingsOverrides: { [p1]: { mcpProfile: "", defaultAutoPull: true } }, + } as ServerSettings; + // Nothing to clear: the key is left out, and the server keeps a blank value no longer. + expect(clearProjectSettingsOverridesWithForkKeys(blank, p1, ["mcpProfile"])).toEqual({ + defaultAutoPull: true, + }); + const patch = { + projectSettingsOverrides: { + [p1]: clearProjectSettingsOverridesWithForkKeys(blank, p1, ["mcpProfile"]), + }, + }; + expect(save(blank, patch).projectSettingsOverrides[p1]).toEqual({ defaultAutoPull: true }); + }); + it("is upstream's clear helper when no stored MCP key is cleared", () => { for (const keys of [ ["defaultAutoPull"], diff --git a/packages/shared/src/forkSettingsPatch.ts b/packages/shared/src/forkSettingsPatch.ts index eba6ad189a1e0..bfd2a9fee0617 100644 --- a/packages/shared/src/forkSettingsPatch.ts +++ b/packages/shared/src/forkSettingsPatch.ts @@ -97,7 +97,8 @@ const KEPT_KEYS: ReadonlyArray = FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT; /** * `next` with each {@link FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT} key a patched project entry leaves * out kept as stored, so an older client's whole-entry save cannot widen the project. A removed - * project keeps nothing; `""` clears the key (not stored; an entry left empty is dropped). + * project keeps nothing, nor does a stored blank value; `""` clears the key (not stored; an entry + * left empty is dropped). */ export function keepLeftOutForkProjectKeys( current: ServerSettings, @@ -115,7 +116,8 @@ export function keepLeftOutForkProjectKeys( for (const key of FORK_PROJECT_KEYS_KEPT_WHEN_LEFT_OUT) { const value = stored?.[key]; if (!Object.hasOwn(entry, key)) { - if (value !== undefined) kept[key] = value; + // A blank value (a hand edit's `""` or `null`) means not set: nothing to keep. + if (value !== undefined && value.trim() !== "") kept[key] = value; } else if (entry[key] === "") { cleared.push(key); } @@ -150,7 +152,10 @@ export function clearProjectSettingsOverridesWithForkKeys( // Everything cleared: upstream removes the project's entry (`null`), which keeps nothing. if (Object.keys(next).length === 0) return null; for (const key of keys) { - if (KEPT_KEYS.includes(key) && current[key] !== undefined) next[key] = ""; + const stored = current[key]; + if (KEPT_KEYS.includes(key) && typeof stored === "string" && stored.trim() !== "") { + next[key] = ""; + } } return next as ProjectSettingsOverrides; }