Skip to content

Commit ef2d43d

Browse files
jakeleventhalclaude
andcommitted
feat(mcp): agents can launch threads on another connected environment
A thread's t3-code MCP server only knew its own environment, so an agent could not start work on another machine the user had connected. Environments still never talk to each other. The server hands the request to a connected app, and the app runs it over the session it already has with the target, so no credential is stored and the target enforces that app's permissions. - t3_environment_list and t3_environment_catalog discover other environments and their projects and provider instances - t3_thread_launch, t3_thread_read and t3_thread_wait take an optional environmentId; omitted means local, unchanged - the shared client runtime registers each app as a carrier with every environment that advertises the peerEnvironments capability Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent 37de6cb commit ef2d43d

33 files changed

Lines changed: 2017 additions & 41 deletions

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ export const RPC_REQUIRED_SCOPES = {
189189
[WS_METHODS.previewAutomationConnect]: AuthOrchestrationOperateScope,
190190
[WS_METHODS.previewAutomationRespond]: AuthOrchestrationOperateScope,
191191
[WS_METHODS.previewAutomationFocusHost]: AuthOrchestrationOperateScope,
192+
[WS_METHODS.peerEnvironmentsConnect]: AuthOrchestrationOperateScope,
193+
[WS_METHODS.peerEnvironmentsRespond]: AuthOrchestrationOperateScope,
192194
[WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
193195
[WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
194196
[WS_METHODS.deviceConfigure]: AuthOrchestrationOperateScope,

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,7 @@ export const make = Effect.gen(function* () {
249249
serverResolvedCommandContext: true,
250250
environmentIcon: true,
251251
projectCloneTracking: true,
252+
peerEnvironments: true,
252253
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
253254
...(serverInstallation === null ? {} : { serverInstallation }),
254255
// V2 restart recovery uses the environment-owned opt-in. The old

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import { AttachmentHandlersLive } from "./toolkits/attachment/handlers.ts";
3131
import { ThreadToolkit } from "./toolkits/thread/tools.ts";
3232
import { ThreadToolkitHandlersLive } from "./toolkits/thread/handlers.ts";
3333
import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";
34+
import * as PeerEnvironmentService from "./PeerEnvironmentService.ts";
3435
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
3536
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
3637
import { OrchestratorToolkitHandlersLive } from "./toolkits/orchestrator/handlers.ts";
@@ -726,4 +727,4 @@ export const layer = Layer.mergeAll(
726727
WorktreeToolkitRegistrationLive,
727728
PullRequestsToolkitRegistrationLive,
728729
DeviceToolkitRegistrationLive,
729-
).pipe(Layer.provideMerge(McpTransportLive));
730+
).pipe(Layer.provide(PeerEnvironmentService.layer), Layer.provideMerge(McpTransportLive));

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

Lines changed: 34 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -72,13 +72,13 @@ import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
7272
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
7373
import type { McpInvocationScope } from "./McpInvocationContext.ts";
7474

75-
const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
76-
const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
75+
export const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
76+
export const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000;
7777
const TASK_POLL_INTERVAL_MS = 50;
7878
const DEFAULT_THREAD_LIST_LIMIT = 50;
79-
const DEFAULT_THREAD_READ_LIMIT = 50;
80-
const DEFAULT_THREAD_RUN_LIMIT = 10;
81-
const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
79+
export const DEFAULT_THREAD_READ_LIMIT = 50;
80+
export const DEFAULT_THREAD_RUN_LIMIT = 10;
81+
export const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
8282

8383
interface ResolvedTarget {
8484
readonly modelSelection: ModelSelection;
@@ -230,6 +230,29 @@ function providerConstraints(
230230
return constraints;
231231
}
232232

233+
/** One provider instance as agents see it when choosing a launch or delegation target. */
234+
export function providerCapability(
235+
provider: ServerProvider,
236+
supportsOrchestrationV2: boolean,
237+
): OrchestratorMcpCapabilitiesResult["providers"][number] {
238+
const constraints = providerConstraints(provider, supportsOrchestrationV2);
239+
return {
240+
providerInstanceId: provider.instanceId,
241+
driverKind: provider.driver,
242+
displayName: provider.displayName ?? null,
243+
models: provider.models.map((model) => ({
244+
id: model.slug,
245+
label: model.name ?? null,
246+
...(model.capabilities?.optionDescriptors === undefined
247+
? {}
248+
: { options: model.capabilities.optionDescriptors }),
249+
})),
250+
canRunChildTask: constraints.length === 0,
251+
canRunCrossProviderChildTask: constraints.length === 0,
252+
constraints: [...constraints],
253+
};
254+
}
255+
233256
/**
234257
* Checks requested option selections for duplicates and, when the model
235258
* advertises option descriptors, against those descriptors. Models without
@@ -591,7 +614,7 @@ function listItemFromShell(shell: OrchestrationV2ThreadShell): OrchestratorMcpTh
591614
};
592615
}
593616

594-
function threadDetail(
617+
export function threadDetail(
595618
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "runtimeRequests">,
596619
itemCount: number,
597620
): OrchestratorMcpThreadDetail {
@@ -635,7 +658,7 @@ function threadDetail(
635658
};
636659
}
637660

638-
function threadRun(run: OrchestrationV2Run): OrchestratorMcpThreadRun {
661+
export function threadRun(run: OrchestrationV2Run): OrchestratorMcpThreadRun {
639662
return {
640663
runId: run.id,
641664
ordinal: run.ordinal,
@@ -715,7 +738,7 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null {
715738
}
716739
}
717740

718-
function timelineItem(input: {
741+
export function timelineItem(input: {
719742
readonly row: OrchestrationV2ThreadProjection["visibleTurnItems"][number];
720743
readonly maxChars: number;
721744
readonly textOffset?: number;
@@ -1332,28 +1355,9 @@ const make = Effect.gen(function* () {
13321355
inheritedModel: parent.thread.modelSelection.model,
13331356
runtimeMode: parent.thread.runtimeMode,
13341357
interactionMode: parent.thread.interactionMode,
1335-
providers: providers.map((provider) => {
1336-
const constraints = providerConstraints(
1337-
provider,
1338-
orchestrationCapableInstanceIds.has(provider.instanceId),
1339-
);
1340-
return {
1341-
providerInstanceId: provider.instanceId,
1342-
driverKind: provider.driver,
1343-
displayName: provider?.displayName ?? null,
1344-
models:
1345-
provider?.models.map((model) => ({
1346-
id: model.slug,
1347-
label: model.name ?? null,
1348-
...(model.capabilities?.optionDescriptors === undefined
1349-
? {}
1350-
: { options: model.capabilities.optionDescriptors }),
1351-
})) ?? [],
1352-
canRunChildTask: constraints.length === 0,
1353-
canRunCrossProviderChildTask: constraints.length === 0,
1354-
constraints: [...constraints],
1355-
};
1356-
}),
1358+
providers: providers.map((provider) =>
1359+
providerCapability(provider, orchestrationCapableInstanceIds.has(provider.instanceId)),
1360+
),
13571361
features: {
13581362
appOwnedSubagents: true,
13591363
asyncPolling: true,
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import { assert, it } from "@effect/vitest";
2+
import {
3+
EnvironmentId,
4+
type PeerEnvironmentOperation,
5+
type PeerEnvironmentResponse,
6+
type PeerEnvironmentSummary,
7+
} from "@t3tools/contracts";
8+
import * as NodeServices from "@effect/platform-node/NodeServices";
9+
import * as Deferred from "effect/Deferred";
10+
import * as Effect from "effect/Effect";
11+
import * as Fiber from "effect/Fiber";
12+
import * as Stream from "effect/Stream";
13+
import * as TestClock from "effect/testing/TestClock";
14+
15+
import * as PeerEnvironmentBroker from "./PeerEnvironmentBroker.ts";
16+
17+
const makeBroker = PeerEnvironmentBroker.make.pipe(Effect.provide(NodeServices.layer));
18+
const r2d2 = EnvironmentId.make("environment-r2d2");
19+
const summary = (status: PeerEnvironmentSummary["status"]): PeerEnvironmentSummary => ({
20+
environmentId: r2d2,
21+
label: "r2d2",
22+
status,
23+
});
24+
25+
/** A connected app that answers every request with `answer`. */
26+
const connectApp = (
27+
broker: PeerEnvironmentBroker.PeerEnvironmentBroker["Service"],
28+
clientId: string,
29+
answer: (operation: PeerEnvironmentOperation) => PeerEnvironmentResponse["outcome"] | null,
30+
) =>
31+
Effect.gen(function* () {
32+
const events = yield* broker.connect({ clientId });
33+
const connected = yield* Deferred.make<void>();
34+
yield* events.pipe(
35+
Stream.runForEach((event) => {
36+
if (event.type === "connected") return Deferred.succeed(connected, undefined);
37+
const outcome = answer(event.request.operation);
38+
return outcome === null
39+
? Effect.void
40+
: broker.respond({
41+
clientId,
42+
connectionId: event.connectionId,
43+
requestId: event.request.requestId,
44+
outcome,
45+
});
46+
}),
47+
Effect.forkScoped,
48+
);
49+
yield* Deferred.await(connected);
50+
});
51+
52+
it.effect("refuses to reach another environment when no app is connected", () =>
53+
Effect.gen(function* () {
54+
const broker = yield* makeBroker;
55+
const error = yield* Effect.flip(broker.invoke({ operation: "catalog", environmentId: r2d2 }));
56+
assert.equal(error.code, "host_unavailable");
57+
assert.include(error.message, "connected to both");
58+
}),
59+
);
60+
61+
it.effect("carries a request through the connected app and returns its answer", () =>
62+
Effect.gen(function* () {
63+
const broker = yield* makeBroker;
64+
const seen: Array<PeerEnvironmentOperation> = [];
65+
yield* connectApp(broker, "desktop", (operation) => {
66+
seen.push(operation);
67+
return { ok: true, result: { operation: "list", environments: [summary("connected")] } };
68+
});
69+
assert.deepEqual(yield* broker.list, [summary("connected")]);
70+
assert.deepEqual(seen, [{ operation: "list" }]);
71+
}).pipe(Effect.scoped),
72+
);
73+
74+
it.effect("tries another app when the newest one cannot reach the target", () =>
75+
Effect.gen(function* () {
76+
const broker = yield* makeBroker;
77+
yield* connectApp(broker, "desktop", () => ({
78+
ok: true,
79+
result: {
80+
operation: "catalog",
81+
label: "r2d2",
82+
serverVersion: "1.0.0",
83+
providers: [],
84+
projects: [],
85+
},
86+
}));
87+
yield* connectApp(broker, "phone", () => ({
88+
ok: false,
89+
code: "environment_not_connected",
90+
message: "not saved on this phone",
91+
}));
92+
const result = yield* broker.invoke({ operation: "catalog", environmentId: r2d2 });
93+
assert.equal(result.label, "r2d2");
94+
}).pipe(Effect.scoped),
95+
);
96+
97+
it.effect("does not retry elsewhere once the target itself refused the request", () =>
98+
Effect.gen(function* () {
99+
const broker = yield* makeBroker;
100+
let olderAppAsked = false;
101+
yield* connectApp(broker, "desktop", () => {
102+
olderAppAsked = true;
103+
return null;
104+
});
105+
yield* connectApp(broker, "phone", () => ({
106+
ok: false,
107+
code: "environment_unauthorized",
108+
message: "r2d2 refused the request",
109+
}));
110+
const error = yield* Effect.flip(broker.invoke({ operation: "catalog", environmentId: r2d2 }));
111+
assert.equal(error.code, "environment_unauthorized");
112+
assert.isFalse(olderAppAsked);
113+
}).pipe(Effect.scoped),
114+
);
115+
116+
it.effect("ignores an answer that does not come from the app that was asked", () =>
117+
Effect.gen(function* () {
118+
const broker = yield* makeBroker;
119+
const events = yield* broker.connect({ clientId: "desktop" });
120+
const fiber = yield* broker
121+
.invoke({ operation: "catalog", environmentId: r2d2 }, 1_000)
122+
.pipe(Effect.flip, Effect.forkScoped);
123+
const request = yield* events.pipe(
124+
Stream.filter((event) => event.type === "request"),
125+
Stream.runHead,
126+
);
127+
assert.isTrue(request._tag === "Some");
128+
if (request._tag !== "Some") return;
129+
yield* broker.respond({
130+
clientId: "someone-else",
131+
connectionId: request.value.connectionId,
132+
requestId: request.value.request.requestId,
133+
outcome: { ok: true, result: { operation: "list", environments: [] } },
134+
});
135+
yield* TestClock.adjust(3_000);
136+
const error = yield* Fiber.join(fiber);
137+
assert.equal(error.code, "host_unavailable");
138+
}).pipe(Effect.scoped),
139+
);
140+
141+
it.effect("reports the best status when several apps know the same environment", () =>
142+
Effect.gen(function* () {
143+
const broker = yield* makeBroker;
144+
yield* connectApp(broker, "desktop", () => ({
145+
ok: true,
146+
result: { operation: "list", environments: [summary("connected")] },
147+
}));
148+
yield* connectApp(broker, "phone", () => ({
149+
ok: true,
150+
result: { operation: "list", environments: [summary("offline")] },
151+
}));
152+
assert.deepEqual(yield* broker.list, [summary("connected")]);
153+
}).pipe(Effect.scoped),
154+
);

0 commit comments

Comments
 (0)