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

main
ts 251 lines 8.87 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Access.McpPortal" as const;
13 type TypeId = typeof TypeId;
14
15 export interface McpPortalProps {
16 /**
17 * The client-supplied portal identifier. Immutable — changing it
18 * triggers a replacement. If omitted, a deterministic id is generated
19 * from the app, stage, and logical ID.
20 * @default ${app}-${stage}-${id}
21 */
22 portalId?: string;
23 /**
24 * Display name of the portal. If omitted, the portal id is reused.
25 * @default the portal id
26 */
27 name?: string;
28 /**
29 * The hostname the portal is served on. Must belong to a zone on the
30 * account.
31 */
32 hostname: string;
33 /**
34 * Optional description of the portal.
35 */
36 description?: string;
37 /**
38 * Allow remote code execution in Dynamic Workers (beta). When omitted,
39 * the server-side default applies (observed: `true`).
40 */
41 allowCodeMode?: boolean;
42 /**
43 * Route outbound MCP traffic through the Zero Trust Secure Web
44 * Gateway.
45 * @default false
46 */
47 secureWebGateway?: boolean;
48 }
49
50 export type McpPortalAttributes = {
51 /** The portal id. */
52 portalId: string;
53 /** Account that owns the portal. */
54 accountId: string;
55 /** Observed display name. */
56 name: string;
57 /** Observed portal hostname. */
58 hostname: string;
59 /** Observed description, if any. */
60 description: string | undefined;
61 /** Whether Dynamic Workers code mode is allowed. */
62 allowCodeMode: boolean;
63 /** Whether outbound MCP traffic routes through the gateway. */
64 secureWebGateway: boolean;
65 /** RFC 3339 timestamp of when the portal was created, if reported. */
66 createdAt: string | undefined;
67 };
68
69 export type McpPortal = Resource<TypeId, McpPortalProps, McpPortalAttributes, never, Providers>;
70
71 /**
72 * A Cloudflare Zero Trust **AI Controls MCP portal** — a hosted gateway
73 * that aggregates MCP servers behind a single Access-protected hostname
74 * so administrators can govern which AI tools and prompts are exposed to
75 * users.
76 *
77 * The product surface is in beta and requires the AI Controls
78 * entitlement; accounts without it receive the typed `Forbidden` error
79 * on all writes. Register upstream endpoints with {@link McpServer}.
80 * Attaching registered servers to this portal is managed outside Alchemy.
81 * ### Creating an MCP portal
82 * **Example:** Minimal portal
83 * ```typescript
84 * const portal = yield* Cloudflare.Access.McpPortal("AiPortal", {
85 * hostname: "mcp.example.com",
86 * });
87 * ```
88 *
89 * **Example:** Portal with gateway egress
90 * ```typescript
91 * const portal = yield* Cloudflare.Access.McpPortal("AiPortal", {
92 * hostname: "mcp.example.com",
93 * description: "Company-approved AI tools",
94 * secureWebGateway: true,
95 * });
96 * ```
97 *
98 * @see https://developers.cloudflare.com/cloudflare-one/access-controls/ai-controls/
99 *
100 * @resource
101 * @product Access
102 * @category Cloudflare One (Zero Trust)
103 */
104 export const McpPortal = Resource<McpPortal>(TypeId);
105
106 /**
107 * Returns true if the given value is an McpPortal resource.
108 */
109 export const isMcpPortal = (value: unknown): value is McpPortal =>
110 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
111
112 export const McpPortalProvider = () =>
113 Provider.succeed(McpPortal, {
114 stables: ["portalId", "accountId", "createdAt"],
115
116 list: Effect.fn(function* () {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 // Account-scoped collection; exhaustively paginate. The list rows
119 // carry the full portal shape, so each maps directly into the same
120 // Attributes `read` returns. Accounts without the AI Controls
121 // entitlement reject the route with the typed `Forbidden` — treat
122 // them as having no portals.
123 return yield* zeroTrust.listAccessAiControlMcpPortals.pages({ accountId }).pipe(
124 Stream.runCollect,
125 Effect.map((chunk) =>
126 Array.from(chunk).flatMap((page) =>
127 (page.result ?? []).map((portal) => toAttributes(portal, accountId)),
128 ),
129 ),
130 Effect.catchTag("Forbidden", () => Effect.succeed([])),
131 );
132 }),
133
134 diff: Effect.fn(function* ({ olds, news, output }) {
135 if (!isResolved(news)) return undefined;
136 // The portal id is the API identity — changing it is a replacement.
137 const oldId = output?.portalId ?? olds?.portalId;
138 if (news.portalId !== undefined && oldId !== undefined && oldId !== news.portalId) {
139 return { action: "replace" } as const;
140 }
141 return undefined;
142 }),
143
144 read: Effect.fn(function* ({ id, output, olds }) {
145 const { accountId } = yield* yield* CloudflareEnvironment;
146 const acct = output?.accountId ?? accountId;
147
148 // The portal id is deterministic (client-supplied or derived from
149 // the logical id), so a direct read covers the cold case too.
150 const portalId = output?.portalId ?? (yield* createPortalId(id, olds?.portalId));
151 const observed = yield* observePortal(acct, portalId);
152 return observed ? toAttributes(observed, acct) : undefined;
153 }),
154
155 reconcile: Effect.fn(function* ({ id, news, output }) {
156 const { accountId } = yield* yield* CloudflareEnvironment;
157 const portalId = output?.portalId ?? (yield* createPortalId(id, news.portalId));
158 const name = news.name ?? portalId;
159
160 // 1. Observe.
161 const observed = yield* observePortal(accountId, portalId);
162
163 // 2. Ensure — create when missing.
164 if (!observed) {
165 const created = yield* zeroTrust.createAccessAiControlMcpPortal({
166 accountId,
167 id: portalId,
168 hostname: news.hostname,
169 name,
170 ...(news.description !== undefined ? { description: news.description } : {}),
171 ...(news.allowCodeMode !== undefined ? { allowCodeMode: news.allowCodeMode } : {}),
172 ...(news.secureWebGateway !== undefined
173 ? { secureWebGateway: news.secureWebGateway }
174 : {}),
175 });
176 return toAttributes(created, accountId);
177 }
178
179 // 3. Sync — update only when the observed state differs. Unset
180 // optional props mean "keep the observed value" (the API applies
181 // server-side defaults on create, e.g. allowCodeMode: true).
182 const dirty =
183 observed.name !== name ||
184 observed.hostname !== news.hostname ||
185 (news.description !== undefined &&
186 (observed.description || undefined) !== news.description) ||
187 (news.allowCodeMode !== undefined &&
188 (observed.allowCodeMode ?? false) !== news.allowCodeMode) ||
189 (news.secureWebGateway !== undefined &&
190 (observed.secureWebGateway ?? false) !== news.secureWebGateway);
191 if (!dirty) {
192 return toAttributes(observed, accountId);
193 }
194 const updated = yield* zeroTrust.updateAccessAiControlMcpPortal({
195 accountId,
196 id: portalId,
197 name,
198 hostname: news.hostname,
199 ...(news.description !== undefined ? { description: news.description } : {}),
200 ...(news.allowCodeMode !== undefined ? { allowCodeMode: news.allowCodeMode } : {}),
201 ...(news.secureWebGateway !== undefined ? { secureWebGateway: news.secureWebGateway } : {}),
202 });
203 return toAttributes(updated, accountId);
204 }),
205
206 delete: Effect.fn(function* ({ output }) {
207 yield* zeroTrust
208 .deleteAccessAiControlMcpPortal({
209 accountId: output.accountId,
210 id: output.portalId,
211 })
212 .pipe(Effect.catchTag("McpPortalNotFound", () => Effect.void));
213 }),
214 });
215
216 /**
217 * Structural shape shared by create/read/update responses.
218 */
219 type ObservedPortal = {
220 id: string;
221 hostname: string;
222 name: string;
223 allowCodeMode?: boolean | null;
224 createdAt?: string | null;
225 description?: string | null;
226 secureWebGateway?: boolean | null;
227 };
228
229 /**
230 * Read a portal by id, mapping "gone" to `undefined`.
231 */
232 const observePortal = (accountId: string, id: string) =>
233 zeroTrust
234 .readAccessAiControlMcpPortal({ accountId, id })
235 .pipe(Effect.catchTag("McpPortalNotFound", () => Effect.undefined));
236
237 const createPortalId = (id: string, portalId: string | undefined) =>
238 Effect.gen(function* () {
239 return portalId ?? (yield* createPhysicalName({ id, lowercase: true }));
240 });
241
242 const toAttributes = (portal: ObservedPortal, accountId: string): McpPortalAttributes => ({
243 portalId: portal.id,
244 accountId,
245 name: portal.name,
246 hostname: portal.hostname,
247 description: portal.description || undefined,
248 allowCodeMode: portal.allowCodeMode ?? false,
249 secureWebGateway: portal.secureWebGateway ?? false,
250 createdAt: portal.createdAt ?? undefined,
251 });