@devries-cameron20 / t3code-1 / commits / 1b1ad0466d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat(server): /mcp narrows a client's modes from T3-Mode-Limit (#16653)

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 14:04 UTC 1b1ad0466d0f213fb7c3686b7ae78df198162bf2
5 files changed +235 -13
apps/server/src/mcp/McpHttpServer.test.ts
+146
@@ -1,5 +1,6 @@
1 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
2 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
3 +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
4 import { expect, it } from "@effect/vitest";
5 import { NodeHttpServer } from "@effect/platform-node";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -8,6 +9,8 @@ import {
9 OrchestratorMcpFailure,
10 PreviewTabId,
11 ProviderInstanceId,
12 + ProviderInteractionMode,
13 + RuntimeMode,
14 ThreadId,
15 } from "@t3tools/contracts";
16 import * as Deferred from "effect/Deferred";
@@ -940,3 +943,146 @@ it.effect("lists pull request watch tools only to threads that are not delegated
943 }),
944 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
945 );
946 +
947 +it.effect(
948 + "narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
949 + () =>
950 + Effect.scoped(
951 + Effect.gen(function* () {
952 + const clientToken = "client-payload.client-signature";
953 + const clientScope: McpInvocationContext.McpInvocationScope = {
954 + environmentId,
955 + requestNamespace: "client:linked",
956 + thread: undefined,
957 + client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
958 + capabilities: new Set(["orchestration"]),
959 + issuedAt: 1,
960 + };
961 + // Starts a thread at the modes the gate hands it, so the outcome is those modes.
962 + const StartsToolkit = Toolkit.make(
963 + Tool.make("starts", {
964 + description: "Reports the modes a started thread would run with.",
965 + parameters: Schema.Struct({
966 + runtimeMode: Schema.optional(RuntimeMode),
967 + interactionMode: Schema.optional(ProviderInteractionMode),
968 + }),
969 + success: Schema.Struct({ modes: Schema.String }),
970 + failure: OrchestratorMcpFailure,
971 + failureMode: "return",
972 + dependencies: [
973 + McpInvocationContext.McpInvocationContext,
974 + ThreadManagementService.ThreadManagementService,
975 + ],
976 + }),
977 + );
978 + const serverLayer = McpHttpServer.toolkitRegistration(
979 + StartsToolkit,
980 + McpToolAccess.toLayer(StartsToolkit, {
981 + starts: McpToolAccess.startsThreads(
982 + (input) => input,
983 + (_, modes) =>
984 + Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
985 + ),
986 + }),
987 + ).pipe(
988 + Layer.provideMerge(McpHttpServer.layerMcpTransport),
989 + Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
990 + Layer.provide(
991 + Layer.mock(McpSessionRegistry.McpSessionRegistry)({
992 + // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
993 + resolve: () => Effect.succeed(undefined),
994 + }),
995 + ),
996 + Layer.provide(
997 + Layer.succeed(McpHttpServer.McpClientAuthenticator, {
998 + authenticate: (request) =>
999 + Effect.succeed(
1000 + request.headers.authorization === `Bearer ${clientToken}`
1001 + ? clientScope
1002 + : undefined,
1003 + ),
1004 + }),
1005 + ),
1006 + );
1007 + yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1008 + Layer.build,
1009 + );
1010 + const httpClient = yield* HttpClient.HttpClient;
1011 + const decodeOutcome = Schema.decodeUnknownEffect(
1012 + Schema.fromJsonString(
1013 + Schema.Struct({
1014 + result: Schema.Struct({
1015 + content: Schema.Array(Schema.Struct({ text: Schema.String })),
1016 + }),
1017 + }),
1018 + ),
1019 + );
1020 + const decodeText = Schema.decodeUnknownEffect(
1021 + Schema.fromJsonString(
1022 + Schema.Union([
1023 + Schema.Struct({ modes: Schema.String }),
1024 + Schema.Struct({ code: Schema.String }),
1025 + ]),
1026 + ),
1027 + );
1028 + /** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1029 + const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1030 + Effect.gen(function* () {
1031 + const headers = {
1032 + accept: "application/json, text/event-stream",
1033 + authorization: `Bearer ${clientToken}`,
1034 + ...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1035 + };
1036 + const initialize = yield* httpClient.post("/mcp", {
1037 + headers,
1038 + body: HttpBody.text(
1039 + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1040 + "application/json",
1041 + ),
1042 + });
1043 + if (initialize.status !== 200) return initialize.status;
1044 + const response = yield* httpClient.post("/mcp", {
1045 + headers: {
1046 + ...headers,
1047 + "mcp-session-id": initialize.headers["mcp-session-id"]!,
1048 + "mcp-protocol-version": "2025-06-18",
1049 + },
1050 + body: HttpBody.text(
1051 + JSON.stringify({
1052 + jsonrpc: "2.0",
1053 + id: 2,
1054 + method: "tools/call",
1055 + params: { name: "starts", arguments: args },
1056 + }),
1057 + "application/json",
1058 + ),
1059 + });
1060 + const body = yield* decodeOutcome(yield* response.text);
1061 + const outcome = yield* decodeText(
1062 + body.result.content.map((part) => part.text).join(""),
1063 + );
1064 + return "code" in outcome ? outcome.code : outcome.modes;
1065 + });
1066 +
1067 + // Approved for auto: without the header the client keeps its ceiling.
1068 + expect(yield* start(undefined)).toBe("auto/default");
1069 + // The header narrows both modes, and asking above it is refused.
1070 + expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
1071 + expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
1072 + "runtime_mode_escalation_denied",
1073 + );
1074 + expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
1075 + "interaction_mode_escalation_denied",
1076 + );
1077 + // A broader header changes nothing: the approved ceiling still holds.
1078 + expect(yield* start("full-access/default")).toBe("auto/default");
1079 + expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
1080 + "runtime_mode_escalation_denied",
1081 + );
1082 + // A malformed header is refused before anything runs.
1083 + expect(yield* start("auto")).toBe(400);
1084 + expect(yield* start("auto/default/extra")).toBe(400);
1085 + expect(yield* start("root/default")).toBe(400);
1086 + }),
1087 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
1088 +);
apps/server/src/mcp/McpHttpServer.ts
+34 -1
@@ -16,7 +16,9 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16 import {
17 OrchestratorMcpFailure,
18 PreviewAutomationError,
19 + ProviderInteractionMode,
20 type RunId,
21 + RuntimeMode,
22 ThreadId,
23 } from "@t3tools/contracts";
24
@@ -150,6 +152,35 @@ const normalizeMcpHttpResponse = (
152 // Session tokens are `<payload>.<signature>`; registry tokens are a bare base64url secret.
153 const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
154
155 +const decodeModeLimit = Schema.decodeUnknownOption(
156 + Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode }),
157 +);
158 +const parseModeLimit = (value: string) => {
159 + const [runtimeMode, interactionMode, ...rest] = value.trim().split("/");
160 + return rest.length === 0 ? decodeModeLimit({ runtimeMode, interactionMode }) : Option.none();
161 +};
162 +
163 +const invalidModeLimit = HttpServerResponse.jsonUnsafe(
164 + {
165 + error: "invalid_mode_limit",
166 + message: "T3-Mode-Limit must be <runtimeMode>/<interactionMode>, e.g. auto/default.",
167 + },
168 + { status: 400, headers: { "cache-control": "no-store" } },
169 +);
170 +
171 +/** Applies a client's requested mode limit; undefined when the header is malformed. */
172 +const withModeLimit = (
173 + invocation: McpInvocationContext.McpInvocationScope,
174 + request: HttpServerRequest.HttpServerRequest,
175 +): McpInvocationContext.McpInvocationScope | undefined => {
176 + const header = request.headers[McpInvocationContext.MODE_LIMIT_HEADER];
177 + if (header === undefined || invocation.client === undefined) return invocation;
178 + const limit = parseModeLimit(header);
179 + return Option.isNone(limit)
180 + ? undefined
181 + : { ...invocation, client: { ...invocation.client, narrowedTo: limit.value } };
182 +};
183 +
184 const makeMcpAuthMiddleware = Effect.gen(function* () {
185 const registry = yield* McpSessionRegistry.McpSessionRegistry;
186 const clients = yield* Effect.serviceOption(McpClientAuthenticator);
@@ -175,8 +206,10 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
206 offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
207 });
208 }
209 + const limited = withModeLimit(invocation, request);
210 + if (limited === undefined) return invalidModeLimit;
211 return yield* httpEffect.pipe(
179 - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
212 + Effect.provideService(McpInvocationContext.McpInvocationContext, limited),
213 Effect.map(normalizeMcpHttpResponse),
214 );
215 }) satisfies McpAuthMiddleware;
apps/server/src/mcp/McpInvocationContext.ts
+52 -3
@@ -5,6 +5,7 @@ import {
5 OrchestratorMcpFailure,
6 PreviewAutomationUnavailableError,
7 type ProviderInstanceId,
8 + type ProviderInteractionMode,
9 type RuntimeMode,
10 type ThreadId,
11 } from "@t3tools/contracts";
@@ -33,11 +34,59 @@ export interface McpClientCaller {
34 readonly sessionId: string;
35 readonly label: string;
36 readonly access: AuthMcpClientAccess;
37 + /**
38 + * Narrower modes the client asked for on this request (`T3-Mode-Limit`):
39 + * another environment passing on the limits of the agent it calls for.
40 + */
41 + readonly narrowedTo?: ClientModes | undefined;
42 }
43
38 -/** Read-only clients map to the lowest mode because McpToolAccess blocks writes first. */
39 -export const clientRuntimeModeCeiling = (client: McpClientCaller | undefined): RuntimeMode =>
40 - client === undefined || client.access === "read-only" ? "approval-required" : client.access;
44 +/**
45 + * `T3-Mode-Limit: <runtimeMode>/<interactionMode>` lets an OAuth client cap
46 + * a request below what it was approved with: another environment passes on
47 + * the limits of the agent it calls for. It can only narrow (see
48 + * `clientModeCeiling`), so a client gains nothing by sending a broad one.
49 + */
50 +export const MODE_LIMIT_HEADER = "t3-mode-limit";
51 +
52 +export interface ClientModes {
53 + readonly runtimeMode: RuntimeMode;
54 + readonly interactionMode: ProviderInteractionMode;
55 +}
56 +
57 +const runtimeModeRank: Record<RuntimeMode, number> = {
58 + "approval-required": 0,
59 + "auto-accept-edits": 1,
60 + auto: 2,
61 + "full-access": 3,
62 +};
63 +const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
64 +
65 +/**
66 + * The modes a client caller's writes are capped at: what it was approved
67 + * with, narrowed by what it asked for on this request. A read-only client
68 + * never reaches a write (`McpToolAccess` refuses it first), so it maps to the
69 + * lowest runtime mode rather than to nothing.
70 + */
71 +export const clientModeCeiling = (client: McpClientCaller | undefined): ClientModes => {
72 + const approved: ClientModes = {
73 + runtimeMode:
74 + client === undefined || client.access === "read-only" ? "approval-required" : client.access,
75 + interactionMode: "default",
76 + };
77 + const asked = client?.narrowedTo;
78 + if (asked === undefined) return approved;
79 + return {
80 + runtimeMode:
81 + runtimeModeRank[asked.runtimeMode] < runtimeModeRank[approved.runtimeMode]
82 + ? asked.runtimeMode
83 + : approved.runtimeMode,
84 + interactionMode:
85 + interactionModeRank[asked.interactionMode] < interactionModeRank[approved.interactionMode]
86 + ? asked.interactionMode
87 + : approved.interactionMode,
88 + };
89 +};
90
91 /** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
92 export interface McpInvocationScope {
apps/server/src/mcp/OrchestratorMcpService.ts
+2 -5
@@ -106,7 +106,7 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
106 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
107 import * as ServerSettings from "../serverSettings.ts";
108 import {
109 - clientRuntimeModeCeiling,
109 + clientModeCeiling,
110 type McpInvocationScope,
111 type McpThreadInvocationScope,
112 requireThreadScope,
@@ -1153,10 +1153,7 @@ const make = Effect.gen(function* () {
1153 if (scope.thread === undefined) {
1154 return {
1155 parent: undefined,
1156 - limits: {
1157 - runtimeMode: clientRuntimeModeCeiling(scope.client),
1158 - interactionMode: "default",
1159 - } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },
1156 + limits: clientModeCeiling(scope.client),
1157 } as const;
1158 }
1159 const parent = yield* loadProjection(scope.thread.threadId);
apps/server/src/mcp/threadAccess.ts
+1 -4
@@ -68,10 +68,7 @@ export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
68 scope,
69 threads,
70 caller: undefined,
71 - limits: {
72 - runtimeMode: McpInvocationContext.clientRuntimeModeCeiling(scope.client),
73 - interactionMode: "default",
74 - },
71 + limits: McpInvocationContext.clientModeCeiling(scope.client),
72 } satisfies Caller;
73 }
74 const caller = yield* threads