@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 788 lines 29.1 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
6 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
7 import * as Output from "alchemy/Output";
8 import * as Provider from "alchemy/Provider";
9 import { isResourceState, State } from "alchemy/State";
10 import * as Cause from "effect/Cause";
11 import * as Effect from "effect/Effect";
12 import * as FetchHttpClient from "effect/http/FetchHttpClient";
13 import * as Redacted from "effect/Redacted";
14 import { MinimumLogLevel } from "effect/References";
15 import * as Schedule from "effect/Schedule";
16 import * as Schema from "effect/Schema";
17 import { testName } from "../../names.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 // Deterministic identifiers — the server id is the API identity, so reruns
24 // converge on the same server instead of leaking. The cases run concurrently,
25 // so each MUST use a distinct server id.
26 const SERVER_ID = testName("alc-mcp-server");
27 const RECREATE_SERVER_ID = testName("alc-mcp-recreate");
28 const REPLACE_SERVER_ID = testName("alc-mcp-replace");
29 const REPLACE_SERVER_ID_V2 = testName("alc-mcp-replaced");
30 const SYNC_SERVER_ID = testName("alc-mcp-sync");
31 const DEFERRED_SYNC_SERVER_ID = testName("alc-mcp-deferred-sync");
32 const TOKEN_SERVER_ID = testName("alc-mcp-service-token");
33
34 // Placeholder upstreams on the standing test zone. These cases opt out of
35 // Alchemy's explicit capability sync; Cloudflare may still discover in the background.
36 const HOSTNAME = "https://mcp.alchemy-test-2.us/mcp";
37 const HOSTNAME_V2 = "https://mcp-v2.alchemy-test-2.us/mcp";
38 // A real, public, unauthenticated MCP server for the capability-sync case.
39 const PUBLIC_HOSTNAME = "https://docs.mcp.cloudflare.com/mcp";
40
41 test.provider(
42 "enabling sync discovers capabilities without changing server configuration",
43 (stack) =>
44 Effect.gen(function* () {
45 const { accountId } = yield* yield* CloudflareEnvironment;
46 yield* stack.destroy();
47
48 const fetch = yield* FetchHttpClient.Fetch;
49 let serverRequests = 0;
50 let syncRequests = 0;
51 // Observe real requests: Cloudflare may discover capabilities in the
52 // background even when Alchemy has not called the sync endpoint.
53 const trackSync = ((input, init) => {
54 const url = input instanceof Request ? input.url : String(input);
55 if (url.endsWith(`/mcp/servers/${DEFERRED_SYNC_SERVER_ID}`)) {
56 serverRequests++;
57 }
58 if (url.endsWith(`/mcp/servers/${DEFERRED_SYNC_SERVER_ID}/sync`)) {
59 syncRequests++;
60 }
61 return fetch(input, init);
62 }) as typeof globalThis.fetch;
63
64 const deploy = (sync: boolean | undefined) =>
65 stack
66 .deploy(
67 Cloudflare.Access.McpServer("DeferredSync", {
68 serverId: DEFERRED_SYNC_SERVER_ID,
69 hostname: PUBLIC_HOSTNAME,
70 authType: "unauthenticated",
71 sync,
72 }),
73 )
74 .pipe(Effect.provideService(FetchHttpClient.Fetch, trackSync));
75
76 const deferred = yield* deploy(false);
77 expect(serverRequests).toBeGreaterThan(0);
78 expect(syncRequests).toEqual(0);
79
80 const synced = yield* deploy(true);
81 expect(syncRequests).toEqual(1);
82 expect(synced.serverId).toEqual(deferred.serverId);
83 expect(synced.createdAt).toEqual(deferred.createdAt);
84 expect(synced.status).toEqual("ready");
85 expect(synced.tools.length).toBeGreaterThan(0);
86 expect(synced.lastSuccessfulSync).toBeDefined();
87
88 const live = yield* getLiveServer(accountId, DEFERRED_SYNC_SERVER_ID);
89 expect(live?.status).toEqual("ready");
90 expect(live?.tools.length).toBeGreaterThan(0);
91
92 const noop = yield* deploy(true);
93 expect(syncRequests).toEqual(1);
94 expect(noop.lastSynced).toEqual(synced.lastSynced);
95
96 yield* deploy(false);
97 expect(syncRequests).toEqual(1);
98 const defaultSync = yield* deploy(undefined);
99 expect(syncRequests).toEqual(2);
100 expect(defaultSync.status).toEqual("ready");
101 yield* deploy(undefined);
102 expect(syncRequests).toEqual(2);
103
104 yield* stack.destroy();
105 expect(yield* getLiveServer(accountId, DEFERRED_SYNC_SERVER_ID)).toBeUndefined();
106 }).pipe(logLevel),
107 {
108 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
109 timeout: 120_000,
110 },
111 );
112
113 test.provider(
114 "service-token outputs resolve into redacted MCP authentication credentials",
115 (stack) =>
116 Effect.gen(function* () {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 yield* stack.destroy();
119
120 const deployed = yield* stack.deploy(
121 Effect.gen(function* () {
122 const token = yield* Cloudflare.Access.ServiceToken("McpToken", {});
123 const credentials = Output.all(token.clientId, token.clientSecret).pipe(
124 Output.map(([clientId, clientSecret]) =>
125 Redacted.make(
126 JSON.stringify({
127 headers: {
128 "cf-access-client-id": clientId,
129 "cf-access-client-secret": Redacted.value(clientSecret!),
130 },
131 }),
132 ),
133 ),
134 );
135 const server = yield* Cloudflare.Access.McpServer("GuardedTools", {
136 serverId: TOKEN_SERVER_ID,
137 hostname: HOSTNAME,
138 authType: "bearer",
139 authCredentials: credentials,
140 sync: false,
141 });
142 return { token, server, credentials };
143 }),
144 );
145
146 expect(Redacted.isRedacted(deployed.credentials)).toBe(true);
147 // Compare without printing either credential on an assertion failure.
148 expect(
149 Redacted.value(deployed.credentials) ===
150 JSON.stringify({
151 headers: {
152 "cf-access-client-id": deployed.token.clientId,
153 "cf-access-client-secret": Redacted.value(deployed.token.clientSecret!),
154 },
155 }),
156 ).toBe(true);
157 expect(deployed.server.authType).toEqual("bearer");
158 const live = yield* getLiveServer(accountId, TOKEN_SERVER_ID);
159 expect(live?.authType).toEqual("bearer");
160
161 yield* stack.destroy();
162 expect(yield* getLiveServer(accountId, TOKEN_SERVER_ID)).toBeUndefined();
163 const deletedToken = yield* zeroTrust
164 .getAccessServiceTokenForAccount({
165 accountId,
166 serviceTokenId: deployed.token.serviceTokenId,
167 })
168 .pipe(Effect.catchTag("AccessServiceTokenNotFound", () => Effect.succeed(undefined)));
169 expect(deletedToken).toBeUndefined();
170 }).pipe(logLevel),
171 {
172 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
173 timeout: 120_000,
174 },
175 );
176
177 // Read a server out-of-band, mapping "gone" to undefined.
178 const getLiveServer = (accountId: string, id: string) =>
179 zeroTrust
180 .readAccessAiControlMcpServer({ accountId, id })
181 .pipe(Effect.catchTag("McpServerNotFound", () => Effect.succeed(undefined)));
182
183 test.provider(
184 "overlong server IDs surface the typed validation error and remain cleanable",
185 (stack) =>
186 Effect.gen(function* () {
187 const { accountId } = yield* yield* CloudflareEnvironment;
188 yield* stack.destroy();
189 const error = yield* zeroTrust
190 .readAccessAiControlMcpServer({
191 accountId,
192 id: "alchemy-test-mcp-server-id-is-too-long",
193 })
194 .pipe(Effect.flip);
195 expect(error._tag).toEqual("McpServerInvalidId");
196 const deployError = yield* stack
197 .deploy(
198 Cloudflare.Access.McpServer("InvalidId", {
199 serverId: "alchemy-test-mcp-server-id-is-too-long",
200 hostname: HOSTNAME,
201 authType: "unauthenticated",
202 sync: false,
203 }),
204 )
205 .pipe(Effect.flip);
206 expect(deployError._tag).toEqual("McpServerInvalidId");
207 yield* stack.destroy();
208 }).pipe(logLevel),
209 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
210 );
211
212 test.provider(
213 "create, update in place, and destroy an MCP server",
214 (stack) =>
215 Effect.gen(function* () {
216 const { accountId } = yield* yield* CloudflareEnvironment;
217
218 yield* stack.destroy();
219
220 const server = yield* stack.deploy(
221 Effect.gen(function* () {
222 return yield* Cloudflare.Access.McpServer("Upstream", {
223 serverId: SERVER_ID,
224 hostname: HOSTNAME,
225 authType: "bearer",
226 authCredentials: Redacted.make("alchemy-test-token-v1"),
227 description: "alchemy mcp server v1",
228 sync: false,
229 });
230 }),
231 );
232
233 expect(server.serverId).toEqual(SERVER_ID);
234 expect(server.accountId).toEqual(accountId);
235 expect(server.hostname).toEqual(HOSTNAME);
236 expect(server.authType).toEqual("bearer");
237 expect(server.name).toEqual(SERVER_ID);
238 expect(server.description).toEqual("alchemy mcp server v1");
239 expect(server.secureWebGateway).toEqual(false);
240 expect(server.isSharedOauthCallbackEnabled).toEqual(false);
241 expect(server.updatedTools).toEqual([]);
242 expect(server.updatedPrompts).toEqual([]);
243
244 const live = yield* getLiveServer(accountId, SERVER_ID);
245 expect(live?.id).toEqual(SERVER_ID);
246 expect(live?.hostname).toEqual(HOSTNAME);
247 expect(live?.authType).toEqual("bearer");
248
249 // Name, description, gateway, overrides, and a credential rotation
250 // converge in place — same server id.
251 const updated = yield* stack.deploy(
252 Effect.gen(function* () {
253 return yield* Cloudflare.Access.McpServer("Upstream", {
254 serverId: SERVER_ID,
255 name: testName("Alchemy MCP Server"),
256 hostname: HOSTNAME,
257 authType: "bearer",
258 authCredentials: Redacted.make("alchemy-test-token-v2"),
259 description: "alchemy mcp server v2",
260 secureWebGateway: true,
261 updatedTools: [
262 { name: "search", enabled: false },
263 { name: "fetch", alias: "get_page" },
264 ],
265 sync: false,
266 });
267 }),
268 );
269 expect(updated.serverId).toEqual(SERVER_ID);
270 expect(updated.name).toEqual(testName("Alchemy MCP Server"));
271 expect(updated.description).toEqual("alchemy mcp server v2");
272 expect(updated.secureWebGateway).toEqual(true);
273 expect(updated.updatedTools).toHaveLength(2);
274 expect(updated.updatedTools.find((tool) => tool.name === "search")?.enabled).toEqual(false);
275 expect(updated.updatedTools.find((tool) => tool.name === "fetch")?.alias).toEqual("get_page");
276
277 const liveUpdated = yield* getLiveServer(accountId, SERVER_ID);
278 expect(liveUpdated?.name).toEqual(testName("Alchemy MCP Server"));
279 expect(liveUpdated?.secureWebGateway).toEqual(true);
280
281 // No-op redeploy keeps the same server without drift.
282 const noop = yield* stack.deploy(
283 Effect.gen(function* () {
284 return yield* Cloudflare.Access.McpServer("Upstream", {
285 serverId: SERVER_ID,
286 name: testName("Alchemy MCP Server"),
287 hostname: HOSTNAME,
288 authType: "bearer",
289 authCredentials: Redacted.make("alchemy-test-token-v2"),
290 description: "alchemy mcp server v2",
291 secureWebGateway: true,
292 updatedTools: [
293 { name: "search", enabled: false },
294 { name: "fetch", alias: "get_page" },
295 ],
296 sync: false,
297 });
298 }),
299 );
300 expect(noop.serverId).toEqual(SERVER_ID);
301
302 yield* stack.destroy();
303
304 const afterDestroy = yield* getLiveServer(accountId, SERVER_ID);
305 expect(afterDestroy).toBeUndefined();
306 }).pipe(logLevel),
307 {
308 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
309 timeout: 90_000,
310 },
311 );
312
313 // `hostname` and `authType` are create-only on the API. Changing either must
314 // converge by recreating the server under the same id rather than failing.
315 test.provider(
316 "changing the upstream hostname or auth type recreates the server under the same id",
317 (stack) =>
318 Effect.gen(function* () {
319 const { accountId } = yield* yield* CloudflareEnvironment;
320
321 yield* stack.destroy();
322
323 const initial = yield* stack.deploy(
324 Effect.gen(function* () {
325 return yield* Cloudflare.Access.McpServer("Recreated", {
326 serverId: RECREATE_SERVER_ID,
327 hostname: HOSTNAME,
328 authType: "unauthenticated",
329 sync: false,
330 });
331 }),
332 );
333 expect(initial.serverId).toEqual(RECREATE_SERVER_ID);
334 expect(initial.authType).toEqual("unauthenticated");
335
336 const rehostPlan = yield* stack.plan(
337 Cloudflare.Access.McpServer("Recreated", {
338 serverId: RECREATE_SERVER_ID,
339 hostname: HOSTNAME_V2,
340 authType: "unauthenticated",
341 sync: false,
342 }),
343 );
344 const rehostChange = rehostPlan.resources.Recreated!;
345 expect(rehostChange.action).toEqual("replace");
346 if (rehostChange.action === "replace") expect(rehostChange.deleteFirst).toBe(true);
347
348 const rehosted = yield* stack.deploy(
349 Effect.gen(function* () {
350 return yield* Cloudflare.Access.McpServer("Recreated", {
351 serverId: RECREATE_SERVER_ID,
352 hostname: HOSTNAME_V2,
353 authType: "unauthenticated",
354 sync: false,
355 });
356 }),
357 );
358 expect(rehosted.serverId).toEqual(RECREATE_SERVER_ID);
359 expect(rehosted.hostname).toEqual(HOSTNAME_V2);
360 expect(rehosted.authType).toEqual("unauthenticated");
361
362 const authPlan = yield* stack.plan(
363 Cloudflare.Access.McpServer("Recreated", {
364 serverId: RECREATE_SERVER_ID,
365 hostname: HOSTNAME_V2,
366 authType: "bearer",
367 authCredentials: Redacted.make("alchemy-test-token-recreate"),
368 sync: false,
369 }),
370 );
371 const authChange = authPlan.resources.Recreated!;
372 expect(authChange.action).toEqual("replace");
373 if (authChange.action === "replace") expect(authChange.deleteFirst).toBe(true);
374
375 const recreated = yield* stack.deploy(
376 Effect.gen(function* () {
377 return yield* Cloudflare.Access.McpServer("Recreated", {
378 serverId: RECREATE_SERVER_ID,
379 hostname: HOSTNAME_V2,
380 authType: "bearer",
381 authCredentials: Redacted.make("alchemy-test-token-recreate"),
382 sync: false,
383 });
384 }),
385 );
386 expect(recreated.serverId).toEqual(RECREATE_SERVER_ID);
387 expect(recreated.hostname).toEqual(HOSTNAME_V2);
388 expect(recreated.authType).toEqual("bearer");
389
390 const live = yield* getLiveServer(accountId, RECREATE_SERVER_ID);
391 expect(live?.hostname).toEqual(HOSTNAME_V2);
392 expect(live?.authType).toEqual("bearer");
393
394 yield* stack.destroy();
395
396 const afterDestroy = yield* getLiveServer(accountId, RECREATE_SERVER_ID);
397 expect(afterDestroy).toBeUndefined();
398 }).pipe(logLevel),
399 {
400 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
401 timeout: 90_000,
402 },
403 );
404
405 // Canonical `list()` test (account collection): deploy a server, then resolve
406 // the provider via the typed helper and assert the deployed server appears in
407 // the exhaustively-paginated result.
408 test.provider(
409 "generates a valid server ID and lists the deployed MCP server",
410 (stack) =>
411 Effect.gen(function* () {
412 const { accountId } = yield* yield* CloudflareEnvironment;
413
414 yield* stack.destroy();
415
416 const deployed = yield* stack.deploy(
417 Effect.gen(function* () {
418 return yield* Cloudflare.Access.McpServer(
419 "ServerWithALongLogicalNameForGeneratedIdCoverage",
420 {
421 hostname: HOSTNAME,
422 authType: "unauthenticated",
423 sync: false,
424 },
425 );
426 }),
427 );
428 expect(deployed.serverId.length).toBeLessThanOrEqual(32);
429
430 const provider = yield* Provider.findProvider(Cloudflare.Access.McpServer);
431 const all = yield* provider.list();
432
433 expect(all.some((s) => s.serverId === deployed.serverId)).toBe(true);
434
435 yield* stack.destroy();
436
437 const afterDestroy = yield* getLiveServer(accountId, deployed.serverId);
438 expect(afterDestroy).toBeUndefined();
439 }).pipe(logLevel),
440 {
441 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
442 timeout: 90_000,
443 },
444 );
445
446 test.provider(
447 "changing the server ID replaces the server and removes the old ID",
448 (stack) =>
449 Effect.gen(function* () {
450 const { accountId } = yield* yield* CloudflareEnvironment;
451 yield* stack.destroy();
452
453 const deploy = (serverId: string) =>
454 stack.deploy(
455 Cloudflare.Access.McpServer("Replaced", {
456 serverId,
457 hostname: HOSTNAME,
458 authType: "unauthenticated",
459 sync: false,
460 }),
461 );
462
463 const initial = yield* deploy(REPLACE_SERVER_ID);
464 expect(initial.serverId).toEqual(REPLACE_SERVER_ID);
465
466 const replaced = yield* deploy(REPLACE_SERVER_ID_V2);
467 expect(replaced.serverId).toEqual(REPLACE_SERVER_ID_V2);
468 expect(yield* getLiveServer(accountId, REPLACE_SERVER_ID)).toBeUndefined();
469 expect((yield* getLiveServer(accountId, REPLACE_SERVER_ID_V2))?.id).toEqual(
470 REPLACE_SERVER_ID_V2,
471 );
472
473 yield* stack.destroy();
474 expect(yield* getLiveServer(accountId, REPLACE_SERVER_ID_V2)).toBeUndefined();
475 }).pipe(logLevel),
476 {
477 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
478 timeout: 90_000,
479 },
480 );
481
482 // The default deploy runs a capability sync against the upstream. Against a
483 // real public server the discovered tools come back on the attributes.
484 test.provider(
485 "sync discovers the capabilities of a public MCP server",
486 (stack) =>
487 Effect.gen(function* () {
488 const { accountId } = yield* yield* CloudflareEnvironment;
489
490 yield* stack.destroy();
491
492 const server = yield* stack.deploy(
493 Effect.gen(function* () {
494 return yield* Cloudflare.Access.McpServer("CloudflareDocs", {
495 serverId: SYNC_SERVER_ID,
496 hostname: PUBLIC_HOSTNAME,
497 authType: "unauthenticated",
498 });
499 }),
500 );
501
502 expect(server.serverId).toEqual(SYNC_SERVER_ID);
503 expect(server.status).toEqual("ready");
504 expect(server.tools.length).toBeGreaterThan(0);
505
506 yield* stack.destroy();
507
508 const afterDestroy = yield* getLiveServer(accountId, SYNC_SERVER_ID);
509 expect(afterDestroy).toBeUndefined();
510 }).pipe(logLevel),
511 {
512 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
513 timeout: 120_000,
514 },
515 );
516
517 test.provider(
518 "existing servers require adoption before their configuration can change",
519 (stack) =>
520 Effect.gen(function* () {
521 const { accountId } = yield* yield* CloudflareEnvironment;
522 yield* stack.destroy();
523 const serverId = testName("alchemy-test-mcp-adoption");
524 const external = yield* zeroTrust.createAccessAiControlMcpServer({
525 accountId,
526 id: serverId,
527 hostname: HOSTNAME,
528 authType: "unauthenticated",
529 name: "External MCP server",
530 });
531 const resource = () =>
532 Cloudflare.Access.McpServer("Adopted", {
533 serverId,
534 hostname: HOSTNAME,
535 authType: "unauthenticated",
536 name: testName("Adopted MCP server"),
537 sync: false,
538 });
539 yield* Effect.gen(function* () {
540 const refused = yield* stack.deploy(resource()).pipe(
541 Effect.as(false),
542 Effect.catchCause((cause) =>
543 Effect.succeed(
544 cause.reasons.some(
545 (reason) =>
546 (Cause.isFailReason(reason) && reason.error instanceof OwnedBySomeoneElse) ||
547 (Cause.isDieReason(reason) && reason.defect instanceof OwnedBySomeoneElse),
548 ),
549 ),
550 ),
551 );
552 expect(refused).toBe(true);
553 expect((yield* getLiveServer(accountId, serverId))?.name).toEqual(external.name);
554 const adopted = yield* stack.deploy(resource().pipe(adopt(true)));
555 expect(adopted.serverId).toEqual(external.id);
556 expect(adopted.createdAt).toEqual(external.createdAt);
557 expect((yield* getLiveServer(accountId, serverId))?.name).toEqual(
558 testName("Adopted MCP server"),
559 );
560 yield* stack.destroy();
561 expect(yield* getLiveServer(accountId, serverId)).toBeUndefined();
562 }).pipe(
563 Effect.ensuring(
564 // This test creates its fixture outside the stack. Reclaim that
565 // exact fixture even if the adoption assertion fails.
566 zeroTrust.deleteAccessAiControlMcpServer({ accountId, id: serverId }).pipe(
567 Effect.catchTag("McpServerNotFound", () => Effect.void),
568 Effect.orDie,
569 ),
570 ),
571 );
572 }).pipe(logLevel),
573 {
574 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
575 timeout: 90_000,
576 },
577 );
578
579 test.provider(
580 "recovers an interrupted create through explicit adoption and replaces across accounts",
581 (stack) =>
582 Effect.gen(function* () {
583 const { accountId } = yield* yield* CloudflareEnvironment;
584 yield* stack.destroy();
585 const props = {
586 hostname: HOSTNAME,
587 authType: "unauthenticated",
588 sync: false,
589 } as const;
590 const resource = () => Cloudflare.Access.McpServer("Recovered", props);
591 const initial = yield* stack.deploy(resource());
592 const provider = yield* Provider.findProvider(Cloudflare.Access.McpServer);
593 // Validate account-change planning without needing credentials for a
594 // second account or issuing any request to an invented account.
595 const diff = yield* provider.diff!({
596 id: "Recovered",
597 fqn: "Recovered",
598 instanceId: "test",
599 olds: props,
600 news: props,
601 oldBindings: [],
602 newBindings: [],
603 output: { ...initial, accountId: "different-account" },
604 });
605 expect(diff?.action).toEqual("replace");
606
607 const state = yield* yield* State;
608 const fqns = yield* state.list({ stack: stack.name, stage: stack.stage });
609 let interrupted = false;
610 for (const fqn of fqns) {
611 const row = yield* state.get({
612 stack: stack.name,
613 stage: stack.stage,
614 fqn,
615 });
616 if (
617 isResourceState(row) &&
618 row.status === "created" &&
619 row.resourceType === "Cloudflare.Access.McpServer"
620 ) {
621 yield* state.set({
622 stack: stack.name,
623 stage: stack.stage,
624 fqn,
625 value: { ...row, status: "creating", attr: undefined },
626 });
627 interrupted = true;
628 }
629 }
630 expect(interrupted).toBe(true);
631 const refused = yield* stack.deploy(resource()).pipe(
632 Effect.as(false),
633 Effect.catchCause((cause) =>
634 Effect.succeed(
635 cause.reasons.some(
636 (reason) =>
637 (Cause.isFailReason(reason) && reason.error instanceof OwnedBySomeoneElse) ||
638 (Cause.isDieReason(reason) && reason.defect instanceof OwnedBySomeoneElse),
639 ),
640 ),
641 ),
642 );
643 expect(refused).toBe(true);
644 const recovered = yield* stack.deploy(resource().pipe(adopt(true)));
645 expect(recovered.serverId).toEqual(initial.serverId);
646 expect(recovered.createdAt).toEqual(initial.createdAt);
647 yield* stack.destroy();
648 expect(yield* getLiveServer(accountId, initial.serverId)).toBeUndefined();
649 }).pipe(logLevel),
650 {
651 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
652 timeout: 90_000,
653 },
654 );
655
656 test.provider(
657 "recreates a server deleted outside the stack",
658 (stack) =>
659 Effect.gen(function* () {
660 const { accountId } = yield* yield* CloudflareEnvironment;
661 yield* stack.destroy();
662 const resource = (name: string) =>
663 Cloudflare.Access.McpServer("Deleted", {
664 hostname: HOSTNAME,
665 authType: "unauthenticated",
666 name,
667 sync: false,
668 });
669 const initial = yield* stack.deploy(resource("Before deletion"));
670 yield* zeroTrust.deleteAccessAiControlMcpServer({
671 accountId,
672 id: initial.serverId,
673 });
674 expect(yield* getLiveServer(accountId, initial.serverId)).toBeUndefined();
675 const recovered = yield* stack.deploy(resource("After deletion"));
676 expect(recovered.serverId).toEqual(initial.serverId);
677 expect((yield* getLiveServer(accountId, recovered.serverId))?.name).toEqual("After deletion");
678 yield* stack.destroy();
679 expect(yield* getLiveServer(accountId, recovered.serverId)).toBeUndefined();
680 }).pipe(logLevel),
681 {
682 tags: ["provider:cloudflare", "provider:cloudflare:access", "live"],
683 timeout: 90_000,
684 },
685 );
686
687 test.provider(
688 "rotating only the bearer credential changes what the upstream receives",
689 (stack) =>
690 Effect.gen(function* () {
691 const { accountId } = yield* yield* CloudflareEnvironment;
692 yield* stack.destroy();
693 const upstream = () =>
694 Cloudflare.Worker("AuthenticatedUpstream", {
695 main: new URL("./fixtures/mcp-auth.ts", import.meta.url).pathname,
696 // Cloudflare discovery can hit Worker-to-Worker error 1042 on
697 // workers.dev. Custom domains support that fetch path.
698 domain: "mcp-credential-rotation.alchemy-test-2.us",
699 workersDev: true,
700 });
701 const worker = yield* stack.deploy(upstream());
702 // Probe the script without negative-caching the new custom domain
703 // in the local DNS resolver. Discovery checks the custom domain below.
704 const health = yield* Test.getWhenReady(
705 `${worker.urls.find((url) => url.endsWith(".workers.dev"))!}/health`,
706 );
707 expect(health.status).toEqual(200);
708 const deploy = (version: "v1" | "v2") =>
709 stack.deploy(
710 Effect.gen(function* () {
711 const endpoint = yield* upstream();
712 return yield* Cloudflare.Access.McpServer("Rotating", {
713 hostname: endpoint.url.pipe(Output.map((url) => `${url}/mcp`)),
714 authType: "bearer",
715 authCredentials: Redacted.make(`alchemy-mcp-rotation-${version}`),
716 });
717 }),
718 );
719 const initial = yield* deploy("v1");
720 // Worker health and Cloudflare's discovery run in different locations.
721 // Let the new route propagate before testing credential rotation. This
722 // setup retry must not wrap the v2 deploy or mask a rotation failure.
723 const ready =
724 initial.status === "ready"
725 ? initial
726 : yield* zeroTrust.syncAccessAiControlMcpServer({ accountId, id: initial.serverId }).pipe(
727 Effect.catchTag("McpServerSyncFailure", () => Effect.void),
728 Effect.andThen(
729 zeroTrust.readAccessAiControlMcpServer({
730 accountId,
731 id: initial.serverId,
732 }),
733 ),
734 Effect.repeat({
735 while: (server) => server.status !== "ready",
736 schedule: Schedule.spaced("1 second"),
737 times: 8,
738 }),
739 );
740 expect(ready.error || undefined).toBeUndefined();
741 expect(ready.status).toEqual("ready");
742 expect(ready.tools.map((tool) => tool.name)).toContain("authenticated_v1");
743 // A rejected upstream credential must retain the complete failure body.
744 yield* zeroTrust.updateAccessAiControlMcpServer({
745 accountId,
746 id: initial.serverId,
747 authCredentials: "invalid-credential",
748 });
749 const failure = yield* zeroTrust
750 .syncAccessAiControlMcpServer({
751 accountId,
752 id: initial.serverId,
753 })
754 .pipe(Effect.catchTag("McpServerSyncFailure", (error) => Effect.succeed(error.body)));
755 const body = Schema.decodeUnknownSync(
756 Schema.Struct({
757 success: Schema.Literal(false),
758 result: Schema.Struct({
759 status: Schema.Literal("error"),
760 error: Schema.String,
761 error_details: Schema.Struct({ status_code: Schema.Number }),
762 }),
763 }),
764 )(failure);
765 expect(body.result.error).toContain("Unauthorized");
766 expect(body.result.error_details.status_code).toEqual(401);
767 const rotated = yield* deploy("v2");
768 expect(rotated.serverId).toEqual(initial.serverId);
769 expect(rotated.createdAt).toEqual(initial.createdAt);
770 // Discovery can report a transient routing error even after fetching
771 // the new capabilities. Verify the credential through the returned tools.
772 expect(rotated.tools.map((tool) => tool.name)).toContain("authenticated_v2");
773 expect(rotated.tools.map((tool) => tool.name)).not.toContain("authenticated_v1");
774 const live = yield* getLiveServer(accountId, rotated.serverId);
775 expect(live?.tools.map((tool) => tool.name)).toContain("authenticated_v2");
776 yield* stack.destroy();
777 expect(yield* getLiveServer(accountId, rotated.serverId)).toBeUndefined();
778 }).pipe(logLevel),
779 {
780 tags: [
781 "provider:cloudflare",
782 "provider:cloudflare:access",
783 "provider:cloudflare:worker",
784 "live",
785 ],
786 timeout: 120_000,
787 },
788 );