Skip to content
Open
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
3 changes: 3 additions & 0 deletions apps/server/src/cli/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -245,6 +246,8 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E,
endpoint: new URL("/mcp", origin).href,
authorization: `Bearer ${issued.token}`,
clientName: "t3-thread-cli",
// A person types what this command sends, so the model reads it as theirs.
headers: { [TYPED_BY_USER_HEADER]: "1" },
}).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
return yield* run(makeThreadTools(session, origin));
}).pipe(
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/mcp/AcpMcpStdioBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export interface McpToolSessionOptions {
readonly endpoint: string;
readonly authorization: string;
readonly clientName: string;
readonly headers?: Readonly<Record<string, string>>;
readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
}

Expand All @@ -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 }),
Expand Down
18 changes: 15 additions & 3 deletions apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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* () {
Expand Down Expand Up @@ -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",
),
}),
Expand Down Expand Up @@ -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<string, string> = {}) =>
const start = (
limit: string | undefined,
args: Record<string, string> = {},
extraHeaders: Record<string, string> = {},
) =>
Effect.gen(function* () {
const headers = {
...extraHeaders,
accept: "application/json, text/event-stream",
authorization: `Bearer ${clientToken}`,
...(limit === undefined ? {} : { "t3-mode-limit": limit }),
Expand Down Expand Up @@ -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)),
);
Expand Down
14 changes: 13 additions & 1 deletion apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
{
Expand Down Expand Up @@ -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;
Expand Down
15 changes: 15 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
24 changes: 24 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
PreviewAutomationUnavailableError,
type ProviderInstanceId,
type ProviderInteractionMode,
type OrchestrationV2Actor,
type OrchestrationV2LinkedSender,
type RuntimeMode,
type ThreadId,
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<McpInvocationScope, "thread" | "client">,
): 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.
Expand Down
8 changes: 7 additions & 1 deletion apps/server/src/mcp/OrchestratorMcpService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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");
}),
);

Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ import {
clientModeCeiling,
type McpInvocationScope,
type McpThreadInvocationScope,
mcpMessageActor,
requireThreadScope,
threadLinkFor,
} from "./McpInvocationContext.ts";
Expand Down Expand Up @@ -3645,7 +3646,7 @@ const make = Effect.gen(function* () {
attachments: [],
mode,
...(input.freshContext ? { freshContext: true } : {}),
createdBy: "agent",
createdBy: mcpMessageActor(scope),
creationSource: "mcp",
})
.pipe(
Expand Down
4 changes: 3 additions & 1 deletion apps/server/src/mcp/toolkits/attachment/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ function makeLocalCommandHarness(input: {
readonly previousNativeSession?: boolean;
readonly previousMessages?: ReadonlyArray<string>;
readonly createdBy?: "agent" | "system";
readonly creationSource?: "mcp";
readonly scheduledTaskId?: ScheduledTaskId;
readonly logoutFailure?: string;
readonly openFailure?: unknown;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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({
Expand Down
4 changes: 3 additions & 1 deletion apps/server/src/orchestration-v2/ProviderTurnStartService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}),
);
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/orchestration-v2/ThreadLaunchService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions docs/user/outside-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading