Skip to content

Commit ee5bbde

Browse files
feat(server): work a linked environment starts stays within its link
A link's T3-Mode-Limit caps the modes of what it starts, but within those modes it could still steer the user's own threads or change this environment's projects and settings. Work a link starts is now fenced to that link. The linking side registers its OAuth client with the t3code-peer-link software id; the receiving side signs that into the session's claims. Every thread such a session launches carries an immutable linkOrigin, and so do the subagents, forks and create_threads it derives. A client's own thread.create cannot set one. In the shared access declarations, a linked caller may change only threads of the same link, and may not use writesEnvironment tools (projects, settings), schedule tasks, or change scheduled tasks. Reads are not fenced. Setup scripts are skipped for stamped threads in ProjectSetupScriptRunner, which every path that runs them goes through. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 8b5d382 commit ee5bbde

32 files changed

Lines changed: 712 additions & 52 deletions

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ export interface McpClientSession {
9090
readonly sessionId: AuthSessionId;
9191
readonly label: string;
9292
readonly access: AuthMcpClientAccess;
93+
/** Another T3 Code environment's link, whose work here stays within it. */
94+
readonly peerLink: boolean;
9395
}
9496

9597
export interface AuthenticatedSession {
@@ -552,6 +554,7 @@ export class EnvironmentAuth extends Context.Service<
552554
readonly issueMcpClientSession: (input: {
553555
readonly label: string;
554556
readonly access: AuthMcpClientAccess;
557+
readonly peerLink: boolean;
555558
readonly client: AuthClientMetadata;
556559
}) => Effect.Effect<
557560
{ readonly token: string; readonly expiresAt: DateTime.DateTime },
@@ -1206,6 +1209,7 @@ export const make = Effect.gen(function* () {
12061209
access: session.scopes.includes(AuthOrchestrationOperateScope)
12071210
? (session.runtimeModeCeiling ?? "approval-required")
12081211
: "read-only",
1212+
peerLink: session.peerLink === true,
12091213
} satisfies McpClientSession)
12101214
: Effect.fail(
12111215
new ServerAuthInvalidCredentialError({
@@ -1225,6 +1229,7 @@ export const make = Effect.gen(function* () {
12251229
scopes: mcpClientScopes(input.access),
12261230
ttl: MCP_CLIENT_SESSION_TTL,
12271231
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
1232+
peerLink: input.peerLink,
12281233
client: { ...input.client, label: input.label, deviceType: "bot" },
12291234
})
12301235
.pipe(

‎apps/server/src/auth/McpOAuth.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
type AuthEnvironmentScope,
1414
AuthOrchestrationOperateScope,
1515
AuthOrchestrationReadScope,
16+
MCP_PEER_LINK_SOFTWARE_ID,
1617
} from "@t3tools/contracts";
1718
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
1819
import * as Clock from "effect/Clock";
@@ -152,13 +153,16 @@ const ClientIdPayload = Schema.Struct({
152153
v: Schema.Literal(1),
153154
n: Schema.String,
154155
r: Schema.Array(Schema.String),
156+
/** Registered as another T3 Code environment's peer link. */
157+
p: Schema.optionalKey(Schema.Literal(1)),
155158
});
156159
const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
157160

158161
export interface McpOAuthClient {
159162
readonly clientId: string;
160163
readonly name: string;
161164
readonly redirectUris: ReadonlyArray<string>;
165+
readonly peerLink: boolean;
162166
}
163167

164168
/** Problems the authorize page shows the user without redirecting anywhere. */
@@ -194,6 +198,7 @@ export interface AuthorizationRequest {
194198
interface PendingCode {
195199
readonly clientId: string;
196200
readonly clientName: string;
201+
readonly peerLink: boolean;
197202
readonly redirectUri: string;
198203
readonly codeChallenge: string;
199204
readonly resource: string;
@@ -269,8 +274,10 @@ const make = Effect.gen(function* () {
269274

270275
const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
271276

272-
const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
273-
const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
277+
const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => {
278+
const body = base64UrlEncode(
279+
JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }),
280+
);
274281
return `${body}.${sign("mcp-client-id", body)}`;
275282
};
276283

@@ -286,7 +293,12 @@ const make = Effect.gen(function* () {
286293
}
287294
return Option.getOrUndefined(
288295
decodeClientIdPayload(json).pipe(
289-
Option.map((payload) => ({ clientId, name: payload.n, redirectUris: payload.r })),
296+
Option.map((payload) => ({
297+
clientId,
298+
name: payload.n,
299+
redirectUris: payload.r,
300+
peerLink: payload.p === 1,
301+
})),
290302
),
291303
);
292304
};
@@ -335,7 +347,13 @@ const make = Effect.gen(function* () {
335347
// than rejected: RFC 7591 lets the server answer with what it supports. Claude Code
336348
// asks for refresh_token, and hosted agents may ask for a client secret; every client
337349
// is registered as public and proves itself with PKCE instead.
338-
return { clientId: signClientId(name, redirectUris), name, redirectUris };
350+
const peerLink = metadata.software_id === MCP_PEER_LINK_SOFTWARE_ID;
351+
return {
352+
clientId: signClientId(name, redirectUris, peerLink),
353+
name,
354+
redirectUris,
355+
peerLink,
356+
};
339357
});
340358

341359
const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = ({ urls, request }) =>
@@ -418,6 +436,7 @@ const make = Effect.gen(function* () {
418436
next.set(code, {
419437
clientId: authorization.client.clientId,
420438
clientName: authorization.client.name,
439+
peerLink: authorization.client.peerLink,
421440
redirectUri: authorization.redirectUri,
422441
codeChallenge: authorization.codeChallenge,
423442
resource: authorization.resource,
@@ -522,6 +541,7 @@ const make = Effect.gen(function* () {
522541
.issueMcpClientSession({
523542
label: pending.clientName,
524543
access: pending.access,
544+
peerLink: pending.peerLink,
525545
client: deriveAuthClientMetadata({ request }),
526546
})
527547
.pipe(
@@ -577,6 +597,7 @@ export const layerMcpClientAuthenticator = Layer.effect(
577597
sessionId: client.sessionId,
578598
label: client.label,
579599
access: client.access,
600+
linked: client.peerLink,
580601
},
581602
capabilities: new Set<McpInvocationContext.McpCapability>([
582603
"orchestration",

‎apps/server/src/auth/SessionStore.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ export interface VerifiedSession {
6161
readonly proofKeyThumbprint?: string;
6262
/** The most an MCP client approved through OAuth may hand to the threads it drives. */
6363
readonly runtimeModeCeiling?: RuntimeMode;
64+
/** An MCP client that is another T3 Code environment's peer link. */
65+
readonly peerLink?: true;
6466
}
6567

6668
export type SessionCredentialChange =
@@ -378,6 +380,7 @@ export class SessionStore extends Context.Service<
378380
readonly client?: AuthClientMetadata;
379381
readonly proofKeyThumbprint?: string;
380382
readonly runtimeModeCeiling?: RuntimeMode;
383+
readonly peerLink?: boolean;
381384
/**
382385
* Atomically revoke active sessions with the same subject and method
383386
* before storing this session.
@@ -438,6 +441,8 @@ const SessionClaims = Schema.Struct({
438441
method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
439442
jkt: Schema.optionalKey(Schema.String),
440443
rtc: Schema.optionalKey(RuntimeMode),
444+
/** Signed, so a client cannot shed its peer link's limits. */
445+
plk: Schema.optionalKey(Schema.Literal(1)),
441446
iat: Schema.Number,
442447
exp: Schema.Number,
443448
});
@@ -674,6 +679,7 @@ export const make = Effect.gen(function* () {
674679
method: input?.method ?? "browser-session-cookie",
675680
...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
676681
...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
682+
...(input?.peerLink === true ? { plk: 1 as const } : {}),
677683
iat: issuedAt.epochMilliseconds,
678684
exp: expiresAt.epochMilliseconds,
679685
};
@@ -855,6 +861,7 @@ export const make = Effect.gen(function* () {
855861
scopes: claims.scopes,
856862
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
857863
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
864+
...(claims.plk === 1 ? { peerLink: true as const } : {}),
858865
} satisfies VerifiedSession;
859866
},
860867
);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ export const make = Effect.gen(function* () {
261261
serverBrowser: true,
262262
peerLinks: true,
263263
mcpModeLimitHeader: true,
264+
linkFence: true,
264265
},
265266
};
266267

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,6 +1109,7 @@ it.effect(
11091109
(input) => input,
11101110
(_, modes) =>
11111111
Effect.succeed({ modes: `${modes.runtimeMode}/${modes.interactionMode}` }),
1112+
"stamped",
11121113
),
11131114
}),
11141115
).pipe(

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ export interface McpClientCaller {
3434
readonly label: string;
3535
/** Read only, or the most the threads it starts or changes may run with. */
3636
readonly access: AuthMcpClientAccess;
37+
/**
38+
* Another T3 Code environment's peer link. What it starts here carries its
39+
* session as `linkOrigin`, and it changes only that work (`linkOrigin.ts`).
40+
*/
41+
readonly linked?: boolean | undefined;
3742
/**
3843
* Narrower modes the client asked for on this request (`T3-Mode-Limit`):
3944
* another environment passing on the limits of the agent it calls for.

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ const probeHandlers: McpToolAccess.Handlers<typeof ProbeToolkit.tools> = {
113113
starts_threads: McpToolAccess.startsThreads(
114114
(input) => input,
115115
(_, modes) => Effect.succeed({ ran: `${modes.runtimeMode}/${modes.interactionMode}` }),
116+
"stamped",
116117
),
117118
writes_environment: McpToolAccess.writesEnvironment(() => ran),
118119
};

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

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
type OrchestrationV2LinkOrigin,
23
OrchestratorMcpFailure,
34
type ProviderInteractionMode,
45
type RuntimeMode,
@@ -15,6 +16,7 @@ import {
1516
DispatchModeLimit,
1617
type DispatchModeRefusal,
1718
} from "../orchestration-v2/DispatchModeLimit.ts";
19+
import { assertNotLinked, assertSameLink, callerLinkOrigin } from "./linkOrigin.ts";
1820
import * as McpInvocationContext from "./McpInvocationContext.ts";
1921
import { resolveInteractionMode, resolveRuntimeMode } from "./OrchestratorMcpService.ts";
2022
import {
@@ -153,9 +155,28 @@ export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A,
153155
),
154156
);
155157

156-
/** Changes something that belongs to no thread, such as a pending upload or a scheduled task. */
157-
export const writes = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
158-
declare((params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))));
158+
/**
159+
* Changes something that belongs to no thread, such as a pending upload or a
160+
* scheduled task. Work a linked environment started may not: none of it
161+
* carries the link's origin, so none of it is that link's.
162+
*/
163+
export const writes = <P, A, E, R>(
164+
handle: (params: P) => Effect.Effect<A, E, R>,
165+
options?: {
166+
/** Whether a linked caller may make it, as for uploads its own sends need. */
167+
readonly linkedCallers?: "allowed";
168+
},
169+
) =>
170+
declare((params: P) =>
171+
orchestratingCaller.pipe(
172+
Effect.tap((caller) =>
173+
options?.linkedCallers === "allowed"
174+
? Effect.void
175+
: assertNotLinked(caller, "change this environment's scheduled tasks"),
176+
),
177+
Effect.flatMap(() => handle(params)),
178+
),
179+
);
159180

160181
/**
161182
* Changes the threads `threads` names. An omitted id is the caller's own
@@ -180,6 +201,7 @@ export const writesThreads = <P, A, E, R>(
180201
.pipe(Effect.mapError(unavailable));
181202
if (target !== null && target.deletedAt === null) {
182203
yield* assertTargetWithinLimits(caller.limits, target);
204+
yield* assertSameLink(caller, target);
183205
}
184206
}
185207
// The target's user can raise its modes after the check above; the
@@ -209,30 +231,40 @@ const escalationDenied = (refusal: DispatchModeRefusal) =>
209231
message: `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this caller's. Its user changed it while this call ran.`,
210232
});
211233

212-
/** The modes a started thread runs with: those requested, else the caller's own. */
234+
/** How a thread starts: the modes requested, else the caller's own, and the link it is for. */
213235
export interface StartedModes {
214236
readonly runtimeMode: RuntimeMode;
215237
readonly interactionMode: ProviderInteractionMode;
238+
/** The linked environment the caller acts for. The thread must carry it. */
239+
readonly linkOrigin: OrchestrationV2LinkOrigin | undefined;
216240
}
217241

218-
/** Starts threads with the modes `modes` requests, which may not be broader than the caller's. */
242+
/**
243+
* Starts threads with the modes `modes` requests, which may not be broader
244+
* than the caller's. `linked` says what a linked caller gets: threads stamped
245+
* with its `linkOrigin`, or a refusal where the tool cannot carry one.
246+
*/
219247
export const startsThreads = <P, A, E, R>(
220248
modes: (params: P) => {
221249
readonly runtimeMode?: RuntimeMode | undefined;
222250
readonly interactionMode?: ProviderInteractionMode | undefined;
223251
},
224252
handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
253+
linked: "stamped" | { readonly refused: string },
225254
) =>
226255
declare((params: P) =>
227256
Effect.gen(function* () {
228-
const { limits } = yield* writingCaller;
257+
const caller = yield* writingCaller;
258+
const { limits } = caller;
259+
if (linked !== "stamped") yield* assertNotLinked(caller, linked.refused);
229260
const requested = modes(params);
230261
const started: StartedModes = {
231262
runtimeMode: yield* resolveRuntimeMode(limits.runtimeMode, requested.runtimeMode),
232263
interactionMode: yield* resolveInteractionMode(
233264
limits.interactionMode,
234265
requested.interactionMode,
235266
),
267+
linkOrigin: callerLinkOrigin(caller),
236268
};
237269
return yield* handle(params, started);
238270
}),
@@ -253,6 +285,7 @@ export const writesEnvironment = <P, A, E, R>(
253285
) => Effect.Effect<A, E, R>,
254286
) => {
255287
const check = orchestratingCaller.pipe(
288+
Effect.tap((caller) => assertNotLinked(caller, "change projects or environment settings")),
256289
Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
257290
);
258291
return declare((params: P) => check.pipe(Effect.flatMap(() => handle(params, check))));

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2167,6 +2167,9 @@ const make = Effect.gen(function* () {
21672167
interactionMode,
21682168
branch: parent.thread.branch,
21692169
worktreePath: parent.thread.worktreePath,
2170+
...(parent.thread.linkOrigin === undefined
2171+
? {}
2172+
: { linkOrigin: parent.thread.linkOrigin }),
21702173
})
21712174
.pipe(
21722175
Effect.mapError((error) =>

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,9 @@ const make = Effect.gen(function* () {
417417
scriptName: result.scriptName,
418418
terminalId: result.terminalId,
419419
}
420-
: { status: "no-script" },
420+
: result.status === "skipped-for-link"
421+
? { status: "skipped" }
422+
: { status: "no-script" },
421423
),
422424
// catchCause via reportFailed: the thread is already re-pointed at the
423425
// worktree, so even a defect in the setup runner must not fail the handoff.

0 commit comments

Comments
 (0)