Skip to content

Commit 48c6bf4

Browse files
feat(server): /mcp narrows a client's modes from T3-Mode-Limit
An OAuth client on /mcp is capped by the access it was approved with. When another environment calls on behalf of one of its agents, that agent may run under narrower modes, and the target has no way to know. /mcp now reads `T3-Mode-Limit: <runtimeMode>/<interactionMode>` from OAuth clients and caps the request at the narrower of the two. The header can only narrow: a broader one changes nothing, and a malformed one is refused with 400. The client's interaction mode can now be capped too; before, it was always default. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 1451e7c commit 48c6bf4

5 files changed

Lines changed: 232 additions & 14 deletions

File tree

‎apps/server/src/mcp/McpHttpServer.test.ts‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
22
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
3+
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
34
import { expect, it } from "@effect/vitest";
45
import { NodeHttpServer } from "@effect/platform-node";
56
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -8,6 +9,8 @@ import {
89
OrchestratorMcpFailure,
910
PreviewTabId,
1011
ProviderInstanceId,
12+
ProviderInteractionMode,
13+
RuntimeMode,
1114
ThreadId,
1215
} from "@t3tools/contracts";
1316
import * as Deferred from "effect/Deferred";
@@ -1178,3 +1181,145 @@ it.effect("admits provider and OAuth client credentials and points only clients
11781181
}),
11791182
).pipe(Effect.provide(NodeHttpServer.layerTest)),
11801183
);
1184+
1185+
it.effect(
1186+
"narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
1187+
() =>
1188+
Effect.scoped(
1189+
Effect.gen(function* () {
1190+
const clientToken = "client-payload.client-signature";
1191+
const clientScope: McpInvocationContext.McpInvocationScope = {
1192+
environmentId,
1193+
requestNamespace: "client:linked",
1194+
thread: undefined,
1195+
client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
1196+
capabilities: new Set(["orchestration"]),
1197+
issuedAt: 1,
1198+
};
1199+
// Starts a thread at the modes the gate hands it, so the outcome is those modes.
1200+
const StartsToolkit = Toolkit.make(
1201+
Tool.make("starts", {
1202+
description: "Reports the modes a started thread would run with.",
1203+
parameters: Schema.Struct({
1204+
runtimeMode: Schema.optional(RuntimeMode),
1205+
interactionMode: Schema.optional(ProviderInteractionMode),
1206+
}),
1207+
success: Schema.Struct({ modes: Schema.String }),
1208+
failure: OrchestratorMcpFailure,
1209+
failureMode: "return",
1210+
dependencies: [
1211+
McpInvocationContext.McpInvocationContext,
1212+
ThreadManagementService.ThreadManagementService,
1213+
],
1214+
}),
1215+
);
1216+
const serverLayer = McpHttpServer.toolkitRegistration(
1217+
StartsToolkit,
1218+
McpToolAccess.toLayer(StartsToolkit, {
1219+
starts: McpToolAccess.startsThreads(
1220+
(input) => input,
1221+
(_, modes) =>
1222+
Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1223+
),
1224+
}),
1225+
).pipe(
1226+
Layer.provideMerge(McpHttpServer.layerMcpTransport),
1227+
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1228+
Layer.provide(
1229+
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1230+
resolve: () => Effect.succeed(undefined),
1231+
}),
1232+
),
1233+
Layer.provide(
1234+
Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1235+
authenticate: (request) =>
1236+
Effect.succeed(
1237+
request.headers.authorization === `Bearer ${clientToken}`
1238+
? clientScope
1239+
: undefined,
1240+
),
1241+
}),
1242+
),
1243+
);
1244+
yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1245+
Layer.build,
1246+
);
1247+
const httpClient = yield* HttpClient.HttpClient;
1248+
const decodeOutcome = Schema.decodeUnknownEffect(
1249+
Schema.fromJsonString(
1250+
Schema.Struct({
1251+
result: Schema.Struct({
1252+
content: Schema.Array(Schema.Struct({ text: Schema.String })),
1253+
}),
1254+
}),
1255+
),
1256+
);
1257+
const decodeText = Schema.decodeUnknownEffect(
1258+
Schema.fromJsonString(
1259+
Schema.Union([
1260+
Schema.Struct({ modes: Schema.String }),
1261+
Schema.Struct({ code: Schema.String }),
1262+
]),
1263+
),
1264+
);
1265+
/** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1266+
const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1267+
Effect.gen(function* () {
1268+
const headers = {
1269+
accept: "application/json, text/event-stream",
1270+
authorization: `Bearer ${clientToken}`,
1271+
...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1272+
};
1273+
const initialize = yield* httpClient.post("/mcp", {
1274+
headers,
1275+
body: HttpBody.text(
1276+
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1277+
"application/json",
1278+
),
1279+
});
1280+
if (initialize.status !== 200) return initialize.status;
1281+
const response = yield* httpClient.post("/mcp", {
1282+
headers: {
1283+
...headers,
1284+
"mcp-session-id": initialize.headers["mcp-session-id"]!,
1285+
"mcp-protocol-version": "2025-06-18",
1286+
},
1287+
body: HttpBody.text(
1288+
JSON.stringify({
1289+
jsonrpc: "2.0",
1290+
id: 2,
1291+
method: "tools/call",
1292+
params: { name: "starts", arguments: args },
1293+
}),
1294+
"application/json",
1295+
),
1296+
});
1297+
const body = yield* decodeOutcome(yield* response.text);
1298+
const outcome = yield* decodeText(
1299+
body.result.content.map((part) => part.text).join(""),
1300+
);
1301+
return "code" in outcome ? outcome.code : outcome.modes;
1302+
});
1303+
1304+
// Approved for auto: without the header the client keeps its ceiling.
1305+
expect(yield* start(undefined)).toBe("auto/default");
1306+
// The header narrows both modes, and asking above it is refused.
1307+
expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
1308+
expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
1309+
"runtime_mode_escalation_denied",
1310+
);
1311+
expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
1312+
"interaction_mode_escalation_denied",
1313+
);
1314+
// A broader header changes nothing: the approved ceiling still holds.
1315+
expect(yield* start("full-access/default")).toBe("auto/default");
1316+
expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
1317+
"runtime_mode_escalation_denied",
1318+
);
1319+
// A malformed header is refused before anything runs.
1320+
expect(yield* start("auto")).toBe(400);
1321+
expect(yield* start("auto/default/extra")).toBe(400);
1322+
expect(yield* start("root/default")).toBe(400);
1323+
}),
1324+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
1325+
);

‎apps/server/src/mcp/McpHttpServer.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import {
1818
PreviewAutomationError,
1919
type RunId,
2020
ThreadId,
21+
ProviderInteractionMode,
22+
RuntimeMode,
2123
} from "@t3tools/contracts";
2224

2325
import packageJson from "../../package.json" with { type: "json" };
@@ -153,6 +155,35 @@ export const normalizeMcpHttpResponse = (
153155
// Session tokens are `<payload>.<signature>`; registry tokens are a bare base64url secret.
154156
const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
155157

158+
const decodeModeLimit = Schema.decodeUnknownOption(
159+
Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode }),
160+
);
161+
const parseModeLimit = (value: string) => {
162+
const [runtimeMode, interactionMode, ...rest] = value.trim().split("/");
163+
return rest.length === 0 ? decodeModeLimit({ runtimeMode, interactionMode }) : Option.none();
164+
};
165+
166+
const invalidModeLimit = HttpServerResponse.jsonUnsafe(
167+
{
168+
error: "invalid_mode_limit",
169+
message: "T3-Mode-Limit must be <runtimeMode>/<interactionMode>, e.g. auto/default.",
170+
},
171+
{ status: 400, headers: { "cache-control": "no-store" } },
172+
);
173+
174+
/** Applies a client's requested mode limit; undefined when the header is malformed. */
175+
const withModeLimit = (
176+
invocation: McpInvocationContext.McpInvocationScope,
177+
request: HttpServerRequest.HttpServerRequest,
178+
): McpInvocationContext.McpInvocationScope | undefined => {
179+
const header = request.headers[McpInvocationContext.MODE_LIMIT_HEADER];
180+
if (header === undefined || invocation.client === undefined) return invocation;
181+
const limit = parseModeLimit(header);
182+
return Option.isNone(limit)
183+
? undefined
184+
: { ...invocation, client: { ...invocation.client, narrowedTo: limit.value } };
185+
};
186+
156187
const makeMcpAuthMiddleware = Effect.gen(function* () {
157188
const registry = yield* McpSessionRegistry.McpSessionRegistry;
158189
const clients = yield* Effect.serviceOption(McpClientAuthenticator);
@@ -178,8 +209,10 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
178209
offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
179210
});
180211
}
212+
const limited = withModeLimit(invocation, request);
213+
if (limited === undefined) return invalidModeLimit;
181214
return yield* httpEffect.pipe(
182-
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
215+
Effect.provideService(McpInvocationContext.McpInvocationContext, limited),
183216
Effect.map(normalizeMcpHttpResponse),
184217
);
185218
}) satisfies McpAuthMiddleware;

‎apps/server/src/mcp/McpInvocationContext.ts‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
OrchestratorMcpFailure,
66
PreviewAutomationUnavailableError,
77
type ProviderInstanceId,
8+
type ProviderInteractionMode,
89
type RuntimeMode,
910
type ThreadId,
1011
} from "@t3tools/contracts";
@@ -30,14 +31,59 @@ export interface McpClientCaller {
3031
readonly sessionId: string;
3132
readonly label: string;
3233
readonly access: AuthMcpClientAccess;
34+
/**
35+
* Narrower modes the client asked for on this request (`T3-Mode-Limit`):
36+
* another environment passing on the limits of the agent it calls for.
37+
*/
38+
readonly narrowedTo?: ClientModes | undefined;
3339
}
3440

3541
/**
36-
* A read-only client never reaches a write (`McpToolAccess` refuses it first),
37-
* so it maps to the lowest mode rather than to nothing.
42+
* `T3-Mode-Limit: <runtimeMode>/<interactionMode>` lets an OAuth client cap
43+
* a request below what it was approved with: another environment passes on
44+
* the limits of the agent it calls for. It can only narrow (see
45+
* `clientModeCeiling`), so a client gains nothing by sending a broad one.
3846
*/
39-
export const clientRuntimeModeCeiling = (client: McpClientCaller | undefined): RuntimeMode =>
40-
client === undefined || client.access === "read-only" ? "approval-required" : client.access;
47+
export const MODE_LIMIT_HEADER = "t3-mode-limit";
48+
49+
export interface ClientModes {
50+
readonly runtimeMode: RuntimeMode;
51+
readonly interactionMode: ProviderInteractionMode;
52+
}
53+
54+
const runtimeModeRank: Record<RuntimeMode, number> = {
55+
"approval-required": 0,
56+
"auto-accept-edits": 1,
57+
auto: 2,
58+
"full-access": 3,
59+
};
60+
const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
61+
62+
/**
63+
* The modes a client caller's writes are capped at: what it was approved
64+
* with, narrowed by what it asked for on this request. A read-only client
65+
* never reaches a write (`McpToolAccess` refuses it first), so it maps to the
66+
* lowest runtime mode rather than to nothing.
67+
*/
68+
export const clientModeCeiling = (client: McpClientCaller | undefined): ClientModes => {
69+
const approved: ClientModes = {
70+
runtimeMode:
71+
client === undefined || client.access === "read-only" ? "approval-required" : client.access,
72+
interactionMode: "default",
73+
};
74+
const asked = client?.narrowedTo;
75+
if (asked === undefined) return approved;
76+
return {
77+
runtimeMode:
78+
runtimeModeRank[asked.runtimeMode] < runtimeModeRank[approved.runtimeMode]
79+
? asked.runtimeMode
80+
: approved.runtimeMode,
81+
interactionMode:
82+
interactionModeRank[asked.interactionMode] < interactionModeRank[approved.interactionMode]
83+
? asked.interactionMode
84+
: approved.interactionMode,
85+
};
86+
};
4187

4288
/**
4389
* A thread caller's omitted target falls back to its own thread; a client

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
9898
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
9999
import * as ServerSettings from "../serverSettings.ts";
100100
import {
101-
clientRuntimeModeCeiling,
101+
clientModeCeiling,
102102
type McpInvocationScope,
103103
type McpThreadInvocationScope,
104104
requireThreadScope,
@@ -1025,10 +1025,7 @@ const make = Effect.gen(function* () {
10251025
if (scope.thread === undefined) {
10261026
return {
10271027
parent: undefined,
1028-
limits: {
1029-
runtimeMode: clientRuntimeModeCeiling(scope.client),
1030-
interactionMode: "default",
1031-
} satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },
1028+
limits: clientModeCeiling(scope.client),
10321029
} as const;
10331030
}
10341031
const parent = yield* loadProjection(scope.thread.threadId);

‎apps/server/src/mcp/threadAccess.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,7 @@ export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
6868
scope,
6969
threads,
7070
caller: undefined,
71-
limits: {
72-
runtimeMode: McpInvocationContext.clientRuntimeModeCeiling(scope.client),
73-
interactionMode: "default",
74-
},
71+
limits: McpInvocationContext.clientModeCeiling(scope.client),
7572
} satisfies Caller;
7673
}
7774
const caller = yield* threads

0 commit comments

Comments
 (0)