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
81 changes: 81 additions & 0 deletions apps/server/src/fork/claudeMcpProfile.adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,65 @@ const preToolUse = (
return answers;
});

/** Hook input for `tool` whose `hook_event_name` is `eventName`, or left out when `omitEvent`. */
const eventCall = (tool: string, eventName: unknown, omitEvent: boolean) => ({
...(omitEvent ? {} : { hook_event_name: eventName }),
tool_name: tool,
tool_input: {},
tool_use_id: "toolu_profile",
session_id: NATIVE_THREAD,
transcript_path: "/tmp/transcript.jsonl",
cwd: "/workspace",
});

/** Event names a guard must not trust: missing, undefined, empty, another event, wrong case, a number. */
const UNTRUSTED_EVENTS: ReadonlyArray<[label: string, eventName: unknown, omit: boolean]> = [
["missing", undefined, true],
["undefined", undefined, false],
["empty", "", false],
["PostToolUse", "PostToolUse", false],
["lower case", "pretooluse", false],
["not a string", 7, false],
];

const decision = (answer: unknown) =>
(answer as { hookSpecificOutput?: { permissionDecision?: string } } | undefined)
?.hookSpecificOutput?.permissionDecision;

/**
* Under every untrusted event name, `refusedTool` is refused and `allowedTool` passes. Each call is
* made twice: the same call made again gets the same answer, as nothing is remembered between calls.
*/
const expectPerEventName = (
options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined,
refusedTool: string,
allowedTool: string,
) =>
Effect.gen(function* () {
for (const [label, eventName, omit] of UNTRUSTED_EVENTS) {
for (const attempt of [1, 2]) {
const answers = yield* preToolUse(
options,
refusedTool,
eventCall(refusedTool, eventName, omit),
);
assert.isTrue(
answers.some((answer) => decision(answer) === "deny"),
`${refusedTool}, event ${label}, try ${attempt}: expected a deny`,
);
const passed = yield* preToolUse(
options,
allowedTool,
eventCall(allowedTool, eventName, omit),
);
assert.isNotEmpty(passed, `${allowedTool}, event ${label}, try ${attempt}: no hook ran`);
for (const answer of passed) {
assert.deepStrictEqual(answer, {}, `${allowedTool}, event ${label}, try ${attempt}`);
}
}
}
});

describe("ClaudeAdapterV2 MCP profile", () => {
it.effect("with no profile set, opens Claude as before and never checks its servers", () =>
Effect.gen(function* () {
Expand Down Expand Up @@ -461,6 +520,28 @@ describe("ClaudeAdapterV2 MCP profile", () => {
}),
);

it.effect(
'the builtinTools "none" guard passes only MCP tools, whatever the event name says (#946)',
() =>
Effect.gen(function* () {
const bare = { servers: "all", t3Tools: "all", builtinTools: "none" } as const;
const { opened } = yield* runTurns({ mcpProfile: "bare", mcpProfiles: { bare } }, []);
yield* expectPerEventName(opened[0], "Bash", "mcp__t3-code__t3_thread_list");
}),
);

it.effect(
"the server-list guard refuses a left-out server, whatever the event name says (#946)",
() =>
Effect.gen(function* () {
const gh = { servers: ["gh"], t3Tools: "all" } as const;
const { opened } = yield* runTurns({ mcpProfile: "gh", mcpProfiles: { gh } }, [
{ name: "gh", status: "connected" },
]);
yield* expectPerEventName(opened[0], "mcp__x__Bash", "mcp__gh__list_issues");
}),
);

it.effect("refuses the turn, without opening Claude, when the profile is missing", () =>
Effect.gen(function* () {
const { opened, refusal } = yield* runTurns({ mcpProfile: "lean" }, []);
Expand Down
20 changes: 11 additions & 9 deletions apps/server/src/fork/claudeMcpProfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type HookCallbackMatcher,
type HookEvent,
type McpServerStatus,
type PreToolUseHookInput,
type Settings as ClaudeSettings,
} from "@anthropic-ai/claude-agent-sdk";
import {
Expand Down Expand Up @@ -138,14 +139,14 @@ export function claudeMcpProfilePlan(
/**
* Refuses a call to any tool but an MCP server's; hooks run in every mode and in sub-agents. Fails
* closed: a tool name that is not a string, or any error while checking, refuses the call (a hook
* that throws would count as a non-blocking error and let the call through).
* that throws would count as a non-blocking error and let the call through). It never trusts
* `hook_event_name`: whatever it says (missing, empty, another event), only an `mcp__` tool passes.
*/
const claudeBuiltinToolsGuard =
(name: string): HookCallback =>
async (input) => {
try {
if (input.hook_event_name !== "PreToolUse") return {};
const toolName: unknown = input.tool_name;
const toolName: unknown = (input as { tool_name?: unknown }).tool_name;
if (typeof toolName === "string" && toolName.startsWith("mcp__")) return {};
const shown = typeof toolName === "string" ? `the built-in tool "${toolName}"` : "a tool";
return builtinToolDenial(
Expand Down Expand Up @@ -264,10 +265,10 @@ export function claudeMcpCallOutsideProfile(
}

/**
* Refuses, at the moment of the call, a tool call to an MCP server the profile leaves out. The
* options keep such servers from loading; this covers what loads anyway (a managed policy that
* drops T3's allowlist, an agent file's servers, a server added mid-session). Hooks run in every
* permission mode and inside sub-agents.
* Refuses, at the call, a tool of an MCP server the profile leaves out but that loaded anyway (a
* managed policy that drops T3's allowlist, an agent file's servers, one added mid-session). Hooks
* run in every permission mode and in sub-agents. It never trusts `hook_event_name`: whatever it
* says (missing, empty, another event), a left-out server's tool is refused.
*/
const claudeMcpProfileGuard =
(
Expand All @@ -276,8 +277,9 @@ const claudeMcpProfileGuard =
t3ServerNames: ReadonlyArray<string>,
): HookCallback =>
async (input) => {
if (input.hook_event_name !== "PreToolUse") return {};
const server = claudeMcpCallOutsideProfile(servers, t3ServerNames, input);
// Registered only under PreToolUse, so the input is read as one whatever its event name.
const call = input as PreToolUseHookInput;
const server = claudeMcpCallOutsideProfile(servers, t3ServerNames, call);
if (server === undefined) return {};
return {
hookSpecificOutput: {
Expand Down
5 changes: 3 additions & 2 deletions apps/server/src/fork/threadRoleTargetsLayer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/**
* Fork (calm sidebar): {@link ThreadRoleTargets} read from upstream's orchestrator, for the
* `threadRoles` save check (threadRoleTargets.ts). Kept apart from that file so the settings file
* never imports orchestration code. Wired in forkLayers.ts (`layerRuntimeServices`).
* never imports orchestration code. Wired in forkLayers.ts (`layerRuntimeServices`); its make span
* shows holdWork.boot.test.ts the real server builds it.
*/
import { isListedThreadLineage, type ThreadId } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
Expand All @@ -26,5 +27,5 @@ export const layer = Layer.effect(
};
}),
}),
),
).pipe(Effect.withSpan("ThreadRoleTargets.make")),
);
3 changes: 3 additions & 0 deletions apps/server/src/holdWork.boot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,9 @@ const FORK_LAYER_SPANS = [
"AgentSlotRoutes.scheduledRunsGated",
// The record of who saved each scheduled task, which needs the server's state folder.
"ScheduledTaskMcpProfiles.stored",
// The `threadRoles` save check's thread lookup in `ForkLayers.layerRuntimeServices`. Without it
// the app refuses every new role ("cannot be checked here") and nothing else fails.
"ThreadRoleTargets.make",
];

const missingForkLayers = (spans: ReadonlySet<string>) =>
Expand Down
Loading