The best way to control Claude Code, Codex and more from any computer or phone
feat(server): agents use linked environments through any T3 tool (#16684)
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 14:04 UTC
cb988502aaf5e085b3fdaba94b1356aed545852c
30 files changed
+1778
-234
apps/server/src/mcp/McpHttpServer.ts
+1
-1
@@ -1084,7 +1084,7 @@ const layerEnvironmentToolkit = toolkitRegistration(
1084
EnvironmentHandlers.layer,
1085
).pipe(Layer.provide(ThreadCommandExecutor.layer));
1086
1087
-const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1087
+export const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1088
1089
export const layerAttachmentToolkit = toolkitRegistration(
1090
AttachmentToolkit,
apps/server/src/mcp/McpToolAccess.test.ts
+113
@@ -1,18 +1,22 @@
1
import { expect, it } from "@effect/vitest";
2
import {
3
EnvironmentId,
4
+ OrchestratorMcpEnvironmentTarget,
5
OrchestratorMcpFailure,
6
ProviderInstanceId,
7
ProviderInteractionMode,
8
RuntimeMode,
9
ThreadId,
10
} from "@t3tools/contracts";
11
+import * as Cause from "effect/Cause";
12
import * as Effect from "effect/Effect";
13
+import * as Exit from "effect/Exit";
14
import * as Layer from "effect/Layer";
15
import * as Schema from "effect/Schema";
16
import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
17
18
import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
19
+import * as PeerForwarding from "../peer/PeerForwarding.ts";
20
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
21
import * as McpHttpServer from "./McpHttpServer.ts";
22
import * as McpInvocationContext from "./McpInvocationContext.ts";
@@ -339,3 +343,112 @@ it.effect("refuses a change when the calling thread cannot be read", () =>
343
),
344
),
345
);
346
+
347
+const box = EnvironmentId.make("environment-box");
348
+const here = EnvironmentId.make("environment");
349
+const linkedProbe = {
350
+ ...probe,
351
+ parameters: Schema.Struct({
352
+ environmentId: OrchestratorMcpEnvironmentTarget,
353
+ threadId: Schema.optional(ThreadId),
354
+ runtimeMode: Schema.optional(RuntimeMode),
355
+ interactionMode: Schema.optional(ProviderInteractionMode),
356
+ }),
357
+};
358
+const LinkedProbeToolkit = Toolkit.make(
359
+ Tool.make("reads", linkedProbe),
360
+ Tool.make("writes", linkedProbe),
361
+ Tool.make("writes_with_capability", linkedProbe),
362
+ Tool.make("writes_threads", linkedProbe),
363
+ Tool.make("starts_threads", linkedProbe),
364
+ Tool.make("writes_environment", linkedProbe),
365
+);
366
+/** Runs here, and tells whether `environmentId` reached the handler. */
367
+const ranHere = <P extends object>(params: P) =>
368
+ Effect.succeed({ ran: "environmentId" in params ? "saw environmentId" : "here" });
369
+
370
+const linkedProbeServer = McpHttpServer.toolkitRegistration(
371
+ LinkedProbeToolkit,
372
+ McpToolAccess.toLayer(LinkedProbeToolkit, {
373
+ reads: McpToolAccess.reads(ranHere),
374
+ writes: McpToolAccess.writes(ranHere),
375
+ writes_with_capability: McpToolAccess.writesWithCapability(ranHere),
376
+ writes_threads: McpToolAccess.writesThreads((input) => [input.threadId], ranHere),
377
+ starts_threads: McpToolAccess.startsThreads((input) => input, ranHere),
378
+ writes_environment: McpToolAccess.writesEnvironment(ranHere),
379
+ }),
380
+).pipe(
381
+ Layer.provideMerge(McpServer.McpServer.layer),
382
+ Layer.provideMerge(
383
+ Layer.mock(ThreadManagement.ThreadManagementService)({
384
+ getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
385
+ }),
386
+ ),
387
+ // Stands in for the linked environment, answering with where the call went.
388
+ Layer.provide(
389
+ Layer.mock(PeerForwarding.PeerForwarding)({
390
+ call: (_scope, tool, environmentId) =>
391
+ Effect.succeed({ ran: `${tool.name} in ${environmentId}` } as never),
392
+ }),
393
+ ),
394
+);
395
+
396
+it.effect.each([
397
+ ["reads", supervised, { environmentId: box }, "reads in environment-box"],
398
+ ["reads", supervised, { environmentId: here }, "here"],
399
+ ["reads", supervised, {}, "here"],
400
+
401
+ // The caller is checked here before anything goes.
402
+ ["writes", readOnlyClient, { environmentId: box }, "capability_denied"],
403
+ ["writes", ended, { environmentId: box }, "parent_not_active"],
404
+ ["writes", supervised, { environmentId: box }, "writes in environment-box"],
405
+ ["writes_with_capability", readOnlyClient, { environmentId: box }, "capability_denied"],
406
+ [
407
+ "starts_threads",
408
+ plan,
409
+ { environmentId: box, interactionMode: "default" },
410
+ "interaction_mode_escalation_denied",
411
+ ],
412
+ ["starts_threads", plan, { environmentId: box }, "starts_threads in environment-box"],
413
+ ["writes_environment", supervised, { environmentId: box }, "capability_denied"],
414
+ [
415
+ "writes_environment",
416
+ fullAccess,
417
+ { environmentId: box },
418
+ "writes_environment in environment-box",
419
+ ],
420
+ ["writes_environment", fullAccess, { environmentId: here }, "here"],
421
+
422
+ // A thread id names a thread where the call runs, and is checked there.
423
+ [
424
+ "writes_threads",
425
+ supervised,
426
+ { environmentId: box, threadId: fullAccessThreadId },
427
+ "writes_threads in environment-box",
428
+ ],
429
+ [
430
+ "writes_threads",
431
+ supervised,
432
+ { environmentId: here, threadId: fullAccessThreadId },
433
+ "runtime_mode_escalation_denied",
434
+ ],
435
+] as const)("a linked %s from %o with %o: %s", ([tool, scope, args, expected]) =>
436
+ call(tool, scope, args).pipe(
437
+ Effect.map((outcome) => expect(outcome).toBe(expected)),
438
+ Effect.provide(linkedProbeServer),
439
+ ),
440
+);
441
+
442
+it.effect("refuses a linked environment to a tool that acts as its calling thread", () =>
443
+ Effect.gen(function* () {
444
+ const CallerToolkit = Toolkit.make(Tool.make("acts_as_caller", linkedProbe));
445
+ const built = yield* Layer.build(
446
+ McpToolAccess.HandlersLayer.layer(
447
+ McpToolAccess.toLayer(CallerToolkit, {
448
+ acts_as_caller: McpToolAccess.actsAsCaller(ranHere),
449
+ }),
450
+ ),
451
+ ).pipe(Effect.scoped, Effect.exit);
452
+ expect(Exit.isFailure(built) && Cause.hasDies(built.cause)).toBe(true);
453
+ }),
454
+);
apps/server/src/mcp/McpToolAccess.ts
+169
-56
@@ -1,10 +1,14 @@
1
import {
2
+ type EnvironmentId,
3
+ OrchestratorMcpEnvironmentTarget,
4
OrchestratorMcpFailure,
5
type ProviderInteractionMode,
6
type RuntimeMode,
7
type ThreadId,
8
} from "@t3tools/contracts";
9
import * as Effect from "effect/Effect";
10
+import * as Option from "effect/Option";
11
+import * as Predicate from "effect/Predicate";
12
import * as Ref from "effect/Ref";
13
import * as Struct from "effect/Struct";
14
import type * as Layer from "effect/Layer";
@@ -15,6 +19,7 @@ import {
19
DispatchModeLimit,
20
type DispatchModeRefusal,
21
} from "../orchestration-v2/DispatchModeLimit.ts";
22
+import * as PeerForwarding from "../peer/PeerForwarding.ts";
23
import * as McpInvocationContext from "./McpInvocationContext.ts";
24
import { resolveInteractionMode, resolveRuntimeMode } from "./OrchestratorMcpService.ts";
25
import {
@@ -38,8 +43,19 @@ const refuseOutsideConstruction = (token: symbol) => {
43
44
let declare: <P, A, E, R>(
45
handle: (params: P) => Effect.Effect<A, E, R>,
46
+ remote: RemoteCheck<P> | undefined,
47
) => Declaration<(params: P) => Effect.Effect<A, E, R>>;
48
49
+/**
50
+ * What a call bound for a linked environment checks here before it goes: the
51
+ * caller, not the thread or project it names, which live there and are
52
+ * checked there. `undefined` for tools that act as the calling thread itself.
53
+ */
54
+type RemoteCheck<P> = (
55
+ params: P,
56
+) => Effect.Effect<unknown, OrchestratorMcpFailure, Effect.Services<typeof writingCaller>>;
57
+let remoteCheckOf: <Handler>(declaration: Declaration<Handler>) => RemoteCheck<never> | undefined;
58
+
59
type CheckedHandlerOf<D> = D extends Declaration<infer Handler> ? Handler : never;
60
61
interface CheckedHandler extends Struct.Lambda {
@@ -55,13 +71,20 @@ let handlersLayer: <Tools extends Record<string, Tool.Any>, EX, RX>(
71
/** t3code/no-raw-mcp-registration confines Effect's unchecked registration API to McpHttpServer. */
72
export class Declaration<out Handler> {
73
readonly #handle: Handler;
58
- private constructor(token: typeof builtHere, handle: Handler) {
74
+ readonly #remote: RemoteCheck<never> | undefined;
75
+ private constructor(
76
+ token: typeof builtHere,
77
+ handle: Handler,
78
+ remote: RemoteCheck<never> | undefined,
79
+ ) {
80
refuseOutsideConstruction(token);
81
this.#handle = handle;
82
+ this.#remote = remote;
83
}
84
static {
63
- declare = (handle) => new Declaration(builtHere, handle);
85
+ declare = (handle, remote) => new Declaration(builtHere, handle, remote);
86
checkedHandler = Struct.lambda<CheckedHandler>((declaration) => declaration.#handle);
87
+ remoteCheckOf = (declaration) => declaration.#remote;
88
}
89
}
90
@@ -94,55 +117,68 @@ const requireThreadCaller = McpInvocationContext.McpInvocationContext.pipe(
117
);
118
119
export const reads = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
97
- declare((params: P) => handle(params));
120
+ declare(
121
+ (params: P) => handle(params),
122
+ () => Effect.void,
123
+ );
124
125
export const readsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
100
- declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))));
126
+ declare((params: P) => requireThreadCaller.pipe(Effect.flatMap(() => handle(params))), undefined);
127
128
export const actsAsCaller = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
103
- declare((params: P) =>
104
- requireThreadCaller.pipe(
105
- Effect.andThen(writingCaller),
106
- Effect.flatMap(() => handle(params)),
107
- ),
129
+ declare(
130
+ (params: P) =>
131
+ requireThreadCaller.pipe(
132
+ Effect.andThen(writingCaller),
133
+ Effect.flatMap(() => handle(params)),
134
+ ),
135
+ undefined,
136
);
137
138
export const writes = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
111
- declare((params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))));
139
+ declare(
140
+ (params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params))),
141
+ () => orchestratingCaller,
142
+ );
143
144
/** Requires handler capability checks, not thread control. */
145
export const writesWithCapability = <P, A, E, R>(handle: (params: P) => Effect.Effect<A, E, R>) =>
115
- declare((params: P) => writingCaller.pipe(Effect.flatMap(() => handle(params))));
146
+ declare(
147
+ (params: P) => writingCaller.pipe(Effect.flatMap(() => handle(params))),
148
+ () => writingCaller,
149
+ );
150
151
export const writesThreads = <P, A, E, R>(
152
threads: (params: P) => ReadonlyArray<ThreadId | undefined>,
153
handle: (params: P) => Effect.Effect<A, E, R>,
154
) =>
121
- declare((params: P) =>
122
- Effect.gen(function* () {
123
- const caller = yield* writingCaller;
124
- for (const threadId of threads(params)) {
125
- if (threadId === undefined || threadId === caller.scope.thread?.threadId) continue;
126
- const target = yield* caller.threads
127
- .getThreadShell(threadId)
128
- .pipe(Effect.mapError(unavailable));
129
- if (target !== null && target.deletedAt === null) {
130
- yield* assertTargetWithinLimits(caller.limits, target);
155
+ declare(
156
+ (params: P) =>
157
+ Effect.gen(function* () {
158
+ const caller = yield* writingCaller;
159
+ for (const threadId of threads(params)) {
160
+ if (threadId === undefined || threadId === caller.scope.thread?.threadId) continue;
161
+ const target = yield* caller.threads
162
+ .getThreadShell(threadId)
163
+ .pipe(Effect.mapError(unavailable));
164
+ if (target !== null && target.deletedAt === null) {
165
+ yield* assertTargetWithinLimits(caller.limits, target);
166
+ }
167
}
132
- }
133
- // Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors.
134
- const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
135
- return yield* handle(params).pipe(
136
- Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }),
137
- Effect.catch((error) =>
138
- Effect.flatMap(Ref.get(refused), (refusal) =>
139
- Effect.fail<E | OrchestratorMcpFailure>(
140
- refusal === undefined ? error : escalationDenied(refusal),
168
+ // Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors.
169
+ const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
170
+ return yield* handle(params).pipe(
171
+ Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }),
172
+ Effect.catch((error) =>
173
+ Effect.flatMap(Ref.get(refused), (refusal) =>
174
+ Effect.fail<E | OrchestratorMcpFailure>(
175
+ refusal === undefined ? error : escalationDenied(refusal),
176
+ ),
177
),
178
),
143
- ),
144
- );
145
- }),
179
+ );
180
+ }),
181
+ () => writingCaller,
182
);
183
184
const escalationDenied = (refusal: DispatchModeRefusal) =>
@@ -165,31 +201,46 @@ export const startsThreads = <P, A, E, R>(
201
readonly interactionMode?: ProviderInteractionMode | undefined;
202
},
203
handle: (params: P, modes: StartedModes) => Effect.Effect<A, E, R>,
168
-) =>
169
- declare((params: P) =>
170
- Effect.gen(function* () {
171
- const { limits } = yield* writingCaller;
172
- const requested = modes(params);
173
- const started: StartedModes = {
174
- runtimeMode: yield* resolveRuntimeMode(limits.runtimeMode, requested.runtimeMode),
175
- interactionMode: yield* resolveInteractionMode(
176
- limits.interactionMode,
177
- requested.interactionMode,
178
- ),
179
- };
180
- return yield* handle(params, started);
181
- }),
204
+) => {
205
+ const started = Effect.fn("McpToolAccess.started")(function* (params: P) {
206
+ const { limits } = yield* writingCaller;
207
+ const requested = modes(params);
208
+ return {
209
+ runtimeMode: yield* resolveRuntimeMode(limits.runtimeMode, requested.runtimeMode),
210
+ interactionMode: yield* resolveInteractionMode(
211
+ limits.interactionMode,
212
+ requested.interactionMode,
213
+ ),
214
+ } satisfies StartedModes;
215
+ });
216
+ return declare(
217
+ (params: P) => Effect.flatMap(started(params), (modes) => handle(params, modes)),
218
+ started,
219
);
220
+};
221
222
/** One tool with two access rules, picked per call, such as create versus update. */
223
export const either = <P, A, E, R, A2, E2, R2>(
224
useFirst: (params: P) => boolean,
225
first: Declaration<(params: P) => Effect.Effect<A, E, R>>,
226
second: Declaration<(params: P) => Effect.Effect<A2, E2, R2>>,
189
-) =>
190
- declare((params: P): Effect.Effect<A | A2, E | E2, R | R2> =>
191
- useFirst(params) ? checkedHandler(first)(params) : checkedHandler(second)(params),
227
+) => {
228
+ const remotes = [remoteCheckOf(first), remoteCheckOf(second)] as ReadonlyArray<
229
+ RemoteCheck<P> | undefined
230
+ >;
231
+ return declare(
232
+ (params: P): Effect.Effect<A | A2, E | E2, R | R2> =>
233
+ useFirst(params) ? checkedHandler(first)(params) : checkedHandler(second)(params),
234
+ (params) =>
235
+ remotes[useFirst(params) ? 0 : 1]?.(params) ??
236
+ Effect.fail(
237
+ new OrchestratorMcpFailure({
238
+ code: "invalid_request",
239
+ message: "This action acts as the calling thread, which is here. Omit environmentId.",
240
+ }),
241
+ ),
242
);
243
+};
244
245
const fullAccessRequired =
246
"Changing projects or environment settings needs a live full-access/default calling thread or a full-access client.";
@@ -204,7 +255,10 @@ export const writesEnvironment = <P, A, E, R>(
255
const check = orchestratingCaller.pipe(
256
Effect.tap((caller) => assertFullAccess(caller, fullAccessRequired)),
257
);
207
- return declare((params: P) => check.pipe(Effect.flatMap(() => handle(params, check))));
258
+ return declare(
259
+ (params: P) => check.pipe(Effect.flatMap(() => handle(params, check))),
260
+ () => check,
261
+ );
262
};
263
264
type CheckServices = Effect.Services<typeof orchestratingCaller>;
@@ -241,14 +295,73 @@ export class HandlersLayer<Tools extends Record<string, Tool.Any>, EX = never, R
295
const checkedHandlers = <Handlers>(declarations: Declarations<Handlers>): Handlers =>
296
Struct.map(declarations, checkedHandler);
297
298
+/**
299
+ * A tool runs in a linked environment when its parameters take this target
300
+ * as `environmentId`. Other tools may name an environment for their own
301
+ * reasons, such as the one to link or to move a thread to.
302
+ */
303
+const takesLinkedEnvironment = (tool: Tool.Any) => {
304
+ const parameters: unknown = tool.parametersSchema;
305
+ return (
306
+ Predicate.hasProperty(parameters, "fields") &&
307
+ Predicate.hasProperty(parameters.fields, "environmentId") &&
308
+ parameters.fields.environmentId === OrchestratorMcpEnvironmentTarget
309
+ );
310
+};
311
+
312
+const linksUnavailable = new OrchestratorMcpFailure({
313
+ code: "orchestration_error",
314
+ message: "This environment cannot reach linked environments.",
315
+});
316
+
317
+/**
318
+ * Every tool that takes a linked environment runs there the same way: its
319
+ * declaration checks the caller here, and the same call goes to the other
320
+ * environment, which checks the rest. The handler here never sees
321
+ * `environmentId`, so it cannot leak into what it writes.
322
+ */
323
+const routed = Effect.fn("McpToolAccess.routed")(function* <Tools extends Record<string, Tool.Any>>(
324
+ toolkit: Toolkit.Toolkit<Tools>,
325
+ declarations: Handlers<Tools>,
326
+ checked: Toolkit.HandlersFrom<Tools>,
327
+) {
328
+ // Optional so toolkits that never leave this environment build without it.
329
+ const forwarding = yield* Effect.serviceOption(PeerForwarding.PeerForwarding);
330
+ const handlers: Record<string, unknown> = { ...checked };
331
+ for (const [name, declaration] of Object.entries<Declaration<unknown>>(declarations)) {
332
+ const tool = toolkit.tools[name];
333
+ if (tool === undefined || !takesLinkedEnvironment(tool)) continue;
334
+ const remote = remoteCheckOf(declaration);
335
+ if (remote === undefined)
336
+ return yield* Effect.die(
337
+ `${name} takes a linked environment, but it acts as its calling thread, which is here.`,
338
+ );
339
+ const here = handlers[name] as (
340
+ params: object,
341
+ ) => Effect.Effect<unknown, Tool.Failure<Tools[keyof Tools]>>;
342
+ handlers[name] = ({ environmentId, ...params }: { readonly environmentId?: EnvironmentId }) =>
343
+ Effect.gen(function* () {
344
+ const scope = yield* McpInvocationContext.McpInvocationContext;
345
+ const target = PeerForwarding.remoteTarget(scope, environmentId);
346
+ if (target === undefined) return yield* here(params);
347
+ yield* (remote as RemoteCheck<typeof params>)(params);
348
+ if (Option.isNone(forwarding)) return yield* linksUnavailable;
349
+ return yield* forwarding.value.call(scope, tool, target, { ...params, environmentId });
350
+ });
351
+ }
352
+ return handlers as Toolkit.HandlersFrom<Tools>;
353
+});
354
+
355
export const toLayer = <Tools extends Record<string, Tool.Any>, EX = never, RX = never>(
356
toolkit: Toolkit.Toolkit<Tools>,
357
build: Handlers<Tools> | Effect.Effect<Handlers<Tools>, EX, RX>,
247
-): HandlersLayer<Tools, EX, Exclude<RX, Scope.Scope>> =>
248
- handlersLayer(
358
+): HandlersLayer<Tools, EX, Exclude<RX, Scope.Scope>> => {
359
+ // Checked as soon as they are given, so a forged declaration fails here.
360
+ const withDeclarations = (declarations: Handlers<Tools>) =>
361
+ routed(toolkit, declarations, checkedHandlers(declarations));
362
+ return handlersLayer(
363
toolkit.toLayer(
250
- Effect.isEffect(build)
251
- ? Effect.map(build, checkedHandlers<Toolkit.HandlersFrom<Tools>>)
252
- : checkedHandlers(build),
364
+ Effect.isEffect(build) ? Effect.flatMap(build, withDeclarations) : withDeclarations(build),
365
),
366
);
367
+};
apps/server/src/mcp/OrchestratorMcpService.test.ts
+188
@@ -14,6 +14,8 @@ import {
14
ProjectId,
15
ProviderDriverKind,
16
ProviderInstanceId,
17
+ ProviderThreadId,
18
+ ProviderTurnId,
19
RunId,
20
ThreadId,
21
type OrchestrationV2ServerCommand,
@@ -23,12 +25,16 @@ import {
25
import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
26
import * as DateTime from "effect/DateTime";
27
import * as Effect from "effect/Effect";
28
+import * as Fiber from "effect/Fiber";
29
import * as Layer from "effect/Layer";
30
+import * as Queue from "effect/Queue";
31
import * as Ref from "effect/Ref";
32
import * as Schema from "effect/Schema";
33
+import * as Stream from "effect/Stream";
34
35
import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
36
import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
37
+import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
38
import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts";
39
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
40
import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
@@ -2671,3 +2677,185 @@ describe("OrchestratorMcpService thread lookup", () => {
2677
}),
2678
);
2679
});
2680
+
2681
+describe("OrchestratorMcpService thread stop", () => {
2682
+ const driver = ProviderDriverKind.make("codex");
2683
+ const instanceId = ProviderInstanceId.make("codex");
2684
+ const modelSelection = { instanceId, model: "gpt-5.4" };
2685
+ const threadId = ThreadId.make("thread:mcp-stop");
2686
+ const client: McpInvocationScope = {
2687
+ environmentId: EnvironmentId.make("environment:mcp-stop"),
2688
+ requestNamespace: "client:mcp-stop",
2689
+ thread: undefined,
2690
+ client: { sessionId: "mcp-stop", label: "Claude Code", access: "full-access" },
2691
+ capabilities: new Set(["orchestration"]),
2692
+ issuedAt: 1,
2693
+ };
2694
+
2695
+ // A provider whose turns run until they are interrupted.
2696
+ const liveAdapter = (cwd: string): ProviderAdapter.ProviderAdapterV2["Service"] => ({
2697
+ instanceId,
2698
+ driver,
2699
+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
2700
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
2701
+ openSession: (input) =>
2702
+ Effect.gen(function* () {
2703
+ const now = yield* DateTime.now;
2704
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
2705
+ return {
2706
+ instanceId,
2707
+ driver,
2708
+ providerSessionId: input.providerSessionId,
2709
+ providerSession: {
2710
+ id: input.providerSessionId,
2711
+ driver,
2712
+ providerInstanceId: instanceId,
2713
+ status: "ready",
2714
+ cwd,
2715
+ model: modelSelection.model,
2716
+ capabilities: CodexProviderCapabilitiesV2,
2717
+ createdAt: now,
2718
+ updatedAt: now,
2719
+ lastError: null,
2720
+ },
2721
+ events: Stream.fromQueue(events),
2722
+ ensureThread: ({ threadId: appThreadId }) =>
2723
+ Effect.succeed({
2724
+ id: ProviderThreadId.make(`provider-thread:${appThreadId}`),
2725
+ driver,
2726
+ providerInstanceId: instanceId,
2727
+ providerSessionId: input.providerSessionId,
2728
+ appThreadId,
2729
+ ownerNodeId: null,
2730
+ nativeThreadRef: { driver, nativeId: `native:${appThreadId}`, strength: "strong" },
2731
+ nativeConversationHeadRef: null,
2732
+ status: "idle",
2733
+ firstRunOrdinal: null,
2734
+ lastRunOrdinal: null,
2735
+ handoffIds: [],
2736
+ forkedFrom: null,
2737
+ createdAt: now,
2738
+ updatedAt: now,
2739
+ }),
2740
+ resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
2741
+ startTurn: (turn) =>
2742
+ Queue.offer(events, {
2743
+ type: "provider_turn.updated",
2744
+ driver,
2745
+ providerTurn: {
2746
+ id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
2747
+ providerThreadId: turn.providerThread.id,
2748
+ nodeId: turn.rootNodeId,
2749
+ runAttemptId: turn.attemptId,
2750
+ nativeTurnRef: null,
2751
+ ordinal: turn.providerTurnOrdinal,
2752
+ status: "running",
2753
+ startedAt: now,
2754
+ completedAt: null,
2755
+ },
2756
+ }).pipe(Effect.asVoid),
2757
+ steerTurn: () => Effect.die("unused"),
2758
+ interruptTurn: () => Effect.void,
2759
+ respondToRuntimeRequest: () => Effect.die("unused"),
2760
+ readThreadSnapshot: () => Effect.die("unused"),
2761
+ rollbackThread: () => Effect.die("unused"),
2762
+ forkThread: () => Effect.die("unused"),
2763
+ };
2764
+ }),
2765
+ });
2766
+
2767
+ it.effect.each([
2768
+ { name: "a running turn", queued: false },
2769
+ { name: "a running turn with a queued message", queued: true },
2770
+ ])("t3_thread_interrupt stop reports the run it interrupted on $name", ({ queued }) =>
2771
+ Effect.scoped(
2772
+ Effect.gen(function* () {
2773
+ const cwd = yield* checkpointWorkspace("mcp-thread-stop");
2774
+ const layerAdapters = ProviderAdapterRegistry.layerSingle(liveAdapter(cwd));
2775
+ const layerDatabase = SqlitePersistence.layerMemory;
2776
+ const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
2777
+ { name: "mcp-thread-stop" },
2778
+ layerAdapters,
2779
+ { databaseLayer: layerDatabase, runEffectWorker: false },
2780
+ );
2781
+ const layerThreads = ThreadManagementService.layer.pipe(
2782
+ Layer.provideMerge(layerOrchestrator),
2783
+ Layer.provide(ServerSettings.layerTest()),
2784
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
2785
+ );
2786
+ const layerTest = layerOrchestratorService.pipe(
2787
+ Layer.provideMerge(layerThreads),
2788
+ Layer.provide(
2789
+ Layer.mergeAll(
2790
+ NodeServices.layer,
2791
+ layerAdapters,
2792
+ ServerSettings.layerTest(),
2793
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
2794
+ Layer.mock(ProjectService.ProjectService)({}),
2795
+ Layer.mock(SecretRequests.SecretRequests)({}),
2796
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
2797
+ ),
2798
+ ),
2799
+ );
2800
+ yield* Effect.gen(function* () {
2801
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2802
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2803
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
2804
+ const send = (text: string, type: "start_immediately" | "queue_after_active") =>
2805
+ orchestrator.dispatch({
2806
+ type: "message.dispatch",
2807
+ commandId: CommandId.make(`send:${text}`),
2808
+ threadId,
2809
+ messageId: MessageId.make(`message:${text}`),
2810
+ text,
2811
+ attachments: [],
2812
+ dispatchMode: { type },
2813
+ createdBy: "user",
2814
+ creationSource: "web",
2815
+ });
2816
+ yield* orchestrator.dispatch({
2817
+ type: "thread.create",
2818
+ commandId: CommandId.make("create"),
2819
+ threadId,
2820
+ projectId: ProjectId.make("project:mcp-stop"),
2821
+ title: "Stop",
2822
+ modelSelection,
2823
+ runtimeMode: "full-access",
2824
+ interactionMode: "default",
2825
+ branch: null,
2826
+ worktreePath: cwd,
2827
+ createdBy: "user",
2828
+ creationSource: "web",
2829
+ });
2830
+ const running = yield* orchestrator.streamDomainEvents.pipe(
2831
+ Stream.filter(
2832
+ (event) =>
2833
+ event.type === "provider-turn.updated" && event.payload.status === "running",
2834
+ ),
2835
+ Stream.take(1),
2836
+ Stream.runDrain,
2837
+ Effect.forkScoped,
2838
+ );
2839
+ yield* send("work", "start_immediately");
2840
+ yield* worker.drain();
2841
+ yield* Fiber.join(running);
2842
+ if (queued) yield* send("later", "queue_after_active");
2843
+ const before = yield* orchestrator.getThreadProjection(threadId);
2844
+ const runningRun = before.runs.find((run) => run.status === "running")!;
2845
+ assert.equal(before.runs.filter((run) => run.status === "queued").length, queued ? 1 : 0);
2846
+
2847
+ const stopped = yield* service.interruptThread(client, {
2848
+ threadId,
2849
+ stop: true,
2850
+ clientRequestId: "stop",
2851
+ });
2852
+ assert.deepEqual(stopped, {
2853
+ threadId,
2854
+ runId: runningRun.id,
2855
+ status: "interrupt_requested",
2856
+ });
2857
+ }).pipe(Effect.provide(layerTest));
2858
+ }),
2859
+ ),
2860
+ );
2861
+});
apps/server/src/mcp/OrchestratorMcpService.ts
+45
@@ -2907,6 +2907,51 @@ const make = Effect.gen(function* () {
2907
yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode);
2908
yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode);
2909
const key = yield* requestKey(input.clientRequestId);
2910
+ // A peer from before `stop` drops it when decoding, so it interrupts
2911
+ // the run instead, as this call did then.
2912
+ if (input.stop === true) {
2913
+ const commandId = stableCommandId({ scope, requestKey: key, operation: "thread-stop" });
2914
+ // The cause goes to the log; the caller learns only that the stop failed.
2915
+ const stopFailed = (error: unknown) =>
2916
+ Effect.logWarning("orchestrator-mcp.thread-stop-failed", {
2917
+ threadId: input.threadId,
2918
+ error,
2919
+ }).pipe(
2920
+ Effect.andThen(
2921
+ Effect.fail(
2922
+ failure("orchestration_error", `Unable to stop thread ${input.threadId}.`),
2923
+ ),
2924
+ ),
2925
+ );
2926
+ const stopped = yield* threadManagement
2927
+ .dispatch({
2928
+ type: "thread.stop",
2929
+ commandId,
2930
+ threadId: input.threadId,
2931
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
2932
+ })
2933
+ .pipe(Effect.catch(stopFailed));
2934
+ // A retry with the same clientRequestId repeats only the stops that failed.
2935
+ yield* threadManagement
2936
+ .stopDelegatedTasks({ threadId: input.threadId, commandId, reason: input.reason })
2937
+ .pipe(Effect.catch(stopFailed));
2938
+ // The run this stop interrupted, from its own events, so a retry
2939
+ // reports the same run even if another has started since. Stop also
2940
+ // holds queued runs and marks runs it could not interrupt, with no
2941
+ // provider turn; neither is the run it interrupted.
2942
+ const interrupted = stopped.storedEvents.find(
2943
+ ({ event }) =>
2944
+ (event.type === "run.updated" && event.payload.status === "interrupted") ||
2945
+ (event.type === "turn-item.updated" &&
2946
+ event.payload.type === "run_interrupt_request" &&
2947
+ event.payload.providerTurnId !== null),
2948
+ )?.event.runId;
2949
+ return {
2950
+ threadId: input.threadId,
2951
+ runId: interrupted ?? null,
2952
+ status: interrupted === undefined ? "no_active_run" : "interrupt_requested",
2953
+ } satisfies OrchestratorMcpThreadInterruptResult;
2954
+ }
2955
const result = yield* threadManagement
2956
.interruptThread({
2957
projectId: target.thread.projectId,
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+2
@@ -46,6 +46,7 @@ import * as SecretRequests from "../secrets/SecretRequests.ts";
46
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
47
import * as McpHttpServer from "./McpHttpServer.ts";
48
import * as McpInvocationContext from "./McpInvocationContext.ts";
49
+import * as PeerForwarding from "../peer/PeerForwarding.ts";
50
51
const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
52
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -220,6 +221,7 @@ describe("orchestrator MCP toolkit", () => {
221
Layer.provide(layerProviderRegistry),
222
Layer.provide(ServerSettings.layerTest()),
223
Layer.provide(layerUnusedScheduledTaskStub),
224
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
225
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
226
Layer.provideMerge(
227
SecretRequests.layer.pipe(
apps/server/src/mcp/toolkits/core.test.ts
+6
@@ -54,6 +54,7 @@ import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
54
import { dispatchFailure } from "../threadAccess.ts";
55
import * as EnvironmentHandlers from "./environment/handlers.ts";
56
import * as AttachmentHandlers from "./attachment/handlers.ts";
57
+import * as PeerForwarding from "../../peer/PeerForwarding.ts";
58
59
const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
60
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -72,6 +73,7 @@ const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadR
73
const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe(
74
Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
75
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
76
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
77
);
78
79
const threadId = ThreadId.make("mcp-core-thread");
@@ -598,6 +600,7 @@ it.effect("refuses act-as-caller tools to a client caller", () =>
600
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
601
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
602
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
603
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
604
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
605
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
606
),
@@ -655,6 +658,7 @@ it.effect("a caller cannot rewrite a scheduled task that runs above its own mode
658
),
659
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
660
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
661
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
662
),
663
),
664
),
@@ -739,6 +743,7 @@ it.effect.each(["t3_thread_interrupt", "t3_workflow_stop"])(
743
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
744
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
745
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
746
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
747
),
748
),
749
),
@@ -829,6 +834,7 @@ it.effect("discovers workflow stop targets and requires orchestration capability
834
Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
835
Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
836
Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
837
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
838
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
839
Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
840
),
apps/server/src/mcp/toolkits/environment/tools.ts
+3
@@ -2,6 +2,7 @@ import {
2
BackgroundActivityProfile,
3
BackgroundActivityProfileSelection,
4
ExecutionEnvironmentDescriptor,
5
+ OrchestratorMcpEnvironmentTarget,
6
OrchestratorMcpFailure,
7
ServerSettings,
8
ServerSettingsPatch,
@@ -41,6 +42,7 @@ const EnvironmentReadTool = Tool.make("t3_environment_read", {
42
...shared,
43
description:
44
"Read this server's identity and preferences. Providers and models: `orchestrator_capabilities`.",
45
+ parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget }),
46
success: Schema.Struct({
47
environmentId: ExecutionEnvironmentDescriptor.fields.environmentId,
48
label: Schema.String,
@@ -56,6 +58,7 @@ const EnvironmentPreferencesTool = Tool.make("t3_environment_preferences_update"
58
description:
59
"Update environment-wide preferences. Live full-access or default caller thread only. Omitted fields are unchanged; `customInstructions: ''` clears it.",
60
parameters: Schema.Struct({
61
+ environmentId: OrchestratorMcpEnvironmentTarget,
62
defaultThreadEnvMode: ServerSettingsPatch.fields.defaultThreadEnvMode,
63
newWorktreesStartFromOrigin: ServerSettingsPatch.fields.newWorktreesStartFromOrigin,
64
enableProviderUpdateChecks: ServerSettingsPatch.fields.enableProviderUpdateChecks,
apps/server/src/mcp/toolkits/orchestrator/handlers.ts
+8
@@ -2,6 +2,7 @@ import { OrchestratorMcpFailure } from "@t3tools/contracts";
2
import { OrchestratorToolkit } from "./tools.ts";
3
import * as Effect from "effect/Effect";
4
5
+import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
6
import { readCaller } from "../../threadAccess.ts";
7
import * as McpInvocationContext from "../../McpInvocationContext.ts";
8
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -179,6 +180,13 @@ const handlers = {
180
return yield* service.waitForThread(scope, input);
181
}),
182
),
183
+ t3_environment_links: McpToolAccess.reads(() =>
184
+ Effect.gen(function* () {
185
+ const scope = yield* McpInvocationContext.McpInvocationContext;
186
+ const forwarding = yield* PeerForwarding.PeerForwarding;
187
+ return yield* forwarding.links(scope);
188
+ }),
189
+ ),
190
t3_thread_interrupt: McpToolAccess.writesThreads(
191
(input) => [input.threadId],
192
(input) =>
apps/server/src/mcp/toolkits/orchestrator/tools.test.ts
new
+29
@@ -0,0 +1,29 @@
1
+import { expect, it } from "@effect/vitest";
2
+import * as Exit from "effect/Exit";
3
+import * as Schema from "effect/Schema";
4
+import { Tool } from "effect/ai";
5
+
6
+import { OrchestratorToolkit } from "./tools.ts";
7
+
8
+// Oversized page sizes clamp on decode, so the schema has no `maximum`; Codex also drops
9
+// bounds from its TypeScript view. The description is the only place a model sees a limit.
10
+it("states t3_thread_read page size limits in the parameter descriptions", () => {
11
+ const schema = Tool.getJsonSchema(OrchestratorToolkit.tools.t3_thread_read) as {
12
+ readonly properties: Readonly<Record<string, { readonly description?: string }>>;
13
+ };
14
+ const limits = { limit: "100", runLimit: "50", maxCharsPerItem: "50000" };
15
+ for (const [name, maximum] of Object.entries(limits)) {
16
+ expect(schema.properties[name]?.description, name).toContain(maximum);
17
+ }
18
+});
19
+
20
+it("refuses a t3_thread_update whose fields do not fit its action", () => {
21
+ const decode = Schema.decodeUnknownExit(
22
+ OrchestratorToolkit.tools.t3_thread_update.parametersSchema,
23
+ );
24
+ expect(Exit.isFailure(decode({ action: "rename" }))).toBe(true);
25
+ expect(Exit.isFailure(decode({ action: "regenerate_title", title: "New" }))).toBe(true);
26
+ expect(Exit.isSuccess(decode({ action: "rename", title: "New", environmentId: undefined }))).toBe(
27
+ true,
28
+ );
29
+});
apps/server/src/mcp/toolkits/orchestrator/tools.ts
+29
-2
@@ -2,12 +2,14 @@ import {
2
OrchestratorMcpCapabilitiesInput,
3
OrchestratorMcpCapabilitiesResult,
4
OrchestrationV2StopWorkflowInput,
5
+ OrchestratorMcpEnvironmentLinksResult,
6
OrchestratorMcpCreateThreadsInput,
7
OrchestratorMcpCreateThreadsResult,
8
OrchestratorMcpDelegateTaskInput,
9
OrchestratorMcpDelegateTaskResult,
10
OrchestratorMcpDeleteScheduledTaskInput,
11
OrchestratorMcpDeleteScheduledTaskResult,
12
+ OrchestratorMcpEnvironmentTarget,
13
OrchestratorMcpRequestSecretInput,
14
OrchestratorMcpRequestSecretResult,
15
OrchestratorMcpFailure,
@@ -34,8 +36,10 @@ import {
36
} from "@t3tools/contracts";
37
import { Tool, Toolkit } from "effect/ai";
38
import * as Schema from "effect/Schema";
39
+import * as Struct from "effect/Struct";
40
41
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
42
+import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
43
import * as McpInvocationContext from "../../McpInvocationContext.ts";
44
import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
45
import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
@@ -45,6 +49,8 @@ const dependencies = [
49
ThreadManagementService.ThreadManagementService,
50
OrchestratorMcpService.OrchestratorMcpService,
51
];
52
+/** Listing this environment's links. */
53
+const linkDependencies = [...dependencies, PeerForwarding.PeerForwarding];
54
const threadMetadataDependencies = [
55
McpInvocationContext.McpInvocationContext,
56
ThreadManagementService.ThreadManagementService,
@@ -107,7 +113,10 @@ const TaskCancelTool = Tool.make("task_cancel", {
113
const WorkflowStopTool = Tool.make("t3_workflow_stop", {
114
description:
115
"Stop a running Claude workflow in a thread. `subagentId`: coordinator from `t3_thread_read` 'activity'. Stops only the workflow, not the thread.",
110
- parameters: OrchestrationV2StopWorkflowInput,
116
+ parameters: Schema.Struct({
117
+ environmentId: OrchestratorMcpEnvironmentTarget,
118
+ ...OrchestrationV2StopWorkflowInput.fields,
119
+ }),
120
success: Schema.Struct({}),
121
failure: OrchestratorMcpFailure,
122
failureMode: "return",
@@ -231,7 +240,11 @@ const ThreadReadTool = Tool.make("t3_thread_read", {
240
const ThreadUpdateTool = Tool.make("t3_thread_update", {
241
description:
242
"Rename a thread (`action:'rename'` with `title`) or regenerate its title. Omit `threadId` for this thread. Workspace and branch cannot change here.",
234
- parameters: ThreadMetadataMcpUpdateInput,
243
+ // Keeps the input's action/field check, which rebuilding the struct would drop.
244
+ parameters: ThreadMetadataMcpUpdateInput.mapFields(
245
+ Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }),
246
+ { unsafePreserveChecks: true },
247
+ ),
248
success: ThreadMetadataMcpUpdateResult,
249
failure: OrchestratorMcpFailure,
250
failureMode: "return",
@@ -280,6 +293,19 @@ const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
293
.annotate(Tool.Title, "Interrupt a T3 thread")
294
.annotate(Tool.Destructive, true);
295
296
+const EnvironmentLinksTool = Tool.make("t3_environment_links", {
297
+ description:
298
+ "List the other T3 Code environments this one is linked to, such as the user's other machines, and whether each answers now. Pass one's environmentId to any tool that takes environmentId, such as t3_thread_launch, t3_thread_send, t3_pending_request_respond, t3_queue_list or t3_project_list, to act there; delegate_task takes it as target.environmentId. A linked environment lets this one's agents do at most its access there, and never more than the calling agent may do here. An expired link has to be linked again from a new pairing code.",
299
+ success: OrchestratorMcpEnvironmentLinksResult,
300
+ failure: OrchestratorMcpFailure,
301
+ failureMode: "return",
302
+ dependencies: linkDependencies,
303
+})
304
+ .annotate(Tool.Title, "List linked environments")
305
+ .annotate(Tool.Readonly, true)
306
+ .annotate(Tool.Destructive, false)
307
+ .annotate(Tool.Idempotent, true);
308
+
309
export const OrchestratorToolkit = Toolkit.make(
310
OrchestratorCapabilitiesTool,
311
DelegateTaskTool,
@@ -298,4 +324,5 @@ export const OrchestratorToolkit = Toolkit.make(
324
ThreadSendTool,
325
ThreadWaitTool,
326
ThreadInterruptTool,
327
+ EnvironmentLinksTool,
328
);
apps/server/src/mcp/toolkits/project/handlers.test.ts
+2
@@ -26,6 +26,7 @@ import * as ServerConfig from "../../../config.ts";
26
import * as ServerSettings from "../../../serverSettings.ts";
27
import * as Project from "../../../project/ProjectService.ts";
28
import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts";
29
+import * as PeerForwarding from "../../../peer/PeerForwarding.ts";
30
import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts";
31
import * as VcsProcess from "../../../vcs/VcsProcess.ts";
32
import * as McpInvocationContext from "../../McpInvocationContext.ts";
@@ -125,6 +126,7 @@ const clientLaunchHarness = (input: {
126
: Option.none(),
127
),
128
}),
129
+ Layer.mock(PeerForwarding.PeerForwarding)({}),
130
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
131
DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer)),
132
).pipe(
apps/server/src/mcp/toolkits/project/handlers.ts
+3
-1
@@ -21,6 +21,7 @@ import * as ServerSettings from "../../../serverSettings.ts";
21
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
22
import { formatThreadLink } from "@t3tools/shared/threadLinks";
23
import { resolveRuntimeMode } from "../../OrchestratorMcpService.ts";
24
+import * as McpInvocationContext from "../../McpInvocationContext.ts";
25
import * as McpToolAccess from "../../McpToolAccess.ts";
26
import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
27
import { ProjectToolkit } from "./tools.ts";
@@ -77,8 +78,9 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
78
(input) => input,
79
(input, { runtimeMode, interactionMode }) =>
80
Effect.gen(function* () {
81
+ const scope = yield* McpInvocationContext.McpInvocationContext;
82
const context = yield* readCaller();
81
- const { caller, scope } = context;
83
+ const { caller } = context;
84
// A retry with the same key replays the first launch: the ids derive
85
// from the caller and the key, and the launch service replays a
86
// command it already accepted.
apps/server/src/mcp/toolkits/project/tools.ts
+23
-5
@@ -14,6 +14,7 @@ import {
14
ProjectUpdatePayload,
15
ProjectId,
16
OrchestratorMcpClientRequestId,
17
+ OrchestratorMcpEnvironmentTarget,
18
OrchestratorMcpFailure,
19
SourceControlCloneRepositoryInput,
20
SourceControlCloneRepositoryResult,
@@ -48,6 +49,7 @@ const ProjectListTool = Tool.make("t3_project_list", {
49
...shared,
50
description: "List projects. Pages can shift.",
51
parameters: Schema.Struct({
52
+ environmentId: OrchestratorMcpEnvironmentTarget,
53
cursor: Schema.optional(NonNegativeInt),
54
limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))),
55
}),
@@ -61,7 +63,10 @@ const ProjectListTool = Tool.make("t3_project_list", {
63
const ProjectReadTool = Tool.make("t3_project_read", {
64
...shared,
65
description: "Read one project: workspace and saved scripts.",
64
- parameters: Schema.Struct({ projectId: ProjectId }),
66
+ parameters: Schema.Struct({
67
+ environmentId: OrchestratorMcpEnvironmentTarget,
68
+ projectId: ProjectId,
69
+ }),
70
})
71
.annotate(Tool.Readonly, true)
72
.annotate(Tool.Destructive, false);
@@ -70,6 +75,7 @@ const ProjectCreateTool = Tool.make("t3_project_create", {
75
description:
76
"Register a project folder. `createWorkspaceRootIfMissing` creates it; a registered folder is rejected. No `workspaceRoot`: makes a git repo from `title` with README, icon, first commit (`commitError` on failure; project still exists). Clone first with `t3_project_clone` if needed.",
77
parameters: Schema.Struct({
78
+ environmentId: OrchestratorMcpEnvironmentTarget,
79
...ProjectCreatePayload.fields,
80
workspaceRoot: Schema.optional(ProjectCreatePayload.fields.workspaceRoot),
81
}),
@@ -79,18 +85,29 @@ const ProjectCreateTool = Tool.make("t3_project_create", {
85
const ProjectUpdateTool = Tool.make("t3_project_update", {
86
...shared,
87
description: "Update one project's settings. Omitted fields are unchanged.",
82
- parameters: Schema.Struct({ projectId: ProjectId, ...ProjectUpdatePayload.fields }),
88
+ parameters: Schema.Struct({
89
+ environmentId: OrchestratorMcpEnvironmentTarget,
90
+ projectId: ProjectId,
91
+ ...ProjectUpdatePayload.fields,
92
+ }),
93
}).annotate(Tool.Destructive, true);
94
const ProjectDeleteTool = Tool.make("t3_project_delete", {
95
...shared,
96
description: "Delete one project. Nonempty needs `force: true`. Folder on disk stays.",
87
- parameters: Schema.Struct({ projectId: ProjectId, force: Schema.optionalKey(Schema.Boolean) }),
97
+ parameters: Schema.Struct({
98
+ environmentId: OrchestratorMcpEnvironmentTarget,
99
+ projectId: ProjectId,
100
+ force: Schema.optionalKey(Schema.Boolean),
101
+ }),
102
}).annotate(Tool.Destructive, true);
103
const ProjectCloneTool = Tool.make("t3_project_clone", {
104
...shared,
105
description:
92
- "Clone a repository (`destinationPath` new or empty). Register after with `t3_project_create`.",
93
- parameters: SourceControlCloneRepositoryInput,
106
+ "Clone a repository (`destinationPath` new or empty). Register after with `t3_project_create`, with the same `environmentId`.",
107
+ parameters: Schema.Struct({
108
+ environmentId: OrchestratorMcpEnvironmentTarget,
109
+ ...SourceControlCloneRepositoryInput.fields,
110
+ }),
111
success: SourceControlCloneRepositoryResult,
112
dependencies: [
113
...shared.dependencies,
@@ -104,6 +121,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", {
121
description:
122
"Create one new top-level thread, bound to its workspace before the agent starts. Task in `message`. Omit `projectId`, model and modes to inherit yours (outside a thread, pass `projectId` or `scratch`); modes cannot exceed yours. After an error or lost reply, retry with the same `clientRequestId`. Follow it with `t3_thread_read` or `t3_thread_wait`. Mention it with its `link`.",
123
parameters: Schema.Struct({
124
+ environmentId: OrchestratorMcpEnvironmentTarget,
125
projectId: Schema.optional(ProjectId),
126
scratch: Schema.optional(
127
Schema.Boolean.annotate({
apps/server/src/mcp/toolkits/pullRequests/tools.ts
+8
-1
@@ -1,5 +1,6 @@
1
import {
2
McpCapabilityUnavailableError,
3
+ OrchestratorMcpEnvironmentTarget,
4
OrchestratorMcpFailure,
5
PositiveInt,
6
PullRequestReviewGuide,
@@ -33,6 +34,7 @@ const guideDependencies = [
34
];
35
36
export const PullRequestTargetInput = Schema.Struct({
37
+ environmentId: OrchestratorMcpEnvironmentTarget,
38
threadId: Schema.optional(
39
ThreadId.annotate({
40
description: "Thread. Default: this thread.",
@@ -299,6 +301,7 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", {
301
description:
302
"List PRs linked to a thread, with last known state and stack order (bottom to top). Call only when you need that list. Never as an end-of-work check.",
303
parameters: Schema.Struct({
304
+ environmentId: OrchestratorMcpEnvironmentTarget,
305
threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })),
306
}),
307
success: ListThreadPullRequestsResult,
@@ -375,6 +378,7 @@ const WritePullRequestGuidesTool = Tool.make("write_pull_request_guides", {
378
description:
379
"Write review guides for up to 20 PRs (the tour in the PR Guide tab). Returns once runs start. Each run takes minutes in a temporary checkout. A run for the same head is joined. Read with `read_pull_request_guide`. Fails while guides are off.",
380
parameters: Schema.Struct({
381
+ environmentId: OrchestratorMcpEnvironmentTarget,
382
pullRequests: Schema.Array(GuideTarget).check(Schema.isMinLength(1), Schema.isMaxLength(20)),
383
}),
384
success: WritePullRequestGuidesResult,
@@ -390,7 +394,10 @@ const WritePullRequestGuidesTool = Tool.make("write_pull_request_guides", {
394
const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", {
395
description:
396
"Read a PR's stored review guide and run state. `guide` is null when none exists. Never starts a run.",
393
- parameters: GuideTarget,
397
+ parameters: Schema.Struct({
398
+ environmentId: OrchestratorMcpEnvironmentTarget,
399
+ ...GuideTarget.fields,
400
+ }),
401
success: ReadPullRequestGuideResult,
402
failure: PullRequestToolError,
403
dependencies: guideDependencies,
apps/server/src/mcp/toolkits/thread/tools.ts
+11
-1
@@ -1,4 +1,5 @@
1
import {
2
+ OrchestratorMcpEnvironmentTarget,
3
ScheduledTaskId,
4
ScheduledTask,
5
OrchestrationSearchThreadsInput,
@@ -32,6 +33,7 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
33
description:
34
"Pin, snooze, settle, archive, or mark a thread unread. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.",
35
parameters: Schema.Struct({
36
+ environmentId: OrchestratorMcpEnvironmentTarget,
37
threadId: Schema.optional(ThreadId),
38
action: Schema.Literals([
39
"pin",
@@ -89,6 +91,7 @@ const QueueTool = Tool.make("t3_queue", {
91
"reorder",
92
"promote_to_steer",
93
]),
94
+ environmentId: OrchestratorMcpEnvironmentTarget,
95
threadId: Schema.optional(ThreadId),
96
queuedRunId: Schema.optional(RunId),
97
text: Schema.optional(Schema.String.check(Schema.isMaxLength(100000))),
@@ -126,6 +129,7 @@ const PendingRequestTool = Tool.make("t3_pending_request", {
129
"Pending user questions in a thread. Omit `threadId` for this thread. list: their ids; approvals are not listed. read: one by `requestId`. respond: answer one with `answers`; this cannot approve a permission request.",
130
parameters: Schema.Struct({
131
action: Schema.Literals(["list", "read", "respond"]),
132
+ environmentId: OrchestratorMcpEnvironmentTarget,
133
threadId: Schema.optional(ThreadId),
134
requestId: Schema.optional(RuntimeRequestId),
135
answers: Schema.optional(ProviderUserInputAnswers),
@@ -150,6 +154,7 @@ const ThreadConfigureTool = Tool.make("t3_thread_configure", {
154
description:
155
"Read a thread's provider, model, and modes, or set its provider, model, and options with `modelSelection`. Omit `threadId` for this thread. Permission modes stay. Values from `orchestrator_capabilities`.",
156
parameters: Schema.Struct({
157
+ environmentId: OrchestratorMcpEnvironmentTarget,
158
threadId: Schema.optional(ThreadId),
159
modelSelection: Schema.optional(ModelSelection),
160
}),
@@ -162,6 +167,7 @@ const ThreadTransferTool = Tool.make("t3_thread_transfer", {
167
"Move context between threads. Omit `threadId` for this thread. fork: copy it from `sourcePoint` (default latest stable run) into a new thread with the same setup; no turn runs yet. merge_back: merge it from `sourcePoint` into a related `targetThreadId` in the same project. status: its context transfers.",
168
parameters: Schema.Struct({
169
action: Schema.Literals(["fork", "merge_back", "status"]),
170
+ environmentId: OrchestratorMcpEnvironmentTarget,
171
threadId: Schema.optional(ThreadId),
172
sourcePoint: Schema.optional(OrchestrationV2ThreadForkSourcePoint),
173
targetThreadId: Schema.optional(ThreadId),
@@ -187,6 +193,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", {
193
description:
194
"Search active threads by title, branch, PR, project, then message text. Skips subagent threads. `projectId`: one project, else yours, else all outside a thread. Not exhaustive.",
195
parameters: Schema.Struct({
196
+ environmentId: OrchestratorMcpEnvironmentTarget,
197
...OrchestrationSearchThreadsInput.fields,
198
projectId: Schema.optional(ProjectId),
199
}),
@@ -212,7 +219,10 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
219
...commandTool,
220
description:
221
"Run one scheduled task now. Needs a full-access or default caller. Returns its thread, or null if not started. Success means started, not finished.",
215
- parameters: Schema.Struct({ taskId: ScheduledTaskId }),
222
+ parameters: Schema.Struct({
223
+ environmentId: OrchestratorMcpEnvironmentTarget,
224
+ taskId: ScheduledTaskId,
225
+ }),
226
success: Schema.Struct({
227
taskId: ScheduledTaskId,
228
threadId: ScheduledTask.fields.threadId,
apps/server/src/mcp/toolkits/worktree/tools.ts
+2
@@ -1,5 +1,6 @@
1
import {
2
WorktreeMcpFailure,
3
+ OrchestratorMcpEnvironmentTarget,
4
OrchestratorMcpFailure,
5
VcsListRefsInput,
6
VcsListRefsResult,
@@ -62,6 +63,7 @@ const WorktreeListTool = Tool.make("t3_worktree_list", {
63
description:
64
"List branch refs and checkout paths for a thread's workspace. Omit `threadId` for this thread. Detached worktrees with no branch are left out.",
65
parameters: Schema.Struct({
66
+ environmentId: OrchestratorMcpEnvironmentTarget,
67
threadId: Schema.optional(ThreadId),
68
query: VcsListRefsInput.fields.query,
69
cursor: VcsListRefsInput.fields.cursor,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+1
@@ -1594,6 +1594,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
1594
"mcp__t3-code__t3_thread_search",
1595
"mcp__t3-code__t3_preview_list",
1596
"mcp__t3-code__t3_environment_read",
1597
+ "mcp__t3-code__t3_environment_links",
1598
"mcp__t3-code__html_preview",
1599
"mcp__t3-code__html_render",
1600
];
apps/server/src/peer/PeerForwarding.test.ts
new
+625
@@ -0,0 +1,625 @@
1
+import * as DocumentText from "../provider/DocumentText.ts";
2
+import { NodeHttpServer } from "@effect/platform-node";
3
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4
+import * as NodeServices from "@effect/platform-node/NodeServices";
5
+import {
6
+ EnvironmentId,
7
+ type OrchestrationV2Run,
8
+ type SourceControlCloneRepositoryInput,
9
+ ProjectId,
10
+ ProviderInstanceId,
11
+ RunId,
12
+ ThreadId,
13
+} from "@t3tools/contracts";
14
+import { expect, it } from "@effect/vitest";
15
+import * as Context from "effect/Context";
16
+import * as Effect from "effect/Effect";
17
+import * as Layer from "effect/Layer";
18
+import * as Ref from "effect/Ref";
19
+import { McpSchema, McpServer } from "effect/ai";
20
+
21
+import * as ServerConfig from "../config.ts";
22
+import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
23
+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
24
+import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts";
25
+import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
26
+import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts";
27
+import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
28
+import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
29
+import * as ProjectService from "../project/ProjectService.ts";
30
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
31
+import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
32
+import * as SecretRequests from "../secrets/SecretRequests.ts";
33
+import * as ServerSettings from "../serverSettings.ts";
34
+import * as McpHttpServer from "../mcp/McpHttpServer.ts";
35
+import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
36
+import { liveThreadShell } from "../mcp/McpToolAccess.testkit.ts";
37
+import * as PeerForwarding from "./PeerForwarding.ts";
38
+import * as PeerLinks from "./PeerLinks.ts";
39
+import { descriptorOf, layerLinkingEnvironment, linkTo, servePeer } from "./PeerLinks.testkit.ts";
40
+
41
+const laptop = descriptorOf("environment-laptop", "Laptop");
42
+const box = descriptorOf("environment-box", "Box");
43
+const boxProject = ProjectId.make("project:box");
44
+const boxThread = ThreadId.make("thread:box-auto");
45
+const boxRun = RunId.make("run:box-auto");
46
+
47
+/** What B's thread service was asked to do. */
48
+interface Seen {
49
+ readonly sends: ReadonlyArray<ThreadManagement.ThreadManagementSendInput>;
50
+ readonly waits: ReadonlyArray<ThreadManagement.ThreadManagementWaitInput>;
51
+ readonly launches: ReadonlyArray<ThreadLaunch.ThreadLaunchInput>;
52
+ readonly projects: ReadonlyArray<ProjectService.ProjectCreateInput>;
53
+ readonly clones: ReadonlyArray<SourceControlCloneRepositoryInput>;
54
+ /** Commands dispatched and delegated-task stops, as `<type> <threadId>`. */
55
+ readonly stops: ReadonlyArray<string>;
56
+}
57
+const nothingSeen: Seen = {
58
+ sends: [],
59
+ waits: [],
60
+ launches: [],
61
+ projects: [],
62
+ clones: [],
63
+ stops: [],
64
+};
65
+
66
+/**
67
+ * B's threads: one `auto` thread in `boxProject`, whose run finishes on the
68
+ * third wait. Every send and wait is recorded.
69
+ */
70
+const boxThreads = (seen: Ref.Ref<Seen>) => {
71
+ const shell = { ...liveThreadShell(boxThread, { runtimeMode: "auto" }), projectId: boxProject };
72
+ const run = (status: OrchestrationV2Run["status"]) =>
73
+ ({ id: boxRun, status }) as unknown as OrchestrationV2Run;
74
+ const projection = { thread: shell, runs: [run("running")], runtimeRequests: [] } as never;
75
+ return Layer.mock(ThreadManagement.ThreadManagementService)({
76
+ getThreadShell: (threadId) => Effect.succeed(threadId === boxThread ? shell : null),
77
+ getProjectThreadRecords: () => Effect.succeed(projection),
78
+ getThreadRecords: () => Effect.succeed(projection),
79
+ listProjectThreads: () => Effect.succeed([shell] as never),
80
+ sendToThread: (input) =>
81
+ Ref.update(seen, (current) => ({ ...current, sends: [...current.sends, input] })).pipe(
82
+ Effect.as({ run: run("running"), delivery: "started" } as never),
83
+ ),
84
+ dispatch: (command) =>
85
+ Ref.update(seen, (current) => ({
86
+ ...current,
87
+ stops: [
88
+ ...current.stops,
89
+ `${command.type} ${"threadId" in command ? command.threadId : ""}`,
90
+ ],
91
+ })).pipe(
92
+ // The stop asks the provider to interrupt the thread's running turn.
93
+ Effect.as({
94
+ sequence: 0,
95
+ storedEvents: [
96
+ {
97
+ sequence: 1,
98
+ commandId: command.commandId,
99
+ event: {
100
+ type: "turn-item.updated",
101
+ runId: boxRun,
102
+ payload: {
103
+ type: "run_interrupt_request",
104
+ providerTurnId: "provider-turn:box-auto",
105
+ },
106
+ },
107
+ },
108
+ ],
109
+ } as never),
110
+ ),
111
+ stopDelegatedTasks: (input) =>
112
+ Ref.update(seen, (current) => ({
113
+ ...current,
114
+ stops: [...current.stops, `delegated-tasks.stop ${input.threadId}`],
115
+ })),
116
+ waitForThread: (input) =>
117
+ Ref.updateAndGet(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe(
118
+ Effect.map(({ waits }) => ({
119
+ threadId: input.threadId,
120
+ run: run(waits.length < 3 ? "running" : "completed"),
121
+ timedOut: waits.length < 3,
122
+ })),
123
+ ),
124
+ });
125
+};
126
+
127
+/** B launches whatever it is asked to, and records it. */
128
+const boxLaunches = (seen: Ref.Ref<Seen>) =>
129
+ Layer.mock(ThreadLaunch.ThreadLaunchService)({
130
+ launch: (input) =>
131
+ Ref.update(seen, (current) => ({ ...current, launches: [...current.launches, input] })).pipe(
132
+ Effect.as({
133
+ threadId: input.threadId,
134
+ projection: {
135
+ thread: {
136
+ id: input.threadId,
137
+ projectId: input.projectId,
138
+ modelSelection: input.modelSelection,
139
+ title: input.title,
140
+ },
141
+ runs: [],
142
+ },
143
+ resumed: false,
144
+ } as unknown as ThreadLaunch.ThreadLaunchResult),
145
+ ),
146
+ });
147
+
148
+/** B clones and registers whatever it is asked to, and records it. */
149
+const boxProjects = (seen: Ref.Ref<Seen>) =>
150
+ Layer.merge(
151
+ Layer.mock(ProjectService.ProjectService)({
152
+ getById: () => Effect.succeedNone,
153
+ create: (input) =>
154
+ Ref.update(seen, (current) => ({
155
+ ...current,
156
+ projects: [...current.projects, input],
157
+ })).pipe(
158
+ Effect.as({
159
+ id: input.projectId,
160
+ title: input.title,
161
+ workspaceRoot: input.workspaceRoot,
162
+ defaultModelSelection: null,
163
+ scripts: [],
164
+ createdAt: "2026-10-18T00:00:00.000Z",
165
+ updatedAt: "2026-10-18T00:00:00.000Z",
166
+ deletedAt: null,
167
+ }),
168
+ ),
169
+ }),
170
+ Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({
171
+ cloneRepository: (input) =>
172
+ Ref.update(seen, (current) => ({ ...current, clones: [...current.clones, input] })).pipe(
173
+ Effect.as({
174
+ cwd: input.destinationPath,
175
+ remoteUrl: "https://github.com/pingdotgg/t3code.git",
176
+ repository: null,
177
+ }),
178
+ ),
179
+ }),
180
+ );
181
+
182
+/** The orchestrator and project toolkits on B's real `/mcp`, behind its real OAuth. */
183
+const serveBox = (seen: Ref.Ref<Seen>) =>
184
+ servePeer(
185
+ box,
186
+ Layer.mergeAll(
187
+ McpHttpServer.layerOrchestratorToolkit,
188
+ McpHttpServer.layerProjectRegistration,
189
+ McpHttpServer.layerThreadToolkit,
190
+ ).pipe(
191
+ Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
192
+ Layer.provide(NodeCrypto.layer),
193
+ Layer.provide(boxThreads(seen)),
194
+ Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
195
+ Layer.provide(boxLaunches(seen)),
196
+ Layer.provide(
197
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
198
+ ),
199
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
200
+ Layer.provide(boxProjects(seen)),
201
+ Layer.provide(
202
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-forwarding-box-" }).pipe(
203
+ Layer.provide(NodeServices.layer),
204
+ ),
205
+ ),
206
+ Layer.provide(NodeServices.layer),
207
+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
208
+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
209
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
210
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
211
+ Layer.provide(ServerSettings.layerTest()),
212
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
213
+ ),
214
+ );
215
+
216
+const mcpClient = McpSchema.McpServerClient.of({
217
+ clientId: 1,
218
+ protocolVersion: "2025-06-18",
219
+ clientCapabilities: {},
220
+ clientInfo: { name: "peer-forwarding-test", version: "1" },
221
+ initializePayload: {
222
+ protocolVersion: "2025-06-18",
223
+ capabilities: {},
224
+ clientInfo: { name: "peer-forwarding-test", version: "1" },
225
+ },
226
+ getClient: Effect.die("unused"),
227
+});
228
+
229
+/**
230
+ * Environment A: its own orchestrator toolkit with forwarding, and a thread
231
+ * caller whose modes the test picks. Its local threads never matter here.
232
+ */
233
+const makeLaptop = Effect.gen(function* () {
234
+ const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
235
+ const layerHere = Layer.mergeAll(
236
+ McpHttpServer.layerOrchestratorToolkit,
237
+ McpHttpServer.layerProjectRegistration,
238
+ McpHttpServer.layerThreadToolkit,
239
+ ).pipe(
240
+ Layer.provide(DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer))),
241
+ Layer.provideMerge(McpServer.McpServer.layer),
242
+ Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})),
243
+ Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
244
+ Layer.provide(
245
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }),
246
+ ),
247
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
248
+ Layer.provide(Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({})),
249
+ Layer.provide(
250
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-forwarding-laptop-" }).pipe(
251
+ Layer.provide(NodeServices.layer),
252
+ ),
253
+ ),
254
+ Layer.provide(NodeServices.layer),
255
+ Layer.provide(PeerForwarding.layer),
256
+ Layer.provide(Layer.succeedContext(linking)),
257
+ Layer.provide(NodeCrypto.layer),
258
+ Layer.provideMerge(
259
+ Layer.mock(ThreadManagement.ThreadManagementService)({
260
+ getThreadShell: (threadId) =>
261
+ Effect.succeed(
262
+ liveThreadShell(
263
+ threadId,
264
+ threadId === ThreadId.make("thread:laptop-plan")
265
+ ? { runtimeMode: "full-access", interactionMode: "plan" }
266
+ : { runtimeMode: "full-access" },
267
+ ),
268
+ ),
269
+ getProjectThreadRecords: ({ threadId }) =>
270
+ Effect.succeed({
271
+ thread: liveThreadShell(threadId, { runtimeMode: "full-access" }),
272
+ } as never),
273
+ }),
274
+ ),
275
+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
276
+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
277
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
278
+ Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
279
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
280
+ Layer.provide(ServerSettings.layerTest()),
281
+ Layer.fresh,
282
+ );
283
+ const here = yield* Layer.build(layerHere);
284
+ const server = Context.get(here, McpServer.McpServer);
285
+ const scopeOf = (
286
+ caller: string,
287
+ capabilities: ReadonlySet<McpInvocationContext.McpCapability> = new Set(["orchestration"]),
288
+ ): McpInvocationContext.McpInvocationScope => ({
289
+ environmentId: laptop.environmentId,
290
+ requestNamespace: `provider-session:${caller}`,
291
+ thread: {
292
+ threadId: ThreadId.make(caller),
293
+ providerSessionId: `provider-session:${caller}`,
294
+ providerInstanceId: ProviderInstanceId.make("codex"),
295
+ },
296
+ client: undefined,
297
+ capabilities,
298
+ issuedAt: 1,
299
+ });
300
+ const call = (
301
+ caller: string,
302
+ name: string,
303
+ args: Record<string, unknown>,
304
+ capabilities?: ReadonlySet<McpInvocationContext.McpCapability>,
305
+ ) =>
306
+ server
307
+ .callTool({ name, arguments: args })
308
+ .pipe(
309
+ Effect.provideService(
310
+ McpInvocationContext.McpInvocationContext,
311
+ scopeOf(caller, capabilities),
312
+ ),
313
+ Effect.provideService(McpSchema.McpServerClient, mcpClient),
314
+ );
315
+ return { links: Context.get(linking, PeerLinks.PeerLinks), call };
316
+});
317
+
318
+const failureOf = (result: McpSchema.CallToolResult) => {
319
+ const text = result.content[0];
320
+ return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined;
321
+};
322
+
323
+it.effect("an agent here works on a linked environment's threads within its own modes", () =>
324
+ Effect.scoped(
325
+ Effect.gen(function* () {
326
+ const seen = yield* Ref.make<Seen>(nothingSeen);
327
+ const b = yield* serveBox(seen);
328
+ const a = yield* makeLaptop;
329
+ yield* linkTo(a.links, b, "auto");
330
+
331
+ const listed = yield* a.call("thread:laptop-full", "t3_environment_links", {});
332
+ expect(listed.structuredContent).toMatchObject({
333
+ environmentId: laptop.environmentId,
334
+ links: [
335
+ { environmentId: box.environmentId, label: "Box", status: "reachable", access: "auto" },
336
+ ],
337
+ });
338
+
339
+ const threads = yield* a.call("thread:laptop-full", "t3_thread_list", {
340
+ environmentId: box.environmentId,
341
+ projectId: boxProject,
342
+ });
343
+ expect(threads.isError).toBe(false);
344
+ expect(threads.structuredContent).toMatchObject({
345
+ projectId: boxProject,
346
+ threads: [{ threadId: boxThread, runtimeMode: "auto" }],
347
+ });
348
+
349
+ // A full-access agent here is held to the link's `auto` there, which
350
+ // the box's `auto` thread is within.
351
+ const sent = yield* a.call("thread:laptop-full", "t3_thread_send", {
352
+ environmentId: box.environmentId,
353
+ threadId: boxThread,
354
+ message: "Carry on there.",
355
+ clientRequestId: "send-1",
356
+ });
357
+ expect(sent.isError).toBe(false);
358
+ expect(sent.structuredContent).toMatchObject({ threadId: boxThread, delivery: "started" });
359
+
360
+ // A plan-mode agent here may not steer that thread there: the box
361
+ // refuses it, because the call carries the agent's own modes.
362
+ const planned = yield* a.call("thread:laptop-plan", "t3_thread_send", {
363
+ environmentId: box.environmentId,
364
+ threadId: boxThread,
365
+ message: "Change course.",
366
+ });
367
+ expect(failureOf(planned)).toMatchObject({ code: "interaction_mode_escalation_denied" });
368
+ expect((yield* Ref.get(seen)).sends).toHaveLength(1);
369
+
370
+ // stop=true stops the thread there as its Stop button does: the whole
371
+ // thread and the tasks it delegated, not just the running turn.
372
+ const stopped = yield* a.call("thread:laptop-full", "t3_thread_interrupt", {
373
+ environmentId: box.environmentId,
374
+ threadId: boxThread,
375
+ stop: true,
376
+ clientRequestId: "stop-1",
377
+ });
378
+ expect(stopped.structuredContent).toMatchObject({
379
+ threadId: boxThread,
380
+ runId: boxRun,
381
+ status: "interrupt_requested",
382
+ });
383
+ expect((yield* Ref.get(seen)).stops).toEqual([
384
+ `thread.stop ${boxThread}`,
385
+ `delegated-tasks.stop ${boxThread}`,
386
+ ]);
387
+ }),
388
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
389
+);
390
+
391
+it.effect("keeps a forwarded wait short and its retries scoped to the caller", () =>
392
+ Effect.scoped(
393
+ Effect.gen(function* () {
394
+ const seen = yield* Ref.make<Seen>(nothingSeen);
395
+ const b = yield* serveBox(seen);
396
+ const a = yield* makeLaptop;
397
+ yield* linkTo(a.links, b, "auto");
398
+
399
+ const waited = yield* a.call("thread:laptop-full", "t3_thread_wait", {
400
+ environmentId: box.environmentId,
401
+ threadId: boxThread,
402
+ timeoutMs: 600_000,
403
+ });
404
+ expect(waited.structuredContent).toEqual({
405
+ threadId: boxThread,
406
+ runId: boxRun,
407
+ status: "completed",
408
+ timedOut: false,
409
+ });
410
+ // Three pieces of at most 50 s each, the later ones pinned to the run
411
+ // the first one found.
412
+ expect(
413
+ (yield* Ref.get(seen)).waits.map(({ timeoutMs, runId }) => [timeoutMs, runId]),
414
+ ).toEqual([
415
+ [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, undefined],
416
+ [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun],
417
+ [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun],
418
+ ]);
419
+
420
+ const send = (caller: string, clientRequestId: string) =>
421
+ a.call(caller, "t3_thread_send", {
422
+ environmentId: box.environmentId,
423
+ threadId: boxThread,
424
+ message: "Once.",
425
+ clientRequestId,
426
+ });
427
+ yield* send("thread:laptop-full", "same-key");
428
+ yield* send("thread:laptop-full", "same-key");
429
+ yield* send("thread:laptop-other", "same-key");
430
+ const [first, retried, other] = (yield* Ref.get(seen)).sends.map((input) => input.commandId);
431
+ // The box sees every caller here as the one link, so the key is scoped
432
+ // to its caller before it leaves: a retry matches, another agent's same
433
+ // key does not.
434
+ expect(retried).toBe(first);
435
+ expect(other).not.toBe(first);
436
+ expect(first).not.toContain("same-key");
437
+ }),
438
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
439
+);
440
+
441
+it.effect("launches in a linked environment with the caller's modes, retry-safe", () =>
442
+ Effect.scoped(
443
+ Effect.gen(function* () {
444
+ const seen = yield* Ref.make<Seen>(nothingSeen);
445
+ const b = yield* serveBox(seen);
446
+ const a = yield* makeLaptop;
447
+ yield* linkTo(a.links, b, "full-access");
448
+ const codex = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
449
+ const launch = (caller: string, args: Record<string, unknown> = {}) =>
450
+ a.call(caller, "t3_thread_launch", {
451
+ environmentId: box.environmentId,
452
+ projectId: boxProject,
453
+ title: "Run the suite there",
454
+ modelSelection: codex,
455
+ message: "Run the suite.",
456
+ clientRequestId: "launch-1",
457
+ ...args,
458
+ });
459
+
460
+ const first = yield* launch("thread:laptop-plan");
461
+ expect(first.isError).toBe(false);
462
+ expect(first.structuredContent).toMatchObject({
463
+ projectId: boxProject,
464
+ modelSelection: codex,
465
+ });
466
+ const retried = yield* launch("thread:laptop-plan");
467
+ const [launched, relaunched] = (yield* Ref.get(seen)).launches;
468
+ // The thread there runs with the caller's own modes here, below the
469
+ // link's full access, and a retry asks for the same thread.
470
+ expect(launched).toMatchObject({ runtimeMode: "full-access", interactionMode: "plan" });
471
+ expect(relaunched?.threadId).toBe(launched?.threadId);
472
+ expect(retried.structuredContent).toEqual(first.structuredContent);
473
+
474
+ // An escalation past the caller's own modes is refused here.
475
+ const escalated = yield* launch("thread:laptop-plan", { interactionMode: "default" });
476
+ expect(failureOf(escalated)).toMatchObject({ code: "interaction_mode_escalation_denied" });
477
+ // A pending upload lives here, so it cannot go along.
478
+ yield* Ref.set(b.bearers, []);
479
+ const withUpload = yield* launch("thread:laptop-full", {
480
+ clientRequestId: "launch-2",
481
+ attachments: [
482
+ { type: "image", id: "upload-1", name: "a.png", mimeType: "image/png", sizeBytes: 1 },
483
+ ],
484
+ });
485
+ expect(failureOf(withUpload)).toMatchObject({ code: "invalid_request" });
486
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
487
+ expect((yield* Ref.get(seen)).launches).toHaveLength(2);
488
+ }),
489
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
490
+);
491
+
492
+it.effect("brings a repository to a linked environment, only through full access", () =>
493
+ Effect.scoped(
494
+ Effect.gen(function* () {
495
+ const seen = yield* Ref.make<Seen>(nothingSeen);
496
+ const b = yield* serveBox(seen);
497
+ const a = yield* makeLaptop;
498
+ const clone = { repository: "pingdotgg/t3code", destinationPath: "/home/box/t3code" };
499
+ const register = { title: "t3code", workspaceRoot: "/home/box/t3code" };
500
+
501
+ yield* linkTo(a.links, b, "full-access");
502
+ const cloned = yield* a.call("thread:laptop-full", "t3_project_clone", {
503
+ environmentId: box.environmentId,
504
+ ...clone,
505
+ });
506
+ expect(cloned.structuredContent).toMatchObject({ cwd: clone.destinationPath });
507
+ const created = yield* a.call("thread:laptop-full", "t3_project_create", {
508
+ environmentId: box.environmentId,
509
+ ...register,
510
+ });
511
+ expect(created.structuredContent).toMatchObject(register);
512
+ expect((yield* Ref.get(seen)).clones).toEqual([clone]);
513
+ expect((yield* Ref.get(seen)).projects).toMatchObject([register]);
514
+
515
+ // A plan-mode agent here may not, and nothing leaves.
516
+ yield* Ref.set(b.bearers, []);
517
+ const planned = yield* a.call("thread:laptop-plan", "t3_project_create", {
518
+ environmentId: box.environmentId,
519
+ ...register,
520
+ });
521
+ expect(failureOf(planned)).toMatchObject({ code: "capability_denied" });
522
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
523
+
524
+ // Nor may a full-access agent through a link with less: the box holds it.
525
+ yield* linkTo(a.links, b, "auto");
526
+ for (const [name, args] of [
527
+ ["t3_project_clone", clone],
528
+ ["t3_project_create", register],
529
+ ] as const) {
530
+ const refused = yield* a.call("thread:laptop-full", name, {
531
+ environmentId: box.environmentId,
532
+ ...args,
533
+ });
534
+ expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
535
+ }
536
+ expect((yield* Ref.get(seen)).clones).toHaveLength(1);
537
+ expect((yield* Ref.get(seen)).projects).toHaveLength(1);
538
+ }),
539
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
540
+);
541
+
542
+it.effect("runs any tool that takes a linked environment there", () =>
543
+ Effect.scoped(
544
+ Effect.gen(function* () {
545
+ const seen = yield* Ref.make<Seen>(nothingSeen);
546
+ const b = yield* serveBox(seen);
547
+ const a = yield* makeLaptop;
548
+ yield* linkTo(a.links, b, "auto");
549
+
550
+ const there = yield* a.call("thread:laptop-full", "t3_thread_configure", {
551
+ environmentId: box.environmentId,
552
+ threadId: boxThread,
553
+ });
554
+ expect(there.structuredContent).toMatchObject({ threadId: boxThread, runtimeMode: "auto" });
555
+ const archived = yield* a.call("thread:laptop-full", "t3_thread_organize", {
556
+ environmentId: box.environmentId,
557
+ threadId: boxThread,
558
+ action: "archive",
559
+ });
560
+ expect(archived.isError).toBe(false);
561
+ expect((yield* Ref.get(seen)).stops).toEqual([`thread.archive ${boxThread}`]);
562
+
563
+ // This environment's own id keeps the call here.
564
+ const own = yield* a.call("thread:laptop-full", "t3_thread_configure", {
565
+ environmentId: laptop.environmentId,
566
+ });
567
+ expect(own.structuredContent).toMatchObject({
568
+ threadId: "thread:laptop-full",
569
+ runtimeMode: "full-access",
570
+ });
571
+ }),
572
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
573
+);
574
+
575
+it.effect("refuses what a linked environment cannot take before anything leaves", () =>
576
+ Effect.scoped(
577
+ Effect.gen(function* () {
578
+ const seen = yield* Ref.make<Seen>(nothingSeen);
579
+ const b = yield* serveBox(seen);
580
+ const a = yield* makeLaptop;
581
+ yield* linkTo(a.links, b, "auto");
582
+ yield* Ref.set(b.bearers, []);
583
+
584
+ const unknown = yield* a.call("thread:laptop-full", "t3_thread_read", {
585
+ environmentId: EnvironmentId.make("environment-elsewhere"),
586
+ threadId: boxThread,
587
+ });
588
+ expect(failureOf(unknown)).toMatchObject({ code: "invalid_request" });
589
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
590
+
591
+ // The box sees only the link's credential, so one that may not control
592
+ // threads here may not reach them there either.
593
+ const previewOnly = new Set<McpInvocationContext.McpCapability>(["preview"]);
594
+ for (const [name, args] of [
595
+ ["t3_environment_links", {}],
596
+ ["t3_project_list", { environmentId: box.environmentId }],
597
+ ["t3_thread_list", { environmentId: box.environmentId, projectId: boxProject }],
598
+ ["t3_thread_read", { environmentId: box.environmentId, threadId: boxThread }],
599
+ ["t3_thread_wait", { environmentId: box.environmentId, threadId: boxThread }],
600
+ [
601
+ "t3_thread_send",
602
+ { environmentId: box.environmentId, threadId: boxThread, message: "Carry on there." },
603
+ ],
604
+ [
605
+ "t3_thread_organize",
606
+ { environmentId: box.environmentId, threadId: boxThread, action: "archive" },
607
+ ],
608
+ [
609
+ "t3_thread_launch",
610
+ {
611
+ environmentId: box.environmentId,
612
+ projectId: boxProject,
613
+ title: "Start there",
614
+ modelSelection: { instanceId: "codex", model: "gpt-5" },
615
+ message: "Start there.",
616
+ },
617
+ ],
618
+ ] as const) {
619
+ const refused = yield* a.call("thread:laptop-full", name, args, previewOnly);
620
+ expect(failureOf(refused), name).toMatchObject({ code: "capability_denied" });
621
+ }
622
+ expect(yield* Ref.get(b.bearers)).toEqual([]);
623
+ }),
624
+ ).pipe(Effect.provide(NodeHttpServer.layerTest)),
625
+);
apps/server/src/peer/PeerForwarding.ts
new
+192
@@ -0,0 +1,192 @@
1
+import {
2
+ type EnvironmentId,
3
+ OrchestratorMcpFailure,
4
+ type OrchestratorMcpEnvironmentLinksResult,
5
+ OrchestratorMcpThreadWaitInput,
6
+ OrchestratorMcpThreadWaitResult,
7
+} from "@t3tools/contracts";
8
+import * as Context from "effect/Context";
9
+import * as Crypto from "effect/Crypto";
10
+import * as DateTime from "effect/DateTime";
11
+import * as Effect from "effect/Effect";
12
+import * as Hex from "effect/encoding/Hex";
13
+import * as Layer from "effect/Layer";
14
+import * as Schema from "effect/Schema";
15
+import type * as Tool from "effect/ai/Tool";
16
+
17
+import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
18
+import { readCaller, unavailable } from "../mcp/threadAccess.ts";
19
+import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
20
+import * as PeerLinks from "./PeerLinks.ts";
21
+import * as PeerMcpClient from "./PeerMcpClient.ts";
22
+
23
+/**
24
+ * A peer's `/mcp` holds a wait open for its whole timeout without sending
25
+ * anything, and T3 Connect's edge drops a request idle for about 100 s, so a
26
+ * forwarded wait goes out in pieces no longer than this.
27
+ */
28
+export const FORWARDED_WAIT_CHUNK_MS = 50_000;
29
+const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
30
+const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
31
+
32
+type Scope = McpInvocationContext.McpInvocationScope;
33
+
34
+/**
35
+ * Runs T3 MCP tools in a linked environment for an agent here. The tool's own
36
+ * declaration checks the agent here first; the linked environment then holds
37
+ * the call to the link's access, narrowed to the agent's modes, which every
38
+ * forwarded call carries.
39
+ */
40
+export class PeerForwarding extends Context.Service<
41
+ PeerForwarding,
42
+ {
43
+ /**
44
+ * Runs `tool` in the linked environment `environmentId` with `params`. A
45
+ * `t3_thread_wait` goes in pieces short enough to survive any route.
46
+ */
47
+ readonly call: <T extends Tool.Any>(
48
+ scope: Scope,
49
+ tool: T,
50
+ environmentId: EnvironmentId,
51
+ params: Tool.Parameters<T>,
52
+ ) => Effect.Effect<Tool.Success<T>, OrchestratorMcpFailure>;
53
+ /** `t3_thread_wait` there, in pieces short enough to survive any route. */
54
+ readonly waitForThread: (
55
+ scope: Scope,
56
+ environmentId: EnvironmentId,
57
+ input: OrchestratorMcpThreadWaitInput,
58
+ ) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
59
+ /** The environments this one links to, as an agent sees them. */
60
+ readonly links: (
61
+ scope: Scope,
62
+ ) => Effect.Effect<OrchestratorMcpEnvironmentLinksResult, OrchestratorMcpFailure>;
63
+ }
64
+>()("t3/peer/PeerForwarding") {}
65
+
66
+/** The linked environment a call names, or nothing when it names this one. */
67
+export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) =>
68
+ environmentId === scope.environmentId ? undefined : environmentId;
69
+
70
+const make = Effect.gen(function* () {
71
+ const peers = yield* PeerMcpClient.PeerMcpClient;
72
+ const links = yield* PeerLinks.PeerLinks;
73
+ const crypto = yield* Crypto.Crypto;
74
+ const threads = yield* ThreadManagement.ThreadManagementService;
75
+
76
+ /**
77
+ * The caller's own limits here, which travel with every call it forwards.
78
+ * The peer sees only the link's credential, so a credential that may not
79
+ * control threads here is refused here.
80
+ */
81
+ const callerLimits = (scope: Scope) =>
82
+ readCaller().pipe(
83
+ Effect.map((caller) => caller.limits),
84
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
85
+ Effect.provideService(ThreadManagement.ThreadManagementService, threads),
86
+ );
87
+
88
+ /**
89
+ * Every caller here reaches the peer as the one link session, so a retry
90
+ * key is scoped to its caller before it leaves: two agents here reusing a
91
+ * key never collide there, and one agent retrying gets its first result.
92
+ */
93
+ const scopedRequestId = (namespace: string, clientRequestId: string) =>
94
+ crypto.digest("SHA-256", new TextEncoder().encode(`${namespace}\n${clientRequestId}`)).pipe(
95
+ Effect.map((digest) => `fwd:${Hex.encode(digest)}`),
96
+ Effect.orDie,
97
+ );
98
+
99
+ /** Tool and contract schemas are plain data: they encode and decode without services. */
100
+ const forward = Effect.fn("PeerForwarding.forward")(function* <A>(
101
+ scope: Scope,
102
+ toolName: string,
103
+ parameters: Schema.Top,
104
+ success: Schema.Top,
105
+ environmentId: EnvironmentId,
106
+ params: unknown,
107
+ ) {
108
+ const limits = yield* callerLimits(scope);
109
+ const encoded = (yield* Schema.encodeUnknownEffect(parameters as Schema.Encoder<unknown>)(
110
+ params,
111
+ ).pipe(Effect.mapError(unavailable))) as Record<string, unknown>;
112
+ const { environmentId: _target, ...args } = encoded;
113
+ // A pending upload lives here, so it cannot go with the call.
114
+ if (Array.isArray(args.attachments) && args.attachments.length > 0) {
115
+ return yield* new OrchestratorMcpFailure({
116
+ code: "invalid_request",
117
+ message: "A launch in a linked environment cannot carry attachments yet.",
118
+ });
119
+ }
120
+ if (typeof args.clientRequestId === "string") {
121
+ args.clientRequestId = yield* scopedRequestId(scope.requestNamespace, args.clientRequestId);
122
+ }
123
+ return yield* peers.call({
124
+ environmentId,
125
+ tool: toolName,
126
+ arguments: args,
127
+ limits,
128
+ success: success as Schema.Decoder<A>,
129
+ });
130
+ });
131
+
132
+ const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn(
133
+ "PeerForwarding.waitForThread",
134
+ )(function* (scope, environmentId, input) {
135
+ let remaining = Math.min(
136
+ MAX_WAIT_TIMEOUT_MS,
137
+ Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
138
+ );
139
+ let runId = input.runId;
140
+ while (true) {
141
+ const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS);
142
+ const result = yield* forward<OrchestratorMcpThreadWaitResult>(
143
+ scope,
144
+ "t3_thread_wait",
145
+ OrchestratorMcpThreadWaitInput,
146
+ OrchestratorMcpThreadWaitResult,
147
+ environmentId,
148
+ { threadId: input.threadId, ...(runId === undefined ? {} : { runId }), timeoutMs: chunk },
149
+ );
150
+ remaining -= chunk;
151
+ if (!result.timedOut || remaining <= 0) return result;
152
+ // Later pieces wait for the run the first one picked, not a newer one.
153
+ runId = result.runId ?? undefined;
154
+ }
155
+ });
156
+
157
+ const call: PeerForwarding["Service"]["call"] = (scope, tool, environmentId, params) =>
158
+ tool.name === "t3_thread_wait"
159
+ ? (waitForThread(
160
+ scope,
161
+ environmentId,
162
+ params as OrchestratorMcpThreadWaitInput,
163
+ ) as Effect.Effect<Tool.Success<typeof tool>, OrchestratorMcpFailure>)
164
+ : forward(scope, tool.name, tool.parametersSchema, tool.successSchema, environmentId, params);
165
+
166
+ const listLinks: PeerForwarding["Service"]["links"] = Effect.fn("PeerForwarding.listLinks")(
167
+ function* (scope) {
168
+ yield* callerLimits(scope);
169
+ const listed = yield* links.list.pipe(
170
+ Effect.mapError(
171
+ (error) =>
172
+ new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }),
173
+ ),
174
+ );
175
+ return {
176
+ environmentId: scope.environmentId,
177
+ links: listed.map((link) => ({
178
+ environmentId: link.environmentId,
179
+ label: link.label,
180
+ status: link.status,
181
+ access: link.access,
182
+ expiresAt: DateTime.formatIso(link.expiresAt),
183
+ lastError: link.lastError,
184
+ })),
185
+ };
186
+ },
187
+ );
188
+
189
+ return PeerForwarding.of({ call, waitForThread, links: listLinks });
190
+});
191
+
192
+export const layer = Layer.effect(PeerForwarding, make);
apps/server/src/peer/PeerLinks.test.ts
+35
-161
@@ -1,11 +1,5 @@
1
import { NodeHttpServer } from "@effect/platform-node";
2
-import * as NodeServices from "@effect/platform-node/NodeServices";
3
-import {
4
- EnvironmentHttpApi,
5
- EnvironmentId,
6
- type ExecutionEnvironmentDescriptor,
7
- OrchestratorMcpFailure,
8
-} from "@t3tools/contracts";
2
+import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
3
import { expect, it } from "@effect/vitest";
4
import * as Context from "effect/Context";
5
import * as Duration from "effect/Duration";
@@ -19,46 +13,23 @@ import { Tool, Toolkit } from "effect/ai";
13
import {
14
FetchHttpClient,
15
HttpClient,
22
- HttpRouter,
16
HttpServer,
17
HttpServerRequest,
18
HttpServerResponse,
19
} from "effect/http";
27
-import * as HttpApi from "effect/http-api/HttpApi";
28
-import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
20
30
-import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
31
-import * as AuthHttp from "../auth/http.ts";
32
-import * as McpOAuth from "../auth/McpOAuth.ts";
33
-import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
34
-import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
35
-import * as ServerConfig from "../config.ts";
36
-import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
37
-import * as ServerHttp from "../http.ts";
21
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
22
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
40
-import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
23
import * as McpToolAccess from "../mcp/McpToolAccess.ts";
42
-import * as Sqlite from "../persistence/Sqlite.ts";
24
import * as PeerLinks from "./PeerLinks.ts";
25
+import {
26
+ descriptorOf,
27
+ layerLinkingEnvironment,
28
+ servePeer,
29
+ type ServedPeer,
30
+} from "./PeerLinks.testkit.ts";
31
import * as PeerMcpClient from "./PeerMcpClient.ts";
32
46
-class PeerTestApi extends HttpApi.make("environment")
47
- .add(EnvironmentHttpApi.groups.metadata)
48
- .add(EnvironmentHttpApi.groups.mcpOAuth) {}
49
-
50
-const descriptorOf = (
51
- environmentId: string,
52
- label: string,
53
- capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
54
-): ExecutionEnvironmentDescriptor => ({
55
- environmentId: EnvironmentId.make(environmentId),
56
- label,
57
- platform: { os: "linux", arch: "x64" },
58
- serverVersion: "0.0.0-test",
59
- capabilities: { repositoryIdentity: true, mcpModeLimitHeader: true, ...capabilities },
60
-});
61
-
33
/** What B's probe saw: the calling client and the modes it may start work with. */
34
const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
35
@@ -78,127 +49,37 @@ const ProbeToolkit = Toolkit.make(
49
}),
50
);
51
81
-/**
82
- * Environment B as it runs: its descriptor, MCP OAuth, and `/mcp` behind the
83
- * real client authenticator, on a real socket. The descriptor can be swapped,
84
- * as when B's address comes to answer as another environment.
85
- */
86
-const serveB = (initial: ExecutionEnvironmentDescriptor) =>
87
- Effect.gen(function* () {
88
- const descriptor = yield* Ref.make(initial);
89
- const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
90
- const probes = yield* Ref.make(0);
91
- const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
92
- getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
93
- getDescriptor: Ref.get(descriptor),
94
- });
95
- const authContext = yield* EnvironmentAuth.layer.pipe(
96
- Layer.provide(Sqlite.layerMemory),
97
- Layer.provideMerge(ServerSecretStore.layer),
98
- Layer.provideMerge(ServerEnvironment.layerIdentity),
99
- Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-b-" })),
100
- Layer.provideMerge(NodeServices.layer),
101
- Layer.fresh,
102
- Layer.build,
103
- );
104
- // Every bearer B receives, on any route, so a test can show one was never sent.
105
- const layerRecordBearers = HttpRouter.middleware(
106
- (httpEffect) =>
107
- Effect.gen(function* () {
108
- const request = yield* HttpServerRequest.HttpServerRequest;
109
- if (request.url.startsWith("/.well-known/t3/environment")) {
110
- yield* Ref.update(probes, (count) => count + 1);
111
- }
112
- const authorization = request.headers.authorization;
113
- if (authorization !== undefined) {
114
- yield* Ref.update(bearers, (seen) => [...seen, authorization]);
115
- }
116
- return yield* httpEffect;
117
- }),
118
- { global: true },
119
- );
120
- const layerRoutes = Layer.mergeAll(
121
- HttpApiBuilder.layer(PeerTestApi).pipe(
122
- Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
123
- Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
124
- Layer.provide(AuthHttp.layerAuthenticatedAuth),
125
- ),
126
- McpHttpServer.toolkitRegistration(
127
- ProbeToolkit,
128
- McpToolAccess.toLayer(ProbeToolkit, {
129
- probe: McpToolAccess.reads(() =>
130
- McpInvocationContext.McpInvocationContext.pipe(
131
- Effect.map((scope) => {
132
- const modes = McpInvocationContext.clientModeCeiling(scope.client);
133
- return {
134
- caller: scope.client?.label ?? "none",
135
- modes: `${modes.runtimeMode}/${modes.interactionMode}`,
136
- };
137
- }),
138
- ),
139
- ),
140
- refuse: McpToolAccess.reads(() =>
141
- Effect.fail(
142
- new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
143
- ),
144
- ),
145
- }),
146
- ).pipe(
147
- Layer.provideMerge(McpHttpServer.layerMcpTransport),
148
- Layer.provide(
149
- Layer.mock(McpSessionRegistry.McpSessionRegistry)({
150
- // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
151
- resolve: () => Effect.succeed(undefined),
152
- }),
153
- ),
154
- Layer.provide(McpOAuth.layerMcpClientAuthenticator),
155
- ),
156
- ).pipe(
157
- Layer.provide(layerRecordBearers),
158
- Layer.provide(layerEnvironment),
159
- Layer.provide(Layer.succeedContext(authContext)),
160
- );
161
- yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
162
- Layer.build,
163
- );
164
- const address = (yield* HttpServer.HttpServer).address;
165
- if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
166
- return {
167
- url: `http://127.0.0.1:${address.port}`,
168
- auth: Context.get(authContext, EnvironmentAuth.EnvironmentAuth),
169
- descriptor,
170
- bearers,
171
- /** How often its descriptor was asked for, as a probe of whether it answers. */
172
- probes,
173
- };
174
- });
52
+const probeHandlers = McpToolAccess.toLayer(ProbeToolkit, {
53
+ probe: McpToolAccess.reads(() =>
54
+ McpInvocationContext.McpInvocationContext.pipe(
55
+ Effect.map((scope) => {
56
+ const modes = McpInvocationContext.clientModeCeiling(scope.client);
57
+ return {
58
+ caller: scope.client?.label ?? "none",
59
+ modes: `${modes.runtimeMode}/${modes.interactionMode}`,
60
+ };
61
+ }),
62
+ ),
63
+ ),
64
+ refuse: McpToolAccess.reads(() =>
65
+ Effect.fail(
66
+ new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
67
+ ),
68
+ ),
69
+});
70
176
-/** Environment A: its own database and secret store, reaching B over plain HTTP. */
71
+const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
72
+ servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
73
+
74
+/** Environment A, which links to B. */
75
const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
178
- Effect.gen(function* () {
179
- const context = yield* PeerMcpClient.layer.pipe(
180
- Layer.provideMerge(PeerLinks.layer),
181
- Layer.provide(
182
- Layer.mergeAll(
183
- Sqlite.layerMemory,
184
- ServerSecretStore.layer,
185
- FetchHttpClient.layer,
186
- Layer.succeed(ServerEnvironment.ServerEnvironment, {
187
- getEnvironmentId: Effect.succeed(descriptor.environmentId),
188
- getDescriptor: Effect.succeed(descriptor),
189
- }),
190
- ),
191
- ),
192
- Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-a-" })),
193
- Layer.provide(NodeServices.layer),
194
- Layer.fresh,
195
- Layer.build,
196
- );
197
- return {
76
+ layerLinkingEnvironment(descriptor).pipe(
77
+ Layer.build,
78
+ Effect.map((context) => ({
79
links: Context.get(context, PeerLinks.PeerLinks),
80
peer: Context.get(context, PeerMcpClient.PeerMcpClient),
200
- };
201
- });
81
+ })),
82
+ );
83
84
const laptop = descriptorOf("environment-laptop", "Laptop");
85
const box = descriptorOf("environment-box", "Box");
@@ -215,14 +96,7 @@ const probe = (
96
success: Probe,
97
});
98
218
-const linkedSessions = (b: Effect.Success<ReturnType<typeof serveB>>) =>
219
- b.auth
220
- .listSessions()
221
- .pipe(
222
- Effect.map((sessions) =>
223
- sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
224
- ),
225
- );
99
+const linkedSessions = (b: ServedPeer) => b.linkedSessions;
100
101
it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
102
Effect.scoped(
apps/server/src/peer/PeerLinks.testkit.ts
new
+177
@@ -0,0 +1,177 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import {
3
+ EnvironmentHttpApi,
4
+ EnvironmentId,
5
+ type AuthMcpClientAccess,
6
+ type ExecutionEnvironmentDescriptor,
7
+} from "@t3tools/contracts";
8
+import * as Context from "effect/Context";
9
+import * as Effect from "effect/Effect";
10
+import * as Layer from "effect/Layer";
11
+import * as Ref from "effect/Ref";
12
+import * as FetchHttpClient from "effect/http/FetchHttpClient";
13
+import * as HttpRouter from "effect/http/HttpRouter";
14
+import * as HttpServer from "effect/http/HttpServer";
15
+import * as HttpServerRequest from "effect/http/HttpServerRequest";
16
+import * as HttpApi from "effect/http-api/HttpApi";
17
+import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
18
+
19
+import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
20
+import * as AuthHttp from "../auth/http.ts";
21
+import * as McpOAuth from "../auth/McpOAuth.ts";
22
+import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
23
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24
+import * as ServerConfig from "../config.ts";
25
+import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26
+import * as ServerHttp from "../http.ts";
27
+import * as McpHttpServer from "../mcp/McpHttpServer.ts";
28
+import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
29
+import * as Sqlite from "../persistence/Sqlite.ts";
30
+import * as PeerLinks from "./PeerLinks.ts";
31
+import * as PeerMcpClient from "./PeerMcpClient.ts";
32
+
33
+class PeerTestApi extends HttpApi.make("environment")
34
+ .add(EnvironmentHttpApi.groups.metadata)
35
+ .add(EnvironmentHttpApi.groups.mcpOAuth) {}
36
+
37
+export const descriptorOf = (
38
+ environmentId: string,
39
+ label: string,
40
+ capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
41
+): ExecutionEnvironmentDescriptor => ({
42
+ environmentId: EnvironmentId.make(environmentId),
43
+ label,
44
+ platform: { os: "linux", arch: "x64" },
45
+ serverVersion: "0.0.0-test",
46
+ capabilities: { repositoryIdentity: true, mcpModeLimitHeader: true, ...capabilities },
47
+});
48
+
49
+/**
50
+ * The environment a link points at, as it runs: its descriptor, MCP OAuth,
51
+ * and `/mcp` with `tools` behind the real client authenticator, on a real
52
+ * socket. The descriptor can be swapped, as when its address comes to answer
53
+ * as another environment, and every bearer it receives is recorded.
54
+ */
55
+export const servePeer = <E, R>(
56
+ initial: ExecutionEnvironmentDescriptor,
57
+ tools: Layer.Layer<never, E, R>,
58
+) =>
59
+ Effect.gen(function* () {
60
+ const descriptor = yield* Ref.make(initial);
61
+ const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
62
+ const probes = yield* Ref.make(0);
63
+ const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
64
+ getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
65
+ getDescriptor: Ref.get(descriptor),
66
+ });
67
+ const authContext = yield* EnvironmentAuth.layer.pipe(
68
+ Layer.provide(Sqlite.layerMemory),
69
+ Layer.provideMerge(ServerSecretStore.layer),
70
+ Layer.provideMerge(ServerEnvironment.layerIdentity),
71
+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
72
+ Layer.provideMerge(NodeServices.layer),
73
+ Layer.fresh,
74
+ Layer.build,
75
+ );
76
+ const layerRecordBearers = HttpRouter.middleware(
77
+ (httpEffect) =>
78
+ Effect.gen(function* () {
79
+ const request = yield* HttpServerRequest.HttpServerRequest;
80
+ if (request.url.startsWith("/.well-known/t3/environment")) {
81
+ yield* Ref.update(probes, (count) => count + 1);
82
+ }
83
+ const authorization = request.headers.authorization;
84
+ if (authorization !== undefined) {
85
+ yield* Ref.update(bearers, (seen) => [...seen, authorization]);
86
+ }
87
+ return yield* httpEffect;
88
+ }),
89
+ { global: true },
90
+ );
91
+ const layerRoutes = Layer.mergeAll(
92
+ HttpApiBuilder.layer(PeerTestApi).pipe(
93
+ Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
94
+ Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
95
+ Layer.provide(AuthHttp.layerAuthenticatedAuth),
96
+ ),
97
+ tools.pipe(
98
+ Layer.provideMerge(McpHttpServer.layerMcpTransport),
99
+ Layer.provide(
100
+ Layer.mock(McpSessionRegistry.McpSessionRegistry)({
101
+ // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
102
+ resolve: () => Effect.succeed(undefined),
103
+ }),
104
+ ),
105
+ Layer.provide(McpOAuth.layerMcpClientAuthenticator),
106
+ ),
107
+ ).pipe(
108
+ Layer.provide(layerRecordBearers),
109
+ Layer.provide(layerEnvironment),
110
+ Layer.provide(Layer.succeedContext(authContext)),
111
+ );
112
+ // Fresh, so the peer never shares a toolkit or MCP server with the
113
+ // environment that links to it in the same test.
114
+ yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
115
+ Layer.fresh,
116
+ Layer.build,
117
+ );
118
+ const address = (yield* HttpServer.HttpServer).address;
119
+ if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
120
+ const url = `http://127.0.0.1:${address.port}`;
121
+ const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
122
+ return {
123
+ url,
124
+ auth,
125
+ descriptor,
126
+ bearers,
127
+ /** How often its descriptor was asked for, as a probe of whether it answers. */
128
+ probes,
129
+ /** The sessions linking created there, which its Connections lists. */
130
+ linkedSessions: auth
131
+ .listSessions()
132
+ .pipe(
133
+ Effect.map((sessions) =>
134
+ sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
135
+ ),
136
+ ),
137
+ };
138
+ });
139
+
140
+export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
141
+
142
+/**
143
+ * The environment that links: its own database and secret store, reaching
144
+ * peers over plain HTTP. Provide it to anything built on its links.
145
+ */
146
+export const layerLinkingEnvironment = (descriptor: ExecutionEnvironmentDescriptor) =>
147
+ PeerMcpClient.layer.pipe(
148
+ Layer.provideMerge(PeerLinks.layer),
149
+ Layer.provide(
150
+ Layer.mergeAll(
151
+ Sqlite.layerMemory,
152
+ ServerSecretStore.layer,
153
+ FetchHttpClient.layer,
154
+ Layer.succeed(ServerEnvironment.ServerEnvironment, {
155
+ getEnvironmentId: Effect.succeed(descriptor.environmentId),
156
+ getDescriptor: Effect.succeed(descriptor),
157
+ }),
158
+ ),
159
+ ),
160
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-here-" })),
161
+ Layer.provideMerge(NodeServices.layer),
162
+ Layer.fresh,
163
+ );
164
+
165
+/** Links `links` to `peer` with a fresh pairing code from it. */
166
+export const linkTo = (
167
+ links: PeerLinks.PeerLinks["Service"],
168
+ peer: ServedPeer,
169
+ access: AuthMcpClientAccess = "auto",
170
+) =>
171
+ peer.auth
172
+ .issuePairingCredential()
173
+ .pipe(
174
+ Effect.flatMap((pairing) =>
175
+ links.link({ url: peer.url, pairingCode: pairing.credential, access }),
176
+ ),
177
+ );
apps/server/src/provider/AgentContextBudget.test.ts
+2
@@ -22,6 +22,7 @@ import { ProviderAdapterRegistryV2 } from "../orchestration-v2/ProviderAdapterRe
22
import { ThreadLaunchService } from "../orchestration-v2/ThreadLaunchService.ts";
23
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
24
import { ThreadSearch } from "../orchestration-v2/ThreadSearch.ts";
25
+import { PeerForwarding } from "../peer/PeerForwarding.ts";
26
import { PreviewManager } from "../preview/Manager.ts";
27
import { PreviewBrowser } from "../preview/PreviewBrowser.ts";
28
import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts";
@@ -48,6 +49,7 @@ const toolHandlerServices = Layer.mergeAll(
49
Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }),
50
Layer.mock(McpProviderSessions)({}),
51
Layer.mock(OrchestratorV2)({}),
52
+ Layer.mock(PeerForwarding)({}),
53
Layer.mock(PreviewAutomationBroker)({}),
54
Layer.mock(PreviewBrowser)({}),
55
Layer.mock(PreviewManager)({}),
apps/server/src/provider/agentContextBudget.json
+3
-3
@@ -1,5 +1,5 @@
1
{
2
- "claudeSystemAppendBytes": 4857,
3
- "codexAdditionalContextBytes": 5409,
4
- "mcpToolListJsonBytes": 42349
2
+ "claudeSystemAppendBytes": 5086,
3
+ "codexAdditionalContextBytes": 5638,
4
+ "mcpToolListJsonBytes": 44232
5
}
apps/server/src/server.ts
+7
-1
@@ -67,6 +67,7 @@ import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceR
67
import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts";
68
import * as TerminalManager from "./terminal/Manager.ts";
69
import * as McpHttpServer from "./mcp/McpHttpServer.ts";
70
+import * as PeerForwarding from "./peer/PeerForwarding.ts";
71
import * as PeerLinks from "./peer/PeerLinks.ts";
72
import * as PeerMcpClient from "./peer/PeerMcpClient.ts";
73
import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
@@ -743,7 +744,12 @@ const layerMakeRoutes = Layer.mergeAll(
744
),
745
Layer.provide(PreviewBrowser.layer),
746
// Links to other environments, shared by Settings (WebSocket) and agents (/mcp).
746
- Layer.provide(PeerMcpClient.layer.pipe(Layer.provideMerge(PeerLinks.layer))),
747
+ Layer.provide(
748
+ PeerForwarding.layer.pipe(
749
+ Layer.provideMerge(PeerMcpClient.layer),
750
+ Layer.provideMerge(PeerLinks.layer),
751
+ ),
752
+ ),
753
Layer.provide(PreviewAutomationBroker.layer),
754
Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))),
755
Layer.provide(layerCommandReadiness),
docs/internals/remote.md
+35
-1
@@ -11,7 +11,8 @@ not introduce another execution model. See
11
An environment keeps its ID across server restarts and endpoint changes. Saved
12
connections are local to a client profile; the server's identity and state are
13
not. A repository identity can correlate clones across environments, but never
14
-routes work between them. A project and its threads belong to one environment.
14
+routes work between them. A project and its threads belong to one environment;
15
+an agent reaches another environment's threads only through a peer link.
16
The canonical key follows the `upstream` remote when one exists, so pull request
17
features target the repository a fork tracks. A fork also reports its own
18
`origin`, and clients group and label by that, so a fork never collapses into a
@@ -66,6 +67,39 @@ miss a DHCP change, and the wildcard keeps the reported addresses current.
67
Pull request routing trust covers the whole route list. Adding or changing a route
68
revokes it; reordering does not, because the same addresses remain trusted.
69
70
+## Peer links
71
+
72
+A [peer link](../../apps/server/src/peer/PeerLinks.ts) lets one environment's
73
+agents work in another. The linking environment signs in to the other's `/mcp`
74
+as an outside MCP client, with a pairing code from it, and keeps that session's
75
+token in its own secret store. The other environment needs nothing new: it
76
+sees one more OAuth client, lists it in Connections, and revokes it there.
77
+Unlinking on the linking side only forgets the token.
78
+
79
+- **A tool runs in a linked environment when its parameters take
80
+ `OrchestratorMcpEnvironmentTarget`** as `environmentId`.
81
+ [`McpToolAccess.toLayer`](../../apps/server/src/mcp/McpToolAccess.ts) sends
82
+ such a call there once the tool's access declaration has checked the caller,
83
+ so a read-only or ended caller is refused before anything is sent. The
84
+ thread or project the call names is checked where it lives. A tool that acts
85
+ as the calling thread itself cannot take a linked environment.
86
+- **Every forwarded call carries the calling agent's modes** in
87
+ `T3-Mode-Limit`, which the receiving `/mcp` only ever narrows the client's
88
+ approved access with. A plan-mode agent therefore cannot start full-access
89
+ work through a full-access link.
90
+- **The token goes only to an address that proves it is the linked
91
+ environment**: its descriptor must report the linked environment id. A LAN
92
+ address that now belongs to another machine never receives it.
93
+- **All callers on one side share the link's single session on the other**,
94
+ so idempotency keys are hashed with the caller's namespace before they
95
+ leave. Without that, two agents reusing a key would collide on the far side.
96
+- **A forwarded wait is split into calls of at most 50 s**, because the
97
+ receiving `/mcp` sends nothing while a wait is open and T3 Connect's edge
98
+ drops idle requests after about 100 s.
99
+
100
+The link is routing, not isolation: an agent the link starts runs as the
101
+receiving environment's user, inside the limits above.
102
+
103
## Hosted web is a client
104
105
The hosted web app stores its connection catalog in the browser and connects
packages/client-runtime/src/t3ToolSummary.ts
+3
@@ -336,6 +336,9 @@ export function summarizeT3ToolCalls(
336
case "environment-update":
337
label = phrase("Updated", "update", `environment preferences ${times}`);
338
break;
339
+ case "environment-links":
340
+ label = phrase("Listed", "list", `linked environments ${times}`);
341
+ break;
342
case "attachment-prepare":
343
label = phrase(
344
"Prepared",
packages/contracts/src/orchestratorMcp.ts
+49
@@ -2,8 +2,10 @@ import * as Effect from "effect/Effect";
2
import * as Schema from "effect/Schema";
3
import * as SchemaTransformation from "effect/SchemaTransformation";
4
5
+import { AuthMcpClientAccess } from "./auth.ts";
6
import {
7
ContextTransferId,
8
+ EnvironmentId,
9
IsoDateTime,
10
MessageId,
11
NodeId,
@@ -296,7 +298,20 @@ const OrchestratorMcpProjectTarget = Schema.optional(
298
}),
299
);
300
301
+/**
302
+ * A linked environment to act in instead of this one. The tools that take it
303
+ * forward the call there, where the link's access and the caller's own modes
304
+ * both apply.
305
+ */
306
+export const OrchestratorMcpEnvironmentTarget = Schema.optional(
307
+ EnvironmentId.annotate({
308
+ description:
309
+ "Linked environment to act in. Omit for this one. Ids are then that environment's.",
310
+ }),
311
+);
312
+
313
export const OrchestratorMcpThreadListInput = Schema.Struct({
314
+ environmentId: OrchestratorMcpEnvironmentTarget,
315
projectId: OrchestratorMcpProjectTarget,
316
statuses: Schema.optional(
317
Schema.Array(OrchestratorMcpThreadStatus).check(Schema.isMaxLength(10)),
@@ -369,6 +384,7 @@ const clampedPositiveInt = (maximum: number) =>
384
);
385
386
export const OrchestratorMcpThreadReadInput = Schema.Struct({
387
+ environmentId: OrchestratorMcpEnvironmentTarget,
388
threadId: ThreadId,
389
itemId: Schema.optional(TurnItemId),
390
textOffset: Schema.optional(NonNegativeInt),
@@ -463,6 +479,7 @@ export const OrchestratorMcpThreadReadResult = Schema.Struct({
479
export type OrchestratorMcpThreadReadResult = typeof OrchestratorMcpThreadReadResult.Type;
480
481
export const OrchestratorMcpThreadSendInput = Schema.Struct({
482
+ environmentId: OrchestratorMcpEnvironmentTarget,
483
threadId: ThreadId,
484
message: OrchestratorMcpPrompt,
485
mode: Schema.optional(Schema.Literals(["auto", "queue", "steer", "restart"])),
@@ -482,6 +499,7 @@ export const OrchestratorMcpThreadSendResult = Schema.Struct({
499
export type OrchestratorMcpThreadSendResult = typeof OrchestratorMcpThreadSendResult.Type;
500
501
export const OrchestratorMcpThreadWaitInput = Schema.Struct({
502
+ environmentId: OrchestratorMcpEnvironmentTarget,
503
threadId: ThreadId,
504
runId: Schema.optional(RunId),
505
timeoutMs: Schema.optional(Schema.Finite),
@@ -498,9 +516,16 @@ export const OrchestratorMcpThreadWaitResult = Schema.Struct({
516
export type OrchestratorMcpThreadWaitResult = typeof OrchestratorMcpThreadWaitResult.Type;
517
518
export const OrchestratorMcpThreadInterruptInput = Schema.Struct({
519
+ environmentId: OrchestratorMcpEnvironmentTarget,
520
threadId: ThreadId,
521
runId: Schema.optional(RunId),
522
reason: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))),
523
+ /**
524
+ * Stop the thread as its Stop button does instead: interrupt its running
525
+ * turn whichever run that is, hold its queued messages, end its pull request
526
+ * watches and stop every task it delegated. `runId` is then not used.
527
+ */
528
+ stop: Schema.optional(Schema.Boolean),
529
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
530
});
531
export type OrchestratorMcpThreadInterruptInput = typeof OrchestratorMcpThreadInterruptInput.Type;
@@ -517,6 +542,7 @@ export const OrchestratorMcpThreadInterruptResult = Schema.Struct({
542
export type OrchestratorMcpThreadInterruptResult = typeof OrchestratorMcpThreadInterruptResult.Type;
543
544
export const OrchestratorMcpCapabilitiesInput = Schema.Struct({
545
+ environmentId: OrchestratorMcpEnvironmentTarget,
546
search: Schema.optional(
547
TrimmedNonEmptyString.check(Schema.isMaxLength(200)).annotate({
548
description: "Match model ids and labels. Replaces the short list.",
@@ -553,6 +579,25 @@ export const OrchestratorMcpProviderCapability = Schema.Struct({
579
});
580
export type OrchestratorMcpProviderCapability = typeof OrchestratorMcpProviderCapability.Type;
581
582
+export const OrchestratorMcpEnvironmentLink = Schema.Struct({
583
+ environmentId: EnvironmentId,
584
+ label: Schema.String,
585
+ /** Whether it answered just now. An expired link must be linked again there. */
586
+ status: Schema.Literals(["reachable", "unreachable", "expired"]),
587
+ /** The most the linked environment lets this one's agents do there. */
588
+ access: AuthMcpClientAccess,
589
+ expiresAt: IsoDateTime,
590
+ lastError: Schema.NullOr(Schema.String),
591
+});
592
+export type OrchestratorMcpEnvironmentLink = typeof OrchestratorMcpEnvironmentLink.Type;
593
+
594
+export const OrchestratorMcpEnvironmentLinksResult = Schema.Struct({
595
+ environmentId: EnvironmentId,
596
+ links: Schema.Array(OrchestratorMcpEnvironmentLink),
597
+});
598
+export type OrchestratorMcpEnvironmentLinksResult =
599
+ typeof OrchestratorMcpEnvironmentLinksResult.Type;
600
+
601
export const OrchestratorMcpCapabilitiesResult = Schema.Struct({
602
parentThreadId: Schema.NullOr(ThreadId),
603
inheritedProviderInstanceId: Schema.NullOr(ProviderInstanceId),
@@ -575,6 +620,7 @@ export const OrchestratorMcpCapabilitiesResult = Schema.Struct({
620
export type OrchestratorMcpCapabilitiesResult = typeof OrchestratorMcpCapabilitiesResult.Type;
621
622
export const OrchestratorMcpScheduleTaskInput = Schema.Struct({
623
+ environmentId: OrchestratorMcpEnvironmentTarget,
624
projectId: OrchestratorMcpProjectTarget,
625
prompt: OrchestratorMcpPrompt,
626
schedule: OrchestratorMcpSchedule,
@@ -621,6 +667,7 @@ export const OrchestratorMcpScheduleTaskResult = OrchestratorMcpScheduledTask;
667
export type OrchestratorMcpScheduleTaskResult = typeof OrchestratorMcpScheduleTaskResult.Type;
668
669
export const OrchestratorMcpListScheduledTasksInput = Schema.Struct({
670
+ environmentId: OrchestratorMcpEnvironmentTarget,
671
projectId: Schema.optional(
672
ProjectId.annotate({
673
description: "Default: your thread's project, or all outside a thread.",
@@ -637,6 +684,7 @@ export type OrchestratorMcpListScheduledTasksResult =
684
typeof OrchestratorMcpListScheduledTasksResult.Type;
685
686
export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({
687
+ environmentId: OrchestratorMcpEnvironmentTarget,
688
scheduledTaskId: ScheduledTaskId,
689
prompt: Schema.optional(OrchestratorMcpPrompt),
690
title: Schema.optional(OrchestratorMcpTitle),
@@ -692,6 +740,7 @@ export const OrchestratorMcpRequestSecretResult = Schema.Union([
740
export type OrchestratorMcpRequestSecretResult = typeof OrchestratorMcpRequestSecretResult.Type;
741
742
export const OrchestratorMcpDeleteScheduledTaskInput = Schema.Struct({
743
+ environmentId: OrchestratorMcpEnvironmentTarget,
744
scheduledTaskId: ScheduledTaskId,
745
});
746
export type OrchestratorMcpDeleteScheduledTaskInput =
packages/provider-core/src/server/orchestrationInstructions.ts
+2
-1
@@ -13,7 +13,8 @@ Ordinary coding tasks need no T3 tools.
13
- If you are a subagent or child, do the work yourself. Start no subagents unless your task says to.`,
14
`- \`t3_thread_launch\` and \`create_threads\` make new top-level threads, only when the user asks for a new thread. "Subagent", "delegate", and "parallel" never mean one. Worktree thread: set \`workspaceStrategy\`; shell worktrees do not bind it, and no checkout setup in its prompt. No \`workspaceStrategy\`: project root, not your worktree.
15
- Given a thread id, \`t3_thread_read\` it before you answer about it.
16
-- In your reply, a thread's first mention is its \`link\` verbatim. No \`link\`: \`[title](t3-thread://v1/<exact id>)\`. Never a plain title or bare id.
16
+- Another machine: \`t3_environment_links\` lists linked ones. Pass its \`environmentId\` to a T3 tool to act there. Ids are then that machine's, so pass \`threadId\`.
17
+- In your reply, a thread's first mention is its \`link\` verbatim. No \`link\`: \`[title](t3-thread://v1/<exact id>)\`. Never a plain title or bare id. A thread on a linked machine: its title and machine, not its link.
18
- A secret: call \`request_secret\` yourself. Pass its \`secretRef\` to a T3 tool, or use \`delivery: "file"\` for a shell command. Never ask in chat or invent one. When asked only to schedule, \`schedule_task\` without running its prompt.
19
- T3 tools may load late. Try the name once before you call it absent.`,
20
`### Visuals and preview
packages/shared/src/t3McpToolPresentation.ts
+5
@@ -51,6 +51,7 @@ export type T3McpToolSummaryAction =
51
| "project-delete"
52
| "project-clone"
53
| "environment-read"
54
+ | "environment-links"
55
| "environment-update"
56
| "attachment-prepare"
57
| "attachment-discard"
@@ -321,6 +322,10 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
322
["Read", "Reading", "Read", "environment preferences"],
323
"environment-read",
324
),
325
+ t3_environment_links: tool(
326
+ ["List", "Listing", "Listed", "linked environments"],
327
+ "environment-links",
328
+ ),
329
t3_environment_preferences_update: tool(
330
["Update", "Updating", "Updated", "environment preferences"],
331
"environment-update",