Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 EnvironmentHttpApi,
4 EnvironmentId,
5 type AuthMcpClientAccess,
6 type ExecutionEnvironmentDescriptor,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Ref from "effect/Ref";
12import * as FetchHttpClient from "effect/http/FetchHttpClient";
13import * as HttpRouter from "effect/http/HttpRouter";
14import * as HttpServer from "effect/http/HttpServer";
15import * as HttpServerRequest from "effect/http/HttpServerRequest";
16import * as HttpApi from "effect/http-api/HttpApi";
17import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
18
19import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
20import * as AuthHttp from "../auth/http.ts";
21import * as McpOAuth from "../auth/McpOAuth.ts";
22import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
23import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24import * as ServerConfig from "../config.ts";
25import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
26import * as ServerHttp from "../http.ts";
27import * as McpHttpServer from "../mcp/McpHttpServer.ts";
28import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
29import * as Sqlite from "../persistence/Sqlite.ts";
30import * as PeerLinks from "./PeerLinks.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import * as PeerMcpClient from "./PeerMcpClient.ts";
33import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
34
35class PeerTestApi extends HttpApi.make("environment")
36 .add(EnvironmentHttpApi.groups.metadata)
37 .add(EnvironmentHttpApi.groups.mcpOAuth) {}
38
39export const descriptorOf = (
40 environmentId: string,
41 label: string,
42 capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
43): ExecutionEnvironmentDescriptor => ({
44 environmentId: EnvironmentId.make(environmentId),
45 label,
46 platform: { os: "linux", arch: "x64" },
47 serverVersion: "0.0.0-test",
48 capabilities: {
49 repositoryIdentity: true,
50 mcpModeLimitHeader: true,
51 linkFence: true,
52 ...capabilities,
53 },
54});
55
56/**
57 * The environment a link points at, as it runs: its descriptor, MCP OAuth,
58 * and `/mcp` with `tools` behind the real client authenticator, on a real
59 * socket. The descriptor can be swapped, as when its address comes to answer
60 * as another environment, and every bearer it receives is recorded.
61 */
62export const servePeer = <E, R>(
63 initial: ExecutionEnvironmentDescriptor,
64 tools: Layer.Layer<never, E, R>,
65) =>
66 Effect.gen(function* () {
67 const descriptor = yield* Ref.make(initial);
68 const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
69 const probes = yield* Ref.make(0);
70 const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
71 getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
72 getDescriptor: Ref.get(descriptor),
73 });
74 const authContext = yield* EnvironmentAuth.layer.pipe(
75 Layer.provide(ManagedPolicy.layerTest()),
76 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
77 Layer.provide(Sqlite.layerMemory),
78 Layer.provideMerge(ServerSecretStore.layer),
79 Layer.provideMerge(ServerEnvironment.layerIdentity),
80 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-peer-" })),
81 Layer.provideMerge(NodeServices.layer),
82 Layer.fresh,
83 Layer.build,
84 );
85 const layerRecordBearers = HttpRouter.middleware(
86 (httpEffect) =>
87 Effect.gen(function* () {
88 const request = yield* HttpServerRequest.HttpServerRequest;
89 if (request.url.startsWith("/.well-known/t3/environment")) {
90 yield* Ref.update(probes, (count) => count + 1);
91 }
92 const authorization = request.headers.authorization;
93 if (authorization !== undefined) {
94 yield* Ref.update(bearers, (seen) => [...seen, authorization]);
95 }
96 return yield* httpEffect;
97 }),
98 { global: true },
99 );
100 const layerRoutes = Layer.mergeAll(
101 HttpApiBuilder.layer(PeerTestApi).pipe(
102 Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
103 Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
104 Layer.provide(AuthHttp.layerAuthenticatedAuth),
105 ),
106 tools.pipe(
107 Layer.provideMerge(McpHttpServer.layerMcpTransport),
108 Layer.provide(
109 Layer.mock(McpSessionRegistry.McpSessionRegistry)({
110 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
111 resolve: () => Effect.succeed(undefined),
112 }),
113 ),
114 Layer.provide(McpOAuth.layerMcpClientAuthenticator),
115 ),
116 ).pipe(
117 Layer.provide(layerRecordBearers),
118 Layer.provide(layerEnvironment),
119 Layer.provide(Layer.succeedContext(authContext)),
120 );
121 // Fresh, so the peer never shares a toolkit or MCP server with the
122 // environment that links to it in the same test.
123 yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
124 Layer.fresh,
125 Layer.build,
126 );
127 const address = (yield* HttpServer.HttpServer).address;
128 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
129 const url = `http://127.0.0.1:${address.port}`;
130 const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
131 return {
132 url,
133 auth,
134 /** Its settings, as for turning its Linked environments beta off. */
135 settings: Context.get(authContext, ServerSettings.ServerSettingsService),
136 descriptor,
137 bearers,
138 /** How often its descriptor was asked for, as a probe of whether it answers. */
139 probes,
140 /** The sessions linking created there, which its Connections lists. */
141 linkedSessions: auth
142 .listSessions()
143 .pipe(
144 Effect.map((sessions) =>
145 sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
146 ),
147 ),
148 };
149 });
150
151export type ServedPeer = Effect.Success<ReturnType<typeof servePeer>>;
152
153/**
154 * The environment that links: its own database and secret store, reaching
155 * peers over plain HTTP. Provide it to anything built on its links.
156 */
157export const layerLinkingEnvironment = (
158 descriptor: ExecutionEnvironmentDescriptor,
159 secrets: typeof ServerSecretStore.layer = ServerSecretStore.layer,
160) =>
161 PeerMcpClient.layer.pipe(
162 Layer.provideMerge(PeerLinks.layer),
163 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
164 Layer.provideMerge(Sqlite.layerMemory),
165 Layer.provide(Layer.mergeAll(secrets, FetchHttpClient.layer)),
166 // Services that act for this environment, such as delegation, name it too.
167 Layer.provideMerge(
168 Layer.succeed(ServerEnvironment.ServerEnvironment, {
169 getEnvironmentId: Effect.succeed(descriptor.environmentId),
170 getDescriptor: Effect.succeed(descriptor),
171 }),
172 ),
173 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-here-" })),
174 Layer.provideMerge(NodeServices.layer),
175 Layer.fresh,
176 );
177
178/** Links `links` to `peer` with a fresh pairing code from it. */
179export const linkTo = (
180 links: PeerLinks.PeerLinks["Service"],
181 peer: ServedPeer,
182 access: AuthMcpClientAccess = "auto",
183) =>
184 peer.auth
185 .issuePairingCredential()
186 .pipe(
187 Effect.flatMap((pairing) =>
188 links.link({ url: peer.url, pairingCode: pairing.credential, access }),
189 ),
190 );