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