Skip to content
Draft
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
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,7 @@ export const make = Effect.gen(function* () {
threadPullRequestLinking: true,
serverResolvedCommandContext: true,
threadStop: true,
humanNote: true,
...(hostPlatform === "win32" ? {} : { localServerStop: true }),
environmentIcon: true,
projectCloneTracking: true,
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ const runtimeModeRank: Record<RuntimeMode, number> = {
};
const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };

export const hiddenFromOutsideClientsAndSubagents = (): boolean =>
hiddenFromOutsideClients() && hiddenFromSubagents();

/**
* The modes a client caller's writes are capped at: what it was approved
* with, narrowed by what it asked for on this request. A read-only client
Expand Down
98 changes: 98 additions & 0 deletions apps/server/src/mcp/McpToolAccess.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, it } from "@effect/vitest";
import {
CommandId,
EnvironmentId,
OrchestratorMcpEnvironmentTarget,
OrchestratorMcpFailure,
Expand All @@ -9,6 +10,7 @@ import {
ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
Expand All @@ -19,11 +21,18 @@ import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";

import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
import * as PeerLinks from "../peer/PeerLinks.ts";
import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpToolAccess from "./McpToolAccess.ts";
import { liveThreadShell } from "./McpToolAccess.testkit.ts";
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";
import * as OrchestratorHandlers from "./toolkits/orchestrator/handlers.ts";
import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";

const supervisedThreadId = ThreadId.make("thread:supervised");
const planThreadId = ThreadId.make("thread:plan");
Expand Down Expand Up @@ -366,6 +375,95 @@ it.effect("refuses a change when the calling thread cannot be read", () =>

const box = EnvironmentId.make("environment-box");
const here = EnvironmentId.make("environment");

const questionToolServer = McpHttpServer.toolkitRegistration(
OrchestratorToolkit,
OrchestratorHandlers.layer,
).pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provide(
Layer.mergeAll(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
}),
Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({
requestSecret: () => Effect.succeed({ status: "timed_out" }),
}),
Layer.mock(ThreadMetadataMcpService.ThreadMetadataMcpService)({
update: (_scope, input) =>
Effect.succeed({
threadId: fullAccessThreadId,
commandId: CommandId.make("command-update"),
action: input.action,
title: input.title ?? "Fixture",
sequence: 1,
titleRegeneration: null,
linkedPullRequest: null,
updatedAt: "2026-06-06T00:00:00.000Z",
}),
}),
Layer.mock(PeerForwarding.PeerForwarding)({
call: () => Effect.succeed({ ran: "forwarded" } as never),
}),
Layer.mock(PeerLinks.PeerLinks)({}),
Layer.mock(PeerLinkRequests.PeerLinkRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
),
),
);

it.effect("keeps human questions out of delegated MCP calls, including forwarded decisions", () =>
Effect.gen(function* () {
const child = { ...fullAccess, thread: { ...fullAccess.thread!, subagent: true } };
const server = yield* McpServer.McpServer;
const secretTool = server.tools.find(({ tool }) => tool.name === "request_secret")!;
const visible = (scope: McpInvocationContext.McpInvocationScope) =>
Effect.sync(() =>
Context.getOrUndefined(
secretTool.annotations,
McpSchema.EnabledWhen,
)?.({
protocolVersion: mcpClient.protocolVersion,
capabilities: mcpClient.clientCapabilities,
}),
).pipe(Effect.provideService(McpInvocationContext.McpInvocationContext, scope));
expect(yield* visible(fullAccess)).toBe(true);
expect(yield* visible(child)).toBe(false);
}).pipe(Effect.provide(questionToolServer)),
);

it.effect("rejects delegated questions at MCP execution before forwarding", () =>
Effect.gen(function* () {
const child = { ...fullAccess, thread: { ...fullAccess.thread!, subagent: true } };
const decision = {
action: "request_decision",
decision: { founder: "kameron", kind: "decision", question: "Synthetic question" },
};
const server = yield* McpServer.McpServer;
const callAs = (scope: McpInvocationContext.McpInvocationScope, name: string, args: object) =>
server
.callTool({ name, arguments: args })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(McpSchema.McpServerClient, mcpClient),
);
const secret = { label: "Fixture", reason: "Synthetic request" };
const parentSecret = yield* callAs(fullAccess, "request_secret", secret);
expect(parentSecret.structuredContent).toMatchObject({ status: "timed_out" });
const childSecret = yield* callAs(child, "request_secret", secret).pipe(Effect.exit);
expect(Exit.isFailure(childSecret) || childSecret.value.isError).toBe(true);
expect(yield* call("t3_thread_update", child, decision)).toBe("capability_denied");
expect(yield* call("t3_thread_update", child, { ...decision, environmentId: box })).toBe(
"capability_denied",
);
const renamed = yield* callAs(child, "t3_thread_update", {
action: "rename",
title: "Fixture",
});
expect(renamed.structuredContent).toMatchObject({ action: "rename", title: "Fixture" });
}).pipe(Effect.provide(questionToolServer)),
);

const linkedProbe = {
...probe,
parameters: Schema.Struct({
Expand Down
29 changes: 27 additions & 2 deletions apps/server/src/mcp/McpToolAccess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,30 @@ export const reads = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>)
() => Effect.void,
);

/** Apply the caller check before local execution or forwarding loses the child identity. */
export const withoutSubagents = <P, A, E, R>(
declaration: Declaration<(params: P) => Effect.Effect<A, E, R>>,
matches: (params: P) => boolean = () => true,
) => {
const check = Effect.fn("McpToolAccess.withoutSubagents")(function* (params: P) {
const scope = yield* McpInvocationContext.McpInvocationContext;
if (scope.thread?.subagent === true && matches(params)) {
return yield* new OrchestratorMcpFailure({
code: "capability_denied",
message: "Child threads must bring questions to their parent thread.",
});
}
});
const handle = checkedHandler(declaration) as (params: P) => Effect.Effect<A, E, R>;
const remote = remoteCheckOf(declaration) as RemoteCheck<P> | undefined;
return declare(
(params: P) => check(params).pipe(Effect.andThen(handle(params))),
remote === undefined
? undefined
: (params: P) => check(params).pipe(Effect.andThen(remote(params))),
);
};

export const readsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), undefined);

Expand Down Expand Up @@ -424,10 +448,11 @@ const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record
const tool = toolkit.tools[name];
if (tool === undefined) continue;
const remote = remoteCheckOf(declaration);
const enabledWhen = Context.getOrUndefined(tool.annotations, McpSchema.EnabledWhen);
if (
remote === undefined &&
Context.getOrUndefined(tool.annotations, McpSchema.EnabledWhen) !==
McpInvocationContext.hiddenFromOutsideClients
enabledWhen !== McpInvocationContext.hiddenFromOutsideClients &&
enabledWhen !== McpInvocationContext.hiddenFromOutsideClientsAndSubagents
)
return yield* Effect.die(
`${name} acts as its calling thread, so outside clients must not be offered it.`,
Expand Down
33 changes: 19 additions & 14 deletions apps/server/src/mcp/toolkits/orchestrator/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,14 @@ const handlers = {
return yield* service.deleteScheduledTask(scope, input);
}),
),
request_secret: McpToolAccess.actsAsCaller((input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
return yield* service.requestSecret(scope, input);
}),
request_secret: McpToolAccess.withoutSubagents(
McpToolAccess.actsAsCaller((input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
return yield* service.requestSecret(scope, input);
}),
),
),
create_threads: McpToolAccess.actsAsCaller((input) =>
Effect.gen(function* () {
Expand All @@ -273,14 +275,17 @@ const handlers = {
return yield* service.readThread(scope, input);
}),
),
t3_thread_update: McpToolAccess.writesThreads(
(input) => [input.threadId],
(input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const service = yield* ThreadMetadataMcpService.ThreadMetadataMcpService;
return yield* service.update(scope, input);
}),
t3_thread_update: McpToolAccess.withoutSubagents(
McpToolAccess.writesThreads(
(input) => [input.threadId],
(input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext.McpInvocationContext;
const service = yield* ThreadMetadataMcpService.ThreadMetadataMcpService;
return yield* service.update(scope, input);
}),
),
(input) => input.action === "request_decision",
),
t3_thread_send: McpToolAccess.afterForwarding(
McpToolAccess.writesThreads(
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ const RequestSecretTool = Tool.make("request_secret", {
.annotate(Tool.Destructive, false)
// Claude Code defers MCP tools behind ToolSearch; agents that never load this one ask in chat.
.annotate(Tool.Meta, { "anthropic/alwaysLoad": true })
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClientsAndSubagents);

const CreateThreadsTool = Tool.make("create_threads", {
description:
Expand Down
8 changes: 6 additions & 2 deletions apps/web/src/components/chat/useComposerSend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ import {
ProviderInteractionMode,
RuntimeMode,
} from "@t3tools/contracts";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import {
deriveThreadTitleSeed,
HumanNoteUnavailableError,
} from "@t3tools/client-runtime/operations";
import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
import {
declinePendingApprovals,
Expand Down Expand Up @@ -619,11 +622,12 @@ export function useComposerSend(input: ComposerSendInput) {
},
});
if (noted._tag === "Failure") {
const error = squashAtomCommandFailure(noted);
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Note not saved",
description: "Try again.",
description: error instanceof HumanNoteUnavailableError ? error.message : "Try again.",
}),
);
return;
Expand Down
65 changes: 60 additions & 5 deletions packages/client-runtime/src/operations/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
readonly projection?: OrchestrationV2ThreadProjection;
readonly projectionRequests?: ThreadId[];
readonly advertiseThreadStop?: boolean;
readonly advertiseHumanNote?: boolean;
}) {
const client = {
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
Expand Down Expand Up @@ -123,6 +124,9 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
capabilities: {
repositoryIdentity: true,
...(input.advertiseThreadStop === true ? { threadStop: true } : {}),
...(input.advertiseHumanNote === undefined
? {}
: { humanNote: input.advertiseHumanNote }),
},
},
} as never),
Expand Down Expand Up @@ -306,6 +310,42 @@ describe("V2 environment commands", () => {
}).pipe(Effect.provide(layerTestRandom)),
);

it.effect.each([undefined, false, true])("requires explicit human note support (%s)", (support) =>
Effect.gen(function* () {
const commands: OrchestrationV2Command[] = [];
const supervisor = yield* makeSupervisor({
commands,
projects: [],
...(support === undefined ? {} : { advertiseHumanNote: support }),
});
const exit = yield* startThreadTurn({
commandId: CommandId.make("command-note"),
threadId: v2ThreadId,
message: {
messageId: MessageId.make("message-note"),
role: "user",
text: "Synthetic note",
attachments: [],
humanNote: true,
},
runtimeMode: "full-access",
interactionMode: "default",
dispatchMode: "start",
}).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.exit,
);

if (support === true) {
expect(commands).toMatchObject([{ type: "message.dispatch", humanNote: true }]);
expect(Exit.isSuccess(exit)).toBe(true);
} else {
expect(commands).toEqual([]);
expect(Exit.isFailure(exit)).toBe(true);
}
}).pipe(Effect.provide(layerTestRandom)),
);

// A dead socket reaches the caller as a protocol error, or as an interrupt when
// the supervisor closes the session before the protocol reports the error.
it.effect.each([
Expand All @@ -317,9 +357,11 @@ describe("V2 environment commands", () => {
cause: new Error("socket closed"),
}),
}),
false,
],
["session close", Effect.failCause(Cause.interrupt())],
] as const)("retries a message dispatch lost to a %s with the same command id", ([, loss]) =>
["session close", Effect.failCause(Cause.interrupt()), false],
["session close followed by an older server", Effect.failCause(Cause.interrupt()), true],
] as const)("handles a message dispatch lost to a %s", ([, loss, humanNote]) =>
Effect.gen(function* () {
const commands: OrchestrationV2Command[] = [];
const supervisor = yield* makeSupervisor({ commands, projects: [] });
Expand All @@ -337,7 +379,19 @@ describe("V2 environment commands", () => {
} as unknown as WsRpcProtocolClient;
yield* SubscriptionRef.set(
supervisor.session,
Option.some({ ...healthySession, client: lostClient }),
Option.some({
...healthySession,
client: lostClient,
initialConfig: healthySession.initialConfig.pipe(
Effect.map((config) => ({
...config,
environment: {
...config.environment,
capabilities: { ...config.environment.capabilities, humanNote: true },
},
})),
),
}),
);

const sendFiber = yield* startThreadTurn({
Expand All @@ -348,6 +402,7 @@ describe("V2 environment commands", () => {
role: "user",
text: "hello",
attachments: [],
...(humanNote ? { humanNote: true as const } : {}),
},
runtimeMode: "full-access",
interactionMode: "default",
Expand All @@ -361,9 +416,9 @@ describe("V2 environment commands", () => {

expect(commands.map((command) => [command.type, command.commandId])).toEqual([
["message.dispatch", "command-lost-ack"],
["message.dispatch", "command-lost-ack"],
...(humanNote ? [] : [["message.dispatch", "command-lost-ack"]]),
]);
expect(Exit.isSuccess(exit)).toBe(true);
expect(Exit.isSuccess(exit)).toBe(!humanNote);
}).pipe(Effect.provide(layerTestRandom)),
);

Expand Down
Loading
Loading