diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 3566b75e20773..c33ac052d9d83 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -30,6 +30,7 @@ import { Argument, Command, Flag, GlobalFlag } from "effect/cli"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; +import { TYPED_BY_USER_HEADER } from "../mcp/McpInvocationContext.ts"; import { expandHomePath } from "../os-jank.ts"; import * as ProcessRunner from "../processRunner.ts"; import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; @@ -245,6 +246,8 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* new ThreadServerUnreachableError({ origin, cause }))); return yield* run(makeThreadTools(session, origin)); }).pipe( diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index ffddcf7d5866b..07742d135b47d 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -68,6 +68,7 @@ export interface McpToolSessionOptions { readonly endpoint: string; readonly authorization: string; readonly clientName: string; + readonly headers?: Readonly>; readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise; } @@ -92,6 +93,7 @@ export const mcpToolSession = ( let nextId = 0; const headers = () => ({ + ...options.headers, accept: "application/json, text/event-stream", authorization: options.authorization, ...(sessionId === null ? {} : { "mcp-session-id": sessionId }), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index e5d47410817f2..2668d44527619 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1881,7 +1881,7 @@ it.effect( ); it.effect( - "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them", + "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and reads T3-Typed-By-User", () => Effect.scoped( Effect.gen(function* () { @@ -1918,7 +1918,9 @@ it.effect( starts: McpToolAccess.startsThreads( (input) => input, (_, modes) => - Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }), + Effect.map(McpInvocationContext.McpInvocationContext, (scope) => ({ + modes: `${modes.runtimeMode}/${modes.interactionMode}${McpInvocationContext.mcpMessageActor(scope) === "user" ? " by user" : ""}`, + })), "stamped", ), }), @@ -1964,9 +1966,14 @@ it.effect( ), ); /** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */ - const start = (limit: string | undefined, args: Record = {}) => + const start = ( + limit: string | undefined, + args: Record = {}, + extraHeaders: Record = {}, + ) => Effect.gen(function* () { const headers = { + ...extraHeaders, accept: "application/json, text/event-stream", authorization: `Bearer ${clientToken}`, ...(limit === undefined ? {} : { "t3-mode-limit": limit }), @@ -2021,6 +2028,11 @@ it.effect( expect(yield* start("auto")).toBe(400); expect(yield* start("auto/default/extra")).toBe(400); expect(yield* start("root/default")).toBe(400); + // Only a client that says a person typed the request's message sends as the user. + expect(yield* start(undefined, {}, { "t3-typed-by-user": "1" })).toBe( + "auto/default by user", + ); + expect(yield* start(undefined, {}, { "t3-typed-by-user": "yes" })).toBe("auto/default"); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index d7bea75493b73..3d31b062077bd 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -264,6 +264,15 @@ const withSenderThread = ( : { ...invocation, client: { ...invocation.client, senderThread: decoded.value } }; }; +const withTypedByUser = ( + invocation: McpInvocationContext.McpInvocationScope, + request: HttpServerRequest.HttpServerRequest, +): McpInvocationContext.McpInvocationScope => + request.headers[McpInvocationContext.TYPED_BY_USER_HEADER]?.trim() === "1" && + invocation.client !== undefined + ? { ...invocation, client: { ...invocation.client, typedByUser: true } } + : invocation; + // The Linked environments beta is off here: links wait until it is on again. const linkedEnvironmentsOff = HttpServerResponse.jsonUnsafe( { @@ -327,7 +336,10 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token), }); } - const asked = withModeLimit(withSenderThread(invocation, request), request); + const asked = withModeLimit( + withTypedByUser(withSenderThread(invocation, request), request), + request, + ); if (asked === undefined) return invalidModeLimit; const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling); const linkedEnvironments = yield* linksEnabled; diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts index 96c71fcd773f9..5eba947cb8d41 100644 --- a/apps/server/src/mcp/McpInvocationContext.test.ts +++ b/apps/server/src/mcp/McpInvocationContext.test.ts @@ -95,3 +95,18 @@ it("acts at an administrator's ceiling for a client approved above it", () => { expect(modes(scope("auto-accept-edits"), "auto").runtimeMode).toBe("auto-accept-edits"); expect(modes(scope("full-access")).runtimeMode).toBe("full-access"); }); + +it("takes a message as the user's only from an outside client that says a person typed it", () => { + const client = { sessionId: "s", label: "T3 WoW", access: "full-access" } as const; + const thread = { + threadId: ThreadId.make("thread-1"), + providerSessionId: "provider-session-1", + providerInstanceId: ProviderInstanceId.make("codex"), + }; + const typed = { ...client, typedByUser: true }; + const actor = McpInvocationContext.mcpMessageActor; + expect(actor({ thread: undefined, client: typed })).toBe("user"); + expect(actor({ thread: undefined, client })).toBe("agent"); + expect(actor({ thread: undefined, client: { ...typed, linked: true } })).toBe("agent"); + expect(actor({ thread, client: typed })).toBe("agent"); +}); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 893c17f23311b..d46f4a28ca59e 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -6,6 +6,7 @@ import { PreviewAutomationUnavailableError, type ProviderInstanceId, type ProviderInteractionMode, + type OrchestrationV2Actor, type OrchestrationV2LinkedSender, type RuntimeMode, type ThreadId, @@ -51,6 +52,8 @@ export interface McpClientCaller { * another environment passing on the limits of the agent it calls for. */ readonly narrowedTo?: ClientModes | undefined; + /** The request says a person typed what it sends (`T3-Typed-By-User`). */ + readonly typedByUser?: boolean | undefined; /** A linked environment's thread this request is made for (`T3-Sender-Thread`). */ readonly senderThread?: OrchestrationV2LinkedSender | undefined; /** An outside client's thread links go through this hosted app, as Copy thread's do. */ @@ -78,6 +81,13 @@ export const LINK_EXPIRES_AT_HEADER = "t3-link-expires-at"; */ export const SENDER_THREAD_HEADER = "t3-sender-thread"; +/** + * `T3-Typed-By-User: 1`: a person typed the message this request sends, as in the `t3` CLI or an + * app that passes on what its user types. Honored only from a client outside any thread that is + * not a linked environment (`mcpMessageActor`). + */ +export const TYPED_BY_USER_HEADER = "t3-typed-by-user"; + export interface ClientModes { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; @@ -161,6 +171,20 @@ export interface McpInvocationScope { readonly forge?: boolean; } +/** + * Outside agents sign in as MCP clients too, so a client's message is the user's only on a request + * that says a person typed it. A thread's agent or a linked environment cannot say so. + */ +export const mcpMessageActor = ( + scope: Pick, +): OrchestrationV2Actor => + scope.client?.typedByUser === true && + scope.thread === undefined && + scope.client !== undefined && + scope.client.linked !== true + ? "user" + : "agent"; + /** * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so * they get the hosted link Copy thread copies, which opens the thread in either app or a browser. diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 2dad1fe68ee6d..c3bf37680cce9 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -5129,7 +5129,7 @@ describe("OrchestratorMcpService thread lookup", () => { }), ); - it.effect("records the linked environment's thread that sent a message", () => + it.effect("records who sent a message: a linked environment's thread, or the user", () => Effect.gen(function* () { const target = liveThreadShell(ThreadId.make("thread:target")); const sender = { @@ -5175,6 +5175,12 @@ describe("OrchestratorMcpService thread lookup", () => { assert.deepStrictEqual(fromLink?.linkedSender, sender); assert.isUndefined(fromLink?.senderThreadId); assert.isUndefined((yield* sendAs(linked()))?.linkedSender); + assert.strictEqual((yield* sendAs(client))?.createdBy, "agent"); + const typed: McpInvocationScope = { + ...client, + client: { sessionId: "app", label: "T3 WoW", access: "full-access", typedByUser: true }, + }; + assert.strictEqual((yield* sendAs(typed))?.createdBy, "user"); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 7b8c99877d974..a65e0ef77e262 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -123,6 +123,7 @@ import { clientModeCeiling, type McpInvocationScope, type McpThreadInvocationScope, + mcpMessageActor, requireThreadScope, threadLinkFor, } from "./McpInvocationContext.ts"; @@ -3645,7 +3646,7 @@ const make = Effect.gen(function* () { attachments: [], mode, ...(input.freshContext ? { freshContext: true } : {}), - createdBy: "agent", + createdBy: mcpMessageActor(scope), creationSource: "mcp", }) .pipe( diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.ts index 25d0ac7fad15d..6fb6b499d9e0f 100644 --- a/apps/server/src/mcp/toolkits/attachment/handlers.ts +++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts @@ -110,7 +110,9 @@ export const layer = McpToolAccess.toLayer( text: input.message ?? "", attachments, mode: "auto", - createdBy: "agent", + createdBy: McpInvocationContext.mcpMessageActor( + yield* McpInvocationContext.McpInvocationContext, + ), creationSource: "mcp", }).pipe( Effect.mapError((error) => diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index dfb346156d40a..2770fdbebe2bc 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -429,7 +429,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { attachments, }, }), - createdBy: "agent", + createdBy: McpInvocationContext.mcpMessageActor(scope), creationSource: "mcp", ...(linkOrigin === undefined ? {} : { linkOrigin }), // Kept only alongside linkOrigin: thread.create drops it otherwise. diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index e4edafd70942b..005043b622095 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -468,6 +468,7 @@ function makeLocalCommandHarness(input: { readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; readonly createdBy?: "agent" | "system"; + readonly creationSource?: "mcp"; readonly scheduledTaskId?: ScheduledTaskId; readonly logoutFailure?: string; readonly openFailure?: unknown; @@ -568,7 +569,7 @@ function makeLocalCommandHarness(input: { attachments: [], streaming: false, createdBy: input.createdBy ?? "user", - creationSource: input.createdBy === undefined ? "web" : "mcp", + creationSource: input.creationSource ?? (input.createdBy === undefined ? "web" : "mcp"), ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }), createdAt: now, updatedAt: now, @@ -3332,6 +3333,8 @@ effectIt.effect.each([ { name: "an agent", createdBy: "agent" as const }, // A scheduled delivery keeps its task author's createdBy. { name: "a scheduled task", scheduledTaskId: ScheduledTaskId.make("task") }, + // An MCP client's word that a person typed it (`T3-Typed-By-User`) does not reach sign-out. + { name: "an MCP client's message typed by the user", creationSource: "mcp" as const }, ])("does not let $name sign a provider out", ({ name: _name, ...sender }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index d423d0c2ea675..ccfbb0d3b9007 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -742,9 +742,11 @@ export const layer: Layer.Layer< records: providerMessage.context?.records ?? [], }), hasAttachments: false, - // A scheduled delivery keeps its task author's createdBy. + // A scheduled delivery keeps its task author's createdBy. An MCP client's own + // word that a person typed a message does not reach provider sign-out. sentByPerson: providerMessage.createdBy === "user" && + providerMessage.creationSource !== "mcp" && providerMessage.scheduledTaskId === undefined, }), ); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 593393cae48eb..49bac58b67e46 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -1431,11 +1431,11 @@ const make = Effect.gen(function* () { creationSource: input.creationSource, }) .pipe( - // An agent's launch can land on a thread that a replay, or a concurrent + // An MCP launch can land on a thread that a replay, or a concurrent // launch with the same key, created with broader modes. The orchestrator // refuses the message under the thread's lock; the user's own clients // launch into their own drafts, whatever modes those hold. - input.createdBy === "agent" + input.creationSource === "mcp" ? Effect.provideService(DispatchModeLimit, { runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 97bc0d385a3d7..df0913cadb2d2 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -95,6 +95,9 @@ T3 Code. `projectId` or `threadId`. - To list threads across projects, call `t3_thread_list` with `allProjects: true`, or use `t3_thread_search`. +- Messages an outside agent sends reach the thread's agent marked as not from + you. An app that passes on what you type sends the `T3-Typed-By-User: 1` + header with those requests, and the thread's agent then reads them as yours. ## Claude Code