diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index a43bf4ce176f0..52f1376f59811 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -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, diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 81c3d43b44c08..80fc16a25b12c 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -98,6 +98,9 @@ const runtimeModeRank: Record = { }; const interactionModeRank: Record = { 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 diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts index 6cfd86bd3d836..b4192a32b6bfc 100644 --- a/apps/server/src/mcp/McpToolAccess.test.ts +++ b/apps/server/src/mcp/McpToolAccess.test.ts @@ -1,5 +1,6 @@ import { expect, it } from "@effect/vitest"; import { + CommandId, EnvironmentId, OrchestratorMcpEnvironmentTarget, OrchestratorMcpFailure, @@ -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"; @@ -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"); @@ -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({ diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index 228facf950d42..de8e7964158ee 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -147,6 +147,30 @@ export const reads = (handle: (params: P) => Effect.Effect) () => Effect.void, ); +/** Apply the caller check before local execution or forwarding loses the child identity. */ +export const withoutSubagents = ( + declaration: Declaration<(params: P) => Effect.Effect>, + 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; + const remote = remoteCheckOf(declaration) as RemoteCheck

| 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 = (handle: (params: P) => Effect.Effect) => declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), undefined); @@ -424,10 +448,11 @@ const routed = Effect.fn("McpToolAccess.routed")(function* - 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* () { @@ -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( diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 2d9ce98bbbe8f..11ecdb4b7f3d5 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -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: diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 0042f1f9d0789..c9f51182a836d 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -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, @@ -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; diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index 87c8b785563b3..5a5ccbab17eff 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -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) => @@ -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), @@ -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([ @@ -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: [] }); @@ -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({ @@ -348,6 +402,7 @@ describe("V2 environment commands", () => { role: "user", text: "hello", attachments: [], + ...(humanNote ? { humanNote: true as const } : {}), }, runtimeMode: "full-access", interactionMode: "default", @@ -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)), ); diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 59ab217f56acc..1e97ee268bea1 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -37,15 +37,18 @@ import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import { + currentSession, EnvironmentRpcUnavailableError, getInitialServerConfig, isRpcClientError, request, + requestInSession, } from "../rpc/client.ts"; interface CommandMetadata { @@ -317,12 +320,28 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; +export class HumanNoteUnavailableError extends Schema.TaggedError()( + "HumanNoteUnavailableError", + { message: Schema.String }, +) {} + const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( command: Extract, resendAfterSocketLoss: boolean, ) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( + const attempt = Effect.gen(function* () { + if (command.humanNote !== true) return yield* dispatch(command); + const session = yield* currentSession(); + const config = yield* session.initialConfig; + if (config.environment.capabilities.humanNote !== true) { + return yield* new HumanNoteUnavailableError({ + message: "This server does not support private notes. Update the server to use /note.", + }); + } + // Check each attempt against the same session that will receive the note. + return yield* requestInSession(session, ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command); + }).pipe( Effect.timeoutOrElse({ duration: MESSAGE_DISPATCH_TIMEOUT, orElse: () => @@ -783,6 +802,16 @@ export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThread export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* ( input: StartThreadTurnInput, ) { + const bootstrap = input.bootstrap?.createThread; + const prepareWorktree = input.bootstrap?.prepareWorktree; + if ( + input.message.humanNote === true && + (bootstrap !== undefined || prepareWorktree !== undefined) + ) { + return yield* new HumanNoteUnavailableError({ + message: "Send a private note from an existing shared thread.", + }); + } const commandId = yield* allocateCommandId(input); const attachments = yield* persistAttachments( input.threadId, @@ -794,8 +823,6 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); - const bootstrap = input.bootstrap?.createThread; - const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { const existingProjection = bootstrap === undefined ? yield* getProjection(input.threadId) : null; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index a04719df3d151..dfeb05ee8e4a2 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -97,6 +97,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ pullRequestChecks: Schema.optionalKey(Schema.Boolean), /** Side chats: hidden `lineage.sideChat` forks. Older servers ignore the fork flag. */ sideChats: Schema.optionalKey(Schema.Boolean), + /** Older servers can silently drop the private-note flag on message dispatch. */ + humanNote: Schema.optionalKey(Schema.Boolean), vcsBranchStatus: Schema.optionalKey(Schema.Boolean), /** Every protocol-2 server sends this; older mobile builds still read it. */ inlineMessageContext: Schema.optionalKey(Schema.Boolean),