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

main
ts 546 lines 20.4 KB
Raw
1 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const TypeId = "Cloudflare.Access.McpServer" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * Authentication method the gateway uses to reach the upstream MCP server.
19 */
20 export type McpServerAuthType = "oauth" | "bearer" | "unauthenticated";
21
22 /**
23 * Capability sync state reported by Cloudflare for an MCP server.
24 */
25 export type McpServerStatus = "waiting" | "ready" | "stale" | "error";
26
27 /**
28 * Whether administrative authentication is required before the server's
29 * capabilities can be synced.
30 */
31 export type McpServerAuthenticationStatus =
32 | "not_required"
33 | "required"
34 | "connected"
35 | "stale"
36 | "manual";
37
38 /**
39 * A server-wide override for a single tool or prompt exposed by the
40 * upstream MCP server.
41 */
42 export interface McpServerCapabilityOverride {
43 /**
44 * Name of the tool or prompt capability to override.
45 */
46 name: string;
47 /**
48 * Custom name exposed for the capability.
49 */
50 alias?: string;
51 /**
52 * Custom description exposed for the capability.
53 */
54 description?: string;
55 /**
56 * Whether the capability is available through the MCP server.
57 */
58 enabled?: boolean;
59 }
60
61 /**
62 * A tool or prompt discovered from the upstream MCP server by a capability
63 * sync. The shape is whatever the upstream advertises (typically `name`,
64 * `description`, and an input schema).
65 */
66 export type McpServerCapability = Record<string, unknown>;
67
68 export interface McpServerProps {
69 /**
70 * The client-supplied server identifier. Immutable — changing it
71 * triggers a replacement. If omitted, a deterministic id is generated
72 * from the stack, stage, logical ID, and resource instance, capped at
73 * the API's 32-character limit.
74 * @default a generated ID of at most 32 characters
75 */
76 serverId?: string;
77 /**
78 * Display name of the server. If omitted, the server id is reused.
79 * @default the server id
80 */
81 name?: string;
82 /**
83 * URL of the upstream MCP endpoint, e.g. `https://mcp.example.com/mcp`.
84 * Create-only on the API: changing it triggers a delete-first replacement.
85 */
86 hostname: string;
87 /**
88 * Authentication method used to connect to the upstream MCP server.
89 * Create-only on the API: changing it triggers a delete-first replacement.
90 */
91 authType: McpServerAuthType;
92 /**
93 * Static credential for the upstream MCP server. For `bearer`, either a
94 * raw token (sent as `Authorization: Bearer <token>`) or a JSON-encoded
95 * `{"headers":{...}}` object for custom or multiple static headers, e.g.
96 * a Cloudflare Access service token. For `oauth`, the JSON-encoded OAuth
97 * configuration. Write-only — the API never returns it, so rotation is
98 * detected by comparing against the previously deployed value.
99 */
100 authCredentials?: Redacted.Redacted<string>;
101 /**
102 * Pre-registered OAuth `client_secret` for manually configured OAuth
103 * servers. Write-only — never returned by the API.
104 */
105 clientSecret?: Redacted.Redacted<string>;
106 /**
107 * Optional description of the server.
108 */
109 description?: string;
110 /**
111 * Route outbound traffic to this server through the Zero Trust Secure
112 * Web Gateway.
113 * @default false
114 */
115 secureWebGateway?: boolean;
116 /**
117 * Use the shared Cloudflare-owned OAuth callback endpoint as the
118 * `redirect_uri` for upstream on-behalf OAuth instead of the portal
119 * hostname.
120 * @default false
121 */
122 isSharedOauthCallbackEnabled?: boolean;
123 /**
124 * Server-wide tool overrides: disable, rename, or re-describe tools the
125 * upstream advertises. When omitted, the observed overrides are kept.
126 */
127 updatedTools?: McpServerCapabilityOverride[];
128 /**
129 * Server-wide prompt overrides: disable, rename, or re-describe prompts
130 * the upstream advertises. When omitted, the observed overrides are kept.
131 */
132 updatedPrompts?: McpServerCapabilityOverride[];
133 /**
134 * Run a capability sync (tool and prompt discovery against the upstream)
135 * after the server is created, its configuration changes, or sync is
136 * enabled after being disabled. Discovery
137 * problems are reported on the `status` and `error` attributes and never
138 * fail the deploy. Skipped while the server still requires an
139 * administrator to complete its OAuth authentication. Cloudflare may
140 * independently discover capabilities even when this option is false.
141 * @default true
142 */
143 sync?: boolean;
144 }
145
146 export type McpServerAttributes = {
147 /** The server id. */
148 serverId: string;
149 /** Account that owns the server. */
150 accountId: string;
151 /** Observed display name. */
152 name: string;
153 /** Observed upstream MCP endpoint URL. */
154 hostname: string;
155 /** Observed authentication method. */
156 authType: McpServerAuthType;
157 /** Observed description, if any. */
158 description: string | undefined;
159 /** Whether outbound traffic routes through the gateway. */
160 secureWebGateway: boolean;
161 /** Whether the shared Cloudflare OAuth callback is used. */
162 isSharedOauthCallbackEnabled: boolean;
163 /** Observed server-wide tool overrides. */
164 updatedTools: McpServerCapabilityOverride[];
165 /** Observed server-wide prompt overrides. */
166 updatedPrompts: McpServerCapabilityOverride[];
167 /** Tools discovered by the last successful capability sync. */
168 tools: McpServerCapability[];
169 /** Prompts discovered by the last successful capability sync. */
170 prompts: McpServerCapability[];
171 /** Current capability sync state, if reported. */
172 status: McpServerStatus | undefined;
173 /** Whether administrative OAuth authentication is still required. */
174 authenticationStatus: McpServerAuthenticationStatus | undefined;
175 /** Error from the last capability sync, if any. */
176 error: string | undefined;
177 /** RFC 3339 timestamp of the last sync attempt, if reported. */
178 lastSynced: string | undefined;
179 /** RFC 3339 timestamp of the last successful sync, if reported. */
180 lastSuccessfulSync: string | undefined;
181 /** RFC 3339 timestamp of when the server was created, if reported. */
182 createdAt: string | undefined;
183 };
184
185 export type McpServer = Resource<TypeId, McpServerProps, McpServerAttributes, never, Providers>;
186
187 /**
188 * A Cloudflare Zero Trust **AI Controls MCP server** — an upstream MCP
189 * endpoint registered on the account so its tools and prompts can be
190 * discovered, governed, and exposed to users through an MCP portal.
191 *
192 * Use {@link McpPortal} to create the gateway. Creating a server does not
193 * attach it to a portal; portal membership is managed outside Alchemy.
194 *
195 * The product surface is in beta and requires the AI Controls
196 * entitlement; accounts without it receive the typed `Forbidden` error
197 * on all writes. The upstream `hostname` and `authType` are create-only
198 * on the API — changing either triggers a delete-first replacement.
199 * Credentials are write-only: the API never returns them, so a rotation
200 * is detected by comparing against the previously deployed value.
201 * Existing servers without saved stack state require explicit adoption;
202 * their IDs alone do not prove ownership.
203 *
204 * ### Registering an MCP server
205 * **Example:** Public server without authentication
206 * ```typescript
207 * const docs = yield* Cloudflare.Access.McpServer("CloudflareDocs", {
208 * hostname: "https://docs.mcp.cloudflare.com/mcp",
209 * authType: "unauthenticated",
210 * });
211 * ```
212 *
213 * **Example:** Server behind a static bearer token
214 * ```typescript
215 * const internal = yield* Cloudflare.Access.McpServer("InternalTools", {
216 * hostname: "https://mcp.internal.example.com/mcp",
217 * authType: "bearer",
218 * authCredentials: yield* Config.Redacted("MCP_BEARER_TOKEN"),
219 * description: "Internal engineering tools",
220 * secureWebGateway: true,
221 * });
222 * ```
223 *
224 * **Example:** Server protected by a Cloudflare Access service token
225 * ```typescript
226 * const token = yield* Cloudflare.Access.ServiceToken("McpToken", {});
227 *
228 * const guarded = yield* Cloudflare.Access.McpServer("GuardedTools", {
229 * hostname: "https://mcp.example.com/mcp",
230 * authType: "bearer",
231 * authCredentials: Output.all(token.clientId, token.clientSecret).pipe(
232 * Output.map(([clientId, clientSecret]) =>
233 * Redacted.make(JSON.stringify({
234 * headers: {
235 * "cf-access-client-id": clientId,
236 * "cf-access-client-secret": Redacted.value(clientSecret!),
237 * },
238 * })),
239 * ),
240 * ),
241 * });
242 * ```
243 *
244 * ### Governing capabilities
245 * **Example:** Disable one tool and rename another
246 * ```typescript
247 * const curated = yield* Cloudflare.Access.McpServer("Curated", {
248 * hostname: "https://docs.mcp.cloudflare.com/mcp",
249 * authType: "unauthenticated",
250 * updatedTools: [
251 * { name: "migrate_pages_to_workers_guide", enabled: false },
252 * { name: "search_cloudflare_documentation", alias: "search_docs" },
253 * ],
254 * });
255 * ```
256 *
257 * **Example:** Register without an explicit capability sync
258 * ```typescript
259 * const deferred = yield* Cloudflare.Access.McpServer("Deferred", {
260 * hostname: "https://mcp.example.com/mcp",
261 * authType: "bearer",
262 * authCredentials: yield* Config.Redacted("MCP_BEARER_TOKEN"),
263 * sync: false,
264 * });
265 * ```
266 *
267 * ### Adopting an existing server
268 * **Example:** Take ownership of a server registered outside Alchemy
269 * ```typescript
270 * const server = yield* Cloudflare.Access.McpServer("Existing", {
271 * serverId: "existing-server",
272 * hostname: "https://mcp.example.com/mcp",
273 * authType: "unauthenticated",
274 * }).pipe(adopt(true));
275 * ```
276 *
277 * @see https://developers.cloudflare.com/cloudflare-one/access-controls/ai-controls/
278 *
279 * @resource
280 * @product Access
281 * @category Cloudflare One (Zero Trust)
282 */
283 export const McpServer = Resource<McpServer>(TypeId);
284
285 /**
286 * Returns true if the given value is an McpServer resource.
287 */
288 export const isMcpServer = (value: unknown): value is McpServer =>
289 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
290
291 export const McpServerProvider = () =>
292 Provider.succeed(McpServer, {
293 stables: ["serverId", "accountId"],
294
295 list: Effect.fn(function* () {
296 const { accountId } = yield* yield* CloudflareEnvironment;
297 // Account-scoped collection; exhaustively paginate. The list rows
298 // carry the full server shape, so each maps directly into the same
299 // Attributes `read` returns. Accounts without the AI Controls
300 // entitlement reject the route with the typed `Forbidden` — treat
301 // them as having no servers.
302 return yield* zeroTrust.listAccessAiControlMcpServers.pages({ accountId }).pipe(
303 Stream.runCollect,
304 Effect.map((chunk) =>
305 Array.from(chunk).flatMap((page) =>
306 (page.result ?? []).map((server) => toAttributes(server, accountId)),
307 ),
308 ),
309 Effect.catchTag("Forbidden", () => Effect.succeed([])),
310 );
311 }),
312
313 diff: Effect.fn(function* ({ olds, news, output }) {
314 const { accountId } = yield* yield* CloudflareEnvironment;
315 if (!isResolved(news)) return undefined;
316 if (output !== undefined && output.accountId !== accountId) {
317 return { action: "replace" } as const;
318 }
319 // The server id is the API identity — changing it is a replacement.
320 const oldId = output?.serverId ?? olds?.serverId;
321 if (news.serverId !== undefined && oldId !== undefined && oldId !== news.serverId) {
322 return { action: "replace" } as const;
323 }
324 if (
325 (output?.hostname ?? olds?.hostname) !== news.hostname ||
326 (output?.authType ?? olds?.authType) !== news.authType
327 ) {
328 return { action: "replace", deleteFirst: true } as const;
329 }
330 return undefined;
331 }),
332
333 read: Effect.fn(function* ({ id, output, olds, previous }) {
334 const { accountId } = yield* yield* CloudflareEnvironment;
335 const acct = output?.accountId ?? accountId;
336
337 // The server id is deterministic (client-supplied or derived from
338 // the logical id), so a direct read covers the cold case too.
339 const serverId = output?.serverId ?? (yield* createServerId(id, olds?.serverId));
340 const observed = yield* observeServer(acct, serverId).pipe(
341 // A failed create can leave props with an invalid ID but no output.
342 // That generation cannot exist; let destroy recover the saved state.
343 Effect.catchTag("McpServerInvalidId", (error) =>
344 output === undefined ? Effect.undefined : Effect.fail(error),
345 ),
346 );
347 if (!observed) return undefined;
348 const attrs = toAttributes(observed, acct);
349 // MCP servers carry no ownership tags. An ID match alone does not
350 // authorize taking over a server when the stack has no saved output,
351 // unless it is the generation a replacement is replacing.
352 return output === undefined &&
353 !(previous?.serverId === observed.id && previous.accountId === acct)
354 ? Unowned(attrs)
355 : attrs;
356 }),
357
358 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
359 const { accountId } = yield* yield* CloudflareEnvironment;
360 const serverId = output?.serverId ?? (yield* createServerId(id, news.serverId));
361 const name = news.name ?? serverId;
362
363 // 1. Observe.
364 let observed = yield* observeServer(accountId, serverId);
365
366 // 2. Ensure — immutable changes are handled by engine replacement.
367 let changed = false;
368 if (observed === undefined) {
369 observed = yield* zeroTrust.createAccessAiControlMcpServer({
370 accountId,
371 id: serverId,
372 authType: news.authType,
373 hostname: news.hostname,
374 ...mutableBody(news, name),
375 });
376 changed = true;
377 } else {
378 // 3. Sync — update only when the observed state differs. Unset
379 // optional props mean "keep the observed value". Credentials are
380 // write-only, so a rotation is detected against the previously
381 // deployed props rather than the cloud.
382 const dirty =
383 observed.name !== name ||
384 (news.description !== undefined &&
385 (observed.description || undefined) !== news.description) ||
386 (news.secureWebGateway !== undefined &&
387 (observed.secureWebGateway ?? false) !== news.secureWebGateway) ||
388 (news.isSharedOauthCallbackEnabled !== undefined &&
389 (observed.isSharedOauthCallbackEnabled ?? false) !==
390 news.isSharedOauthCallbackEnabled) ||
391 (news.updatedTools !== undefined &&
392 !overridesEqual(observed.updatedTools, news.updatedTools)) ||
393 (news.updatedPrompts !== undefined &&
394 !overridesEqual(observed.updatedPrompts, news.updatedPrompts)) ||
395 secretRotated(news.authCredentials, olds?.authCredentials) ||
396 secretRotated(news.clientSecret, olds?.clientSecret);
397 if (dirty) {
398 observed = yield* zeroTrust.updateAccessAiControlMcpServer({
399 accountId,
400 id: serverId,
401 ...mutableBody(news, name),
402 });
403 changed = true;
404 }
405 }
406
407 // 4. Capability sync — best effort after a configuration change or
408 // when sync is enabled, and never while an administrator still
409 // has to complete the OAuth flow.
410 // Upstream discovery problems come back in the response body
411 // (`status`/`error`) and are matched as typed McpServerSyncFailure errors.
412 if (
413 (changed || olds?.sync === false) &&
414 news.sync !== false &&
415 observed.authenticationStatus !== "required"
416 ) {
417 yield* zeroTrust
418 .syncAccessAiControlMcpServer({ accountId, id: serverId })
419 .pipe(
420 Effect.catchTag("McpServerSyncFailure", (error) =>
421 Effect.logDebug(`capability sync for MCP server ${serverId} failed`, error.body),
422 ),
423 );
424 // 5. Return — re-read so the discovered capabilities are reported.
425 observed = (yield* observeServer(accountId, serverId)) ?? observed;
426 }
427
428 return toAttributes(observed, accountId);
429 }),
430
431 delete: Effect.fn(function* ({ output }) {
432 yield* zeroTrust
433 .deleteAccessAiControlMcpServer({
434 accountId: output.accountId,
435 id: output.serverId,
436 })
437 .pipe(Effect.catchTag("McpServerNotFound", () => Effect.void));
438 }),
439 });
440
441 /**
442 * Structural shape of a capability override as returned by the API.
443 */
444 type ObservedOverride = {
445 name: string;
446 alias?: string | null;
447 description?: string | null;
448 enabled?: boolean | null;
449 };
450
451 /**
452 * Structural shape shared by create/read/update/list responses.
453 */
454 type ObservedServer = zeroTrust.ReadAccessAiControlMcpServerResponse;
455
456 /**
457 * Read a server by id, mapping "gone" to `undefined`.
458 */
459 const observeServer = (accountId: string, id: string) =>
460 zeroTrust
461 .readAccessAiControlMcpServer({ accountId, id })
462 .pipe(Effect.catchTag("McpServerNotFound", () => Effect.undefined));
463
464 const createServerId = (id: string, serverId: string | undefined) =>
465 Effect.gen(function* () {
466 return serverId ?? (yield* createPhysicalName({ id, lowercase: true, maxLength: 32 }));
467 });
468
469 /**
470 * The request members shared by create and update, derived from the
471 * desired props. Unset optional props are omitted so the API keeps (or
472 * defaults) the server-side value.
473 */
474 const mutableBody = (news: McpServerProps, name: string) => ({
475 name,
476 ...(news.description !== undefined ? { description: news.description } : {}),
477 ...(news.secureWebGateway !== undefined ? { secureWebGateway: news.secureWebGateway } : {}),
478 ...(news.isSharedOauthCallbackEnabled !== undefined
479 ? { isSharedOauthCallbackEnabled: news.isSharedOauthCallbackEnabled }
480 : {}),
481 ...(news.updatedTools !== undefined ? { updatedTools: news.updatedTools } : {}),
482 ...(news.updatedPrompts !== undefined ? { updatedPrompts: news.updatedPrompts } : {}),
483 ...(news.authCredentials !== undefined
484 ? { authCredentials: Redacted.value(news.authCredentials) }
485 : {}),
486 ...(news.clientSecret !== undefined ? { clientSecret: Redacted.value(news.clientSecret) } : {}),
487 });
488
489 /**
490 * A write-only secret changed when it is set and differs from what was
491 * last deployed (including the first time it is set).
492 */
493 const secretRotated = (
494 desired: Redacted.Redacted<string> | undefined,
495 previous: Redacted.Redacted<string> | undefined,
496 ): boolean =>
497 desired !== undefined &&
498 (previous === undefined || Redacted.value(previous) !== Redacted.value(desired));
499
500 /**
501 * Drop null/undefined members so API echoes and desired overrides compare
502 * structurally.
503 */
504 const normalizeOverride = (override: ObservedOverride): McpServerCapabilityOverride => ({
505 name: override.name,
506 ...(override.alias != null ? { alias: override.alias } : {}),
507 ...(override.description != null ? { description: override.description } : {}),
508 ...(override.enabled != null ? { enabled: override.enabled } : {}),
509 });
510
511 const normalizeOverrides = (
512 overrides: ReadonlyArray<ObservedOverride> | null | undefined,
513 ): McpServerCapabilityOverride[] => (overrides ?? []).map(normalizeOverride);
514
515 const overridesEqual = (
516 observed: ReadonlyArray<ObservedOverride> | null | undefined,
517 desired: ReadonlyArray<ObservedOverride>,
518 ): boolean => {
519 const byName = (a: McpServerCapabilityOverride, b: McpServerCapabilityOverride) =>
520 a.name.localeCompare(b.name);
521 return (
522 JSON.stringify(normalizeOverrides(observed).sort(byName)) ===
523 JSON.stringify(normalizeOverrides(desired).sort(byName))
524 );
525 };
526
527 const toAttributes = (server: ObservedServer, accountId: string): McpServerAttributes => ({
528 serverId: server.id,
529 accountId,
530 name: server.name,
531 hostname: server.hostname,
532 authType: server.authType,
533 description: server.description || undefined,
534 secureWebGateway: server.secureWebGateway ?? false,
535 isSharedOauthCallbackEnabled: server.isSharedOauthCallbackEnabled ?? false,
536 updatedTools: normalizeOverrides(server.updatedTools),
537 updatedPrompts: normalizeOverrides(server.updatedPrompts),
538 tools: Array.from(server.tools ?? []),
539 prompts: Array.from(server.prompts ?? []),
540 status: server.status ?? undefined,
541 authenticationStatus: server.authenticationStatus ?? undefined,
542 error: server.error || undefined,
543 lastSynced: server.lastSynced ?? undefined,
544 lastSuccessfulSync: server.lastSuccessfulSync ?? undefined,
545 createdAt: server.createdAt ?? undefined,
546 });