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

main
ts 351 lines 12.6 KB
Raw
1 import * as control from "@distilled.cloud/aws/bedrock-agentcore-control";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import {
11 AgentCoreProvisioningFailed,
12 createGatewayName,
13 readAgentCoreTags,
14 retryWhileConflict,
15 retryWhileValidation,
16 syncAgentCoreTags,
17 unredact,
18 } from "./internal.ts";
19
20 export interface GatewayProps {
21 /**
22 * Name of the gateway. Must match `([0-9a-zA-Z][-]?){1,100}` (hyphens
23 * allowed, never consecutive). If omitted, a deterministic physical name is
24 * generated from the app, stage, and logical ID. Changing the name triggers
25 * a replacement.
26 */
27 name?: string;
28 /**
29 * A description of the gateway.
30 */
31 description?: string;
32 /**
33 * The ARN of an IAM role the gateway assumes to invoke its targets. Must
34 * trust `bedrock-agentcore.amazonaws.com`.
35 */
36 roleArn: string;
37 /**
38 * The protocol the gateway speaks to callers.
39 * @default "MCP"
40 */
41 protocolType?: control.GatewayProtocolType;
42 /**
43 * Protocol-specific configuration (MCP instructions, search, supported
44 * versions). Passed through to the AgentCore API unchanged.
45 */
46 protocolConfiguration?: control.GatewayProtocolConfiguration;
47 /**
48 * How inbound callers are authorized. `AWS_IAM` uses SigV4; `CUSTOM_JWT`
49 * requires `authorizerConfiguration`.
50 * @default "AWS_IAM"
51 */
52 authorizerType?: control.AuthorizerType;
53 /**
54 * Authorizer configuration (JWT discovery URL, allowed audiences/clients).
55 * Required when `authorizerType` is `CUSTOM_JWT`.
56 */
57 authorizerConfiguration?: control.AuthorizerConfiguration;
58 /**
59 * The ARN of a KMS key used to encrypt gateway data.
60 */
61 kmsKeyArn?: string;
62 /**
63 * Set to `DEBUG` to surface detailed exception traces to callers.
64 */
65 exceptionLevel?: control.ExceptionLevel;
66 /**
67 * Tags to apply to the gateway. Merged with internal Alchemy tags.
68 */
69 tags?: Record<string, string>;
70 }
71
72 export interface Gateway extends Resource<
73 "AWS.BedrockAgentCore.Gateway",
74 GatewayProps,
75 {
76 /**
77 * The unique identifier of the gateway.
78 */
79 gatewayId: string;
80 /**
81 * The ARN of the gateway.
82 */
83 gatewayArn: string;
84 /**
85 * The MCP endpoint URL clients connect to (available once the gateway is
86 * `READY`).
87 */
88 gatewayUrl: string | undefined;
89 /**
90 * Name of the gateway.
91 */
92 name: string;
93 /**
94 * Current status of the gateway (e.g. `READY`).
95 */
96 status: string;
97 }
98 > {}
99
100 /**
101 * An Amazon Bedrock AgentCore Gateway — a managed MCP endpoint that turns
102 * APIs and Lambda functions into agent-callable tools.
103 *
104 * A gateway fronts one or more targets (OpenAPI specs, Smithy models, Lambda
105 * functions) behind a single MCP URL with centralized authorization (SigV4 or
106 * JWT).
107 *
108 * ### Creating Gateways
109 * **Example:** IAM-Authorized MCP Gateway
110 * ```typescript
111 * import * as AgentCore from "@alchemy.run/aws/BedrockAgentCore";
112 * import * as IAM from "@alchemy.run/aws/IAM";
113 *
114 * const role = yield* IAM.Role("GatewayRole", {
115 * assumeRolePolicyDocument: {
116 * Version: "2012-10-17",
117 * Statement: [
118 * {
119 * Effect: "Allow",
120 * Principal: { Service: "bedrock-agentcore.amazonaws.com" },
121 * Action: ["sts:AssumeRole"],
122 * },
123 * ],
124 * },
125 * });
126 *
127 * const gateway = yield* AgentCore.Gateway("ToolGateway", {
128 * roleArn: role.roleArn,
129 * authorizerType: "AWS_IAM",
130 * });
131 * ```
132 *
133 * **Example:** JWT-Authorized Gateway
134 * ```typescript
135 * const gateway = yield* AgentCore.Gateway("JwtGateway", {
136 * roleArn: role.roleArn,
137 * authorizerType: "CUSTOM_JWT",
138 * authorizerConfiguration: {
139 * customJWTAuthorizer: {
140 * discoveryUrl: `https://cognito-idp.us-west-2.amazonaws.com/${userPool.userPoolId}/.well-known/openid-configuration`,
141 * allowedClients: [client.clientId],
142 * },
143 * },
144 * });
145 * ```
146 *
147 * @resource
148 */
149 export const Gateway = Resource<Gateway>("AWS.BedrockAgentCore.Gateway");
150
151 /** Statuses indicating an in-flight transition to wait out. */
152 const GATEWAY_TRANSIENT = new Set(["CREATING", "UPDATING", "DELETING"]);
153
154 export const GatewayProvider = () =>
155 Provider.effect(
156 Gateway,
157 Effect.gen(function* () {
158 const createName = Effect.fn(function* (id: string, props: Pick<GatewayProps, "name">) {
159 return props.name ?? (yield* createGatewayName(id));
160 });
161
162 const getGatewayOrUndefined = Effect.fn(function* (gatewayIdentifier: string) {
163 return yield* control
164 .getGateway({ gatewayIdentifier })
165 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
166 });
167
168 const findByName = Effect.fn(function* (name: string) {
169 const pages = yield* control.listGateways.pages({}).pipe(Stream.runCollect);
170 const summary = Array.from(pages)
171 .flatMap((page) => page.items ?? [])
172 .find((s) => s.name === name);
173 return summary === undefined ? undefined : yield* getGatewayOrUndefined(summary.gatewayId);
174 });
175
176 const waitForSettled = Effect.fn(function* (gatewayId: string) {
177 return yield* getGatewayOrUndefined(gatewayId).pipe(
178 Effect.repeat({
179 schedule: Schedule.fixed("5 seconds"),
180 until: (g) => g === undefined || !GATEWAY_TRANSIENT.has(g.status),
181 times: 36,
182 }),
183 );
184 });
185
186 const toAttributes = (gateway: control.GetGatewayResponse) => ({
187 gatewayId: gateway.gatewayId,
188 gatewayArn: gateway.gatewayArn,
189 gatewayUrl: gateway.gatewayUrl,
190 name: gateway.name,
191 status: gateway.status,
192 });
193
194 return Gateway.Provider.of({
195 stables: ["gatewayId", "gatewayArn", "name"],
196
197 list: () =>
198 Effect.gen(function* () {
199 const pages = yield* control.listGateways.pages({}).pipe(Stream.runCollect);
200 const summaries = Array.from(pages).flatMap((page) => page.items ?? []);
201 const hydrated = yield* Effect.forEach(
202 summaries,
203 (s) => getGatewayOrUndefined(s.gatewayId),
204 { concurrency: 5 },
205 );
206 return hydrated.filter((g) => g !== undefined).map(toAttributes);
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 const gateway = output?.gatewayId
211 ? yield* getGatewayOrUndefined(output.gatewayId)
212 : yield* findByName(yield* createName(id, olds ?? ({} as GatewayProps)));
213 if (gateway === undefined || gateway.status === "DELETING") {
214 return undefined;
215 }
216 const attrs = toAttributes(gateway);
217 const tags = yield* readAgentCoreTags(gateway.gatewayArn);
218 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
219 }),
220
221 diff: Effect.fn(function* ({ id, news, olds }) {
222 if (!isResolved(news)) return undefined;
223 const oldName = yield* createName(id, olds ?? ({} as GatewayProps));
224 const newName = yield* createName(id, news ?? ({} as GatewayProps));
225 if (oldName !== newName) {
226 return { action: "replace" } as const;
227 }
228 if ((olds?.kmsKeyArn ?? undefined) !== (news?.kmsKeyArn ?? undefined)) {
229 return { action: "replace" } as const;
230 }
231 // description, role, authorizer, protocol config, and tags converge
232 // via update.
233 }),
234
235 reconcile: Effect.fn(function* ({ id, news, output, session }) {
236 const props = news ?? ({} as GatewayProps);
237 const name = output?.name ?? (yield* createName(id, props));
238 const internalTags = yield* createInternalTags(id);
239 const desiredTags = { ...props.tags, ...internalTags };
240 const protocolType = props.protocolType ?? "MCP";
241 const authorizerType = props.authorizerType ?? "AWS_IAM";
242
243 // 1. OBSERVE
244 let gateway = output?.gatewayId
245 ? yield* getGatewayOrUndefined(output.gatewayId)
246 : undefined;
247 if (gateway === undefined) {
248 gateway = yield* findByName(name);
249 }
250
251 // 2. ENSURE — a freshly created IAM role is not instantly assumable
252 // by the AgentCore service principal, so ride out the transient
253 // ValidationException; tolerate the name-exists conflict race.
254 if (gateway === undefined) {
255 const created = yield* control
256 .createGateway({
257 name,
258 description: props.description,
259 roleArn: props.roleArn,
260 protocolType,
261 protocolConfiguration: props.protocolConfiguration,
262 authorizerType,
263 authorizerConfiguration: props.authorizerConfiguration,
264 kmsKeyArn: props.kmsKeyArn,
265 exceptionLevel: props.exceptionLevel,
266 tags: desiredTags,
267 })
268 .pipe(
269 retryWhileValidation,
270 Effect.catchTag("ConflictException", () => findByName(name)),
271 );
272 gateway =
273 created === undefined
274 ? yield* findByName(name)
275 : yield* getGatewayOrUndefined(created.gatewayId);
276 }
277 if (gateway === undefined) {
278 return yield* new AgentCoreProvisioningFailed({
279 message: `gateway '${name}' was neither created nor found`,
280 });
281 }
282
283 gateway = (yield* waitForSettled(gateway.gatewayId)) ?? gateway;
284 if (gateway.status === "FAILED") {
285 return yield* new AgentCoreProvisioningFailed({
286 message: `gateway '${name}' failed: ${(gateway.statusReasons ?? []).join("; ")}`,
287 });
288 }
289
290 // 3. SYNC — converge mutable settings from OBSERVED state.
291 const drifted =
292 (unredact(gateway.description) ?? undefined) !==
293 (props.description ?? unredact(gateway.description)) ||
294 gateway.roleArn !== props.roleArn ||
295 gateway.authorizerType !== authorizerType ||
296 (gateway.protocolType ?? "MCP") !== protocolType ||
297 (gateway.exceptionLevel ?? undefined) !== (props.exceptionLevel ?? undefined) ||
298 JSON.stringify(gateway.authorizerConfiguration ?? null) !==
299 JSON.stringify(
300 props.authorizerConfiguration ?? gateway.authorizerConfiguration ?? null,
301 ) ||
302 (props.protocolConfiguration !== undefined &&
303 JSON.stringify(gateway.protocolConfiguration ?? null) !==
304 JSON.stringify(props.protocolConfiguration));
305 if (drifted) {
306 yield* control
307 .updateGateway({
308 gatewayIdentifier: gateway.gatewayId,
309 name,
310 description: props.description,
311 roleArn: props.roleArn,
312 protocolType,
313 protocolConfiguration: props.protocolConfiguration,
314 authorizerType,
315 authorizerConfiguration: props.authorizerConfiguration,
316 kmsKeyArn: props.kmsKeyArn,
317 exceptionLevel: props.exceptionLevel,
318 })
319 .pipe(retryWhileConflict);
320 gateway = (yield* waitForSettled(gateway.gatewayId)) ?? gateway;
321 }
322
323 // 3b. SYNC TAGS against observed cloud tags.
324 yield* syncAgentCoreTags(gateway.gatewayArn, desiredTags);
325
326 // 4. RETURN fresh attributes.
327 yield* session.note(gateway.gatewayId);
328 return toAttributes(gateway);
329 }),
330
331 // A gateway with live targets rejects deletion with a
332 // ConflictException until they are gone — the engine deletes targets
333 // first, but their teardown is eventually consistent.
334 delete: Effect.fn(function* ({ output }) {
335 yield* control.deleteGateway({ gatewayIdentifier: output.gatewayId }).pipe(
336 retryWhileConflict,
337 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
338 );
339 yield* control.getGateway({ gatewayIdentifier: output.gatewayId }).pipe(
340 Effect.map((g) => g.status as string),
341 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("GONE" as string)),
342 Effect.repeat({
343 schedule: Schedule.fixed("5 seconds"),
344 until: (status) => status === "GONE",
345 times: 24,
346 }),
347 );
348 }),
349 });
350 }),
351 );