Skip to content

Commit 77ec4c8

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 611132c commit 77ec4c8

5 files changed

Lines changed: 235 additions & 15 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";
@@ -1067,3 +1070,145 @@ it.effect("admits provider and OAuth client credentials and points only clients
10671070
}),
10681071
).pipe(Effect.provide(NodeHttpServer.layerTest)),
10691072
);
1073+
1074+
it.effect(
1075+
"narrows an OAuth client's modes to the T3-Mode-Limit it sends, and never widens them",
1076+
() =>
1077+
Effect.scoped(
1078+
Effect.gen(function* () {
1079+
const clientToken = "client-payload.client-signature";
1080+
const clientScope: McpInvocationContext.McpInvocationScope = {
1081+
environmentId,
1082+
requestNamespace: "client:linked",
1083+
thread: undefined,
1084+
client: { sessionId: "linked", label: "T3 Code · laptop", access: "auto" },
1085+
capabilities: new Set(["orchestration"]),
1086+
issuedAt: 1,
1087+
};
1088+
// Starts a thread at the modes the gate hands it, so the outcome is those modes.
1089+
const StartsToolkit = Toolkit.make(
1090+
Tool.make("starts", {
1091+
description: "Reports the modes a started thread would run with.",
1092+
parameters: Schema.Struct({
1093+
runtimeMode: Schema.optional(RuntimeMode),
1094+
interactionMode: Schema.optional(ProviderInteractionMode),
1095+
}),
1096+
success: Schema.Struct({ modes: Schema.String }),
1097+
failure: OrchestratorMcpFailure,
1098+
failureMode: "return",
1099+
dependencies: [
1100+
McpInvocationContext.McpInvocationContext,
1101+
ThreadManagementService.ThreadManagementService,
1102+
],
1103+
}),
1104+
);
1105+
const serverLayer = McpHttpServer.toolkitRegistration(
1106+
StartsToolkit,
1107+
McpToolAccess.toLayer(StartsToolkit, {
1108+
starts: McpToolAccess.startsThreads(
1109+
(input) => input,
1110+
(_, modes) =>
1111+
Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1112+
),
1113+
}),
1114+
).pipe(
1115+
Layer.provideMerge(McpHttpServer.layerMcpTransport),
1116+
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
1117+
Layer.provide(
1118+
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
1119+
resolve: () => Effect.succeed(undefined),
1120+
}),
1121+
),
1122+
Layer.provide(
1123+
Layer.succeed(McpHttpServer.McpClientAuthenticator, {
1124+
authenticate: (request) =>
1125+
Effect.succeed(
1126+
request.headers.authorization === `Bearer ${clientToken}`
1127+
? clientScope
1128+
: undefined,
1129+
),
1130+
}),
1131+
),
1132+
);
1133+
yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe(
1134+
Layer.build,
1135+
);
1136+
const httpClient = yield* HttpClient.HttpClient;
1137+
const decodeOutcome = Schema.decodeUnknownEffect(
1138+
Schema.fromJsonString(
1139+
Schema.Struct({
1140+
result: Schema.Struct({
1141+
content: Schema.Array(Schema.Struct({ text: Schema.String })),
1142+
}),
1143+
}),
1144+
),
1145+
);
1146+
const decodeText = Schema.decodeUnknownEffect(
1147+
Schema.fromJsonString(
1148+
Schema.Union([
1149+
Schema.Struct({ modes: Schema.String }),
1150+
Schema.Struct({ code: Schema.String }),
1151+
]),
1152+
),
1153+
);
1154+
/** Starts a thread as the client, with `limit` as T3-Mode-Limit; the HTTP status or the outcome. */
1155+
const start = (limit: string | undefined, args: Record<string, string> = {}) =>
1156+
Effect.gen(function* () {
1157+
const headers = {
1158+
accept: "application/json, text/event-stream",
1159+
authorization: `Bearer ${clientToken}`,
1160+
...(limit === undefined ? {} : { "t3-mode-limit": limit }),
1161+
};
1162+
const initialize = yield* httpClient.post("/mcp", {
1163+
headers,
1164+
body: HttpBody.text(
1165+
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`,
1166+
"application/json",
1167+
),
1168+
});
1169+
if (initialize.status !== 200) return initialize.status;
1170+
const response = yield* httpClient.post("/mcp", {
1171+
headers: {
1172+
...headers,
1173+
"mcp-session-id": initialize.headers["mcp-session-id"]!,
1174+
"mcp-protocol-version": "2025-06-18",
1175+
},
1176+
body: HttpBody.text(
1177+
JSON.stringify({
1178+
jsonrpc: "2.0",
1179+
id: 2,
1180+
method: "tools/call",
1181+
params: { name: "starts", arguments: args },
1182+
}),
1183+
"application/json",
1184+
),
1185+
});
1186+
const body = yield* decodeOutcome(yield* response.text);
1187+
const outcome = yield* decodeText(
1188+
body.result.content.map((part) => part.text).join(""),
1189+
);
1190+
return "code" in outcome ? outcome.code : outcome.modes;
1191+
});
1192+
1193+
// Approved for auto: without the header the client keeps its ceiling.
1194+
expect(yield* start(undefined)).toBe("auto/default");
1195+
// The header narrows both modes, and asking above it is refused.
1196+
expect(yield* start("approval-required/plan")).toBe("approval-required/plan");
1197+
expect(yield* start("approval-required/plan", { runtimeMode: "auto" })).toBe(
1198+
"runtime_mode_escalation_denied",
1199+
);
1200+
expect(yield* start("auto-accept-edits/plan", { interactionMode: "default" })).toBe(
1201+
"interaction_mode_escalation_denied",
1202+
);
1203+
// A broader header changes nothing: the approved ceiling still holds.
1204+
expect(yield* start("full-access/default")).toBe("auto/default");
1205+
expect(yield* start("full-access/default", { runtimeMode: "full-access" })).toBe(
1206+
"runtime_mode_escalation_denied",
1207+
);
1208+
// A malformed header is refused before anything runs.
1209+
expect(yield* start("auto")).toBe(400);
1210+
expect(yield* start("auto/default/extra")).toBe(400);
1211+
expect(yield* start("root/default")).toBe(400);
1212+
}),
1213+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
1214+
);

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

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@ import * as Stream from "effect/Stream";
1313
import type * as Types from "effect/Types";
1414
import { AiError, McpProtocol, McpSchema, McpServer, Tool, type Toolkit } from "effect/ai";
1515
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16-
import { OrchestratorMcpFailure, PreviewAutomationError } from "@t3tools/contracts";
16+
import {
17+
OrchestratorMcpFailure,
18+
PreviewAutomationError,
19+
ProviderInteractionMode,
20+
RuntimeMode,
21+
} from "@t3tools/contracts";
1722

1823
import packageJson from "../../package.json" with { type: "json" };
1924
import * as ServerConfig from "../config.ts";
@@ -144,6 +149,35 @@ export const normalizeMcpHttpResponse = (
144149
// Session tokens are `<payload>.<signature>`; registry tokens are a bare base64url secret.
145150
const looksLikeProviderToken = (token: string) => token.length > 0 && !token.includes(".");
146151

152+
const decodeModeLimit = Schema.decodeUnknownOption(
153+
Schema.Struct({ runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode }),
154+
);
155+
const parseModeLimit = (value: string) => {
156+
const [runtimeMode, interactionMode, ...rest] = value.trim().split("/");
157+
return rest.length === 0 ? decodeModeLimit({ runtimeMode, interactionMode }) : Option.none();
158+
};
159+
160+
const invalidModeLimit = HttpServerResponse.jsonUnsafe(
161+
{
162+
error: "invalid_mode_limit",
163+
message: "T3-Mode-Limit must be <runtimeMode>/<interactionMode>, e.g. auto/default.",
164+
},
165+
{ status: 400, headers: { "cache-control": "no-store" } },
166+
);
167+
168+
/** Applies a client's requested mode limit; undefined when the header is malformed. */
169+
const withModeLimit = (
170+
invocation: McpInvocationContext.McpInvocationScope,
171+
request: HttpServerRequest.HttpServerRequest,
172+
): McpInvocationContext.McpInvocationScope | undefined => {
173+
const header = request.headers[McpInvocationContext.MODE_LIMIT_HEADER];
174+
if (header === undefined || invocation.client === undefined) return invocation;
175+
const limit = parseModeLimit(header);
176+
return Option.isNone(limit)
177+
? undefined
178+
: { ...invocation, client: { ...invocation.client, narrowedTo: limit.value } };
179+
};
180+
147181
const makeMcpAuthMiddleware = Effect.gen(function* () {
148182
const registry = yield* McpSessionRegistry.McpSessionRegistry;
149183
const clients = yield* Effect.serviceOption(McpClientAuthenticator);
@@ -172,8 +206,10 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
172206
offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
173207
});
174208
}
209+
const limited = withModeLimit(invocation, request);
210+
if (limited === undefined) return invalidModeLimit;
175211
return yield* httpEffect.pipe(
176-
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
212+
Effect.provideService(McpInvocationContext.McpInvocationContext, limited),
177213
Effect.map(normalizeMcpHttpResponse),
178214
);
179215
}) satisfies McpAuthMiddleware;

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

Lines changed: 49 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";
@@ -33,15 +34,59 @@ export interface McpClientCaller {
3334
readonly label: string;
3435
/** Read only, or the most the threads it starts or changes may run with. */
3536
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;
3642
}
3743

3844
/**
39-
* The runtime mode a client caller's writes are capped at. A read-only client
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
4068
* never reaches a write (`McpToolAccess` refuses it first), so it maps to the
41-
* lowest mode rather than to nothing.
69+
* lowest runtime mode rather than to nothing.
4270
*/
43-
export const clientRuntimeModeCeiling = (client: McpClientCaller | undefined): RuntimeMode =>
44-
client === undefined || client.access === "read-only" ? "approval-required" : client.access;
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+
};
4590

4691
/**
4792
* Who is calling and what they may do. Tool parameters choose the target

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

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ import * as ProjectService from "../project/ProjectService.ts";
8888
import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
8989
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
9090
import {
91-
clientRuntimeModeCeiling,
91+
clientModeCeiling,
9292
type McpInvocationScope,
9393
type McpThreadInvocationScope,
9494
requireThreadScope,
@@ -948,10 +948,7 @@ const make = Effect.gen(function* () {
948948
if (scope.thread === undefined) {
949949
return {
950950
parent: undefined,
951-
limits: {
952-
runtimeMode: clientRuntimeModeCeiling(scope.client),
953-
interactionMode: "default",
954-
} satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode },
951+
limits: clientModeCeiling(scope.client),
955952
} as const;
956953
}
957954
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
@@ -75,10 +75,7 @@ export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
7575
scope,
7676
threads,
7777
caller: undefined,
78-
limits: {
79-
runtimeMode: McpInvocationContext.clientRuntimeModeCeiling(scope.client),
80-
interactionMode: "default",
81-
},
78+
limits: McpInvocationContext.clientModeCeiling(scope.client),
8279
} satisfies Caller;
8380
}
8481
const caller = yield* threads

0 commit comments

Comments
 (0)