Skip to content

Commit fd14efc

Browse files
fix(server): integrate forwarding with reviewed peer links
1 parent 3aac959 commit fd14efc

9 files changed

Lines changed: 123 additions & 229 deletions

File tree

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@ const dependencies = [
4848
ThreadManagementService.ThreadManagementService,
4949
OrchestratorMcpService.OrchestratorMcpService,
5050
];
51-
/** Listing this environment's links. */
5251
const linkDependencies = [...dependencies, PeerForwarding.PeerForwarding];
5352
const threadMetadataDependencies = [
5453
McpInvocationContext.McpInvocationContext,

‎apps/server/src/peer/PeerForwarding.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { expect, it } from "@effect/vitest";
1313
import * as Context from "effect/Context";
1414
import * as Effect from "effect/Effect";
1515
import * as Layer from "effect/Layer";
16+
import * as Option from "effect/Option";
1617
import * as Ref from "effect/Ref";
1718
import { McpSchema, McpServer } from "effect/ai";
1819

@@ -120,6 +121,7 @@ const boxThreads = (seen: Ref.Ref<Seen>) => {
120121
/** B launches whatever it is asked to, and records it. */
121122
const boxLaunches = (seen: Ref.Ref<Seen>) =>
122123
Layer.mock(ThreadLaunch.ThreadLaunchService)({
124+
getAcceptedLaunch: () => Effect.succeed(Option.none()),
123125
launch: (input) =>
124126
Ref.update(seen, (current) => ({ ...current, launches: [...current.launches, input] })).pipe(
125127
Effect.as({
@@ -359,6 +361,18 @@ it.effect("an agent here works on a linked environment's threads within its own
359361
`thread.stop ${boxThread}`,
360362
`delegated-tasks.stop ${boxThread}`,
361363
]);
364+
365+
yield* Ref.set(
366+
b.descriptor,
367+
descriptorOf("environment-box", "Box", {
368+
mcpModeLimitHeader: false,
369+
}),
370+
);
371+
const incompatible = yield* a.call("thread:laptop-full", "t3_environment_links", {});
372+
expect(incompatible.isError).toBe(false);
373+
expect(incompatible.structuredContent).toMatchObject({
374+
links: [{ environmentId: box.environmentId, status: "incompatible" }],
375+
});
362376
}),
363377
).pipe(Effect.provide(NodeHttpServer.layerTest)),
364378
);

‎apps/server/src/peer/PeerForwarding.ts‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -39,33 +39,21 @@ const hasScheduleSecretRef = Schema.is(
3939

4040
type Scope = McpInvocationContext.McpInvocationScope;
4141

42-
/**
43-
* Runs T3 MCP tools in a linked environment for an agent here. The tool's own
44-
* declaration checks the agent here first; the linked environment then holds
45-
* the call to the link's access, narrowed to the agent's modes, which every
46-
* forwarded call carries.
47-
*/
4842
export class PeerForwarding extends Context.Service<
4943
PeerForwarding,
5044
{
51-
/**
52-
* Runs `tool` in the linked environment `environmentId` with `params`. A
53-
* `t3_thread_wait` goes in pieces short enough to survive any route.
54-
*/
5545
readonly call: <T extends Tool.Any>(
5646
scope: Scope,
5747
tool: T,
5848
environmentId: EnvironmentId,
5949
params: Tool.Parameters<T>,
6050
) => Effect.Effect<Tool.Success<T>, OrchestratorMcpFailure>;
61-
/** The environments this one links to, as an agent sees them. */
6251
readonly links: (
6352
scope: Scope,
6453
) => Effect.Effect<OrchestratorMcpEnvironmentLinksResult, OrchestratorMcpFailure>;
6554
}
6655
>()("t3/peer/PeerForwarding") {}
6756

68-
/** The linked environment a call names, or nothing when it names this one. */
6957
export const remoteTarget = (scope: Scope, environmentId: EnvironmentId | undefined) =>
7058
environmentId === scope.environmentId ? undefined : environmentId;
7159

@@ -98,7 +86,6 @@ const make = Effect.gen(function* () {
9886
Effect.orDie,
9987
);
10088

101-
/** Tool and contract schemas are plain data: they encode and decode without services. */
10289
const forward = <A>(
10390
scope: Scope,
10491
toolName: string,

‎apps/server/src/peer/PeerLinks.test.ts‎

Lines changed: 27 additions & 162 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
import { NodeHttpServer } from "@effect/platform-node";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
3-
import {
4-
EnvironmentHttpApi,
5-
EnvironmentId,
6-
type ExecutionEnvironmentDescriptor,
7-
OrchestratorMcpFailure,
8-
} from "@t3tools/contracts";
3+
import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
94
import { expect, it } from "@effect/vitest";
105
import * as Context from "effect/Context";
116
import * as Deferred from "effect/Deferred";
@@ -21,54 +16,21 @@ import * as Schema from "effect/Schema";
2116
import * as SqlClient from "effect/sql/SqlClient";
2217
import * as TestClock from "effect/testing/TestClock";
2318
import { McpSchema, Tool, Toolkit } from "effect/ai";
24-
import {
25-
FetchHttpClient,
26-
HttpRouter,
27-
HttpServer,
28-
HttpServerRequest,
29-
HttpServerResponse,
30-
} from "effect/http";
31-
import * as HttpApi from "effect/http-api/HttpApi";
32-
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
19+
import * as FetchHttpClient from "effect/http/FetchHttpClient";
3320

34-
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
35-
import * as AuthHttp from "../auth/http.ts";
36-
import * as McpOAuth from "../auth/McpOAuth.ts";
37-
import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
3821
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
3922
import * as ServerConfig from "../config.ts";
4023
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
41-
import * as ServerHttp from "../http.ts";
4224
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
4325
import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
44-
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
4526
import * as McpToolAccess from "../mcp/McpToolAccess.ts";
4627
import * as Sqlite from "../persistence/Sqlite.ts";
4728
import * as PeerLinks from "./PeerLinks.ts";
29+
import { descriptorOf, servePeer } from "./PeerLinks.testkit.ts";
4830
import * as PeerMcpClient from "./PeerMcpClient.ts";
4931

50-
class PeerTestApi extends HttpApi.make("environment")
51-
.add(EnvironmentHttpApi.groups.metadata)
52-
.add(EnvironmentHttpApi.groups.mcpOAuth) {}
53-
54-
const descriptorOf = (
55-
environmentId: string,
56-
label: string,
57-
capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
58-
): ExecutionEnvironmentDescriptor => ({
59-
environmentId: EnvironmentId.make(environmentId),
60-
label,
61-
platform: { os: "linux", arch: "x64" },
62-
serverVersion: "0.0.0-test",
63-
capabilities: { repositoryIdentity: true, mcpModeLimitHeader: true, ...capabilities },
64-
});
65-
6632
/** What B's probe saw: the calling client and the modes it may start work with. */
6733
const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
68-
const decodeMcpRequest = Schema.decodeUnknownEffect(
69-
Schema.Struct({ method: Schema.String, id: Schema.optional(Schema.Number) }),
70-
);
71-
7234
const ProbeToolkit = Toolkit.make(
7335
Tool.make("probe", {
7436
description: "Reports the calling client and the modes it may start work with.",
@@ -85,131 +47,34 @@ const ProbeToolkit = Toolkit.make(
8547
}),
8648
);
8749

88-
/**
89-
* Environment B as it runs: its descriptor, MCP OAuth, and `/mcp` behind the
90-
* real client authenticator, on a real socket. The descriptor can be swapped,
91-
* as when B's address comes to answer as another environment.
92-
*/
9350
const serveB = (initial: ExecutionEnvironmentDescriptor) =>
94-
Effect.gen(function* () {
95-
const descriptor = yield* Ref.make(initial);
96-
const alternateDescriptor = yield* Ref.make(initial);
97-
const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
98-
const probes = yield* Ref.make(0);
99-
const redirects = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
100-
const redirectedBodies = yield* Ref.make<ReadonlyArray<string>>([]);
101-
const toolResult = yield* Ref.make<McpSchema.CallToolResult | null>(null);
102-
const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
103-
getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
104-
getDescriptor: Ref.get(descriptor),
105-
});
106-
const authContext = yield* EnvironmentAuth.layer.pipe(
107-
Layer.provide(Sqlite.layerMemory),
108-
Layer.provideMerge(ServerSecretStore.layer),
109-
Layer.provideMerge(ServerEnvironment.layerIdentity),
110-
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-b-" })),
111-
Layer.provideMerge(NodeServices.layer),
112-
Layer.fresh,
113-
Layer.build,
114-
);
115-
// Every bearer B receives, on any route, so a test can show one was never sent.
116-
const layerRecordBearers = HttpRouter.middleware(
117-
(httpEffect) =>
118-
Effect.gen(function* () {
119-
const request = yield* HttpServerRequest.HttpServerRequest;
120-
if (request.url.startsWith("/.well-known/t3/environment")) {
121-
yield* Ref.update(probes, (count) => count + 1);
122-
if (request.headers.host?.startsWith("localhost:")) {
123-
return HttpServerResponse.jsonUnsafe(yield* Ref.get(alternateDescriptor));
124-
}
125-
}
126-
const redirect = (yield* Ref.get(redirects)).get(request.url);
127-
if (redirect !== undefined) {
128-
return HttpServerResponse.redirect(redirect, { status: 307 });
129-
}
130-
if (request.url === "/redirect-target") {
131-
const body = yield* request.text;
132-
yield* Ref.update(redirectedBodies, (bodies) => [...bodies, body]);
133-
return HttpServerResponse.empty({ status: 400 });
134-
}
135-
const authorization = request.headers.authorization;
136-
if (authorization !== undefined) {
137-
yield* Ref.update(bearers, (seen) => [...seen, authorization]);
138-
}
139-
const response = yield* httpEffect;
140-
// Keep real authentication and dispatch, but exercise richer peer wire results.
141-
const result = yield* Ref.get(toolResult);
142-
if (result !== null && request.url === "/mcp" && response.status === 200) {
143-
const rpc = yield* decodeMcpRequest(yield* request.json);
144-
if (rpc.method === "tools/call") {
145-
return HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: rpc.id, result });
146-
}
147-
}
148-
return response;
149-
}),
150-
{ global: true },
151-
);
152-
const layerRoutes = Layer.mergeAll(
153-
HttpApiBuilder.layer(PeerTestApi).pipe(
154-
Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
155-
Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
156-
Layer.provide(AuthHttp.layerAuthenticatedAuth),
157-
),
158-
McpHttpServer.toolkitRegistration(
159-
ProbeToolkit,
160-
McpToolAccess.toLayer(ProbeToolkit, {
161-
probe: McpToolAccess.reads(() =>
162-
McpInvocationContext.McpInvocationContext.pipe(
163-
Effect.map((scope) => {
164-
const modes = McpInvocationContext.clientModeCeiling(scope.client);
165-
return {
166-
caller: scope.client?.label ?? "none",
167-
modes: `${modes.runtimeMode}/${modes.interactionMode}`,
168-
};
169-
}),
170-
),
51+
servePeer(
52+
initial,
53+
McpHttpServer.toolkitRegistration(
54+
ProbeToolkit,
55+
McpToolAccess.toLayer(ProbeToolkit, {
56+
probe: McpToolAccess.reads(() =>
57+
McpInvocationContext.McpInvocationContext.pipe(
58+
Effect.map((scope) => {
59+
const modes = McpInvocationContext.clientModeCeiling(scope.client);
60+
return {
61+
caller: scope.client?.label ?? "none",
62+
modes: `${modes.runtimeMode}/${modes.interactionMode}`,
63+
};
64+
}),
17165
),
172-
refuse: McpToolAccess.reads(() =>
173-
Effect.fail(
174-
new OrchestratorMcpFailure({
175-
code: "thread_not_found",
176-
message: "No such thread.",
177-
}),
178-
),
66+
),
67+
refuse: McpToolAccess.reads(() =>
68+
Effect.fail(
69+
new OrchestratorMcpFailure({
70+
code: "thread_not_found",
71+
message: "No such thread.",
72+
}),
17973
),
180-
}),
181-
).pipe(
182-
Layer.provideMerge(McpHttpServer.layerMcpTransport),
183-
Layer.provide(
184-
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
185-
resolve: () => Effect.succeed(undefined),
186-
}),
18774
),
188-
Layer.provide(McpOAuth.layerMcpClientAuthenticator),
189-
),
190-
).pipe(
191-
Layer.provide(layerRecordBearers),
192-
Layer.provide(layerEnvironment),
193-
Layer.provide(Layer.succeedContext(authContext)),
194-
);
195-
yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
196-
Layer.build,
197-
);
198-
const address = (yield* HttpServer.HttpServer).address;
199-
if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
200-
return {
201-
url: `http://127.0.0.1:${address.port}`,
202-
auth: Context.get(authContext, EnvironmentAuth.EnvironmentAuth),
203-
descriptor,
204-
alternateDescriptor,
205-
bearers,
206-
toolResult,
207-
redirects,
208-
redirectedBodies,
209-
/** How often its descriptor was asked for, as a probe of whether it answers. */
210-
probes,
211-
};
212-
});
75+
}),
76+
),
77+
);
21378

21479
/** Environment A: its own database and secret store, reaching B over plain HTTP. */
21580
const makeA = (

0 commit comments

Comments
 (0)