Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/fork-seams.json
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@
]
},
"apps/server/src/mcp/McpToolExposure.ts": {
"why": "MCP profile design PR 4 (T3 tool groups): tool_search leaves out the T3 tools the calling thread's MCP profile leaves out (its t3Tools groups), before it ranks them, so a search never finds or loads a tool the thread cannot call. The filter and the global rule that hides those tools from tools/list and refuses them on tools/call are in fork/mcpT3ToolFilter.ts; the rule is installed in McpHttpServer's production `layer` (a pending file, no new line). A server without the rule (upstream's tests) searches as upstream does. Tested in apps/server/src/fork/mcpT3ToolFilter.test.ts.",
"why": "MCP profile design PR 4 (T3 tool groups): tool_search leaves out the T3 tools the calling thread's MCP profile leaves out (its t3Tools groups), before it ranks them, so a search never finds or loads a tool the thread cannot call. The filter is in fork/mcpT3ToolFilter.ts, which imports no toolkit, profile resolver or store (fork issue #812); the global rule that hides those tools from tools/list, refuses them on tools/call and installs the filter's check is in fork/mcpT3ToolRule.ts, installed in McpHttpServer's production `layer` (a pending file, no new line; its import names the rule's module). A server without the rule (upstream's tests) searches as upstream does. Tested in apps/server/src/fork/mcpT3ToolFilter.test.ts.",
"added": [
"import { searchableT3Tool } from \"../fork/mcpT3ToolFilter.ts\"; // Fork: MCP profile T3 tool groups",
".filter(searchableT3Tool) // Fork: MCP profile T3 tool groups"
Expand Down
70 changes: 62 additions & 8 deletions apps/server/src/fork/claudeMcpProfile.adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ProviderInstanceId,
ProviderSessionId,
type ServerSettings,
ServerSettingsError,
ThreadId,
} from "@t3tools/contracts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
Expand All @@ -30,6 +31,7 @@ import { makeTurnInput } from "../orchestration-v2/Adapters/AcpAdapterV2.testkit
import * as ClaudeAdapterV2 from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import * as ServerSettingsService from "../serverSettings.ts";
import { type LineageThread, makeClaudeMcpProfiles } from "./claudeMcpProfile.ts";
import * as T3ToolSets from "./mcpT3ToolSets.ts";

const MODEL = {
instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
Expand All @@ -47,14 +49,18 @@ const NATIVE_THREAD = "native-thread-mcp-profile";

/**
* Runs Claude turns on one thread with these server settings, saving each of `saves` before the
* next turn; records each open and the sessions' closes. Stops at the first refused turn.
* next turn; records each open, the sessions' closes and the thread's T3 tool set after each turn.
* Stops at the first refused turn, unless `pastRefusals`.
*/
const runTurns = (
settings: McpSettings,
statuses: ReadonlyArray<{ readonly name: string; readonly status: "connected" }> | "unexpected",
saves: ReadonlyArray<McpSettings> = [],
) =>
Effect.gen(function* () {
saves: ReadonlyArray<McpSettings | "unreadable"> = [],
pastRefusals = false,
) => {
/** True for a turn whose settings read fails (`"unreadable"`): only that one. */
let unreadable = false;
return Effect.gen(function* () {
const opened: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOptions> = [];
const processes: Array<Queue.Queue<SDKMessage>> = [];
let closed = 0;
Expand Down Expand Up @@ -123,8 +129,10 @@ const runTurns = (
);
const settingsService = yield* ServerSettingsService.ServerSettingsService;
let refusal: string | undefined;
const sets: Array<T3ToolSets.T3ToolSet | undefined> = [];
for (const [index, save] of [undefined, ...saves].entries()) {
if (save !== undefined) yield* settingsService.updateSettings(save);
unreadable = save === "unreadable";
if (save !== undefined && save !== "unreadable") yield* settingsService.updateSettings(save);
const started = yield* runtime
.startTurn(
makeTurnInput({
Expand All @@ -138,16 +146,18 @@ const runTurns = (
}),
)
.pipe(Effect.exit);
sets.push(T3ToolSets.t3ToolSetFor(threadId));
if (started._tag === "Failure") {
refusal = makeProviderFailure({ cause: started.cause, class: "provider_error" }).message;
refusal ??= makeProviderFailure({ cause: started.cause, class: "provider_error" }).message;
if (pastRefusals) continue;
break;
}
if (index === saves.length) break;
// Ends the turn so the next one may reuse the live process.
yield* Queue.offer(processes.at(-1)!, resultFrame(index + 1));
yield* Queue.take(terminals);
}
return { opened, closed, refusal };
return { opened, closed, refusal, sets };
}).pipe(
Effect.scoped,
Effect.provide(
Expand All @@ -156,10 +166,29 @@ const runTurns = (
McpProviderSessions.layer,
NodeServices.layer,
NodeCrypto.layer,
ServerSettingsService.layerTest(settings),
Layer.effect(
ServerSettingsService.ServerSettingsService,
Effect.map(ServerSettingsService.ServerSettingsService, (service) =>
ServerSettingsService.ServerSettingsService.of({
...service,
getSettings: Effect.suspend(() =>
unreadable
? Effect.fail(
new ServerSettingsError({
settingsPath: "settings.json",
operation: "read-secret",
cause: new Error("secret store unreadable"),
}),
)
: service.getSettings,
),
}),
),
).pipe(Layer.provideMerge(ServerSettingsService.layerTest(settings))),
),
),
);
};

const resultFrame = (ordinal: number) =>
({
Expand Down Expand Up @@ -274,6 +303,31 @@ describe("ClaudeAdapterV2 MCP profile", () => {
}),
);

it.effect(
"runs again after a refused turn: the next good turn on the same process gets its set back",
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
const lean = { servers: "all", t3Tools: ["waits"] } as const;
// Turn 2's settings read fails once, so it is refused and the live process stays; turn 3
// reads them again: the same plan as the process opened with, so it reuses that process.
const { opened, refusal, sets } = yield* runTurns(
{ mcpProfile: "lean", mcpProfiles: { lean } },
[],
["unreadable", {}],
true,
);
assert.isDefined(refusal);
assert.lengthOf(opened, 1);
assert.deepStrictEqual(
sets.map((set) =>
set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set?._tag,
),
[["waits"], "Refused", ["waits"]],
);
}),
);

it.effect(
'builtinTools "none" opens Claude with no built-in tools and refuses any at the call',
() =>
Expand Down
48 changes: 44 additions & 4 deletions apps/server/src/fork/claudeMcpProfile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ describe("makeClaudeMcpProfiles", () => {
const sets: Array<unknown> = [];
for (const _ of reads) {
const overrides = {};
yield* plan(self, overrides);
// The adapter reads the options only as it opens the query's process.
void (yield* plan(self, overrides)).options;
keys.push(planKeyFor(overrides));
const set = T3ToolSets.t3ToolSetFor(self.id);
sets.push(set?._tag === "Groups" && set.groups !== "all" ? [...set.groups] : set);
Expand All @@ -271,6 +272,41 @@ describe("makeClaudeMcpProfiles", () => {
),
);

it.effect(
"the set is fixed only once the plan opens a process: a turn that keeps the old one keeps its set",
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
const lean = { mcpProfile: "lean", mcpProfiles: { lean: { servers: "all", t3Tools: [] } } };
const service = yield* ServerSettingsService.ServerSettingsService;
const plan = yield* makeClaudeMcpProfiles.pipe(
Effect.provideService(ServerSettingsService.ServerSettingsService, {
...service,
getSettings: Effect.succeed(fromFile(lean)),
}),
);
const before: T3ToolSets.T3ToolSet = { _tag: "Groups", name: "all", groups: "all" };
T3ToolSets.fixT3ToolSet("t", before);
const planned = yield* plan(thread("t"), {});
// Planned, not opened (a continuation, or background work blocks the replacement).
assert.strictEqual(planned.name, "lean");
assert.deepStrictEqual(planned.servers, "all");
assert.strictEqual(T3ToolSets.t3ToolSetFor("t"), before);
// The new process opens: its options are read, and the new set applies from then.
assert.deepStrictEqual(planned.options, {});
const set = T3ToolSets.t3ToolSetFor("t");
assert.deepStrictEqual(set?._tag === "Groups" ? [...(set.groups as Set<string>)] : set, []);
}).pipe(
Effect.provide(
Layer.mergeAll(
ServerSettingsService.ServerSettingsService.layerTest(),
ManagedPolicy.layerTest(),
Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-mcp-profile-" })),
).pipe(Layer.provideMerge(NodeServices.layer)),
),
),
);

it.effect("a profile that cannot be worked out fixes no T3 tool but the ungrouped ones", () =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
Expand All @@ -285,7 +321,7 @@ describe("makeClaudeMcpProfiles", () => {
);

it.effect(
"stopped half-way: a query whose profile read is interrupted leaves no T3 tool set",
"stopped half-way: a query whose profile read is interrupted leaves the set as it was",
() =>
Effect.gen(function* () {
T3ToolSets.__testing.clear();
Expand All @@ -301,8 +337,12 @@ describe("makeClaudeMcpProfiles", () => {
const fiber = yield* Effect.forkChild(plan(thread("t"), {}));
yield* Deferred.await(reading);
yield* Fiber.interrupt(fiber);
// The next request works the set out again from the settings, rather than the old turn's.
assert.isUndefined(T3ToolSets.t3ToolSetFor("t"));
// No process opened: the last turn's set stands until one does.
assert.deepStrictEqual(T3ToolSets.t3ToolSetFor("t"), {
_tag: "Groups",
name: "all",
groups: "all",
});
}).pipe(
Effect.provide(
Layer.mergeAll(
Expand Down
84 changes: 70 additions & 14 deletions apps/server/src/fork/claudeMcpProfile.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* Fork: a thread's MCP profile, applied to its Claude session. This applies the outside servers;
* T3's own tools are filtered on the T3 MCP server for every provider (mcpT3ToolFilter.ts), with
* T3's own tools are filtered on the T3 MCP server for every provider (mcpT3ToolRule.ts), with
* the groups fixed as each query opens. A profile that cannot be applied refuses the turn instead
* of starting it with every tool: the owner chose refusing over warning.
*/
Expand Down Expand Up @@ -42,7 +42,13 @@ import {
type McpProfileThread,
resolveMcpProfile,
} from "./mcpProfile.ts";
import { fixT3ToolSet, forgetT3ToolSet, refusedT3ToolSet, t3ToolSetOf } from "./mcpT3ToolSets.ts";
import {
MAX_T3_TOOL_SETS,
type T3ToolSet,
fixT3ToolSet,
refusedT3ToolSet,
t3ToolSetOf,
} from "./mcpT3ToolSets.ts";
import {
type McpProfileFileKeys,
mcpProfileFileKeysOf,
Expand Down Expand Up @@ -76,7 +82,7 @@ export interface ClaudeMcpProfilePlan {
readonly disallowedTools?: Array<string>;
};
readonly servers: McpProfileSet["servers"];
/** T3's own tool groups; the T3 MCP server applies them (mcpT3ToolFilter.ts). */
/** T3's own tool groups; the T3 MCP server applies them (mcpT3ToolRule.ts). */
readonly t3Tools: McpProfileSet["t3Tools"];
readonly builtinTools?: McpProfileSet["builtinTools"];
}
Expand Down Expand Up @@ -669,6 +675,14 @@ export const makeThreadMcpProfiles = Effect.gen(function* () {
});
});

const NOT_IN_STORE = `T3 cannot read this thread from its store, so its MCP profile cannot be worked out and it cannot start: retry, or ${FIX}.`;

/** {@link makeThreadMcpProfilesById}'s refusal of a thread the store did not give. */
export const threadNotInStore = () => new ClaudeMcpProfileError({ reason: NOT_IN_STORE });
/** True for {@link threadNotInStore}'s refusal. */
export const isNotInStore = (error: ClaudeMcpProfileError): boolean =>
error.reason === NOT_IN_STORE;

/**
* A thread's resolved profile, or a refusal, found by its id alone (a Codex thread request carries
* only the id). A thread the store cannot give refuses, as an unreadable parent does. With no store
Expand All @@ -686,35 +700,77 @@ export const makeThreadMcpProfilesById = Effect.gen(function* () {
} as LineageThread);
}
const thread = yield* findThread(threadId);
if (thread === null) {
return yield* new ClaudeMcpProfileError({
reason: `T3 cannot read this thread from its store, so its MCP profile cannot be worked out and it cannot start: retry, or ${FIX}.`,
});
}
if (thread === null) return yield* threadNotInStore();
return yield* read(thread);
});
});

/**
* The plan key each thread's Claude process last opened with. Its T3 tool groups are part of the
* key, so a later plan with the same key has the same set as that process. Memory only, bounded
* like the sets: a thread dropped here just waits for its next process to fix its set.
*/
const openedPlanKeys = new Map<ThreadId, string | undefined>();

const keepOpenedPlanKey = (threadId: ThreadId, key: string | undefined) => {
openedPlanKeys.delete(threadId);
openedPlanKeys.set(threadId, key);
for (const oldest of openedPlanKeys.keys()) {
if (openedPlanKeys.size <= MAX_T3_TOOL_SETS) break;
openedPlanKeys.delete(oldest);
}
};

/**
* The plan with its T3 tool set fixed when its `options` are first read: ClaudeAdapterV2 reads
* them only to open a new process, after the old one closed. A turn that keeps the live process (a
* continuation, the same plan) or is refused before replacing it (background work still runs)
* leaves that process's set as its turn fixed it, so a running turn keeps its set.
*/
const fixedWhenOpened = (
plan: ClaudeMcpProfilePlan,
threadId: ThreadId,
set: T3ToolSet,
): ClaudeMcpProfilePlan => {
const { options, ...rest } = plan;
return Object.defineProperty({ ...rest }, "options", {
enumerable: true,
get: () => {
fixT3ToolSet(threadId, set);
keepOpenedPlanKey(threadId, planKey(plan));
return options;
},
}) as ClaudeMcpProfilePlan;
};

/** The thread's Claude plan, or a refusal, from {@link makeThreadMcpProfiles}. */
export const makeClaudeMcpProfiles = Effect.gen(function* () {
const profileFor = yield* makeThreadMcpProfiles;
const planFor = Effect.fn("ClaudeMcpProfile.planFor")(function* (
thread: LineageThread,
overrides: McpOverrides,
) {
// The query opens for a turn: its T3 tool groups are fixed here until the next one opens, and
// a profile that cannot be worked out keeps only the tools every profile keeps.
// A profile that cannot apply refuses the turn and keeps only the tools every profile keeps,
// at once: narrowing never waits. A profile that applies is fixed as its process opens.
const resolved: McpProfileResolved = yield* profileFor(thread).pipe(
Effect.tapError((refusal) =>
Effect.sync(() => fixT3ToolSet(thread.id, refusedT3ToolSet(refusal.reason))),
),
// Stopped half-way: no set stands, so the next request works it out again.
Effect.onInterrupt(() => Effect.sync(() => forgetT3ToolSet(thread.id))),
);
fixT3ToolSet(thread.id, t3ToolSetOf(resolved));
const t3ServerNames = Object.keys(overrides.mcpServers ?? {});
const plan = claudeMcpProfilePlan(resolved.name, resolved.profile, t3ServerNames);
return isRefusal(plan) ? yield* plan : plan;
if (isRefusal(plan)) {
fixT3ToolSet(thread.id, refusedT3ToolSet(plan.reason));
return yield* plan;
}
const set = t3ToolSetOf(resolved);
// The same plan as the thread's process opened with: the adapter keeps that process without
// reading the options, so its set is fixed here, the one that process has (never wider). This
// is how a good turn after a refused one gets its set back on the process the refusal kept.
if (openedPlanKeys.has(thread.id) && openedPlanKeys.get(thread.id) === planKey(plan)) {
fixT3ToolSet(thread.id, set);
}
return fixedWhenOpened(plan, thread.id, set);
});

return Effect.fn("ClaudeMcpProfile.plan")(function* (
Expand Down
Loading
Loading