From f925a5134f5882b3bd035281d0abc13fdc067eb7 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 15:46:01 -0800 Subject: [PATCH 01/22] feat(box): Let a boxed agent use the MCP tools of the other gateways of its project A runtime without a box gets the URL of each gateway of its project in `AGENTCORE_GATEWAY__URL`, and its code uses the MCP tools of that gateway. A boxed agent on AgentCore Runtime cannot do this. Its box has no route to the host of the gateway, so the box refuses each request. The user cannot add the route. Build refuses `aws://` for a gateway host with `UNSIGNABLE_HOST`, and the ID of the gateway is not known before the first deploy. A target and a grant that you make by hand operate, but build does not keep them in `agentcore.json`. - **Which gateways.** A box runtime gets each gateway without `boundRuntime`, the same gateways that the L3 binds to a runtime without a box (`projectGatewaysOf`). A `PRIVATE_VPC` runtime gets none. A `CUSTOM_JWT` gateway gets a warning and no target, because the Box gateway signs only with its role. - **The target.** Build writes `egress-gateway-` on the Box gateway of the runtime, with `passthrough.gateway: ""` and `GATEWAY_IAM_ROLE` for `bedrock-agentcore` in the build region. A `NONE` gateway gets no outbound auth. Build changes and removes the target as it does each other `egress-` target. A host of the profile cannot use its name (`TARGET_NAME_COLLISION`), and the limit of 100 targets counts it. - **The schema.** `passthrough` can have `gateway` or `endpoint`, but not the two. The name must be a gateway of the project without `boundRuntime`, and not the gateway of the target. - **The pack.** The `@box/agentcore` pack of each box runtime declares `gateways..url` from `env:_URL` and `gateways..host` from `env:_HOST`, each with a pattern. The agent gets `_URL` in `[agent.env]` from the input, so the code that uses the gateway without a box operates in the box. - **The Runtime profile.** Only the Runtime profile gets `[mcp.]`, with `destinations = ["${{ inputs.gateways..host }}"]` and one backend to the URL of the Box gateway and `/egress-gateway-`, signed with `aws://` for `bedrock-agentcore`. Box adds a permit for each tool of a declared server, and a forbid rule of the policy stays. The local profile does not change. A server of the local profile with the name of a gateway stops build (`RUNTIME_GATEWAY_SERVER_NAME_TAKEN`). - **Gateway hosts in the profile.** `AWS_ENDPOINTS` has the gateway host, with the service `bedrock-agentcore`. An entry that signs for a gateway host with `aws://` stops build with `UNSIGNABLE_HOST`, and the message names the route that build adds. Build cannot tell a gateway of this project from a gateway of a different project by its host, because the ID of a gateway is known only after deploy. - **IAM warnings.** `boxGatewayIamWarnings` gives no warning for a target with `passthrough.gateway`, because the L3 gives the grant. It gives a warning for a target to a gateway host when the role has no `bedrock-agentcore:InvokeGateway`. - **Interfaces that changed.** `PassthroughConfigSchema` (`endpoint` is optional, `gateway` is new), `BoxNetwork.projectGateways`, `RuntimeProfileContext.projectGateways`, `renderAgentCorePack(spec, gateways)`, and the problem code `RUNTIME_GATEWAY_SERVER_NAME_TAKEN`. - **Dependency.** The target needs the L3 branch `sa/box-gateway-to-gateway` of aws/agentcore-l3-cdk-constructs. That branch gives the endpoint, the grant, and `_HOST`. - **Not done.** box 0.1.11-preview.10 takes an input in `destinations` only when its value is a host. Thus the pack reads `_HOST` and not the URL. If the CLI wrote the target from `deployed-state.json`, each new project must deploy two times. - `src/core/project/boxNetwork/network.test.ts`, "the gateways of the project": the gateways that the agent gets, a `PRIVATE_VPC` runtime, a `CUSTOM_JWT` gateway, the name collision, the target that build wrote, the limit of 100, and the refusal of a signed gateway host in `[egress]` and `[mcp]`. "boxGatewayIamWarnings for a gateway of the project" pins the two warnings. - `src/core/project/boxNetworkWriters.test.ts`, "gatewayTargetsWriter for the gateways of the project": the writer adds, changes, and removes the target. "stages the inputs of each gateway that the agent calls in the @box/agentcore pack" pins the staged pack. - `src/core/project/runtimeProfile/rules/gateway.test.ts`, "the gateway rule for a gateway of the project": the `[mcp.]` server, no server with no gateway, and the stop for a server name that a gateway has. - `src/core/project/templates/boxProfile.test.ts`, "for a gateway of the project that the agent calls" (a test name): the two inputs, the agent variable, and the host and URL patterns. - `src/projectSchemas/project.test.ts`, "a passthrough target that names a gateway": the spec that it accepts and the five refusals. - `src/core/project/boxNetwork/projectGateways.test.ts`: the two target shapes. "the box on PATH" operates box 0.1.11-preview.10 on the Runtime profile and the pack that build makes, with the variables that the L3 sets. Box resolves the server to the host, the backend to the target, the agent variable to the URL, and adds its `net:connect` permit for the host. The test skips when no box is on `PATH`. - Without the change in `src/`, 35 of the 265 tests of these six files fail. Each of 19 mutations of `src/` fails one or more of these tests. - `bun test` with box 0.1.11-preview.10 on `PATH`: 5867 pass, 6 skip, 1 fail. The one failure is "the box on PATH > resolves a profile into the rules the tests fake" in `boxProfileResolver.test.ts`. It fails on `upstream/box-integration` too, with this box. CI has no box, so CI skips it. - `bun run typecheck`, `bun run lint:check`, and `bun run format:check` pass. - Live test in a test account in us-west-2: a new project from this branch and the L3 branch, with a second gateway `toolsgw` (`AWS_IAM`) and one Lambda target that gives a known answer. I added the gateway and the target with `agentcore add gateway` and `agentcore add gateway-target`. I did not change the box profile, the targets of the Box gateway, or IAM. One deploy made the target, the grant, and the variables. The agent used `echo___known_answer` and gave the known answer `gw2gw-known-answer-7319`. Box logged a permit for `mcp:call toolsgw/echo___known_answer`, the Box gateway sent the request to `egress-gateway-toolsgw`, and `toolsgw` logged the tool call and the known answer. The test project only had these changes: agent code that uses the gateway, `enableApplicationLogs` on `toolsgw`. I did `agentcore deploy` two more times for that agent code. `add gateway` gives `protocolType: "None"`, so `_URL` has no `/mcp`, and the agent code must add it, the same as without a box. - I did not do these: `bun run test:e2e`, `bun run audit`, `bun run secrets:check`, and `bun run build`. --- docs/box-local-testing.md | 20 +- src/core/project/boxMemory.ts | 2 +- src/core/project/boxNetwork/egress.ts | 17 ++ src/core/project/boxNetwork/network.test.ts | 193 +++++++++++++++++- src/core/project/boxNetwork/network.ts | 45 +++- .../boxNetwork/projectGateways.test.ts | 123 +++++++++++ .../project/boxNetwork/projectGateways.ts | 85 ++++++++ src/core/project/boxNetworkWriters.test.ts | 87 ++++++++ src/core/project/boxNetworkWriters.ts | 47 ++++- .../runtimeProfile/rules/gateway.test.ts | 54 +++++ .../project/runtimeProfile/rules/gateway.ts | 42 +++- src/core/project/runtimeProfile/types.ts | 5 + src/core/project/templates/boxProfile.test.ts | 56 +++++ src/core/project/templates/boxProfile.ts | 45 +++- src/projectSchemas/gateway.ts | 10 +- src/projectSchemas/project.test.ts | 54 +++++ src/projectSchemas/project.ts | 23 +++ 17 files changed, 874 insertions(+), 34 deletions(-) create mode 100644 src/core/project/boxNetwork/projectGateways.test.ts create mode 100644 src/core/project/boxNetwork/projectGateways.ts diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index bc54379df..f9e3e1cf4 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -222,6 +222,14 @@ profile that names a pack `box/` fails: box refuses it and names the `@box `mcp:call`. A host the gateway already has a target for keeps that target. Build owns only the targets whose name starts with `egress-`: it adds them, changes them, and removes one when no host needs it. It never changes another target. +- **The other gateways of the project.** A runtime without a box gets each gateway without + `boundRuntime` in `AGENTCORE_GATEWAY__URL`. For a box runtime, each of these gateways gets + the target `egress-gateway-` on `-box-egress`, with `passthrough.gateway` set to + the gateway's name. The L3 sets the target's endpoint to that gateway's URL, gives the Box + gateway's role `bedrock-agentcore:InvokeGateway` on that gateway only, and sets + `AGENTCORE_GATEWAY__URL` and `_HOST` on the runtime. A `PRIVATE_VPC` runtime gets none of + them. A `CUSTOM_JWT` gateway gets a warning and no target. You write nothing for them. A profile + entry that signs for a gateway host with `aws://` stops build. - **Outbound auth.** An `aws://` secret signs with the gateway's role, an `env://` secret sends an API key from AgentCore Identity, and an entry with no secret sends no credential. - **Failures.** A profile Box refuses stops build and deploy with box's own error. A wildcard host, @@ -249,13 +257,18 @@ profile that names a pack `box/` fails: box refuses it and names the `@box the Runtime's Python, in every table: the agent, each stdio `[mcp.]` server, each `[tool.]`; - the `@box/agentcore` packs, the project name, and the build region come in, and each CloudWatch - target signs with the execution role. + target signs with the execution role; - with `instrumentation.enableOtel` on, which is the default for a box template too, a command of the Python of the venv starts with `opentelemetry-instrument`. On CodeZip, the Python of the Runtime runs the script in the zip, `/bin/opentelemetry-instrument`. The `@box/agentcore` pack gives the agent the ADOT variables and the `OTEL_RESOURCE_ATTRIBUTES` that the Runtime sets. When your `[agent.env]` sets one of these variables, box uses your value. The pack sets no - `OTEL_EXPORTER_OTLP_*` variable, because box sets each one. + `OTEL_EXPORTER_OTLP_*` variable, because box sets each one; + - each other gateway of the project gets `[mcp.]`, to the host that `@box/agentcore` + reads from `AGENTCORE_GATEWAY__HOST`, through its `egress-gateway-` target. The agent + gets `AGENTCORE_GATEWAY__URL`, so the code that calls the gateway without a box works in + the box. Box permits each tool of the server, and a forbid rule of your policy still applies. + A server of your profile with the name of a gateway stops build. **The default log target.** With no `cloudwatch_logs` target, the Runtime profile gets `[telemetry.agentcore]`: box sends its deny, permit, and trace records to the log group of the @@ -293,7 +306,8 @@ profile that names a pack `box/` fails: box refuses it and names the `@box - **No-auth targets need a newer L3.** A passthrough target with no outbound auth synthesizes only with an `@aws/agentcore-cdk` that accepts it. Until that release is pinned, use a local L3 build, - as in step 5. + as in step 5. A target with `passthrough.gateway` also needs an L3 that + accepts that field. ## 5. Point the generated CDK app at the local L3 tarball diff --git a/src/core/project/boxMemory.ts b/src/core/project/boxMemory.ts index a407cbf93..362c32a79 100644 --- a/src/core/project/boxMemory.ts +++ b/src/core/project/boxMemory.ts @@ -305,7 +305,7 @@ function boxGatewayFor(spec: ProjectSpec, runtime: ProjectRuntime): AgentCoreGat */ function servesTarget(targets: readonly AgentCoreGatewayTarget[], wanted: AgentCoreGatewayTarget) { const endpoint = (target: AgentCoreGatewayTarget) => - target.passthrough && new URL(target.passthrough.endpoint).host; + target.passthrough?.endpoint && new URL(target.passthrough.endpoint).host; return targets.some( (target) => target.name === wanted.name || endpoint(target) === endpoint(wanted), ); diff --git a/src/core/project/boxNetwork/egress.ts b/src/core/project/boxNetwork/egress.ts index 3a9dcbd16..ad1cf2f48 100644 --- a/src/core/project/boxNetwork/egress.ts +++ b/src/core/project/boxNetwork/egress.ts @@ -132,6 +132,12 @@ const AWS_ENDPOINTS = [ api: "lambda-url", service: "lambda", }, + { + pattern: + /^[a-z0-9][a-z0-9-]*\.gateway\.bedrock-agentcore\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?$/, + api: "gateway", + service: "bedrock-agentcore", + }, ] as const; /** The API of an AWS endpoint that the gateway signs for. */ @@ -191,6 +197,17 @@ export function outboundAuthFor( if (!secret) return { ok: true, auth: { kind: "none" } }; const [scheme, value = ""] = secret.ref.split("://", 2); if (scheme === "aws") { + if (awsEndpoint(host)?.api === "gateway") { + return { + ok: false, + code: "UNSIGNABLE_HOST", + reason: + `signs requests to ${host}, the host of an AgentCore gateway, with ${secret.ref}. ` + + "Build signs only for the gateways of this project, and it adds the route to each of " + + "them on AgentCore Runtime itself, as [mcp.], with the host that the " + + "deploy gives the gateway. Remove this entry. To call a gateway, add it to this project.", + }; + } const signing = signingService(host); if (!signing) { return { diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 04e2b6dc9..2d6db6354 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -45,6 +45,9 @@ interface Options { readonly credentials?: ProjectSpec["credentials"]; readonly grantedActions?: string[]; readonly executionRoleArn?: string; + /** The other gateways of the project, after the Box gateway. */ + readonly gateways?: Record[]; + readonly runtime?: Partial; } /** The local box profile of runtime `agent`. */ @@ -56,10 +59,11 @@ const PROFILE = ".box/agent/local/profile.toml"; * sets `packs` on line 1, then each entry of `egress` and `mcp` on a line of its own. */ function model(policy: string, egress: Record = {}, options: Options = {}) { + const runtime = { ...RUNTIME, ...options.runtime } as ProjectRuntime; const spec = { name: "demo", projectType: "box", - runtimes: [RUNTIME], + runtimes: [runtime], memories: [], credentials: options.credentials ?? [], agentCoreGateways: [ @@ -68,6 +72,7 @@ function model(policy: string, egress: Record = {}, options: Op targets: options.targets ?? [], ...(options.executionRoleArn && { executionRoleArn: options.executionRoleArn }), }, + ...(options.gateways ?? []), ], } as unknown as ProjectSpec; const mcp = options.mcp ?? {}; @@ -89,7 +94,7 @@ function model(policy: string, egress: Record = {}, options: Op ); const network = buildBoxNetwork(parsed, failures, { spec, - runtime: RUNTIME, + runtime, gateway: "agent-box-egress", region: "us-west-2", targets: options.targets ?? [], @@ -1190,3 +1195,187 @@ describe("warnings", () => { }); }); }); + +describe("the gateways of the project", () => { + const TOOLS = { name: "tools", authorizerType: "AWS_IAM", targets: [] }; + const OPEN = { name: "open-tools", authorizerType: "NONE", targets: [] }; + const JWT = { name: "jwt-tools", authorizerType: "CUSTOM_JWT", targets: [] }; + const OTHER_BOX = { ...boxGatewaySpec("other"), targets: [] }; + + test("gives the agent each gateway without boundRuntime, with its target and its variables", () => { + const { network } = model("", {}, { gateways: [TOOLS, OPEN, OTHER_BOX] }); + + expect(network.projectGateways).toEqual([ + { + name: "tools", + target: "egress-gateway-tools", + variablePrefix: "AGENTCORE_GATEWAY_TOOLS", + auth: "iam", + }, + { + name: "open-tools", + target: "egress-gateway-open-tools", + variablePrefix: "AGENTCORE_GATEWAY_OPEN_TOOLS", + auth: "none", + }, + ]); + expect(network.failures).toEqual([]); + }); + + test("gives a PRIVATE_VPC runtime no gateway, as the CDK library binds none to it", () => { + const { network } = model( + "", + {}, + { gateways: [TOOLS], runtime: { containment: "PRIVATE_VPC" } }, + ); + + expect(network.projectGateways).toEqual([]); + }); + + test("warns for a CUSTOM_JWT gateway, and gives the agent no route to it", () => { + const { network } = model("", {}, { gateways: [JWT] }); + + expect(network.projectGateways).toEqual([]); + expect(network.warnings).toContain( + "The gateway 'jwt-tools' takes CUSTOM_JWT tokens, and the Box gateway of runtime 'agent' " + + "signs only with its IAM role, so the boxed agent cannot call 'jwt-tools' on AgentCore " + + "Runtime. Set its authorizerType to AWS_IAM to let the agent call it.", + ); + }); + + test("fails an entry whose target would take the name of a gateway's target", () => { + const r = model( + "", + { "gateway-tools": { destinations: ["x.example.com"] } }, + { gateways: [TOOLS] }, + ); + + expect(r.failures()).toEqual([["TARGET_NAME_COLLISION", "gateway-tools"]]); + expect(r.reasons()[0]).toContain("the target that build adds for the gateway 'tools'"); + }); + + test("keeps the target that build wrote for a gateway as build's own", () => { + const written = { + name: "egress-gateway-tools", + targetType: "passthrough", + passthrough: { gateway: "tools", protocolType: "CUSTOM" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + } as AgentCoreGatewayTarget; + + expect(model("", {}, { gateways: [TOOLS], targets: [written] }).failures()).toEqual([]); + }); + + test("counts the gateways' targets toward the limit of 100", () => { + const egress = Object.fromEntries( + Array.from({ length: 100 }, (_, i) => [`h${i}`, { destinations: [`h${i}.example.com`] }]), + ); + const r = model("", egress, { gateways: [TOOLS] }); + + expect(r.reasons()).toEqual([ + "The gateway 'agent-box-egress' needs 101 targets, 100 for the hosts of the Box profile, 1 " + + "for the gateways of the project, and 0 of your own, and a gateway can have at most 100. " + + "Remove hosts from the profile, or targets from the gateway.", + ]); + }); + + test.each([ + [ + "an [egress] entry", + { tools: { destinations: [GATEWAY_HOST], secret: { ref: "aws://" } } }, + {}, + ], + [ + "an HTTP [mcp] server", + {}, + { mcp: { tools: { type: "http", destinations: [GATEWAY_HOST], secret: { ref: "aws://" } } } }, + ], + ])( + "refuses %s that signs for a gateway host, and names the route build adds", + (_, egress, options) => { + const r = model("", egress, { ...options, gateways: [TOOLS] }); + + expect(r.failures().map(([code]) => code)).toEqual(["UNSIGNABLE_HOST"]); + expect(r.reasons()[0]).toContain( + `signs requests to ${GATEWAY_HOST}, the host of an AgentCore gateway, with aws://. Build ` + + "signs only for the gateways of this project, and it adds the route to each of them on " + + "AgentCore Runtime itself, as [mcp.]", + ); + }, + ); +}); + +const GATEWAY_HOST = + "other-project-tools-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com"; + +describe("boxGatewayIamWarnings for a gateway of the project", () => { + test("gives no warning for a target that names a gateway, which the CDK library grants", () => { + const spec = { + name: "demo", + projectType: "box", + runtimes: [RUNTIME], + agentCoreGateways: [ + { + ...boxGatewaySpec("agent"), + targets: [ + { + name: "egress-gateway-tools", + targetType: "passthrough", + passthrough: { gateway: "tools", protocolType: "CUSTOM" }, + outboundAuth: { + type: "GATEWAY_IAM_ROLE", + service: "bedrock-agentcore", + region: "us-west-2", + }, + }, + ], + }, + { name: "tools", authorizerType: "AWS_IAM", targets: [] }, + ], + } as unknown as ProjectSpec; + + expect( + boxGatewayIamWarnings(spec, { + runtime: "agent", + gateway: "agent-box-egress", + grantedActions: [], + region: "us-west-2", + }), + ).toEqual([]); + }); + + test("warns for a target to a gateway host that the role has no InvokeGateway for", () => { + const spec = { + name: "demo", + projectType: "box", + runtimes: [RUNTIME], + agentCoreGateways: [ + { + ...boxGatewaySpec("agent"), + targets: [ + passthrough("mine", `https://${GATEWAY_HOST}`, { + outboundAuth: { + type: "GATEWAY_IAM_ROLE", + service: "bedrock-agentcore", + region: "us-west-2", + }, + }), + ], + additionalPolicies: ["agentcore/box-memory-policy.json"], + }, + ], + } as unknown as ProjectSpec; + const network = { runtime: "agent", gateway: "agent-box-egress", region: "us-west-2" }; + + expect(boxGatewayIamWarnings(spec, { ...network, grantedActions: [] })).toEqual([ + `Target 'mine' calls ${GATEWAY_HOST} with the gateway's role, which has no bedrock-agentcore ` + + "permissions for that host. Add an IAM policy file to additionalPolicies of the " + + "'agent-box-egress' gateway.", + ]); + expect( + boxGatewayIamWarnings(spec, { + ...network, + grantedActions: ["bedrock-agentcore:InvokeGateway"], + }), + ).toEqual([]); + }); +}); diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index b23cbc380..ce289802c 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -31,6 +31,7 @@ import { deriveRuntimeProfile } from "../runtimeProfile/derive"; import { defaultTracesTelemetry, runtimeProfileHeader } from "../runtimeProfile/rules/additions"; import type { TomlTable } from "../runtimeProfile/types"; import { withDeployRegion, type CloudWatchTelemetry } from "./telemetry"; +import { projectGatewaysOf, type BoxProjectGateway } from "./projectGateways"; import { outboundAuthWords, sameOutboundAuth, targetOutboundAuth } from "./projectSpec"; import { MAX_GATEWAY_TARGETS, @@ -117,6 +118,11 @@ export interface BoxNetwork { readonly hosts: readonly BoxNetworkHost[]; /** The `env://` route of each target that sends an API key, for the credentials writer. */ readonly envRoutes: readonly BoxEnvRoute[]; + /** + * The gateways of the project that the agent calls through the Box gateway, each with its + * target; absent means none. + */ + readonly projectGateways?: readonly BoxProjectGateway[]; /** * The policy files, relative to the agent's local box folder, to copy beside the AgentCore * Runtime profile. @@ -198,7 +204,8 @@ export function buildBoxNetwork( return { ...rest, reason: `${where.subject} ${reason}`, place: where.place }; }; const failures: BoxNetworkFailure[] = [...parseFailures, ...map.failures.map(located)]; - const targets = hostTargets(map.hosts, project, located, parsed.profile.path); + const reached = projectGatewaysOf(project.spec, project.runtime); + const targets = hostTargets(map.hosts, project, reached.gateways, located, parsed.profile.path); failures.push(...targets.failures); const telemetry = parsed.profile.telemetry && @@ -213,6 +220,7 @@ export function buildBoxNetwork( region: project.region, gateway: { name: project.gateway, targets: project.targets }, hosts: targets.hosts, + projectGateways: reached.gateways, telemetry: telemetry?.telemetry ?? [], places: source.places, }); @@ -231,6 +239,7 @@ export function buildBoxNetwork( region: project.region, hosts: targets.hosts, envRoutes: envRoutesOf(targets.hosts), + projectGateways: reached.gateways, policyFiles: parsed.profile.policyFiles, ...(sent && { telemetry: sent }), ...(derived && @@ -249,6 +258,7 @@ export function buildBoxNetwork( ); }), ...(telemetry?.warnings ?? []), + ...reached.warnings, ...(derived?.warnings ?? []), ], failures, @@ -278,7 +288,7 @@ export function isManagedTarget(target: Pick): b /** The host map key of a passthrough target's endpoint, or `undefined` for another target. */ function endpointKey(target: AgentCoreGatewayTarget): string | undefined { - const at = target.passthrough && parseEndpoint(target.passthrough.endpoint); + const at = target.passthrough?.endpoint && parseEndpoint(target.passthrough.endpoint); return at ? hostKey(at.host, at.port) : undefined; } @@ -327,6 +337,7 @@ function duplicateRule( function hostTargets( mapped: readonly MappedHost[], project: BoxNetworkProject, + gateways: readonly BoxProjectGateway[], located: (failure: ConversionFailure) => BoxNetworkFailure, profilePath: string, ): { hosts: BoxNetworkHost[]; failures: BoxNetworkFailure[] } { @@ -450,6 +461,9 @@ function hostTargets( for (const target of existing) { if (!isManagedTarget(target)) owners.set(target.name, `the gateway target '${target.name}'`); } + for (const gateway of gateways) { + owners.set(gateway.target, `the target that build adds for the gateway '${gateway.name}'`); + } const describeHost = (host: MappedHost) => host.entry ? `${entryLabel(host.entry)} for ${host.authority}` : `the host ${host.authority}`; for (const index of reused) owners.set(hosts[index]!.target!, describeHost(mapped[index]!)); @@ -474,13 +488,19 @@ function hostTargets( const served = hosts.filter((host) => host.target !== undefined).length; const kept = existing.filter((target) => !isManagedTarget(target) && !claimed.has(target.name)); - if (served + kept.length > MAX_GATEWAY_TARGETS) { + const needed = served + gateways.length + kept.length; + if (needed > MAX_GATEWAY_TARGETS) { + const builds = + gateways.length === 0 + ? `${served} for the hosts of the Box profile and` + : `${served} for the hosts of the Box profile, ${gateways.length} for the gateways of ` + + "the project, and"; failures.push({ code: "TOO_MANY_TARGETS", reason: - `The gateway '${project.gateway}' needs ${served + kept.length} targets, ${served} for ` + - `the hosts of the Box profile and ${kept.length} of your own, and a gateway can have at ` + - `most ${MAX_GATEWAY_TARGETS}. Remove hosts from the profile, or targets from the gateway.`, + `The gateway '${project.gateway}' needs ${needed} targets, ${builds} ${kept.length} of ` + + `your own, and a gateway can have at most ${MAX_GATEWAY_TARGETS}. Remove hosts from the ` + + "profile, or targets from the gateway.", place: profilePath, }); } @@ -514,7 +534,10 @@ function unmanagedShape(target: AgentCoreGatewayTarget): string | undefined { const { endpoint, protocolType, stickinessConfiguration } = target.passthrough; if (protocolType !== "CUSTOM") return `has protocolType ${protocolType}`; if (stickinessConfiguration) return "has a stickinessConfiguration"; - if (!/^https:\/\/[a-z0-9.-]+(:\d+)?$/.test(endpoint)) return `has the endpoint ${endpoint}`; + // A target that names a gateway of the project has no endpoint. + if (endpoint !== undefined && !/^https:\/\/[a-z0-9.-]+(:\d+)?$/.test(endpoint)) { + return `has the endpoint ${endpoint}`; + } const auth = target.outboundAuth; const fields = auth ? Object.keys(auth).sort().join(",") : ""; const shapes: Record = { @@ -540,7 +563,7 @@ function targetConflict( auth: BoxEgressAuth, profilePath: string, ): string | undefined { - const endpoint = target.passthrough && parseEndpoint(target.passthrough.endpoint); + const endpoint = target.passthrough?.endpoint && parseEndpoint(target.passthrough.endpoint); const named = `The gateway target '${target.name}' for ${host.authority}`; if (target.passthrough?.protocolType !== "CUSTOM") { return ( @@ -650,13 +673,17 @@ export function boxGatewayIamWarnings( ); case "lambda-url": return grants("lambda:InvokeFunctionUrl"); + case "gateway": + return grants("bedrock-agentcore:InvokeGateway"); } }; const warnings: string[] = []; for (const target of gateway.targets) { const auth = target.outboundAuth; if (auth?.type !== "GATEWAY_IAM_ROLE" || !auth.service) continue; - const at = target.passthrough && parseEndpoint(target.passthrough.endpoint); + // The CDK library grants the role InvokeGateway on the gateway that the target names. + if (target.passthrough?.gateway !== undefined) continue; + const at = target.passthrough?.endpoint && parseEndpoint(target.passthrough.endpoint); const endpoint = at && awsEndpoint(at.host); const host = at && hostKey(at.host, at.port); if (endpoint && host ? allows(endpoint.api, host) : holds(auth.service)) continue; diff --git a/src/core/project/boxNetwork/projectGateways.test.ts b/src/core/project/boxNetwork/projectGateways.test.ts new file mode 100644 index 000000000..e6c703dbf --- /dev/null +++ b/src/core/project/boxNetwork/projectGateways.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { cp, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { parse } from "smol-toml"; +import type { ProjectSpec } from "../../../projectSchemas/project"; +import { profileKeyPlaces, runtimeProfileContext } from "../runtimeProfile/context"; +import { apply } from "../runtimeProfile/rules/gateway"; +import { serializeRuntimeProfile } from "../runtimeProfile/serialize"; +import type { TomlTable } from "../runtimeProfile/types"; +import { AGENTCORE_PACK_PATH, renderAgentCorePack } from "../templates/boxProfile"; +import { projectGatewayTargetFor, type BoxProjectGateway } from "./projectGateways"; + +const TOOLS: BoxProjectGateway = { + name: "tools", + target: "egress-gateway-tools", + variablePrefix: "AGENTCORE_GATEWAY_TOOLS", + auth: "iam", +}; + +describe("projectGatewayTargetFor", () => { + test("names the gateway and signs for AgentCore in the build region, for an AWS_IAM gateway", () => { + expect(projectGatewayTargetFor(TOOLS, "us-west-2")).toEqual({ + name: "egress-gateway-tools", + targetType: "passthrough", + passthrough: { gateway: "tools", protocolType: "CUSTOM" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + }); + }); + + test("sends no credential to a gateway that takes none", () => { + expect(projectGatewayTargetFor({ ...TOOLS, auth: "none" }, "us-west-2").outboundAuth).toBe( + undefined, + ); + }); +}); + +const directories: string[] = []; +afterEach(async () => { + await Promise.all(directories.splice(0).map((d) => rm(d, { recursive: true, force: true }))); +}); + +/** The box on PATH, when it has `box profile show --format json --full`. */ +const box = (() => { + const path = Bun.which("box"); + if (!path) return undefined; + const help = Bun.spawnSync([path, "profile", "show", "--help"], { stderr: "ignore" }).stdout; + return ["--format", "--full"].every((flag) => help.toString().includes(flag)) ? path : undefined; +})(); + +const HOST = "demo-default-tools-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com"; +const BOX_GATEWAY_URL = + "https://demo-default-agent-box-egress-klmnopqrst.gateway.bedrock-agentcore.us-west-2.amazonaws.com"; + +describe("the box on PATH", () => { + test.skipIf(box === undefined)( + "resolves the server and the agent variable of a gateway from the variables the CDK library sets (skipped without a box with --format json --full on PATH)", + async () => { + const root = await mkdtemp(join(tmpdir(), "box-project-gateway-")); + directories.push(root); + const resources = join(root, "resources"); + await cp(join(dirname(await realpath(box!)), "resources"), resources, { recursive: true }); + const spec = { name: "demo", memories: [] } as unknown as ProjectSpec; + const pack = join(root, AGENTCORE_PACK_PATH); + await mkdir(dirname(pack), { recursive: true }); + await writeFile(pack, renderAgentCorePack(spec, [TOOLS])); + const local = + 'packs = ["@box/base", "@box/agentcore"]\n\n[profile]\nname = "demo"\n\n' + + '[agent]\ncommand = ["/bin/sh"]\n'; + const context = runtimeProfileContext({ + spec, + runtime: { name: "agent", build: "Container" } as never, + profileFile: ".box/profile.toml", + region: "us-west-2", + gateway: { name: "agent-box-egress", targets: [] }, + hosts: [], + projectGateways: [TOOLS], + telemetry: [], + places: profileKeyPlaces(local, ".box/profile.toml"), + }); + const runtimeProfile = apply(parse(local) as TomlTable, context).table; + const project = join(root, "project"); + await mkdir(join(project, ".box"), { recursive: true }); + await writeFile( + join(project, ".box", "profile.toml"), + serializeRuntimeProfile(runtimeProfile), + ); + + const run = Bun.spawnSync( + [box!, "profile", "show", ".box/profile.toml", "--format", "json", "--full"], + { + cwd: project, + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + BOX_RESOURCES: resources, + AWS_REGION: "us-west-2", + AGENTCORE_GATEWAY_BOX_URL: BOX_GATEWAY_URL, + AGENTCORE_GATEWAY_TOOLS_URL: `https://${HOST}/mcp`, + AGENTCORE_GATEWAY_TOOLS_HOST: HOST, + }, + }, + ); + expect(run.stderr.toString()).toBe(""); + const shown = JSON.parse(run.stdout.toString()) as { + box_toml: { + agent: { env: Record }; + mcp: Record; + }; + policy: string; + }; + expect(shown.box_toml.mcp.tools!.destinations).toEqual([HOST]); + expect(shown.box_toml.mcp.tools!.backends.map(({ url }) => url)).toEqual([ + `${BOX_GATEWAY_URL}/egress-gateway-tools`, + ]); + expect(shown.box_toml.agent.env.AGENTCORE_GATEWAY_TOOLS_URL).toBe(`https://${HOST}/mcp`); + expect(shown.policy).toContain( + `permit (principal, action == Box::Action::"net:connect", resource) when { (context.input.host == "${HOST}" && context.input.port == 443) };`, + ); + }, + 120_000, + ); +}); diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts new file mode 100644 index 000000000..0d8a479ff --- /dev/null +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -0,0 +1,85 @@ +/** + * The gateways of the project that a boxed agent calls through its runtime's Box gateway. A runtime + * without a box gets each gateway without `boundRuntime` in `AGENTCORE_GATEWAY__URL`. On + * AgentCore Runtime, the boxed agent gets the same variable, and box sends each call to the + * gateway's host to a Box gateway target that names that gateway (`passthrough.gateway`). + */ +import type { AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; +import { gatewayDiscoveryPrefix, type ProjectSpec } from "../../../projectSchemas/project"; +import type { ProjectRuntime } from "../../../projectSchemas/runtime"; +import { targetNameFor } from "./egress"; + +/** A gateway of the project that a boxed runtime calls through its Box gateway. */ +export interface BoxProjectGateway { + /** The gateway's name in agentcore.json, and the name of its `[mcp]` server on the Runtime. */ + readonly name: string; + /** The target of the Box gateway that calls it. */ + readonly target: string; + /** The prefix of the variables the CDK library sets for it: `_URL` and `_HOST`. */ + readonly variablePrefix: string; + /** How the Box gateway authenticates to it: with its role for `AWS_IAM`, with nothing for `NONE`. */ + readonly auth: "iam" | "none"; +} + +/** The start of the name of each Box gateway target that calls a gateway of the project. */ +const PROJECT_GATEWAY_TARGET_PREFIX = "gateway-"; + +/** + * The gateways of `spec` that `runtime` calls through its Box gateway: each gateway without + * `boundRuntime`, as the CDK library binds it to a runtime without a box. A `PRIVATE_VPC` runtime + * gets none, and a `CUSTOM_JWT` gateway gets a warning, because the Box gateway cannot get its + * token. + */ +export function projectGatewaysOf( + spec: ProjectSpec, + runtime: Pick, +): { gateways: BoxProjectGateway[]; warnings: string[] } { + const gateways: BoxProjectGateway[] = []; + const warnings: string[] = []; + if (runtime.containment === "PRIVATE_VPC") return { gateways, warnings }; + for (const gateway of spec.agentCoreGateways) { + if (gateway.boundRuntime !== undefined) continue; + if (gateway.authorizerType === "CUSTOM_JWT") { + warnings.push( + `The gateway '${gateway.name}' takes CUSTOM_JWT tokens, and the Box gateway of runtime ` + + `'${runtime.name}' signs only with its IAM role, so the boxed agent cannot call ` + + `'${gateway.name}' on AgentCore Runtime. Set its authorizerType to AWS_IAM to let the ` + + "agent call it.", + ); + continue; + } + gateways.push({ + name: gateway.name, + target: targetNameFor(`${PROJECT_GATEWAY_TARGET_PREFIX}${gateway.name}`)!, + variablePrefix: gatewayDiscoveryPrefix(gateway), + auth: gateway.authorizerType === "AWS_IAM" ? "iam" : "none", + }); + } + return { gateways, warnings }; +} + +/** + * The Box gateway target that calls `gateway`, signed for AgentCore in `region` for an `AWS_IAM` + * gateway. The CDK library sets its endpoint and grants the Box gateway's role `InvokeGateway`. + */ +export function projectGatewayTargetFor( + gateway: BoxProjectGateway, + region: string, +): AgentCoreGatewayTarget { + return { + name: gateway.target, + targetType: "passthrough", + passthrough: { gateway: gateway.name, protocolType: "CUSTOM" }, + ...(gateway.auth === "iam" && { + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region }, + }), + }; +} + +/** The `@box/agentcore` inputs that carry the URL and the host of `gateway` on the Runtime. */ +export function projectGatewayInputs(gateway: Pick): { + readonly url: string; + readonly host: string; +} { + return { url: `gateways.${gateway.name}.url`, host: `gateways.${gateway.name}.host` }; +} diff --git a/src/core/project/boxNetworkWriters.test.ts b/src/core/project/boxNetworkWriters.test.ts index c1d957ba7..e502706d0 100644 --- a/src/core/project/boxNetworkWriters.test.ts +++ b/src/core/project/boxNetworkWriters.test.ts @@ -238,6 +238,73 @@ describe("gatewayTargetsWriter", () => { }); }); +describe("gatewayTargetsWriter for the gateways of the project", () => { + const TOOLS = { + name: "tools", + target: "egress-gateway-tools", + variablePrefix: "AGENTCORE_GATEWAY_TOOLS", + auth: "iam", + } as const; + const OPEN = { + name: "open", + target: "egress-gateway-open", + variablePrefix: "AGENTCORE_GATEWAY_OPEN", + auth: "none", + } as const; + const toolsTarget: AgentCoreGatewayTarget = { + name: "egress-gateway-tools", + targetType: "passthrough", + passthrough: { gateway: "tools", protocolType: "CUSTOM" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + }; + + test("adds a target that names each gateway, signed with the role only for an AWS_IAM gateway", () => { + const edits = run([gatewayTargetsWriter], [network({ projectGateways: [TOOLS, OPEN] })]); + + expect(edits.spec.agentCoreGateways[0]!.targets).toEqual([ + MINE, + toolsTarget, + { + name: "egress-gateway-open", + targetType: "passthrough", + passthrough: { gateway: "open", protocolType: "CUSTOM" }, + }, + ]); + expect(edits.messages).toEqual([ + "adding gateway target 'egress-gateway-tools' to 'agent-box-egress', for the boxed agent's calls to the gateway 'tools'", + "adding gateway target 'egress-gateway-open' to 'agent-box-egress', for the boxed agent's calls to the gateway 'open'", + ]); + }); + + test("rewrites the target for the build region in place, and changes nothing the next time", () => { + const stale = { + ...toolsTarget, + outboundAuth: { ...toolsTarget.outboundAuth!, region: "us-east-1" }, + }; + const edits = run( + [gatewayTargetsWriter], + [network({ projectGateways: [TOOLS] })], + spec([stale, MINE]), + ); + + expect(edits.spec.agentCoreGateways[0]!.targets).toEqual([toolsTarget, MINE]); + expect(edits.messages).toEqual([ + "updating gateway target 'egress-gateway-tools' of 'agent-box-egress' for the gateway 'tools'", + ]); + const again = run([gatewayTargetsWriter], [network({ projectGateways: [TOOLS] })], edits.spec); + expect(again.specChanged).toBe(false); + }); + + test("removes the target of a gateway that the agent no longer calls", () => { + const edits = run([gatewayTargetsWriter], [network()], spec([toolsTarget, MINE])); + + expect(targetNames(edits.spec)).toEqual(["mine"]); + expect(edits.messages).toEqual([ + "removing gateway target 'egress-gateway-tools' from 'agent-box-egress': the boxed agent no longer calls the gateway 'tools'", + ]); + }); +}); + describe("credentialsWriter", () => { test("declares each credential once and seeds its key from the box variable", () => { const envRoutes = [{ route: "github", variable: "GITHUB_TOKEN" }]; @@ -501,6 +568,26 @@ describe("runtimeProfileWriter", () => { ); }); + test("stages the inputs of each gateway that the agent calls in the @box/agentcore pack", () => { + const writer = runtimeProfileWriter([ + { runtime: "agent", dist: "app/agent/.box-dist", kind: "container" }, + ]); + const tools = { + name: "tools", + target: "egress-gateway-tools", + variablePrefix: "AGENTCORE_GATEWAY_TOOLS", + auth: "iam", + } as const; + + const { files } = run([writer], [network({ projectGateways: [tools] })]); + + const pack = files.find(({ path }) => path.endsWith(AGENTCORE_PACK_PATH)); + expect(pack && "text" in pack && pack.text).toContain( + "[inputs.gateways.tools.host]\ndescription = \"The deployed 'tools' gateway host.\"\n" + + 'from = "env:AGENTCORE_GATEWAY_TOOLS_HOST"\n', + ); + }); + test("stages only the @box/agentcore pack for a container", () => { const writer = runtimeProfileWriter([ { runtime: "agent", dist: "app/agent/.box-dist", kind: "container" }, diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 36764b374..2d92b92c2 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -19,6 +19,7 @@ import { type BoxNetwork, type BoxNetworkHost, } from "./boxNetwork"; +import { projectGatewayTargetFor } from "./boxNetwork/projectGateways"; import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, @@ -242,11 +243,11 @@ export const gatewayTargetsWriter: BoxNetworkWriter = { }; /** - * Sets the build-owned targets of the network's Box gateway: a managed target that a host takes is - * rewritten in place, every other managed target goes, a host whose managed target the gateway - * lacks gets one at the end, and every target build does not manage stays. A host whose target - * sends an API key credential that agentcore.json does not declare gets no target. Returns the - * step messages. + * Sets the build-owned targets of the network's Box gateway: a managed target that a host or a + * gateway of the project takes is rewritten in place, every other managed target goes, a host or a + * gateway whose managed target the gateway lacks gets one at the end, and every target build does + * not manage stays. A host whose target sends an API key credential that agentcore.json does not + * declare gets no target. Returns the step messages. */ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { const gateway = boxGatewayOf(spec, network.runtime); @@ -262,18 +263,35 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { const messages: string[] = []; const targets: AgentCoreGatewayTarget[] = []; const gatewayName = `'${gateway.name}'`; + const reached = network.projectGateways ?? []; for (const target of existing) { if (!isManagedTarget(target)) { targets.push(target); continue; } + const called = reached.find((candidate) => candidate.target === target.name); + if (called) { + const written = projectGatewayTargetFor(called, network.region); + if (!isDeepStrictEqual(written, target)) { + messages.push( + `updating gateway target '${target.name}' of ${gatewayName} for the gateway ` + + `'${called.name}'`, + ); + } + targets.push(written); + continue; + } const host = sent.find((candidate) => candidate.target === target.name); if (!host) { if (unsent.some((candidate) => candidate.target === target.name)) continue; - const at = target.passthrough && parseEndpoint(target.passthrough.endpoint); + const named = target.passthrough?.gateway; + const at = target.passthrough?.endpoint && parseEndpoint(target.passthrough.endpoint); messages.push( - `removing gateway target '${target.name}' from ${gatewayName}: the Box profile no ` + - `longer allows ${at ? hostKey(at.host, at.port) : "its host"}`, + named !== undefined + ? `removing gateway target '${target.name}' from ${gatewayName}: the boxed agent no ` + + `longer calls the gateway '${named}'` + : `removing gateway target '${target.name}' from ${gatewayName}: the Box profile no ` + + `longer allows ${at ? hostKey(at.host, at.port) : "its host"}`, ); continue; } @@ -290,6 +308,14 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { targets.push(gatewayTargetFor(host)); messages.push(`adding gateway target '${host.target}' to ${gatewayName} for ${host.authority}`); } + for (const called of reached) { + if (existing.some(({ name }) => name === called.target)) continue; + targets.push(projectGatewayTargetFor(called, network.region)); + messages.push( + `adding gateway target '${called.target}' to ${gatewayName}, for the boxed agent's calls ` + + `to the gateway '${called.name}'`, + ); + } for (const host of unsent) { const auth = undeclaredKey(spec, host)!; const removed = existing.some(({ name }) => name === host.target); @@ -442,7 +468,10 @@ export function runtimeProfileWriter(staged: readonly StagedRuntime[]): BoxNetwo const entry = spec.runtimes.find(({ name }) => name === runtime) ?? { name: runtime }; return [ { path: `${dist}/profile.toml`, text: runtimeProfileText(runtime, network, spec) }, - { path: `${dist}/${AGENTCORE_PACK_PATH}`, text: renderAgentCorePack(spec, entry) }, + { + path: `${dist}/${AGENTCORE_PACK_PATH}`, + text: renderAgentCorePack(spec, entry, network?.projectGateways), + }, ...(kind === "codezip" ? [ { diff --git a/src/core/project/runtimeProfile/rules/gateway.test.ts b/src/core/project/runtimeProfile/rules/gateway.test.ts index 4b708650d..005986b37 100644 --- a/src/core/project/runtimeProfile/rules/gateway.test.ts +++ b/src/core/project/runtimeProfile/rules/gateway.test.ts @@ -715,3 +715,57 @@ describe("the gateway rule and the Runtime renderer it replaced", () => { expect(old.mcp).toBeUndefined(); }); }); + +describe("the gateway rule for a gateway of the project", () => { + const TOOLS = { + name: "tools", + target: "egress-gateway-tools", + variablePrefix: "AGENTCORE_GATEWAY_TOOLS", + auth: "iam", + } as const; + const PROFILE_TEXT = 'packs = ["@box/base"]\n\n[profile]\nname = "demo"\n'; + const withGateways = (text: string) => + apply(parse(text) as TomlTable, { ...contextOf(text, []), projectGateways: [TOOLS] }); + + test("adds an HTTP server under the gateway's name, to its host on the Runtime, through its target", () => { + const result = withGateways(PROFILE_TEXT); + + expect(result.problems).toEqual([]); + expect(serializeRuntimeProfile({ mcp: result.table.mcp as TomlTable })).toBe( + "[mcp.tools]\n" + + 'type = "http"\n' + + 'destinations = [ "${{ inputs.gateways.tools.host }}" ]\n\n' + + "[[mcp.tools.backends]]\n" + + 'url = "${{ inputs.gateway.url }}/egress-gateway-tools"\n\n' + + "[mcp.tools.backends.auth]\n" + + 'ref = "aws://"\n\n' + + "[mcp.tools.backends.auth.aws]\n" + + 'service = "bedrock-agentcore"\n' + + 'region = "${{ inputs.aws.region }}"\n\n', + ); + }); + + test("adds no server to the local profile's own tables when the project has no gateway", () => { + const result = apply(parse(PROFILE_TEXT) as TomlTable, contextOf(PROFILE_TEXT, [])); + + expect(result.table.mcp).toBeUndefined(); + }); + + test("stops for a server of the local profile with the gateway's name", () => { + const text = `${PROFILE_TEXT}\n[mcp.tools]\ncommand = ["/usr/bin/tools"]\n`; + + const result = withGateways(text); + + expect(result.problems).toEqual([ + { + code: "RUNTIME_GATEWAY_SERVER_NAME_TAKEN", + key: ["mcp", "tools"], + reason: + "[mcp.tools] has the name of the gateway 'tools' of this project. On AgentCore " + + "Runtime, build adds the server [mcp.tools] so the agent can call that gateway. Rename " + + "your server.", + place: `${PROFILE}:6:1`, + }, + ]); + }); +}); diff --git a/src/core/project/runtimeProfile/rules/gateway.ts b/src/core/project/runtimeProfile/rules/gateway.ts index e4ef203c8..c3e7bcc19 100644 --- a/src/core/project/runtimeProfile/rules/gateway.ts +++ b/src/core/project/runtimeProfile/rules/gateway.ts @@ -13,6 +13,7 @@ * | a target that no entry of the profile names | `[egress.]`, or the `[mcp]` server it serves | * | an entry whose hosts the policy denies | removed; the Box network model warns for it | * | an entry with no host in the Box network model | removed; the model fails the entry, and build stops | + * | a gateway of the project that the agent calls (projectGatewaysOf) | `[mcp.]` to the host in `_HOST`, a backend to its target | * * A stdio `[mcp.]` stays as it is: the `refusals` and `paths` rules own it. * @@ -24,6 +25,7 @@ import { InputValidationError } from "../../../../errors/errors"; import type { AgentCoreGatewayTarget } from "../../../../projectSchemas/gateway"; import type { BoxHostSource, BoxNetworkHost } from "../../boxNetwork"; import { BOX_EGRESS_TARGET_PREFIX } from "../../boxNetwork/egress"; +import { projectGatewayInputs, type BoxProjectGateway } from "../../boxNetwork/projectGateways"; import { gatewayTargetFor } from "../../boxNetwork/projectSpec"; import { BOX_BEDROCK_API_KEY_ROUTE, @@ -36,6 +38,7 @@ import { RUNTIME_INPUTS, type RuleResult, type RuntimeProfileContext, + type RuntimeProfileProblem, type TomlTable, } from "../types"; @@ -96,12 +99,42 @@ export function apply(table: Readonly, context: RuntimeProfileContext } } + const problems: RuntimeProfileProblem[] = []; + for (const gateway of context.projectGateways ?? []) { + if (gateway.name in mcp) { + problems.push({ + code: "RUNTIME_GATEWAY_SERVER_NAME_TAKEN", + key: ["mcp", gateway.name], + reason: + `[mcp.${gateway.name}] has the name of the gateway '${gateway.name}' of this project. ` + + `On AgentCore Runtime, build adds the server [mcp.${gateway.name}] so the agent can ` + + "call that gateway. Rename your server.", + place: context.placeOf(["mcp", gateway.name]), + }); + continue; + } + mcp[gateway.name] = projectGatewayServer(gateway); + } + // Each table keeps its place when the profile has it, and comes last when it does not. An empty // table goes. const result: TomlTable = { ...table, egress, mcp }; if (Object.keys(egress).length === 0) delete result.egress; if (Object.keys(mcp).length === 0) delete result.mcp; - return { table: result, problems: [], warnings: [] }; + return { table: result, problems, warnings: [] }; +} + +/** + * The HTTP `[mcp.]` server for a gateway of the project: the host the CDK library sets in + * `_HOST`, through the Box gateway target that calls the gateway. Box permits each tool of + * the server, and a forbid rule of the policy still applies. + */ +function projectGatewayServer(gateway: BoxProjectGateway): TomlTable { + return { + type: "http", + destinations: [`\${{ inputs.${projectGatewayInputs(gateway).host} }}`], + backends: [gatewayBackend({ target: gateway.target })], + }; } /** @@ -130,10 +163,11 @@ function gatewayRoutes(context: RuntimeProfileContext): GatewayRoute[] { if (!targets.some(({ name }) => name === host.target)) targets.push(gatewayTargetFor(host)); } + // A target that names a gateway of the project has no host here: that gateway's server does. const passthrough = targets.filter( - (target) => target.targetType === "passthrough" && target.passthrough, + (target) => target.targetType === "passthrough" && target.passthrough?.endpoint !== undefined, ); - const hostOf = (target: AgentCoreGatewayTarget) => new URL(target.passthrough!.endpoint).host; + const hostOf = (target: AgentCoreGatewayTarget) => new URL(target.passthrough!.endpoint!).host; const byHost = new Map(); for (const target of passthrough) { const other = byHost.get(hostOf(target)); @@ -241,7 +275,7 @@ function mcpServer(entry: Readonly, route: GatewayRoute, server: McpS * The backend of a route: the route's gateway target, signed for the gateway in the Runtime's own * region, which box reads from the `aws.region` input of the agentcore pack. */ -function gatewayBackend(route: GatewayRoute): TomlTable { +function gatewayBackend(route: Pick): TomlTable { return { url: `${RUNTIME_INPUTS.gatewayUrl}/${route.target}`, auth: { diff --git a/src/core/project/runtimeProfile/types.ts b/src/core/project/runtimeProfile/types.ts index 31901f824..8c24da20e 100644 --- a/src/core/project/runtimeProfile/types.ts +++ b/src/core/project/runtimeProfile/types.ts @@ -7,6 +7,7 @@ import type { AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; import type { ProjectSpec } from "../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; import type { BoxNetworkHost, CloudWatchTelemetry } from "../boxNetwork"; +import type { BoxProjectGateway } from "../boxNetwork/projectGateways"; /** A TOML table as smol-toml parses it: a key holds a string, a number, a boolean, a list, or a table. */ export type TomlTable = Record; @@ -75,6 +76,8 @@ export interface RuntimeProfileContext { readonly gateway: { readonly name: string; readonly targets: readonly AgentCoreGatewayTarget[] }; /** The hosts of the Box network model, each with the gateway target it gets. */ readonly hosts: readonly BoxNetworkHost[]; + /** The gateways of the project that the agent calls through the Box gateway; absent means none. */ + readonly projectGateways?: readonly BoxProjectGateway[]; /** The CloudWatch targets of the local profile, with the deploy region set. */ readonly telemetry: readonly CloudWatchTelemetry[]; readonly paths: RuntimePaths; @@ -101,6 +104,8 @@ export const RUNTIME_PROFILE_PROBLEM_CODES = [ "RUNTIME_TELEMETRY_NOT_CLOUDWATCH", /** A CloudWatch telemetry target that box refuses when a run starts. */ "RUNTIME_TELEMETRY_REFUSED", + /** An `[mcp]` server with the name of a gateway of the project, which build adds on the Runtime. */ + "RUNTIME_GATEWAY_SERVER_NAME_TAKEN", ] as const; export type RuntimeProfileProblemCode = (typeof RUNTIME_PROFILE_PROBLEM_CODES)[number]; diff --git a/src/core/project/templates/boxProfile.test.ts b/src/core/project/templates/boxProfile.test.ts index 30f249f9b..ab966e19d 100644 --- a/src/core/project/templates/boxProfile.test.ts +++ b/src/core/project/templates/boxProfile.test.ts @@ -478,6 +478,62 @@ describe("renderAgentCorePack", () => { ) as Record; } + describe("for a gateway of the project that the agent calls", () => { + const TOOLS = { + name: "tools", + target: "egress-gateway-tools", + variablePrefix: "AGENTCORE_GATEWAY_TOOLS", + auth: "iam", + } as const; + const withTools = (memories: { name: string }[] = []) => + parse( + renderAgentCorePack( + { name: "V3Demo", memories } as unknown as ProjectSpec, + { name: "agent", instrumentation: { enableOtel: false } }, + [TOOLS], + ), + ) as Record; + const HOST = + "v3demo-default-tools-abcdefghij.gateway.bedrock-agentcore.us-west-2.amazonaws.com"; + + test("reads its host and its URL from the variables the CDK library sets for it", () => { + const { inputs } = withTools(); + expect(inputs.gateways.tools.host.from).toBe("env:AGENTCORE_GATEWAY_TOOLS_HOST"); + expect(inputs.gateways.tools.url.from).toBe("env:AGENTCORE_GATEWAY_TOOLS_URL"); + }); + + test("gives the agent the URL under the name a runtime without a box reads, beside the memory IDs", () => { + expect(withTools([{ name: "notes" }]).agent.env).toEqual({ + MEMORY_NOTES_ID: "${{ inputs.memory.notes.id }}", + AGENTCORE_GATEWAY_TOOLS_URL: "${{ inputs.gateways.tools.url }}", + }); + }); + + test.each([ + [HOST, true], + [`https://${HOST}`, false], + [`${HOST}/mcp`, false], + ["evil.example.com", false], + ["x.gateway.bedrock-agentcore.us-west-2.amazonaws.com.evil.example.com", false], + ])("the host pattern takes %s: %p", (host, matches) => { + expect(new RegExp(`^${withTools().inputs.gateways.tools.host.pattern}$`).test(host)).toBe( + matches, + ); + }); + + test.each([ + [`https://${HOST}/mcp`, true], + [`https://${HOST}`, true], + [`http://${HOST}/mcp`, false], + [`https://${HOST}/mcp/x`, false], + ["https://evil.example.com/mcp", false], + ])("the URL pattern takes %s: %p", (url, matches) => { + expect(new RegExp(`^${withTools().inputs.gateways.tools.url.pattern}$`).test(url)).toBe( + matches, + ); + }); + }); + test("names itself @box/agentcore and ships as a support pack", () => { const toml = pack([]); expect(toml.pack).toEqual({ name: "@box/agentcore", version: 1, kind: "support" }); diff --git a/src/core/project/templates/boxProfile.ts b/src/core/project/templates/boxProfile.ts index a053d105e..d360115b1 100644 --- a/src/core/project/templates/boxProfile.ts +++ b/src/core/project/templates/boxProfile.ts @@ -8,6 +8,7 @@ import { DEFAULT_MODEL_IDS, type ProjectRuntime } from "../../../projectSchemas/ import { DEV_PORTS } from "../../dev/port"; import { PYTHON_ENV } from "../../dev/codezip"; import { modelProviderCredentialName } from "./runtime"; +import { projectGatewayInputs, type BoxProjectGateway } from "../boxNetwork/projectGateways"; /** Where a box template's venv gets its uv-managed Python, relative to the home folder. */ const UV_PYTHON_HOME_DIR = ".local/share/uv/python"; @@ -87,6 +88,15 @@ export const AGENTCORE_CODEZIP_PACK_PATH = "resources/packs/agentcore-codezip/pa const GATEWAY_URL_PATTERN = "https://[a-z0-9][-a-z0-9.]*[.]amazonaws[.]com(/[A-Za-z0-9_-][A-Za-z0-9_.-]*)*"; +/** + * The host of a gateway of the project, which the CDK library sets in `_HOST`, and that + * gateway's URL in `_URL`, with `/mcp` for an MCP gateway. Each input that reaches a route's + * destinations needs a pattern. + */ +const PROJECT_GATEWAY_HOST_PATTERN = + "[a-z0-9][-a-z0-9]*[.]gateway[.]bedrock-agentcore[.][a-z0-9-]+[.]amazonaws[.]com"; +const PROJECT_GATEWAY_URL_PATTERN = `https://${PROJECT_GATEWAY_HOST_PATTERN}(/mcp)?`; + /** As @box/bedrock bounds `bedrock.region`. */ const AWS_REGION_PATTERN = "[a-z]{2}(-[a-z]+)?-(central|north|south|east|west)+-[0-9]+"; @@ -729,12 +739,16 @@ const RUNTIME_RESOURCE_ATTRIBUTES_ENV = "OTEL_RESOURCE_ATTRIBUTES"; * {@link RUNTIME_LOGS_HEADERS_ENV}, for the default telemetry target of the Runtime profile. One * input per project memory carries its ID into the agent's environment. With OTEL on for `runtime`, * the agent gets {@link AGENT_OTEL_ENV} and the Runtime's resource attributes, so the console links - * its spans to the runtime; the profile merges after the pack, so a value of the user wins. box - * finds the pack beside its binary at {@link AGENTCORE_PACK_PATH}; build and deploy stage it there. + * its spans to the runtime; the profile merges after the pack, so a value of the user wins. Each + * gateway of the project that the agent calls through the Box gateway gets two inputs: its host, + * for the destination of its `[mcp]` server, and its URL, which the agent gets under the variable + * name that a runtime without a box reads. box finds the pack beside its binary at + * {@link AGENTCORE_PACK_PATH}; build and deploy stage it there. */ export function renderAgentCorePack( spec: ProjectSpec, runtime: Pick, + gateways: readonly BoxProjectGateway[] = [], ): string { const otel = otelOn(runtime); const memories = spec.memories ?? []; @@ -767,7 +781,30 @@ description = "The OpenTelemetry resource attributes of the runtime." from = ${str(`env:${RUNTIME_RESOURCE_ATTRIBUTES_ENV}`)} default = ${str(`service.name=${runtime.name}`)}` : ""; - const env = [memoryEnv, otelEnv].filter((lines) => lines !== "").join("\n"); + const gatewayInputs = gateways + .map((gateway) => { + const inputs = projectGatewayInputs(gateway); + return ` + +# The '${gateway.name}' gateway of the project, which the agent calls through the Box gateway. +[inputs.${inputs.url}] +description = ${str(`The deployed '${gateway.name}' gateway URL.`)} +from = ${str(`env:${gateway.variablePrefix}_URL`)} +pattern = ${str(PROJECT_GATEWAY_URL_PATTERN)} + +[inputs.${inputs.host}] +description = ${str(`The deployed '${gateway.name}' gateway host.`)} +from = ${str(`env:${gateway.variablePrefix}_HOST`)} +pattern = ${str(PROJECT_GATEWAY_HOST_PATTERN)}`; + }) + .join(""); + const gatewayEnv = gateways + .map( + (gateway) => + `${gateway.variablePrefix}_URL = ${str(`\${{ inputs.${projectGatewayInputs(gateway).url} }}`)}`, + ) + .join("\n"); + const env = [memoryEnv, otelEnv, gatewayEnv].filter((lines) => lines !== "").join("\n"); const agentEnv = env ? `\n[agent.env]\n${env}\n` : ""; return `# The deployed AgentCore resources of '${spec.name}', read from the environment the Runtime sets. # Written by agentcore build and deploy. The runtime profile imports it as ${AGENTCORE_PACK_NAME}. @@ -806,7 +843,7 @@ key = "x-aws-log-stream" [inputs.runtime.url] description = "The URL an A2A agent card advertises on the Runtime." from = "env:AGENTCORE_RUNTIME_URL" -default = "http://localhost:9000/"${memoryInputs}${otelInput} +default = "http://localhost:9000/"${memoryInputs}${otelInput}${gatewayInputs} ${agentEnv}`; } diff --git a/src/projectSchemas/gateway.ts b/src/projectSchemas/gateway.ts index b456a9c3d..dcac12828 100644 --- a/src/projectSchemas/gateway.ts +++ b/src/projectSchemas/gateway.ts @@ -278,11 +278,17 @@ export const PassthroughConfigSchema = z endpoint: z .string() .min(1) - .regex(/^https:\/\/[a-zA-Z0-9\-.]+(:[0-9]{1,5})?(\/.*)?$/, "Must be a valid HTTPS URL"), + .regex(/^https:\/\/[a-zA-Z0-9\-.]+(:[0-9]{1,5})?(\/.*)?$/, "Must be a valid HTTPS URL") + .optional(), + /** A gateway of this project, in place of `endpoint`: the CDK library calls its URL. */ + gateway: GatewayNameSchema.optional(), protocolType: PassthroughProtocolTypeSchema.default("CUSTOM"), stickinessConfiguration: StickinessConfigSchema.optional(), }) - .strict(); + .strict() + .refine((config) => (config.endpoint === undefined) !== (config.gateway === undefined), { + message: "A passthrough configuration needs exactly one of endpoint and gateway.", + }); export type PassthroughConfig = z.infer; const TARGET_CONFIGURATION_FIELDS = [ "toolDefinitions", diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index 8e7d4e0f6..b1910166e 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -620,6 +620,60 @@ describe("Box project runtimes on AgentCore Runtime V2", () => { }); }); +describe("a passthrough target that names a gateway", () => { + const target = (passthrough: Record) => ({ + name: "egress-gateway-tools", + targetType: "passthrough", + passthrough: { protocolType: "CUSTOM", ...passthrough }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + }); + const messages = (gateways: unknown[]) => { + const result = ProjectSpecSchema.safeParse({ + ...minimalProject, + runtimes: [runtime], + agentCoreGateways: gateways, + }); + return result.success ? [] : result.error.issues.map(({ message }) => message); + }; + const front = (passthrough: Record, fields: Record = {}) => ({ + name: "front", + authorizerType: "AWS_IAM", + protocolType: "None", + targets: [target(passthrough)], + ...fields, + }); + const TOOLS = { name: "tools", authorizerType: "AWS_IAM", targets: [] }; + + test("accepts a gateway of the project without boundRuntime", () => { + expect(messages([front({ gateway: "tools" }), TOOLS])).toEqual([]); + }); + + test.each([ + [ + "no gateway of that name", + [front({ gateway: "gone" })], + 'names the gateway "gone" in passthrough.gateway, but the project has no gateway of that name', + ], + ["its own gateway", [front({ gateway: "front" })], "which is its own gateway"], + [ + "a gateway bound to a runtime", + [front({ gateway: "tools" }), { ...TOOLS, boundRuntime: "agent" }], + 'which is bound to the runtime "agent"', + ], + ])("refuses %s", (_, gateways, message) => { + expect(messages(gateways)).toContainEqual(expect.stringContaining(message)); + }); + + test.each([ + ["both endpoint and gateway", { endpoint: "https://api.example.com", gateway: "tools" }], + ["neither endpoint nor gateway", {}], + ])("refuses %s", (_, passthrough) => { + expect(messages([front(passthrough), TOOLS])).toContain( + "A passthrough configuration needs exactly one of endpoint and gateway.", + ); + }); +}); + describe("Box project gateways", () => { const runtimeNamed = (name: string) => ({ ...runtime, diff --git a/src/projectSchemas/project.ts b/src/projectSchemas/project.ts index 4a078d3f6..dd565c63e 100644 --- a/src/projectSchemas/project.ts +++ b/src/projectSchemas/project.ts @@ -181,6 +181,29 @@ export const ProjectSpecSchema = z }); } } + // A passthrough target that names a gateway calls a gateway of this project. A gateway bound to + // a runtime belongs to that runtime, so no target of another gateway calls it. + for (const gateway of spec.agentCoreGateways) { + for (const target of gateway.targets) { + const reached = target.passthrough?.gateway; + if (reached === undefined) continue; + const named = spec.agentCoreGateways.find((other) => other.name === reached); + const problem = + named === undefined + ? "but the project has no gateway of that name" + : named === gateway + ? "which is its own gateway" + : named.boundRuntime !== undefined + ? `which is bound to the runtime "${named.boundRuntime}"` + : undefined; + if (problem === undefined) continue; + ctx.addIssue({ + code: "custom", + message: `Target "${target.name}" of gateway "${gateway.name}" names the gateway "${reached}" in passthrough.gateway, ${problem}. Name a gateway of this project without boundRuntime`, + path: ["agentCoreGateways"], + }); + } + } // A Box project keeps one Box gateway for each runtime. Without it, a deploy would delete the // deployed gateway, so every command stops here and prints the entry to add back. if (isBoxProject(spec)) { From 6c7a1d6d45f503205dbb639f10913a575f217cd2 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 16:43:06 -0800 Subject: [PATCH 02/22] fix(box): Accept a China host in the gateway host and URL inputs Review feedback: the `_HOST` and `_URL` patterns of `@box/agentcore` stopped at `amazonaws.com`, and the gateway host of `AWS_ENDPOINTS` also accepts `amazonaws.com.cn`. Thus box refused the two inputs in a China region. Each pattern now accepts `amazonaws.com.cn`. Test: "the host pattern takes ... amazonaws.com.cn: true" and "the URL pattern takes https://....amazonaws.com.cn/mcp: true" in `boxProfile.test.ts` fail before this change. --- src/core/project/templates/boxProfile.test.ts | 6 ++++++ src/core/project/templates/boxProfile.ts | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/core/project/templates/boxProfile.test.ts b/src/core/project/templates/boxProfile.test.ts index ab966e19d..54c91a651 100644 --- a/src/core/project/templates/boxProfile.test.ts +++ b/src/core/project/templates/boxProfile.test.ts @@ -509,8 +509,13 @@ describe("renderAgentCorePack", () => { }); }); + const CHINA_HOST = + "v3demo-default-tools-abcdefghij.gateway.bedrock-agentcore.cn-north-1.amazonaws.com.cn"; + test.each([ [HOST, true], + [CHINA_HOST, true], + [`${HOST}.cn.evil.example.com`, false], [`https://${HOST}`, false], [`${HOST}/mcp`, false], ["evil.example.com", false], @@ -524,6 +529,7 @@ describe("renderAgentCorePack", () => { test.each([ [`https://${HOST}/mcp`, true], [`https://${HOST}`, true], + [`https://${CHINA_HOST}/mcp`, true], [`http://${HOST}/mcp`, false], [`https://${HOST}/mcp/x`, false], ["https://evil.example.com/mcp", false], diff --git a/src/core/project/templates/boxProfile.ts b/src/core/project/templates/boxProfile.ts index d360115b1..50cd627be 100644 --- a/src/core/project/templates/boxProfile.ts +++ b/src/core/project/templates/boxProfile.ts @@ -90,11 +90,11 @@ const GATEWAY_URL_PATTERN = /** * The host of a gateway of the project, which the CDK library sets in `_HOST`, and that - * gateway's URL in `_URL`, with `/mcp` for an MCP gateway. Each input that reaches a route's - * destinations needs a pattern. + * gateway's URL in `_URL`, with `/mcp` for an MCP gateway, in the `aws` and `aws-cn` + * partitions. Each input that reaches a route's destinations needs a pattern. */ const PROJECT_GATEWAY_HOST_PATTERN = - "[a-z0-9][-a-z0-9]*[.]gateway[.]bedrock-agentcore[.][a-z0-9-]+[.]amazonaws[.]com"; + "[a-z0-9][-a-z0-9]*[.]gateway[.]bedrock-agentcore[.][a-z0-9-]+[.]amazonaws[.]com([.]cn)?"; const PROJECT_GATEWAY_URL_PATTERN = `https://${PROJECT_GATEWAY_HOST_PATTERN}(/mcp)?`; /** As @box/bedrock bounds `bedrock.region`. */ From ea30c9aa9b43d983359283e27f0201694b55bd4e Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 16:43:57 -0800 Subject: [PATCH 03/22] test(box): Resolve a gateway name with "-" and upper case with the box on PATH Review question: a gateway name can hold "-" and upper case, so the Runtime profile has `${{ inputs.gateways.My-Tools-GW.host }}` and `[mcp.My-Tools-GW]`. The test "the box on PATH" now also uses the gateway `My-Tools-GW`. box 0.1.11-preview.10 resolves the input, the server, the backend, the agent variable, and the permit `context.input.server == "My-Tools-GW"`. No code changes, because box accepts these names. This test does not fail before this commit. It pins the behaviour, and it skips when no box is on PATH. --- .../boxNetwork/projectGateways.test.ts | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/core/project/boxNetwork/projectGateways.test.ts b/src/core/project/boxNetwork/projectGateways.test.ts index e6c703dbf..11e0f96cb 100644 --- a/src/core/project/boxNetwork/projectGateways.test.ts +++ b/src/core/project/boxNetwork/projectGateways.test.ts @@ -52,10 +52,21 @@ const HOST = "demo-default-tools-abcdefghij.gateway.bedrock-agentcore.us-west-2. const BOX_GATEWAY_URL = "https://demo-default-agent-box-egress-klmnopqrst.gateway.bedrock-agentcore.us-west-2.amazonaws.com"; +/** A gateway named `name`, with the variable prefix and the target that build gives it. */ +const gatewayNamed = (name: string, prefix: string): BoxProjectGateway => ({ + name, + target: `egress-gateway-${name}`, + variablePrefix: prefix, + auth: "iam", +}); + describe("the box on PATH", () => { - test.skipIf(box === undefined)( - "resolves the server and the agent variable of a gateway from the variables the CDK library sets (skipped without a box with --format json --full on PATH)", - async () => { + // A gateway name can hold "-" and upper case, which reach an input name and a server name. + test + .skipIf(box === undefined) + .each([[TOOLS], [gatewayNamed("My-Tools-GW", "AGENTCORE_GATEWAY_MY_TOOLS_GW")]])( + "resolves the server and the agent variable of the gateway %o from the variables the CDK library sets (skipped without a box with --format json --full on PATH)", + async (gateway) => { const root = await mkdtemp(join(tmpdir(), "box-project-gateway-")); directories.push(root); const resources = join(root, "resources"); @@ -63,7 +74,12 @@ describe("the box on PATH", () => { const spec = { name: "demo", memories: [] } as unknown as ProjectSpec; const pack = join(root, AGENTCORE_PACK_PATH); await mkdir(dirname(pack), { recursive: true }); - await writeFile(pack, renderAgentCorePack(spec, [TOOLS])); + await writeFile( + pack, + renderAgentCorePack(spec, { name: "agent", instrumentation: { enableOtel: false } }, [ + gateway, + ]), + ); const local = 'packs = ["@box/base", "@box/agentcore"]\n\n[profile]\nname = "demo"\n\n' + '[agent]\ncommand = ["/bin/sh"]\n'; @@ -74,7 +90,7 @@ describe("the box on PATH", () => { region: "us-west-2", gateway: { name: "agent-box-egress", targets: [] }, hosts: [], - projectGateways: [TOOLS], + projectGateways: [gateway], telemetry: [], places: profileKeyPlaces(local, ".box/profile.toml"), }); @@ -96,8 +112,8 @@ describe("the box on PATH", () => { BOX_RESOURCES: resources, AWS_REGION: "us-west-2", AGENTCORE_GATEWAY_BOX_URL: BOX_GATEWAY_URL, - AGENTCORE_GATEWAY_TOOLS_URL: `https://${HOST}/mcp`, - AGENTCORE_GATEWAY_TOOLS_HOST: HOST, + [`${gateway.variablePrefix}_URL`]: `https://${HOST}/mcp`, + [`${gateway.variablePrefix}_HOST`]: HOST, }, }, ); @@ -109,11 +125,13 @@ describe("the box on PATH", () => { }; policy: string; }; - expect(shown.box_toml.mcp.tools!.destinations).toEqual([HOST]); - expect(shown.box_toml.mcp.tools!.backends.map(({ url }) => url)).toEqual([ - `${BOX_GATEWAY_URL}/egress-gateway-tools`, + const server = shown.box_toml.mcp[gateway.name]!; + expect(server.destinations).toEqual([HOST]); + expect(server.backends.map(({ url }) => url)).toEqual([ + `${BOX_GATEWAY_URL}/${gateway.target}`, ]); - expect(shown.box_toml.agent.env.AGENTCORE_GATEWAY_TOOLS_URL).toBe(`https://${HOST}/mcp`); + expect(shown.box_toml.agent.env[`${gateway.variablePrefix}_URL`]).toBe(`https://${HOST}/mcp`); + expect(shown.policy).toContain(`context.input.server == "${gateway.name}"`); expect(shown.policy).toContain( `permit (principal, action == Box::Action::"net:connect", resource) when { (context.input.host == "${HOST}" && context.input.port == 443) };`, ); From 67110ba980f8a047d63891f058de2c8a6795d024 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 16:44:49 -0800 Subject: [PATCH 04/22] fix(box): Give each gateway of the project its own Box gateway target name Review feedback: `targetNameFor` changes `--` to `-` and cuts a name at 100 characters. Thus the gateways `a--b` and `a-b`, or two long names with the same start, got the same target name, and the writer added two targets with one name. The target name stays `egress-gateway-` when that name keeps the gateway name whole. When `targetNameFor` changes the name, the target name ends in 8 hex digits of the SHA-256 of the gateway name, and it has at most 100 characters. The name is the same on each build. Test: "is not the same for a--b and a-b" and "is not the same for" two names of 96 characters with the same start, in `projectGateways.test.ts`, fail before this change. --- .../boxNetwork/projectGateways.test.ts | 39 ++++++++++++++++++- .../project/boxNetwork/projectGateways.ts | 25 +++++++++++- 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/src/core/project/boxNetwork/projectGateways.test.ts b/src/core/project/boxNetwork/projectGateways.test.ts index 11e0f96cb..9eb7faf05 100644 --- a/src/core/project/boxNetwork/projectGateways.test.ts +++ b/src/core/project/boxNetwork/projectGateways.test.ts @@ -9,7 +9,11 @@ import { apply } from "../runtimeProfile/rules/gateway"; import { serializeRuntimeProfile } from "../runtimeProfile/serialize"; import type { TomlTable } from "../runtimeProfile/types"; import { AGENTCORE_PACK_PATH, renderAgentCorePack } from "../templates/boxProfile"; -import { projectGatewayTargetFor, type BoxProjectGateway } from "./projectGateways"; +import { + projectGatewaysOf, + projectGatewayTargetFor, + type BoxProjectGateway, +} from "./projectGateways"; const TOOLS: BoxProjectGateway = { name: "tools", @@ -35,6 +39,39 @@ describe("projectGatewayTargetFor", () => { }); }); +describe("the target name of each gateway", () => { + const targetsOf = (...names: string[]) => + projectGatewaysOf( + { + agentCoreGateways: names.map((name) => ({ name, authorizerType: "AWS_IAM", targets: [] })), + } as unknown as ProjectSpec, + { name: "agent" }, + ).gateways.map(({ target }) => target); + + test("is egress-gateway- when the name fits as it is", () => { + expect(targetsOf("tools", "My-Tools-GW")).toEqual([ + "egress-gateway-tools", + "egress-gateway-My-Tools-GW", + ]); + }); + + test.each([ + ["a--b", "a-b"], + ["x".repeat(95) + "1", "x".repeat(95) + "2"], + ])("is not the same for %s and %s", (first, second) => { + const targets = targetsOf(first, second); + expect(new Set(targets).size).toBe(2); + for (const target of targets) { + expect(target.length).toBeLessThanOrEqual(100); + expect(target).toMatch(/^egress-gateway-[A-Za-z0-9]+(-[A-Za-z0-9]+)*$/); + } + }); + + test("is the same on each build", () => { + expect(targetsOf("a--b")).toEqual(targetsOf("a--b")); + }); +}); + const directories: string[] = []; afterEach(async () => { await Promise.all(directories.splice(0).map((d) => rm(d, { recursive: true, force: true }))); diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index 0d8a479ff..9540791b3 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -4,10 +4,11 @@ * AgentCore Runtime, the boxed agent gets the same variable, and box sends each call to the * gateway's host to a Box gateway target that names that gateway (`passthrough.gateway`). */ +import { createHash } from "node:crypto"; import type { AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; import { gatewayDiscoveryPrefix, type ProjectSpec } from "../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; -import { targetNameFor } from "./egress"; +import { BOX_EGRESS_TARGET_PREFIX, targetNameFor } from "./egress"; /** A gateway of the project that a boxed runtime calls through its Box gateway. */ export interface BoxProjectGateway { @@ -24,6 +25,26 @@ export interface BoxProjectGateway { /** The start of the name of each Box gateway target that calls a gateway of the project. */ const PROJECT_GATEWAY_TARGET_PREFIX = "gateway-"; +/** The longest name of a gateway target, as AgentCore takes it. */ +const MAX_TARGET_NAME = 100; + +/** + * The Box gateway target name for the gateway `name`: `egress-gateway-` when that name keeps + * `name` whole. When {@link targetNameFor} changes it, as for `a--b` or a name that is too long, + * the name ends in 8 hex digits of the SHA-256 of `name`, so two gateways never share a target. + */ +function projectGatewayTargetName(name: string): string { + const plain = `${BOX_EGRESS_TARGET_PREFIX}${PROJECT_GATEWAY_TARGET_PREFIX}${name}`; + if (targetNameFor(`${PROJECT_GATEWAY_TARGET_PREFIX}${name}`) === plain) return plain; + const suffix = createHash("sha256").update(name).digest("hex").slice(0, 8); + const room = MAX_TARGET_NAME - BOX_EGRESS_TARGET_PREFIX.length - suffix.length - 1; + const kept = targetNameFor(`${PROJECT_GATEWAY_TARGET_PREFIX}${name}`)! + .slice(BOX_EGRESS_TARGET_PREFIX.length) + .slice(0, room) + .replace(/-+$/, ""); + return `${BOX_EGRESS_TARGET_PREFIX}${kept}-${suffix}`; +} + /** * The gateways of `spec` that `runtime` calls through its Box gateway: each gateway without * `boundRuntime`, as the CDK library binds it to a runtime without a box. A `PRIVATE_VPC` runtime @@ -50,7 +71,7 @@ export function projectGatewaysOf( } gateways.push({ name: gateway.name, - target: targetNameFor(`${PROJECT_GATEWAY_TARGET_PREFIX}${gateway.name}`)!, + target: projectGatewayTargetName(gateway.name), variablePrefix: gatewayDiscoveryPrefix(gateway), auth: gateway.authorizerType === "AWS_IAM" ? "iam" : "none", }); From 6573b8784c92bfe1600a9308b7fff5fdff66deda Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 16:48:05 -0800 Subject: [PATCH 05/22] fix(box): Write a gateway target only when the CDK library of the project accepts it Review feedback (blocking): `@aws/agentcore-cdk` 1.1.0, which `box-integration` pins, has a strict `PassthroughConfigSchema` that requires `endpoint`. It refuses `passthrough.gateway`. Build wrote that target for each gateway without `boundRuntime` of a Box project, so the synth of such a project failed until a new library ships. Build now asks the library of the CDK app, with `node` in `agentcore/cdk`, whether `PassthroughConfigSchema` accepts `{ gateway, protocolType }` (`cdkAcceptsPassthroughGateway`). Thus it reads the same library as synth, and a local build of the library works too. A version number cannot tell this, because aws/agentcore-l3-cdk-constructs has not released the change, and a local build of its `box-integration` branch has the version 1.0.2. Build asks only when a box runtime and a gateway without `boundRuntime` are in the project. When the library refuses the field, is not there, or the check fails, build writes no target, no server, and no pack input. It removes a target that it wrote before, and gives one warning that names the gateways. The manager takes the check in `cdkAcceptsPassthroughGateway`, so tests do not run `node`. Equal warnings of two box runtimes show once. Tests that fail before this change: - `compatibility.test.ts`, "cdkAcceptsPassthroughGateway": true for a library that accepts the field, false for one that requires `endpoint`, and false with no library or no schema. - `network.test.ts`, "gives the agent no gateway when the @aws/agentcore-cdk of the project refuses passthrough.gateway, and warns once". - `manager.boxNetwork.test.ts`, "writes no target and no server, and warns once, when it does not". The test "writes the target and the server when the @aws/agentcore-cdk of the project accepts passthrough.gateway" pins the other case. I also ran the check on two real libraries: `@aws/agentcore-cdk` 1.1.0 from npm gives false, and the build of aws/agentcore-l3-cdk-constructs branch `sa/box-gateway-to-gateway` gives true. --- docs/box-local-testing.md | 4 +- .../backends/cdk/compatibility.test.ts | 56 +++++++++++++++++++ .../project/backends/cdk/compatibility.ts | 28 ++++++++++ src/core/project/boxNetwork/network.test.ts | 16 ++++++ src/core/project/boxNetwork/network.ts | 11 +++- .../project/boxNetwork/projectGateways.ts | 16 +++++- src/core/project/boxNetworkSource.ts | 3 + src/core/project/manager.boxNetwork.test.ts | 56 ++++++++++++++++++- src/core/project/manager.tsx | 29 ++++++++-- 9 files changed, 211 insertions(+), 8 deletions(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index f9e3e1cf4..b72a7fe6a 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -229,7 +229,9 @@ profile that names a pack `box/` fails: box refuses it and names the `@box gateway's role `bedrock-agentcore:InvokeGateway` on that gateway only, and sets `AGENTCORE_GATEWAY__URL` and `_HOST` on the runtime. A `PRIVATE_VPC` runtime gets none of them. A `CUSTOM_JWT` gateway gets a warning and no target. You write nothing for them. A profile - entry that signs for a gateway host with `aws://` stops build. + entry that signs for a gateway host with `aws://` stops build. Build writes these targets only when + the `@aws/agentcore-cdk` in `agentcore/cdk` accepts `passthrough.gateway`: it asks that library + with `node`. Otherwise build writes none of them, and gives one warning. - **Outbound auth.** An `aws://` secret signs with the gateway's role, an `env://` secret sends an API key from AgentCore Identity, and an entry with no secret sends no credential. - **Failures.** A profile Box refuses stops build and deploy with box's own error. A wildcard host, diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 8aa60252a..442c0317f 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { tmpdir } from "node:os"; import { assertCdkLocalContainerSupport, + cdkAcceptsPassthroughGateway, cdkCompatibilityWarning, MINIMUM_COMPATIBLE_CDK_VERSION, } from "./compatibility"; @@ -101,3 +102,58 @@ describe("cdkCompatibilityWarning", () => { expect(await cdkCompatibilityWarning(directory)).toBeUndefined(); }); }); + +describe("cdkAcceptsPassthroughGateway", () => { + /** A CDK app whose @aws/agentcore-cdk exports `PassthroughConfigSchema` as `schema`, a JS text. */ + async function cdkDirectoryExporting(schema: string | undefined): Promise { + const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-passthrough-gateway-")); + tempDirectories.push(directory); + if (schema === undefined) return directory; + const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await mkdir(packageDirectory, { recursive: true }); + await writeFile( + join(packageDirectory, "package.json"), + JSON.stringify({ name: "@aws/agentcore-cdk", version: "1.1.0", main: "index.js" }), + ); + await writeFile( + join(packageDirectory, "index.js"), + `exports.PassthroughConfigSchema = ${schema};\n`, + ); + return directory; + } + /** As each @aws/agentcore-cdk parses a passthrough: with `gateway`, or with `endpoint` only. */ + const WITH_GATEWAY = + "{ safeParse: (config) => ({ success: typeof config.gateway === 'string' }) }"; + const ENDPOINT_ONLY = + "{ safeParse: (config) => ({ success: typeof config.endpoint === 'string' }) }"; + + test.skipIf(!Bun.which("node"))( + "is true when the installed library accepts passthrough.gateway", + async () => { + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(WITH_GATEWAY))).toBe( + true, + ); + }, + ); + + test.skipIf(!Bun.which("node"))( + "is false when the installed library requires passthrough.endpoint", + async () => { + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(ENDPOINT_ONLY))).toBe( + false, + ); + }, + ); + + test.skipIf(!Bun.which("node"))( + "is false when the library is not installed, or has no PassthroughConfigSchema", + async () => { + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(undefined))).toBe( + false, + ); + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting("undefined"))).toBe( + false, + ); + }, + ); +}); diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 5dbfcd3f9..05473b693 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -1,5 +1,7 @@ +import { execFile } from "node:child_process"; import { readFile } from "node:fs/promises"; import { join } from "node:path"; +import { promisify } from "node:util"; import semver from "semver"; import { createRequire } from "node:module"; import { ProjectStateError } from "../../../../errors"; @@ -62,3 +64,29 @@ export async function cdkCompatibilityWarning(cdkDirectory: string): Promise { + try { + const { stdout } = await promisify(execFile)("node", ["-e", PASSTHROUGH_GATEWAY_CHECK], { + cwd: cdkDirectory, + timeout: 60_000, + }); + return stdout.trim() === "accepts"; + } catch { + return false; + } +} diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 2d6db6354..730081fe4 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -48,6 +48,8 @@ interface Options { /** The other gateways of the project, after the Box gateway. */ readonly gateways?: Record[]; readonly runtime?: Partial; + /** Whether the @aws/agentcore-cdk of the project accepts `passthrough.gateway`; true here. */ + readonly projectGatewayTargets?: boolean; } /** The local box profile of runtime `agent`. */ @@ -99,6 +101,7 @@ function model(policy: string, egress: Record = {}, options: Op region: "us-west-2", targets: options.targets ?? [], grantedActions: options.grantedActions ?? [], + projectGatewayTargets: options.projectGatewayTargets ?? true, }); return { spec, @@ -1222,6 +1225,19 @@ describe("the gateways of the project", () => { expect(network.failures).toEqual([]); }); + test("gives the agent no gateway when the @aws/agentcore-cdk of the project refuses passthrough.gateway, and warns once", () => { + const { network } = model("", {}, { gateways: [TOOLS, OPEN], projectGatewayTargets: false }); + + expect(network.projectGateways).toEqual([]); + expect(network.failures).toEqual([]); + expect(network.warnings).toEqual([ + "The gateways 'tools' and 'open-tools' of this project get no route for a boxed agent on " + + "AgentCore Runtime, because the @aws/agentcore-cdk in agentcore/cdk does not accept " + + "passthrough.gateway. Update @aws/agentcore-cdk in agentcore/cdk/package.json to a " + + "version that accepts it, then build again.", + ]); + }); + test("gives a PRIVATE_VPC runtime no gateway, as the CDK library binds none to it", () => { const { network } = model( "", diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index ce289802c..b52ede514 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -166,6 +166,11 @@ export interface BoxNetworkProject { readonly targets: readonly AgentCoreGatewayTarget[]; /** The IAM actions that the gateway's `additionalPolicies` files grant, except build's own. */ readonly grantedActions: readonly string[]; + /** + * Whether the @aws/agentcore-cdk of the project accepts a target with `passthrough.gateway` + * (`cdkAcceptsPassthroughGateway`); absent means it does not, and no gateway gets a target. + */ + readonly projectGatewayTargets?: boolean; } /** The Box gateway of `runtime`: the gateway bound to it. */ @@ -204,7 +209,11 @@ export function buildBoxNetwork( return { ...rest, reason: `${where.subject} ${reason}`, place: where.place }; }; const failures: BoxNetworkFailure[] = [...parseFailures, ...map.failures.map(located)]; - const reached = projectGatewaysOf(project.spec, project.runtime); + const reached = projectGatewaysOf( + project.spec, + project.runtime, + project.projectGatewayTargets ?? false, + ); const targets = hostTargets(map.hosts, project, reached.gateways, located, parsed.profile.path); failures.push(...targets.failures); const telemetry = diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index 9540791b3..0e5b89646 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -49,11 +49,13 @@ function projectGatewayTargetName(name: string): string { * The gateways of `spec` that `runtime` calls through its Box gateway: each gateway without * `boundRuntime`, as the CDK library binds it to a runtime without a box. A `PRIVATE_VPC` runtime * gets none, and a `CUSTOM_JWT` gateway gets a warning, because the Box gateway cannot get its - * token. + * token. With `targets` false, because the @aws/agentcore-cdk of the project refuses + * `passthrough.gateway`, the runtime gets none, and one warning names them. */ export function projectGatewaysOf( spec: ProjectSpec, runtime: Pick, + targets = true, ): { gateways: BoxProjectGateway[]; warnings: string[] } { const gateways: BoxProjectGateway[] = []; const warnings: string[] = []; @@ -76,6 +78,18 @@ export function projectGatewaysOf( auth: gateway.authorizerType === "AWS_IAM" ? "iam" : "none", }); } + if (!targets && gateways.length > 0) { + const names = gateways.map(({ name }) => `'${name}'`); + const list = + names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0]; + warnings.push( + `The gateways ${list} of this project get no route for a boxed agent on AgentCore ` + + "Runtime, because the @aws/agentcore-cdk in agentcore/cdk does not accept " + + "passthrough.gateway. Update @aws/agentcore-cdk in agentcore/cdk/package.json to a " + + "version that accepts it, then build again.", + ); + return { gateways: [], warnings }; + } return { gateways, warnings }; } diff --git a/src/core/project/boxNetworkSource.ts b/src/core/project/boxNetworkSource.ts index 0b18cb0c2..0cbad886d 100644 --- a/src/core/project/boxNetworkSource.ts +++ b/src/core/project/boxNetworkSource.ts @@ -55,6 +55,8 @@ export async function readBoxNetworks( projectRoot: string, resolver: BoxProfileResolver, region: string = DEFAULT_EGRESS_BEDROCK_REGION, + /** Whether the @aws/agentcore-cdk of the project accepts `passthrough.gateway`. */ + projectGatewayTargets = false, ): Promise { const runtimes = spec.runtimes.filter((runtime) => runtimeRunsInBox(spec, runtime)); if (runtimes.length === 0) return []; @@ -84,6 +86,7 @@ export async function readBoxNetworks( region, targets: entry.targets, grantedActions: granted.actions, + projectGatewayTargets, }); networks.push({ ...network, diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 418ac1156..0b40151ba 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -144,7 +144,12 @@ function countingJson() { /** A new Strands project, with the Box gateway entry and the box profile `create` writes. */ async function strandsProject( - options: { backends?: { CDK: ProjectBackend }; env?: NodeJS.ProcessEnv } = {}, + options: { + backends?: { CDK: ProjectBackend }; + env?: NodeJS.ProcessEnv; + /** What the probe of agentcore/cdk answers; it refuses passthrough.gateway when absent. */ + acceptsPassthroughGateway?: boolean; + } = {}, ) { const directory = await temporary("agentcore-box-network-"); process.chdir(directory); @@ -163,6 +168,7 @@ async function strandsProject( ...options.env, }, boxProfileResolver: box, + cdkAcceptsPassthroughGateway: async () => options.acceptsPassthroughGateway ?? false, ...(options.backends && { backends: options.backends }), }); const { value: created, warnings: createWarnings } = await drain( @@ -674,6 +680,54 @@ describe("build writes the Box network of the box profile", () => { }); }); +describe("build routes the other gateways of the project for the boxed agent", () => { + /** Adds the gateway `tools` without boundRuntime, as `agentcore add gateway` writes it. */ + async function addToolsGateway(root: string) { + const spec = JSON.parse(await text(root, SPEC)); + spec.agentCoreGateways.push({ + name: "tools", + authorizerType: "AWS_IAM", + protocolType: "None", + enableSemanticSearch: false, + exceptionLevel: "NONE", + targets: [], + }); + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + } + + test("writes the target and the server when the @aws/agentcore-cdk of the project accepts passthrough.gateway", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: true }); + await addToolsGateway(root); + + const { warnings } = await build(manager, root); + + expect((await boxGateway(root)).targets).toContainEqual({ + name: "egress-gateway-tools", + targetType: "passthrough", + passthrough: { gateway: "tools", protocolType: "CUSTOM" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + }); + expect((await runtimeProfile(root)).mcp).toHaveProperty("tools"); + expect(warnings.filter((warning) => warning.includes("passthrough.gateway"))).toEqual([]); + }); + + test("writes no target and no server, and warns once, when it does not", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); + await addToolsGateway(root); + + const { warnings } = await build(manager, root); + + expect(await targetNames(root)).not.toContain("egress-gateway-tools"); + expect((await runtimeProfile(root)).mcp).toBeUndefined(); + expect(warnings.filter((warning) => warning.includes("passthrough.gateway"))).toEqual([ + "The gateways 'tools' of this project get no route for a boxed agent on AgentCore " + + "Runtime, because the @aws/agentcore-cdk in agentcore/cdk does not accept " + + "passthrough.gateway. Update @aws/agentcore-cdk in agentcore/cdk/package.json to a " + + "version that accepts it, then build again.", + ]); + }); +}); + describe("build sets box.version to the pinned box", () => { // The box features and the profiles that the CLI writes change together, so a project created // by an earlier CLI builds with the box this one ships, and agentcore.json says so. diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index e7b556a90..5c5c3a0fe 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -81,6 +81,7 @@ import { renderAwsMetadataPolicy, renderBoxProfile, runsInBox, + runtimeRunsInBox, startsInBoxOnCodeZip, } from "./templates/boxProfile"; import { defaultLogTargetNotice } from "./runtimeProfile/rules/additions"; @@ -131,6 +132,7 @@ import { import { isChinaRegion } from "../partition"; import z from "zod"; import { CdkBackend, type TransactionSearchEnabler } from "./backends/cdk"; +import { cdkAcceptsPassthroughGateway } from "./backends/cdk/compatibility"; import { resolveAwsAccount } from "./backends/cdk/environment"; import { pinnedVersion } from "./backends/cdk/dependencies"; import type { ProjectBackend } from "./backends/types"; @@ -450,6 +452,11 @@ type ProjectManagerConfig = { * PATH by default. */ boxProfileResolver?: BoxProfileResolver; + /** + * Whether the @aws/agentcore-cdk of the CDK app in a folder accepts a passthrough target with + * `gateway`; build writes such a target only then. `cdkAcceptsPassthroughGateway` by default. + */ + cdkAcceptsPassthroughGateway?: (cdkDirectory: string) => Promise; backends?: Partial>; templateRenderer?: TemplateRenderer; /** @@ -474,6 +481,7 @@ export class FsProjectManager implements ProjectManager { private readonly resolveAccount: (region: string) => Promise; private readonly processEnv: NodeJS.ProcessEnv; private readonly boxProfileResolver: BoxProfileResolver; + private readonly cdkAcceptsPassthroughGateway: (cdkDirectory: string) => Promise; constructor(config: ProjectManagerConfig) { this.logger = config.logger; @@ -499,6 +507,8 @@ export class FsProjectManager implements ProjectManager { this.processEnv = config.processEnv ?? process.env; this.boxProfileResolver = config.boxProfileResolver ?? new BoxCliProfileResolver({ env: this.processEnv }); + this.cdkAcceptsPassthroughGateway = + config.cdkAcceptsPassthroughGateway ?? cdkAcceptsPassthroughGateway; } public async resolve(input: ResolveProjectInput): Promise { @@ -1706,11 +1716,19 @@ export class FsProjectManager implements ProjectManager { command: "build" | "deploy", region: string, ): Promise<{ project: Project; networks: BoxNetwork[]; events: ProjectEvent[] }> { + // Only a box runtime and a gateway without boundRuntime need the check of the CDK app. + const unbound = project.spec.agentCoreGateways.some(({ boundRuntime }) => !boundRuntime); + const boxed = project.spec.runtimes.some((runtime) => runtimeRunsInBox(project.spec, runtime)); + const projectGatewayTargets = + unbound && + boxed && + (await this.cdkAcceptsPassthroughGateway(join(project.rootPath, "agentcore", "cdk"))); const networks = await readBoxNetworks( project.spec, project.rootPath, this.boxProfileResolver, region, + projectGatewayTargets, ); if (networks.some(({ failures }) => failures.length > 0)) { throw new InputValidationError(boxNetworkFailureMessage(networks, command)); @@ -1758,11 +1776,14 @@ export class FsProjectManager implements ProjectManager { const { written } = await envLocal.upsert([...edits.envLocal]); for (const key of written) messages.push(`writing ${key} to ${ENV_LOCAL_RELATIVE_PATH}`); } + // Each box runtime gives the same warning for the CDK app, so it appears once. const warnings = [ - ...edits.warnings, - ...networks.flatMap((network) => [ - ...network.warnings, - ...boxGatewayIamWarnings(edits.spec, network), + ...new Set([ + ...edits.warnings, + ...networks.flatMap((network) => [ + ...network.warnings, + ...boxGatewayIamWarnings(edits.spec, network), + ]), ]), ]; const events: ProjectEvent[] = [ From ca324acc3f7e314c80e7c9aa553f89f0fc93465f Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 16:49:11 -0800 Subject: [PATCH 06/22] fix(remove): Remove the Box gateway target of a gateway with the gateway Review feedback (blocking): after one build, each Box gateway has the target `egress-gateway-` with `passthrough.gateway: ""`. `agentcore remove gateway ` kept that target, the project schema refused the new spec because the target names no gateway, and thus the user could not remove the gateway, and build could not remove the target. `removeResource` now also removes, from each other gateway, each target that build owns (its name starts with `egress-`) and that names the removed gateway in `passthrough.gateway`. A target of the user's that names the gateway stays, and the schema still refuses it with its name, so build never removes a target that the user wrote. I did not make the schema accept a target that names no gateway, because the spec then is not valid for the CDK library until the next build. Test: `manager.boxNetwork.test.ts`, "lets remove gateway remove the gateway after a build, with the target build wrote for it", fails before this change with the schema error. It builds, removes the gateway, and then builds again. The user's own target stays. --- src/core/project/manager.boxNetwork.test.ts | 20 ++++++++++++++++++++ src/core/project/manager.tsx | 18 +++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 0b40151ba..0a9fa73fd 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -711,6 +711,26 @@ describe("build routes the other gateways of the project for the boxed agent", ( expect(warnings.filter((warning) => warning.includes("passthrough.gateway"))).toEqual([]); }); + test("lets remove gateway remove the gateway after a build, with the target build wrote for it", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: true }); + await addToolsGateway(root); + const user = userTarget("mine", "https://mine.example.com"); + await editGateway(root, (gateway) => gateway.targets.push(user)); + await build(manager, root); + expect(await targetNames(root)).toContain("egress-gateway-tools"); + + const project = (await manager.resolve({ filePath: root })) as Project; + await manager.removeResource(project, { resourceType: "gateway", name: "tools" }); + + const spec = JSON.parse(await text(root, SPEC)); + expect(spec.agentCoreGateways.map(({ name }: { name: string }) => name)).toEqual([GATEWAY]); + expect(await targetNames(root)).not.toContain("egress-gateway-tools"); + expect((await boxGateway(root)).targets).toContainEqual(user); + // The next build writes no target for the gateway that is gone. + await build(manager, root); + expect(await targetNames(root)).not.toContain("egress-gateway-tools"); + }); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 5c5c3a0fe..ea01c6ec8 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -55,7 +55,7 @@ import { harnessApiKeyCredentialName, validateHarnessTemplateSource, } from "./templates/harness"; -import { boxGatewayIamWarnings, type BoxNetwork } from "./boxNetwork"; +import { boxGatewayIamWarnings, isManagedTarget, type BoxNetwork } from "./boxNetwork"; import { reservedBoxTargetNameProblem } from "./boxMemory"; import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource"; import { resolveRegion } from "../region"; @@ -1299,6 +1299,22 @@ export class FsProjectManager implements ProjectManager { const newResources = existingResources.filter((resource) => resource.name !== input.name); removed = newResources.length !== existingResources.length; newSpec = { ...existingProjectSpec, [projectSpecKey]: newResources }; + // Build writes a target on each Box gateway for each other gateway of the project. Such a + // target goes with its gateway; a target of the user's that names it stays, and fails. + if (input.resourceType === "gateway" && removed) { + newSpec = { + ...(newSpec as object), + agentCoreGateways: existingProjectSpec.agentCoreGateways + .filter((gateway) => gateway.name !== input.name) + .map((gateway) => ({ + ...gateway, + targets: gateway.targets.filter( + (target) => + !(isManagedTarget(target) && target.passthrough?.gateway === input.name), + ), + })), + }; + } // A gateway bound to the runtime (each Box gateway is) goes with the runtime, and its // targets go too. A gateway bound to a runtime that does not exist fails validation. if (input.resourceType === "runtime" && removed) { From dc64c5bb2b5542fc52c8b8e6f234b13fdded124c Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 17:32:06 -0800 Subject: [PATCH 07/22] fix(box): Read a project whose build-owned gateway target names a gateway that it cannot call Review feedback: after a build, a gateway of the project that gets `boundRuntime`, or that is removed from agentcore.json by hand, left the target `egress-gateway-` with a reference that the project schema refused. Each command then stopped when it read agentcore.json, so build could not remove the target. The schema does not do this check for a target whose name starts with `egress-` (`BOX_EGRESS_TARGET_PREFIX`), because build writes and removes each such target. The next build removes the target. A target of the user that names such a gateway is still refused. The prefix moves to `projectSchemas/project.ts`, and `boxNetwork/egress.ts` exports it from there. Tests that fail before this change: `manager.boxNetwork.test.ts`, "reads the project and removes the target after a build when the gateway gets boundRuntime" and "reads the project and removes the target when the gateway is gone from agentcore.json". `project.test.ts`, "accepts a target that build owns and that names ...", pins the schema. The refusals in that file now use a target of the user. --- src/core/project/boxNetwork/egress.ts | 7 ++--- src/core/project/manager.boxNetwork.test.ts | 34 +++++++++++++++++++++ src/projectSchemas/project.test.ts | 25 ++++++++++++--- src/projectSchemas/project.ts | 11 +++++-- 4 files changed, 66 insertions(+), 11 deletions(-) diff --git a/src/core/project/boxNetwork/egress.ts b/src/core/project/boxNetwork/egress.ts index ad1cf2f48..df3cb65d6 100644 --- a/src/core/project/boxNetwork/egress.ts +++ b/src/core/project/boxNetwork/egress.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { BOX_EGRESS_TARGET_PREFIX } from "../../../projectSchemas/project"; import type { BoxEgressAuth } from "./network"; import type { FailureCode } from "./types"; @@ -160,11 +161,7 @@ export function signingService(host: string): { service: string; region: string return endpoint && { service: endpoint.service, region: endpoint.region }; } -/** - * The start of the name of each target that build adds to a Box gateway. Build manages every - * target whose name has it, and no other. - */ -export const BOX_EGRESS_TARGET_PREFIX = "egress-"; +export { BOX_EGRESS_TARGET_PREFIX }; /** * The gateway target name build gives `name`: {@link BOX_EGRESS_TARGET_PREFIX}, then the letters diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 0a9fa73fd..7e5b8ff35 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -731,6 +731,40 @@ describe("build routes the other gateways of the project for the boxed agent", ( expect(await targetNames(root)).not.toContain("egress-gateway-tools"); }); + test("reads the project and removes the target after a build when the gateway gets boundRuntime", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: true }); + await addToolsGateway(root); + await build(manager, root); + expect(await targetNames(root)).toContain("egress-gateway-tools"); + const spec = JSON.parse(await text(root, SPEC)); + spec.agentCoreGateways.find(({ name }: { name: string }) => name === "tools").boundRuntime = + "agent_python_strands"; + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + + const { steps } = await build(manager, root); + + expect(await targetNames(root)).not.toContain("egress-gateway-tools"); + expect(steps).toContain( + "removing gateway target 'egress-gateway-tools' from 'agent-python-strands-box-egress': " + + "the boxed agent no longer calls the gateway 'tools'", + ); + }); + + test("reads the project and removes the target when the gateway is gone from agentcore.json", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: true }); + await addToolsGateway(root); + await build(manager, root); + const spec = JSON.parse(await text(root, SPEC)); + spec.agentCoreGateways = spec.agentCoreGateways.filter( + ({ name }: { name: string }) => name !== "tools", + ); + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + + await build(manager, root); + + expect(await targetNames(root)).not.toContain("egress-gateway-tools"); + }); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index b1910166e..074a71f90 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -621,8 +621,8 @@ describe("Box project runtimes on AgentCore Runtime V2", () => { }); describe("a passthrough target that names a gateway", () => { - const target = (passthrough: Record) => ({ - name: "egress-gateway-tools", + const target = (passthrough: Record, name = "tools-call") => ({ + name, targetType: "passthrough", passthrough: { protocolType: "CUSTOM", ...passthrough }, outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, @@ -635,11 +635,15 @@ describe("a passthrough target that names a gateway", () => { }); return result.success ? [] : result.error.issues.map(({ message }) => message); }; - const front = (passthrough: Record, fields: Record = {}) => ({ + const front = ( + passthrough: Record, + fields: Record = {}, + name?: string, + ) => ({ name: "front", authorizerType: "AWS_IAM", protocolType: "None", - targets: [target(passthrough)], + targets: [target(passthrough, name)], ...fields, }); const TOOLS = { name: "tools", authorizerType: "AWS_IAM", targets: [] }; @@ -664,6 +668,19 @@ describe("a passthrough target that names a gateway", () => { expect(messages(gateways)).toContainEqual(expect.stringContaining(message)); }); + test.each([ + ["no gateway of that name", [front({ gateway: "gone" }, {}, "egress-gateway-gone")]], + [ + "a gateway bound to a runtime", + [ + front({ gateway: "tools" }, {}, "egress-gateway-tools"), + { ...TOOLS, boundRuntime: "agent" }, + ], + ], + ])("accepts a target that build owns and that names %s, as build removes it", (_, gateways) => { + expect(messages(gateways)).toEqual([]); + }); + test.each([ ["both endpoint and gateway", { endpoint: "https://api.example.com", gateway: "tools" }], ["neither endpoint nor gateway", {}], diff --git a/src/projectSchemas/project.ts b/src/projectSchemas/project.ts index dd565c63e..865ca9450 100644 --- a/src/projectSchemas/project.ts +++ b/src/projectSchemas/project.ts @@ -36,6 +36,11 @@ export const ProjectNameSchema = z export const ProjectTypeSchema = z.enum(["box"]); /** Whether the project is a Box project, so the CLI keeps a Box gateway for each runtime. */ export const isBoxProject = (spec: { projectType?: string }) => spec.projectType === "box"; +/** + * The start of the name of each target that build adds to a Box gateway. Build manages every + * target whose name has it, and no other. + */ +export const BOX_EGRESS_TARGET_PREFIX = "egress-"; /** The suffix of each Box gateway name: the runtime `agent` gets the gateway `agent-box-egress`. */ export const BOX_GATEWAY_SUFFIX = "-box-egress"; /** @@ -182,11 +187,13 @@ export const ProjectSpecSchema = z } } // A passthrough target that names a gateway calls a gateway of this project. A gateway bound to - // a runtime belongs to that runtime, so no target of another gateway calls it. + // a runtime belongs to that runtime, so no target of another gateway calls it. Build writes + // and removes each target whose name starts with BOX_EGRESS_TARGET_PREFIX, so such a target + // that names no such gateway is not refused here: the next build removes it. for (const gateway of spec.agentCoreGateways) { for (const target of gateway.targets) { const reached = target.passthrough?.gateway; - if (reached === undefined) continue; + if (reached === undefined || target.name.startsWith(BOX_EGRESS_TARGET_PREFIX)) continue; const named = spec.agentCoreGateways.find((other) => other.name === reached); const problem = named === undefined From 7755174f75366e5e41eb4931d128566a75a2e65d Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 17:32:52 -0800 Subject: [PATCH 08/22] fix(box): Stop build when two gateways of the project get one target name Review feedback: `hostTargets` put the target of each gateway of the project in `owners` with `owners.set`. When two gateways got one target name, the second name replaced the first one with no report, and the writer added two targets with one name. The target names of 7545175a already differ for gateway names that share their first 90 characters: the test now has "a".repeat(90) + "x1" and + "x2". A gateway can still have, as its name, the name that a different gateway gets with its hash, for example `a--b` and `a-b-`. Build now stops with `TARGET_NAME_COLLISION` for two gateways with one target name, as it does for two hosts. Thus the writer never runs with two targets of one name. Test: `network.test.ts`, "fails two gateways whose targets still have one name, as for two hosts", fails before this change. `projectGateways.test.ts`, "is not the same for" the two names of 92 characters, passes before and after. --- src/core/project/boxNetwork/network.test.ts | 15 +++++++++++++++ src/core/project/boxNetwork/network.ts | 14 ++++++++++++++ .../project/boxNetwork/projectGateways.test.ts | 1 + 3 files changed, 30 insertions(+) diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 730081fe4..e3af763d6 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test"; +import { createHash } from "node:crypto"; import { getBoxGatewayAgentCoreTargetSpec, getBoxGatewayBedrockTargetSpec, @@ -1259,6 +1260,20 @@ describe("the gateways of the project", () => { ); }); + test("fails two gateways whose targets still have one name, as for two hosts", () => { + // The target of "a--b" ends in the hash of its name, which a second gateway can have as a name. + const hash = createHash("sha256").update("a--b").digest("hex").slice(0, 8); + const first = { name: "a--b", authorizerType: "AWS_IAM", targets: [] }; + const second = { name: `a-b-${hash}`, authorizerType: "AWS_IAM", targets: [] }; + const r = model("", {}, { gateways: [first, second] }); + + expect(r.failures()).toEqual([["TARGET_NAME_COLLISION", `egress-gateway-a-b-${hash}`]]); + expect(r.reasons()).toEqual([ + `The gateways 'a--b' and 'a-b-${hash}' of this project would both get the gateway target ` + + `'egress-gateway-a-b-${hash}'. Rename one of the gateways.`, + ]); + }); + test("fails an entry whose target would take the name of a gateway's target", () => { const r = model( "", diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index b52ede514..b0ff649c5 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -470,7 +470,21 @@ function hostTargets( for (const target of existing) { if (!isManagedTarget(target)) owners.set(target.name, `the gateway target '${target.name}'`); } + const gatewayOf = new Map(); for (const gateway of gateways) { + const other = gatewayOf.get(gateway.target); + if (other !== undefined) { + failures.push({ + code: "TARGET_NAME_COLLISION", + target: gateway.target, + reason: + `The gateways '${other}' and '${gateway.name}' of this project would both get the ` + + `gateway target '${gateway.target}'. Rename one of the gateways.`, + place: PROJECT_SPEC_PLACE, + }); + continue; + } + gatewayOf.set(gateway.target, gateway.name); owners.set(gateway.target, `the target that build adds for the gateway '${gateway.name}'`); } const describeHost = (host: MappedHost) => diff --git a/src/core/project/boxNetwork/projectGateways.test.ts b/src/core/project/boxNetwork/projectGateways.test.ts index 9eb7faf05..cda03138f 100644 --- a/src/core/project/boxNetwork/projectGateways.test.ts +++ b/src/core/project/boxNetwork/projectGateways.test.ts @@ -58,6 +58,7 @@ describe("the target name of each gateway", () => { test.each([ ["a--b", "a-b"], ["x".repeat(95) + "1", "x".repeat(95) + "2"], + ["a".repeat(90) + "x1", "a".repeat(90) + "x2"], ])("is not the same for %s and %s", (first, second) => { const targets = targetsOf(first, second); expect(new Set(targets).size).toBe(2); From 892246693571ba456385272689fedf3bae37df05 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 17:33:21 -0800 Subject: [PATCH 09/22] fix(box): Add the server of a gateway named constructor to the Runtime profile Review feedback: the gateway rule checked `gateway.name in mcp`, which is true for a key that each object has from its prototype. Thus a gateway named `constructor` or `toString` stopped build with `RUNTIME_GATEWAY_SERVER_NAME_TAKEN`. The rule now uses `Object.hasOwn(mcp, gateway.name)`. Test: `gateway.test.ts`, "adds the server of a gateway whose name is a key of every object, such as constructor", fails before this change. --- src/core/project/runtimeProfile/rules/gateway.test.ts | 11 +++++++++++ src/core/project/runtimeProfile/rules/gateway.ts | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/core/project/runtimeProfile/rules/gateway.test.ts b/src/core/project/runtimeProfile/rules/gateway.test.ts index 005986b37..b04f17ba9 100644 --- a/src/core/project/runtimeProfile/rules/gateway.test.ts +++ b/src/core/project/runtimeProfile/rules/gateway.test.ts @@ -751,6 +751,17 @@ describe("the gateway rule for a gateway of the project", () => { expect(result.table.mcp).toBeUndefined(); }); + test("adds the server of a gateway whose name is a key of every object, such as constructor", () => { + const named = { ...TOOLS, name: "constructor", target: "egress-gateway-constructor" }; + const result = apply(parse(PROFILE_TEXT) as TomlTable, { + ...contextOf(PROFILE_TEXT, []), + projectGateways: [named], + }); + + expect(result.problems).toEqual([]); + expect(Object.keys(result.table.mcp as TomlTable)).toEqual(["constructor"]); + }); + test("stops for a server of the local profile with the gateway's name", () => { const text = `${PROFILE_TEXT}\n[mcp.tools]\ncommand = ["/usr/bin/tools"]\n`; diff --git a/src/core/project/runtimeProfile/rules/gateway.ts b/src/core/project/runtimeProfile/rules/gateway.ts index c3e7bcc19..45893ae08 100644 --- a/src/core/project/runtimeProfile/rules/gateway.ts +++ b/src/core/project/runtimeProfile/rules/gateway.ts @@ -101,7 +101,7 @@ export function apply(table: Readonly, context: RuntimeProfileContext const problems: RuntimeProfileProblem[] = []; for (const gateway of context.projectGateways ?? []) { - if (gateway.name in mcp) { + if (Object.hasOwn(mcp, gateway.name)) { problems.push({ code: "RUNTIME_GATEWAY_SERVER_NAME_TAKEN", key: ["mcp", gateway.name], From 89f4333f3396d2f17fbc455223c41c4599eb12b7 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 17:35:49 -0800 Subject: [PATCH 10/22] fix(box): Give the CUSTOM_JWT gateway notice once, at add gateway, and not on each build Review feedback: build gave the warning for a `CUSTOM_JWT` gateway on each build, one time for each boxed runtime. The CLI gives a notice about a resource when a command writes that resource: `create` and `add runtime` give the notices of the Box gateway logs and of the default log target. This change does the same. `agentcore add gateway` gives `customJwtGatewayNotice` one time, after it writes a `CUSTOM_JWT` gateway without `boundRuntime` to a project that has a boxed runtime that is not `PRIVATE_VPC`. Build gives no warning for the gateway. I did not add an opt-out, because a notice at the write is simpler and is what the CLI does for its other notices. Tests that fail before this change: `network.test.ts`, "gives the agent no route to a CUSTOM_JWT gateway, and no warning on each build", and `manager.boxNetwork.test.ts`, "add gateway gives one notice for a CUSTOM_JWT gateway, and build gives none". --- docs/box-local-testing.md | 2 +- src/core/project/boxNetwork/network.test.ts | 8 ++--- .../project/boxNetwork/projectGateways.ts | 23 +++++++------ src/core/project/manager.boxNetwork.test.ts | 34 +++++++++++++++++++ src/core/project/manager.tsx | 14 ++++++++ 5 files changed, 63 insertions(+), 18 deletions(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index b72a7fe6a..6f91bfe3e 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -228,7 +228,7 @@ profile that names a pack `box/` fails: box refuses it and names the `@box the gateway's name. The L3 sets the target's endpoint to that gateway's URL, gives the Box gateway's role `bedrock-agentcore:InvokeGateway` on that gateway only, and sets `AGENTCORE_GATEWAY__URL` and `_HOST` on the runtime. A `PRIVATE_VPC` runtime gets none of - them. A `CUSTOM_JWT` gateway gets a warning and no target. You write nothing for them. A profile + them. A `CUSTOM_JWT` gateway gets no target, and `agentcore add gateway` gives one notice for it. You write nothing for them. A profile entry that signs for a gateway host with `aws://` stops build. Build writes these targets only when the `@aws/agentcore-cdk` in `agentcore/cdk` accepts `passthrough.gateway`: it asks that library with `node`. Otherwise build writes none of them, and gives one warning. diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index e3af763d6..76d0ad375 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -1249,15 +1249,11 @@ describe("the gateways of the project", () => { expect(network.projectGateways).toEqual([]); }); - test("warns for a CUSTOM_JWT gateway, and gives the agent no route to it", () => { + test("gives the agent no route to a CUSTOM_JWT gateway, and no warning on each build", () => { const { network } = model("", {}, { gateways: [JWT] }); expect(network.projectGateways).toEqual([]); - expect(network.warnings).toContain( - "The gateway 'jwt-tools' takes CUSTOM_JWT tokens, and the Box gateway of runtime 'agent' " + - "signs only with its IAM role, so the boxed agent cannot call 'jwt-tools' on AgentCore " + - "Runtime. Set its authorizerType to AWS_IAM to let the agent call it.", - ); + expect(network.warnings).toEqual([]); }); test("fails two gateways whose targets still have one name, as for two hosts", () => { diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index 0e5b89646..6bf2f4671 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -48,8 +48,8 @@ function projectGatewayTargetName(name: string): string { /** * The gateways of `spec` that `runtime` calls through its Box gateway: each gateway without * `boundRuntime`, as the CDK library binds it to a runtime without a box. A `PRIVATE_VPC` runtime - * gets none, and a `CUSTOM_JWT` gateway gets a warning, because the Box gateway cannot get its - * token. With `targets` false, because the @aws/agentcore-cdk of the project refuses + * gets none, and no `CUSTOM_JWT` gateway, because the Box gateway cannot get its token; + * `add gateway` gives {@link customJwtGatewayNotice} for it once. With `targets` false, because the @aws/agentcore-cdk of the project refuses * `passthrough.gateway`, the runtime gets none, and one warning names them. */ export function projectGatewaysOf( @@ -62,15 +62,7 @@ export function projectGatewaysOf( if (runtime.containment === "PRIVATE_VPC") return { gateways, warnings }; for (const gateway of spec.agentCoreGateways) { if (gateway.boundRuntime !== undefined) continue; - if (gateway.authorizerType === "CUSTOM_JWT") { - warnings.push( - `The gateway '${gateway.name}' takes CUSTOM_JWT tokens, and the Box gateway of runtime ` + - `'${runtime.name}' signs only with its IAM role, so the boxed agent cannot call ` + - `'${gateway.name}' on AgentCore Runtime. Set its authorizerType to AWS_IAM to let the ` + - "agent call it.", - ); - continue; - } + if (gateway.authorizerType === "CUSTOM_JWT") continue; gateways.push({ name: gateway.name, target: projectGatewayTargetName(gateway.name), @@ -111,6 +103,15 @@ export function projectGatewayTargetFor( }; } +/** What `add gateway` tells the user once about a `CUSTOM_JWT` gateway in a Box project. */ +export function customJwtGatewayNotice(gatewayName: string): string { + return ( + `the gateway '${gatewayName}' takes CUSTOM_JWT tokens, and a Box gateway signs only with its ` + + `IAM role, so a boxed agent cannot call '${gatewayName}' on AgentCore Runtime, and build adds ` + + "no route to it. Set its authorizerType to AWS_IAM to let a boxed agent call it" + ); +} + /** The `@box/agentcore` inputs that carry the URL and the host of `gateway` on the Runtime. */ export function projectGatewayInputs(gateway: Pick): { readonly url: string; diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 7e5b8ff35..008023650 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -765,6 +765,40 @@ describe("build routes the other gateways of the project for the boxed agent", ( expect(await targetNames(root)).not.toContain("egress-gateway-tools"); }); + test("add gateway gives one notice for a CUSTOM_JWT gateway, and build gives none", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: true }); + const project = (await manager.resolve({ filePath: root })) as Project; + const jwt = { + name: "secure", + authorizerType: "CUSTOM_JWT", + authorizerConfiguration: { + customJwtAuthorizer: { + discoveryUrl: "https://idp.example.com/.well-known/openid-configuration", + allowedAudience: ["agentcore"], + }, + }, + enableSemanticSearch: false, + exceptionLevel: "NONE", + protocolType: "MCP", + targets: [], + }; + + const added = await drain( + manager.addResource(project, { + resourceType: "gateway", + resourceConfig: jwt, + } as unknown as Parameters[1]), + ); + const built = await build(manager, root); + + const notice = + "the gateway 'secure' takes CUSTOM_JWT tokens, and a Box gateway signs only with its IAM " + + "role, so a boxed agent cannot call 'secure' on AgentCore Runtime, and build adds no route " + + "to it. Set its authorizerType to AWS_IAM to let a boxed agent call it"; + expect(added.warnings).toEqual([notice]); + expect(built.warnings.filter((warning) => warning.includes("CUSTOM_JWT"))).toEqual([]); + }); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index ea01c6ec8..d49c3a029 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -133,6 +133,7 @@ import { isChinaRegion } from "../partition"; import z from "zod"; import { CdkBackend, type TransactionSearchEnabler } from "./backends/cdk"; import { cdkAcceptsPassthroughGateway } from "./backends/cdk/compatibility"; +import { customJwtGatewayNotice } from "./boxNetwork/projectGateways"; import { resolveAwsAccount } from "./backends/cdk/environment"; import { pinnedVersion } from "./backends/cdk/dependencies"; import type { ProjectBackend } from "./backends/types"; @@ -1142,6 +1143,19 @@ export class FsProjectManager implements ProjectManager { ]); throw err; } + // After the write, so a failed write gives no notice for a gateway that was not written. + if (input.resourceType === "gateway") { + const added = newProjectSpec.agentCoreGateways.find( + ({ name }) => name === input.resourceConfig.name, + ); + const boxed = newProjectSpec.runtimes.some( + (runtime) => + runtimeRunsInBox(newProjectSpec, runtime) && runtime.containment !== "PRIVATE_VPC", + ); + if (added && !added.boundRuntime && added.authorizerType === "CUSTOM_JWT" && boxed) { + yield { type: "warning", message: customJwtGatewayNotice(added.name) }; + } + } // After the write, so a failed write gives no notice for a runtime that was not written. if (input.resourceType === "runtime") { const added = input.resourceConfig.name; From 6827831e5b663a8af9414cd799891f091179a3b3 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 17:55:52 -0800 Subject: [PATCH 11/22] fix(box): Ask the CDK library about a whole gateway target, as its schema now splits passthrough aws/agentcore-l3-cdk-constructs PR 478, commit a1c7d24 (for its review), keeps `PassthroughConfigSchema` with a required `endpoint`, and gives `passthrough.gateway` the schema `GatewayPassthroughConfigSchema`. Thus the check of 801cff58, which parsed `{ gateway }` with `PassthroughConfigSchema`, gave false for the library that accepts the field, and build wrote no target. `cdkAcceptsPassthroughGateway` now parses a whole target as build writes it with `AgentCoreGatewayTargetSchema`, which both libraries export. `@aws/agentcore-cdk` 1.1.0 from npm gives false, and the build of PR 478 at d57f789 gives true. Test: in `compatibility.test.ts`, "is true when the installed library accepts passthrough.gateway" fails before this change. Its fake library now exports `AgentCoreGatewayTargetSchema`. --- .../project/backends/cdk/compatibility.test.ts | 12 ++++++------ src/core/project/backends/cdk/compatibility.ts | 15 +++++++++++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 442c0317f..78dd861c5 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -104,7 +104,7 @@ describe("cdkCompatibilityWarning", () => { }); describe("cdkAcceptsPassthroughGateway", () => { - /** A CDK app whose @aws/agentcore-cdk exports `PassthroughConfigSchema` as `schema`, a JS text. */ + /** A CDK app whose @aws/agentcore-cdk exports `AgentCoreGatewayTargetSchema` as `schema`, a JS text. */ async function cdkDirectoryExporting(schema: string | undefined): Promise { const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-passthrough-gateway-")); tempDirectories.push(directory); @@ -117,15 +117,15 @@ describe("cdkAcceptsPassthroughGateway", () => { ); await writeFile( join(packageDirectory, "index.js"), - `exports.PassthroughConfigSchema = ${schema};\n`, + `exports.AgentCoreGatewayTargetSchema = ${schema};\n`, ); return directory; } - /** As each @aws/agentcore-cdk parses a passthrough: with `gateway`, or with `endpoint` only. */ + /** As each @aws/agentcore-cdk parses the passthrough of a target: with `gateway`, or `endpoint` only. */ const WITH_GATEWAY = - "{ safeParse: (config) => ({ success: typeof config.gateway === 'string' }) }"; + "{ safeParse: (target) => ({ success: typeof target.passthrough.gateway === 'string' }) }"; const ENDPOINT_ONLY = - "{ safeParse: (config) => ({ success: typeof config.endpoint === 'string' }) }"; + "{ safeParse: (target) => ({ success: typeof target.passthrough.endpoint === 'string' }) }"; test.skipIf(!Bun.which("node"))( "is true when the installed library accepts passthrough.gateway", @@ -146,7 +146,7 @@ describe("cdkAcceptsPassthroughGateway", () => { ); test.skipIf(!Bun.which("node"))( - "is false when the library is not installed, or has no PassthroughConfigSchema", + "is false when the library is not installed, or has no AgentCoreGatewayTargetSchema", async () => { expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(undefined))).toBe( false, diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 05473b693..e3c7c81a5 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -67,14 +67,21 @@ export async function cdkCompatibilityWarning(cdkDirectory: string): Promise Date: Fri, 20 Nov 2026 18:00:53 -0800 Subject: [PATCH 12/22] fix(schema): Skip the passthrough.gateway check only for an egress- target of a Box gateway Review feedback on ff0c48f7: the schema skipped the check for each target whose name starts with `egress-`, on each gateway of each project. Build manages `egress-` targets only on the Box gateway of a runtime: a gateway with `boundRuntime` in a project with `"projectType": "box"`. The skip now applies only to such a target. An `egress-` target on a gateway without `boundRuntime`, or in a project that is not a Box project, gets the check, as each other target does. Tests: in `project.test.ts`, "is refused on a gateway without boundRuntime, which build does not write" and "is refused in a project that is not a Box project" fail before this change. "is accepted on the Box gateway of a Box project when it names ..." pins the case that build removes. --- src/projectSchemas/project.test.ts | 49 +++++++++++++++++++++++------- src/projectSchemas/project.ts | 13 +++++--- 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index 074a71f90..58dbaf58a 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -668,17 +668,44 @@ describe("a passthrough target that names a gateway", () => { expect(messages(gateways)).toContainEqual(expect.stringContaining(message)); }); - test.each([ - ["no gateway of that name", [front({ gateway: "gone" }, {}, "egress-gateway-gone")]], - [ - "a gateway bound to a runtime", - [ - front({ gateway: "tools" }, {}, "egress-gateway-tools"), - { ...TOOLS, boundRuntime: "agent" }, - ], - ], - ])("accepts a target that build owns and that names %s, as build removes it", (_, gateways) => { - expect(messages(gateways)).toEqual([]); + describe("a target that build owns", () => { + /** The Box gateway of `agent`, with one egress- target that names `gateway`. */ + const boxGateway = (gateway: string) => ({ + ...boxGatewaySpec("agent"), + targets: [target({ gateway }, `egress-gateway-${gateway}`)], + }); + const parse = (projectType: string | undefined, gateways: unknown[]) => { + const result = ProjectSpecSchema.safeParse({ + ...minimalProject, + ...(projectType && { projectType }), + runtimes: [runtime], + agentCoreGateways: gateways, + }); + return result.success ? [] : result.error.issues.map(({ message }) => message); + }; + + test.each([ + ["no gateway of that name", [boxGateway("gone")]], + ["a gateway bound to a runtime", [boxGateway("tools"), { ...TOOLS, boundRuntime: "agent" }]], + ])( + "is accepted on the Box gateway of a Box project when it names %s, as build removes it", + (_, gateways) => { + expect(parse("box", gateways)).toEqual([]); + }, + ); + + test("is refused on a gateway without boundRuntime, which build does not write", () => { + const ordinary = front({ gateway: "gone" }, {}, "egress-foo"); + expect(parse("box", [boxGatewaySpec("agent"), ordinary])).toContainEqual( + expect.stringContaining('Target "egress-foo" of gateway "front" names the gateway "gone"'), + ); + }); + + test("is refused in a project that is not a Box project", () => { + expect(parse(undefined, [boxGateway("gone")])).toContainEqual( + expect.stringContaining('names the gateway "gone" in passthrough.gateway'), + ); + }); }); test.each([ diff --git a/src/projectSchemas/project.ts b/src/projectSchemas/project.ts index 865ca9450..f318f5541 100644 --- a/src/projectSchemas/project.ts +++ b/src/projectSchemas/project.ts @@ -187,13 +187,18 @@ export const ProjectSpecSchema = z } } // A passthrough target that names a gateway calls a gateway of this project. A gateway bound to - // a runtime belongs to that runtime, so no target of another gateway calls it. Build writes - // and removes each target whose name starts with BOX_EGRESS_TARGET_PREFIX, so such a target - // that names no such gateway is not refused here: the next build removes it. + // a runtime belongs to that runtime, so no target of another gateway calls it. On the Box + // gateway of a runtime of a Box project, build writes and removes each target whose name starts + // with BOX_EGRESS_TARGET_PREFIX, so such a target that names no such gateway is not refused + // here: the next build removes it. + const buildOwns = (gateway: { boundRuntime?: string }, target: { name: string }) => + isBoxProject(spec) && + isBoundGateway(gateway) && + target.name.startsWith(BOX_EGRESS_TARGET_PREFIX); for (const gateway of spec.agentCoreGateways) { for (const target of gateway.targets) { const reached = target.passthrough?.gateway; - if (reached === undefined || target.name.startsWith(BOX_EGRESS_TARGET_PREFIX)) continue; + if (reached === undefined || buildOwns(gateway, target)) continue; const named = spec.agentCoreGateways.find((other) => other.name === reached); const problem = named === undefined From f628172c442cb3895b23e359fdb3342c1111784f Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 18:03:39 -0800 Subject: [PATCH 13/22] fix(box): Say why build could not check the CDK library for passthrough.gateway Review feedback: `cdkAcceptsPassthroughGateway` gave false for a library that refuses the field, and also when `node` is not there, when the check takes more than 60 seconds, and when the check fails. In each case, the warning told the user to update the library. The check now gives `PassthroughGatewayCheck`: `{ accepts: true }`, or `{ accepts: false, reason }` with the reason `refuses`, `not-installed`, `no-node`, `timed-out`, or `failed`, and for `failed` the first line of the error. The one warning of build says that reason and its fix. Build still writes no target, no server, and no pack input in each case that is not `accepts`. `cdkAcceptsPassthroughGateway` also takes `node` and `timeoutMs`, for tests. Tests that fail before this change: in `compatibility.test.ts`, one test for each answer, with a fake library, a library that throws, a library that does not stop, and a `node` that is not there; in `network.test.ts`, "gives the agent no gateway, and one warning that says why, when the check gives ..." for each reason. --- .../backends/cdk/compatibility.test.ts | 95 +++++++++++-------- .../project/backends/cdk/compatibility.ts | 68 +++++++++---- src/core/project/boxNetwork/network.test.ts | 59 +++++++++--- src/core/project/boxNetwork/network.ts | 10 +- .../project/boxNetwork/projectGateways.ts | 32 ++++++- src/core/project/boxNetworkSource.ts | 7 +- src/core/project/manager.boxNetwork.test.ts | 3 +- src/core/project/manager.tsx | 21 ++-- 8 files changed, 204 insertions(+), 91 deletions(-) diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index 78dd861c5..afaeb70da 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -104,56 +104,75 @@ describe("cdkCompatibilityWarning", () => { }); describe("cdkAcceptsPassthroughGateway", () => { - /** A CDK app whose @aws/agentcore-cdk exports `AgentCoreGatewayTargetSchema` as `schema`, a JS text. */ - async function cdkDirectoryExporting(schema: string | undefined): Promise { + /** A CDK app whose @aws/agentcore-cdk has the module text `index`. */ + async function cdkDirectoryWithIndex(index: string | undefined): Promise { const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-passthrough-gateway-")); tempDirectories.push(directory); - if (schema === undefined) return directory; + if (index === undefined) return directory; const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); await mkdir(packageDirectory, { recursive: true }); await writeFile( join(packageDirectory, "package.json"), JSON.stringify({ name: "@aws/agentcore-cdk", version: "1.1.0", main: "index.js" }), ); - await writeFile( - join(packageDirectory, "index.js"), - `exports.AgentCoreGatewayTargetSchema = ${schema};\n`, - ); + await writeFile(join(packageDirectory, "index.js"), index); return directory; } + /** A library that exports `AgentCoreGatewayTargetSchema` as `schema`, a JS text. */ + const exporting = (schema: string) => `exports.AgentCoreGatewayTargetSchema = ${schema};\n`; /** As each @aws/agentcore-cdk parses the passthrough of a target: with `gateway`, or `endpoint` only. */ - const WITH_GATEWAY = - "{ safeParse: (target) => ({ success: typeof target.passthrough.gateway === 'string' }) }"; - const ENDPOINT_ONLY = - "{ safeParse: (target) => ({ success: typeof target.passthrough.endpoint === 'string' }) }"; - - test.skipIf(!Bun.which("node"))( - "is true when the installed library accepts passthrough.gateway", - async () => { - expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(WITH_GATEWAY))).toBe( - true, - ); - }, + const WITH_GATEWAY = exporting( + "{ safeParse: (target) => ({ success: typeof target.passthrough.gateway === 'string' }) }", ); - - test.skipIf(!Bun.which("node"))( - "is false when the installed library requires passthrough.endpoint", - async () => { - expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(ENDPOINT_ONLY))).toBe( - false, - ); - }, + const ENDPOINT_ONLY = exporting( + "{ safeParse: (target) => ({ success: typeof target.passthrough.endpoint === 'string' }) }", ); + const withNode = test.skipIf(!Bun.which("node")); - test.skipIf(!Bun.which("node"))( - "is false when the library is not installed, or has no AgentCoreGatewayTargetSchema", - async () => { - expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting(undefined))).toBe( - false, - ); - expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryExporting("undefined"))).toBe( - false, - ); - }, - ); + withNode("accepts when the installed library accepts passthrough.gateway", async () => { + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryWithIndex(WITH_GATEWAY))).toEqual({ + accepts: true, + }); + }); + + withNode.each([ + ["requires passthrough.endpoint", ENDPOINT_ONLY], + ["has no AgentCoreGatewayTargetSchema", "exports.Other = 1;\n"], + ])("refuses when the installed library %s", async (_, index) => { + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryWithIndex(index))).toEqual({ + accepts: false, + reason: "refuses", + }); + }); + + withNode("says that the library is not installed", async () => { + expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryWithIndex(undefined))).toEqual({ + accepts: false, + reason: "not-installed", + }); + }); + + withNode("says that the check failed, with the error of the library", async () => { + const directory = await cdkDirectoryWithIndex('throw new Error("the library is broken");\n'); + expect(await cdkAcceptsPassthroughGateway(directory)).toEqual({ + accepts: false, + reason: "failed", + detail: "the library is broken", + }); + }); + + withNode("says that the check took too long", async () => { + const directory = await cdkDirectoryWithIndex("while (true) {}\n"); + expect(await cdkAcceptsPassthroughGateway(directory, { timeoutMs: 500 })).toEqual({ + accepts: false, + reason: "timed-out", + }); + }); + + test("says that build cannot run node", async () => { + const directory = await cdkDirectoryWithIndex(WITH_GATEWAY); + expect( + await cdkAcceptsPassthroughGateway(directory, { node: "/nonexistent/agentcore-test/node" }), + ).toEqual({ accepts: false, reason: "no-node" }); + }); }); diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index e3c7c81a5..61cb87b98 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -66,34 +66,68 @@ export async function cdkCompatibilityWarning(cdkDirectory: string): Promise { +/** The answer of {@link cdkAcceptsPassthroughGateway}, with the reason when it is not `accepts`. */ +export type PassthroughGatewayCheck = + | { readonly accepts: true } + | { + readonly accepts: false; + readonly reason: "refuses" | "not-installed" | "no-node" | "timed-out" | "failed"; + readonly detail?: string; + }; + +/** + * Asks the @aws/agentcore-cdk of the CDK app in `cdkDirectory` whether it accepts + * `passthrough.gateway`. Node runs the check in that folder, so it loads the same library as synth. + * Each answer other than `accepts` says why: the library refuses the field, is not installed, the + * check took more than `timeoutMs`, `node` is not there, or the check failed. + */ +export async function cdkAcceptsPassthroughGateway( + cdkDirectory: string, + options: { readonly node?: string; readonly timeoutMs?: number } = {}, +): Promise { + let stdout: string; try { - const { stdout } = await promisify(execFile)("node", ["-e", PASSTHROUGH_GATEWAY_CHECK], { - cwd: cdkDirectory, - timeout: 60_000, - }); - return stdout.trim() === "accepts"; - } catch { - return false; + ({ stdout } = await promisify(execFile)( + options.node ?? "node", + ["-e", PASSTHROUGH_GATEWAY_CHECK], + { cwd: cdkDirectory, timeout: options.timeoutMs ?? 60_000 }, + )); + } catch (error) { + const failure = error as NodeJS.ErrnoException & { killed?: boolean; stderr?: string }; + if (failure.code === "ENOENT") return { accepts: false, reason: "no-node" }; + if (failure.killed) return { accepts: false, reason: "timed-out" }; + const detail = (failure.stderr ?? failure.message).trim().split("\n")[0]; + return { accepts: false, reason: "failed", ...(detail && { detail }) }; } + const answer = stdout.trim(); + if (answer === "accepts") return { accepts: true }; + if (answer === "refuses" || answer === "not-installed") return { accepts: false, reason: answer }; + const detail = answer.replace(/^failed\s*/, ""); + return { accepts: false, reason: "failed", ...(detail && { detail }) }; } diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 76d0ad375..058e28df4 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -8,6 +8,7 @@ import type { AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; import { boxGatewaySpec, type ProjectSpec } from "../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; import { boxNetworkRules } from "../boxProfileResolver-test-support"; +import type { PassthroughGatewayCheck } from "../backends/cdk/compatibility"; import { boxGatewayIamWarnings, buildBoxNetwork } from "./network"; import { parseResolvedPolicy } from "./policyParser"; import { profilePlaces } from "./profileParser"; @@ -49,8 +50,8 @@ interface Options { /** The other gateways of the project, after the Box gateway. */ readonly gateways?: Record[]; readonly runtime?: Partial; - /** Whether the @aws/agentcore-cdk of the project accepts `passthrough.gateway`; true here. */ - readonly projectGatewayTargets?: boolean; + /** What the check of the @aws/agentcore-cdk of the project gives; it accepts here. */ + readonly projectGatewayCheck?: PassthroughGatewayCheck; } /** The local box profile of runtime `agent`. */ @@ -102,7 +103,7 @@ function model(policy: string, egress: Record = {}, options: Op region: "us-west-2", targets: options.targets ?? [], grantedActions: options.grantedActions ?? [], - projectGatewayTargets: options.projectGatewayTargets ?? true, + projectGatewayCheck: options.projectGatewayCheck ?? { accepts: true }, }); return { spec, @@ -1226,18 +1227,46 @@ describe("the gateways of the project", () => { expect(network.failures).toEqual([]); }); - test("gives the agent no gateway when the @aws/agentcore-cdk of the project refuses passthrough.gateway, and warns once", () => { - const { network } = model("", {}, { gateways: [TOOLS, OPEN], projectGatewayTargets: false }); - - expect(network.projectGateways).toEqual([]); - expect(network.failures).toEqual([]); - expect(network.warnings).toEqual([ - "The gateways 'tools' and 'open-tools' of this project get no route for a boxed agent on " + - "AgentCore Runtime, because the @aws/agentcore-cdk in agentcore/cdk does not accept " + - "passthrough.gateway. Update @aws/agentcore-cdk in agentcore/cdk/package.json to a " + - "version that accepts it, then build again.", - ]); - }); + test.each([ + [ + { accepts: false, reason: "refuses" }, + "the @aws/agentcore-cdk in agentcore/cdk does not accept passthrough.gateway. Update " + + "@aws/agentcore-cdk in agentcore/cdk/package.json to a version that accepts it, then " + + "build again.", + ], + [ + { accepts: false, reason: "not-installed" }, + "build found no @aws/agentcore-cdk in agentcore/cdk. Run npm install in agentcore/cdk, " + + "then build again.", + ], + [ + { accepts: false, reason: "no-node" }, + "build cannot run node to check the @aws/agentcore-cdk in agentcore/cdk. Put node on " + + "PATH, then build again.", + ], + [ + { accepts: false, reason: "timed-out" }, + "the check of the @aws/agentcore-cdk in agentcore/cdk took more than 60 seconds. Build " + + "again.", + ], + [ + { accepts: false, reason: "failed", detail: "the library is broken" }, + "the check of the @aws/agentcore-cdk in agentcore/cdk failed: the library is broken. " + + "Build again.", + ], + ] as const)( + "gives the agent no gateway, and one warning that says why, when the check gives %o", + (projectGatewayCheck, why) => { + const { network } = model("", {}, { gateways: [TOOLS, OPEN], projectGatewayCheck }); + + expect(network.projectGateways).toEqual([]); + expect(network.failures).toEqual([]); + expect(network.warnings).toEqual([ + "The gateways 'tools' and 'open-tools' of this project get no route for a boxed agent " + + `on AgentCore Runtime, because ${why}`, + ]); + }, + ); test("gives a PRIVATE_VPC runtime no gateway, as the CDK library binds none to it", () => { const { network } = model( diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index b0ff649c5..f15b76524 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -31,6 +31,7 @@ import { deriveRuntimeProfile } from "../runtimeProfile/derive"; import { defaultTracesTelemetry, runtimeProfileHeader } from "../runtimeProfile/rules/additions"; import type { TomlTable } from "../runtimeProfile/types"; import { withDeployRegion, type CloudWatchTelemetry } from "./telemetry"; +import type { PassthroughGatewayCheck } from "../backends/cdk/compatibility"; import { projectGatewaysOf, type BoxProjectGateway } from "./projectGateways"; import { outboundAuthWords, sameOutboundAuth, targetOutboundAuth } from "./projectSpec"; import { @@ -167,10 +168,11 @@ export interface BoxNetworkProject { /** The IAM actions that the gateway's `additionalPolicies` files grant, except build's own. */ readonly grantedActions: readonly string[]; /** - * Whether the @aws/agentcore-cdk of the project accepts a target with `passthrough.gateway` - * (`cdkAcceptsPassthroughGateway`); absent means it does not, and no gateway gets a target. + * What the check of the @aws/agentcore-cdk of the project gives for a target with + * `passthrough.gateway` (`cdkAcceptsPassthroughGateway`). Absent means no check, and no gateway + * of the project gets a target. */ - readonly projectGatewayTargets?: boolean; + readonly projectGatewayCheck?: PassthroughGatewayCheck; } /** The Box gateway of `runtime`: the gateway bound to it. */ @@ -212,7 +214,7 @@ export function buildBoxNetwork( const reached = projectGatewaysOf( project.spec, project.runtime, - project.projectGatewayTargets ?? false, + project.projectGatewayCheck ?? { accepts: false, reason: "refuses" }, ); const targets = hostTargets(map.hosts, project, reached.gateways, located, parsed.profile.path); failures.push(...targets.failures); diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index 6bf2f4671..7a850e604 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -8,6 +8,7 @@ import { createHash } from "node:crypto"; import type { AgentCoreGatewayTarget } from "../../../projectSchemas/gateway"; import { gatewayDiscoveryPrefix, type ProjectSpec } from "../../../projectSchemas/project"; import type { ProjectRuntime } from "../../../projectSchemas/runtime"; +import type { PassthroughGatewayCheck } from "../backends/cdk/compatibility"; import { BOX_EGRESS_TARGET_PREFIX, targetNameFor } from "./egress"; /** A gateway of the project that a boxed runtime calls through its Box gateway. */ @@ -55,7 +56,7 @@ function projectGatewayTargetName(name: string): string { export function projectGatewaysOf( spec: ProjectSpec, runtime: Pick, - targets = true, + check: PassthroughGatewayCheck = { accepts: true }, ): { gateways: BoxProjectGateway[]; warnings: string[] } { const gateways: BoxProjectGateway[] = []; const warnings: string[] = []; @@ -70,15 +71,13 @@ export function projectGatewaysOf( auth: gateway.authorizerType === "AWS_IAM" ? "iam" : "none", }); } - if (!targets && gateways.length > 0) { + if (!check.accepts && gateways.length > 0) { const names = gateways.map(({ name }) => `'${name}'`); const list = names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0]; warnings.push( `The gateways ${list} of this project get no route for a boxed agent on AgentCore ` + - "Runtime, because the @aws/agentcore-cdk in agentcore/cdk does not accept " + - "passthrough.gateway. Update @aws/agentcore-cdk in agentcore/cdk/package.json to a " + - "version that accepts it, then build again.", + `Runtime, because ${uncheckedBecause(check)}`, ); return { gateways: [], warnings }; } @@ -103,6 +102,29 @@ export function projectGatewayTargetFor( }; } +/** Why build writes no gateway target, from the check of the CDK library, and how to fix it. */ +function uncheckedBecause(check: Extract): string { + const library = "the @aws/agentcore-cdk in agentcore/cdk"; + switch (check.reason) { + case "refuses": + return ( + `${library} does not accept passthrough.gateway. Update @aws/agentcore-cdk in ` + + "agentcore/cdk/package.json to a version that accepts it, then build again." + ); + case "not-installed": + return ( + "build found no @aws/agentcore-cdk in agentcore/cdk. Run npm install in agentcore/cdk, " + + "then build again." + ); + case "no-node": + return `build cannot run node to check ${library}. Put node on PATH, then build again.`; + case "timed-out": + return `the check of ${library} took more than 60 seconds. Build again.`; + case "failed": + return `the check of ${library} failed: ${check.detail ?? "no error message"}. Build again.`; + } +} + /** What `add gateway` tells the user once about a `CUSTOM_JWT` gateway in a Box project. */ export function customJwtGatewayNotice(gatewayName: string): string { return ( diff --git a/src/core/project/boxNetworkSource.ts b/src/core/project/boxNetworkSource.ts index 0cbad886d..477c3a6ab 100644 --- a/src/core/project/boxNetworkSource.ts +++ b/src/core/project/boxNetworkSource.ts @@ -12,6 +12,7 @@ import type { ProjectSpec } from "../../projectSchemas/project"; import type { ProjectRuntime } from "../../projectSchemas/runtime"; import { InvalidEnvironmentError, ProjectStateError } from "../../errors/errors"; import type { PolicyFileCopy } from "./backends/boxContainer"; +import type { PassthroughGatewayCheck } from "./backends/cdk/compatibility"; import { DEFAULT_EGRESS_BEDROCK_REGION } from "../../handlers/project/shortcuts"; import { addBoxGatewayTargets, BOX_BEDROCK_POLICY_FILE, BOX_MEMORY_POLICY_FILE } from "./boxMemory"; import { @@ -55,8 +56,8 @@ export async function readBoxNetworks( projectRoot: string, resolver: BoxProfileResolver, region: string = DEFAULT_EGRESS_BEDROCK_REGION, - /** Whether the @aws/agentcore-cdk of the project accepts `passthrough.gateway`. */ - projectGatewayTargets = false, + /** What the check of the @aws/agentcore-cdk of the project gives for `passthrough.gateway`. */ + projectGatewayCheck?: PassthroughGatewayCheck, ): Promise { const runtimes = spec.runtimes.filter((runtime) => runtimeRunsInBox(spec, runtime)); if (runtimes.length === 0) return []; @@ -86,7 +87,7 @@ export async function readBoxNetworks( region, targets: entry.targets, grantedActions: granted.actions, - projectGatewayTargets, + ...(projectGatewayCheck && { projectGatewayCheck }), }); networks.push({ ...network, diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 008023650..f5671d12d 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -168,7 +168,8 @@ async function strandsProject( ...options.env, }, boxProfileResolver: box, - cdkAcceptsPassthroughGateway: async () => options.acceptsPassthroughGateway ?? false, + cdkAcceptsPassthroughGateway: async () => + options.acceptsPassthroughGateway ? { accepts: true } : { accepts: false, reason: "refuses" }, ...(options.backends && { backends: options.backends }), }); const { value: created, warnings: createWarnings } = await drain( diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index d49c3a029..4a043d970 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -132,7 +132,10 @@ import { import { isChinaRegion } from "../partition"; import z from "zod"; import { CdkBackend, type TransactionSearchEnabler } from "./backends/cdk"; -import { cdkAcceptsPassthroughGateway } from "./backends/cdk/compatibility"; +import { + cdkAcceptsPassthroughGateway, + type PassthroughGatewayCheck, +} from "./backends/cdk/compatibility"; import { customJwtGatewayNotice } from "./boxNetwork/projectGateways"; import { resolveAwsAccount } from "./backends/cdk/environment"; import { pinnedVersion } from "./backends/cdk/dependencies"; @@ -457,7 +460,7 @@ type ProjectManagerConfig = { * Whether the @aws/agentcore-cdk of the CDK app in a folder accepts a passthrough target with * `gateway`; build writes such a target only then. `cdkAcceptsPassthroughGateway` by default. */ - cdkAcceptsPassthroughGateway?: (cdkDirectory: string) => Promise; + cdkAcceptsPassthroughGateway?: (cdkDirectory: string) => Promise; backends?: Partial>; templateRenderer?: TemplateRenderer; /** @@ -482,7 +485,9 @@ export class FsProjectManager implements ProjectManager { private readonly resolveAccount: (region: string) => Promise; private readonly processEnv: NodeJS.ProcessEnv; private readonly boxProfileResolver: BoxProfileResolver; - private readonly cdkAcceptsPassthroughGateway: (cdkDirectory: string) => Promise; + private readonly cdkAcceptsPassthroughGateway: ( + cdkDirectory: string, + ) => Promise; constructor(config: ProjectManagerConfig) { this.logger = config.logger; @@ -1749,16 +1754,16 @@ export class FsProjectManager implements ProjectManager { // Only a box runtime and a gateway without boundRuntime need the check of the CDK app. const unbound = project.spec.agentCoreGateways.some(({ boundRuntime }) => !boundRuntime); const boxed = project.spec.runtimes.some((runtime) => runtimeRunsInBox(project.spec, runtime)); - const projectGatewayTargets = - unbound && - boxed && - (await this.cdkAcceptsPassthroughGateway(join(project.rootPath, "agentcore", "cdk"))); + const projectGatewayCheck = + unbound && boxed + ? await this.cdkAcceptsPassthroughGateway(join(project.rootPath, "agentcore", "cdk")) + : undefined; const networks = await readBoxNetworks( project.spec, project.rootPath, this.boxProfileResolver, region, - projectGatewayTargets, + projectGatewayCheck, ); if (networks.some(({ failures }) => failures.length > 0)) { throw new InputValidationError(boxNetworkFailureMessage(networks, command)); From 354eeea4f80bcf4429e4b0eb5cd52bac92520cd7 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 18:05:06 -0800 Subject: [PATCH 14/22] fix(box): Give the CUSTOM_JWT gateway notice also when add runtime adds a boxed runtime Review feedback: `customJwtGatewayNotice` came only from `add gateway`, when a boxed runtime was in the project already. A boxed runtime that `add runtime` adds after the gateway got no notice. `add runtime` now gives `customJwtGatewayNotice` after it writes agentcore.json, for each `CUSTOM_JWT` gateway without `boundRuntime`, when the new runtime runs in a box and is not `PRIVATE_VPC`. `docs/box-local-testing.md` says so. Test: in `manager.box.test.ts`, "add runtime gives the notice of each CUSTOM_JWT gateway without boundRuntime, as the new runtime is boxed" fails before this change. --- docs/box-local-testing.md | 3 ++- src/core/project/manager.box.test.ts | 31 ++++++++++++++++++++++++++++ src/core/project/manager.tsx | 12 +++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index 6f91bfe3e..32759fa1f 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -228,7 +228,8 @@ profile that names a pack `box/` fails: box refuses it and names the `@box the gateway's name. The L3 sets the target's endpoint to that gateway's URL, gives the Box gateway's role `bedrock-agentcore:InvokeGateway` on that gateway only, and sets `AGENTCORE_GATEWAY__URL` and `_HOST` on the runtime. A `PRIVATE_VPC` runtime gets none of - them. A `CUSTOM_JWT` gateway gets no target, and `agentcore add gateway` gives one notice for it. You write nothing for them. A profile + them. A `CUSTOM_JWT` gateway gets no target, and `agentcore add gateway`, and `agentcore add runtime` for a + box runtime, give one notice for it. You write nothing for them. A profile entry that signs for a gateway host with `aws://` stops build. Build writes these targets only when the `@aws/agentcore-cdk` in `agentcore/cdk` accepts `passthrough.gateway`: it asks that library with `node`. Otherwise build writes none of them, and gives one warning. diff --git a/src/core/project/manager.box.test.ts b/src/core/project/manager.box.test.ts index 7f77cd3b9..14fb8f348 100644 --- a/src/core/project/manager.box.test.ts +++ b/src/core/project/manager.box.test.ts @@ -13,6 +13,7 @@ import { boxGatewayLogsNotice, FsProjectManager } from "./manager"; import { newProjectSpec } from "./templates/project"; import { defaultLogTargetNotice } from "./runtimeProfile/rules/additions"; import { boxStartFolder, renderAwsMetadataPolicy } from "./templates/boxProfile"; +import { customJwtGatewayNotice } from "./boxNetwork/projectGateways"; import { boxGatewaySpec, ProjectSpecSchema } from "../../projectSchemas/project"; /** @@ -376,6 +377,36 @@ describe("gateway targets in a Box project", () => { expect(await specText(project)).toBe(before); }); + test("add runtime gives the notice of each CUSTOM_JWT gateway without boundRuntime, as the new runtime is boxed", async () => { + const manager = subject(); + const project = await createdProject(manager); + const spec = await specOnDisk(project); + spec.agentCoreGateways.push({ + name: "secure", + authorizerType: "CUSTOM_JWT", + authorizerConfiguration: { + customJwtAuthorizer: { + discoveryUrl: "https://idp.example.com/.well-known/openid-configuration", + allowedAudience: ["agentcore"], + }, + }, + protocolType: "MCP", + targets: [], + } as never); + await writeFile(join(project.rootPath, "agentcore", "agentcore.json"), JSON.stringify(spec)); + + const warnings: string[] = []; + const generator = manager.addResource(project, { + resourceType: "runtime", + resourceConfig: { name: "search", language: "Python", protocol: "HTTP" }, + } as never); + for (let next = await generator.next(); !next.done; next = await generator.next()) { + if (next.value.type === "warning") warnings.push(next.value.message); + } + + expect(warnings).toContain(customJwtGatewayNotice("secure")); + }); + test("add runtime gives the new runtime a box, its Box gateway, and its own box profile", async () => { const manager = subject(); const project = await createdProject(manager); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 4a043d970..86cebdfb0 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -1171,6 +1171,18 @@ export class FsProjectManager implements ProjectManager { yield* boxGatewayLogsWarnings( newProjectSpec.agentCoreGateways.filter(({ boundRuntime }) => boundRuntime === added), ); + // A new boxed runtime cannot call a CUSTOM_JWT gateway that is in the project already. + const runtime = newProjectSpec.runtimes.find(({ name }) => name === added); + if ( + runtime && + runtimeRunsInBox(newProjectSpec, runtime) && + runtime.containment !== "PRIVATE_VPC" + ) { + for (const gateway of newProjectSpec.agentCoreGateways) { + if (gateway.boundRuntime || gateway.authorizerType !== "CUSTOM_JWT") continue; + yield { type: "warning", message: customJwtGatewayNotice(gateway.name) }; + } + } } return { From ffe7eece3bfd8a2224ea1adb05d426605e2c9c36 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Fri, 20 Nov 2026 18:15:16 -0800 Subject: [PATCH 15/22] docs(box): Name the check parameter and add runtime in the comments of projectGateways.ts (comment of Leo on projectGateways.ts line 53) --- src/core/project/boxNetwork/projectGateways.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index 7a850e604..256ad6197 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -50,8 +50,9 @@ function projectGatewayTargetName(name: string): string { * The gateways of `spec` that `runtime` calls through its Box gateway: each gateway without * `boundRuntime`, as the CDK library binds it to a runtime without a box. A `PRIVATE_VPC` runtime * gets none, and no `CUSTOM_JWT` gateway, because the Box gateway cannot get its token; - * `add gateway` gives {@link customJwtGatewayNotice} for it once. With `targets` false, because the @aws/agentcore-cdk of the project refuses - * `passthrough.gateway`, the runtime gets none, and one warning names them. + * `add gateway` or `add runtime` gives {@link customJwtGatewayNotice} for it once. When `check` + * does not accept `passthrough.gateway`, the runtime gets none, and one warning names them and says + * why. */ export function projectGatewaysOf( spec: ProjectSpec, @@ -125,7 +126,7 @@ function uncheckedBecause(check: Extract Date: Mon, 23 Nov 2026 13:18:22 -0800 Subject: [PATCH 16/22] fix(box): Write no signing region for a gateway target, as the L3 signs in the region of the stack Review feedback: the signing region of a gateway-to-gateway target came from the spec, which build wrote with its own region. A stack in another region then signed for the wrong one. aws/agentcore-l3-cdk-constructs PR 478 (d87cfea) now signs such a target in the region of the stack, and its schema refuses a `region` on it. So that the two agree, `projectGatewayTargetFor` writes `GATEWAY_IAM_ROLE` with the service `bedrock-agentcore` and no region. The writer removes a region that an earlier build wrote. `unmanagedShape` takes `service,type` for such a target. The check of the CDK library parses a target with no region, so the new L3 accepts it. Tests that fail before this change: `projectGateways.test.ts`, "names the gateway and signs for AgentCore with no region ..."; `boxNetworkWriters.test.ts`, "adds a target that names each gateway ..." and "removes a region that an earlier build wrote ..."; `network.test.ts`, "keeps the target that build wrote for a gateway as build's own"; and the build test in `manager.boxNetwork.test.ts`. The check gives `refuses` for `@aws/agentcore-cdk` 1.1.0 from npm, and `accepts` for the build of PR 478 at d87cfea. --- src/core/project/backends/cdk/compatibility.ts | 2 +- src/core/project/boxNetwork/network.test.ts | 2 +- src/core/project/boxNetwork/network.ts | 5 ++++- src/core/project/boxNetwork/projectGateways.test.ts | 10 ++++------ src/core/project/boxNetwork/projectGateways.ts | 12 +++++------- src/core/project/boxNetworkWriters.test.ts | 4 ++-- src/core/project/boxNetworkWriters.ts | 4 ++-- src/core/project/manager.boxNetwork.test.ts | 2 +- src/projectSchemas/project.test.ts | 2 +- 9 files changed, 21 insertions(+), 22 deletions(-) diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index 61cb87b98..ee9983bf6 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -87,7 +87,7 @@ const accepts = name: "egress-gateway-check", targetType: "passthrough", passthrough: { gateway: "check", protocolType: "CUSTOM" }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-east-1" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, }).success === true; process.stdout.write(accepts ? "accepts" : "refuses"); `; diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 058e28df4..5c03d956b 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -1315,7 +1315,7 @@ describe("the gateways of the project", () => { name: "egress-gateway-tools", targetType: "passthrough", passthrough: { gateway: "tools", protocolType: "CUSTOM" }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, } as AgentCoreGatewayTarget; expect(model("", {}, { gateways: [TOOLS], targets: [written] }).failures()).toEqual([]); diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index f15b76524..9ca3d2540 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -567,7 +567,10 @@ function unmanagedShape(target: AgentCoreGatewayTarget): string | undefined { const fields = auth ? Object.keys(auth).sort().join(",") : ""; const shapes: Record = { NONE: ["type"], - GATEWAY_IAM_ROLE: ["region,service,type"], + // A target to a gateway of the project signs in the region of the stack, so it has no region. + GATEWAY_IAM_ROLE: [ + target.passthrough.gateway === undefined ? "region,service,type" : "service,type", + ], API_KEY: [ "credentialName,location,parameterName,type", "credentialName,location,parameterName,prefix,type", diff --git a/src/core/project/boxNetwork/projectGateways.test.ts b/src/core/project/boxNetwork/projectGateways.test.ts index cda03138f..cb5adc9d5 100644 --- a/src/core/project/boxNetwork/projectGateways.test.ts +++ b/src/core/project/boxNetwork/projectGateways.test.ts @@ -23,19 +23,17 @@ const TOOLS: BoxProjectGateway = { }; describe("projectGatewayTargetFor", () => { - test("names the gateway and signs for AgentCore in the build region, for an AWS_IAM gateway", () => { - expect(projectGatewayTargetFor(TOOLS, "us-west-2")).toEqual({ + test("names the gateway and signs for AgentCore with no region, which the L3 takes from the stack, for an AWS_IAM gateway", () => { + expect(projectGatewayTargetFor(TOOLS)).toEqual({ name: "egress-gateway-tools", targetType: "passthrough", passthrough: { gateway: "tools", protocolType: "CUSTOM" }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, }); }); test("sends no credential to a gateway that takes none", () => { - expect(projectGatewayTargetFor({ ...TOOLS, auth: "none" }, "us-west-2").outboundAuth).toBe( - undefined, - ); + expect(projectGatewayTargetFor({ ...TOOLS, auth: "none" }).outboundAuth).toBe(undefined); }); }); diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index 256ad6197..fd643e8d0 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -86,19 +86,17 @@ export function projectGatewaysOf( } /** - * The Box gateway target that calls `gateway`, signed for AgentCore in `region` for an `AWS_IAM` - * gateway. The CDK library sets its endpoint and grants the Box gateway's role `InvokeGateway`. + * The Box gateway target that calls `gateway`, signed for AgentCore for an `AWS_IAM` gateway. The + * CDK library sets its endpoint, signs in the region of the stack, where the gateway is, and grants + * the Box gateway's role `InvokeGateway`. Thus the target has no region. */ -export function projectGatewayTargetFor( - gateway: BoxProjectGateway, - region: string, -): AgentCoreGatewayTarget { +export function projectGatewayTargetFor(gateway: BoxProjectGateway): AgentCoreGatewayTarget { return { name: gateway.target, targetType: "passthrough", passthrough: { gateway: gateway.name, protocolType: "CUSTOM" }, ...(gateway.auth === "iam" && { - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, }), }; } diff --git a/src/core/project/boxNetworkWriters.test.ts b/src/core/project/boxNetworkWriters.test.ts index e502706d0..c0c63ac69 100644 --- a/src/core/project/boxNetworkWriters.test.ts +++ b/src/core/project/boxNetworkWriters.test.ts @@ -255,7 +255,7 @@ describe("gatewayTargetsWriter for the gateways of the project", () => { name: "egress-gateway-tools", targetType: "passthrough", passthrough: { gateway: "tools", protocolType: "CUSTOM" }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, }; test("adds a target that names each gateway, signed with the role only for an AWS_IAM gateway", () => { @@ -276,7 +276,7 @@ describe("gatewayTargetsWriter for the gateways of the project", () => { ]); }); - test("rewrites the target for the build region in place, and changes nothing the next time", () => { + test("removes a region that an earlier build wrote, as the L3 signs in the region of the stack, and changes nothing the next time", () => { const stale = { ...toolsTarget, outboundAuth: { ...toolsTarget.outboundAuth!, region: "us-east-1" }, diff --git a/src/core/project/boxNetworkWriters.ts b/src/core/project/boxNetworkWriters.ts index 2d92b92c2..03f1b22cb 100644 --- a/src/core/project/boxNetworkWriters.ts +++ b/src/core/project/boxNetworkWriters.ts @@ -271,7 +271,7 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { } const called = reached.find((candidate) => candidate.target === target.name); if (called) { - const written = projectGatewayTargetFor(called, network.region); + const written = projectGatewayTargetFor(called); if (!isDeepStrictEqual(written, target)) { messages.push( `updating gateway target '${target.name}' of ${gatewayName} for the gateway ` + @@ -310,7 +310,7 @@ function writeGatewayTargets(spec: ProjectSpec, network: BoxNetwork): string[] { } for (const called of reached) { if (existing.some(({ name }) => name === called.target)) continue; - targets.push(projectGatewayTargetFor(called, network.region)); + targets.push(projectGatewayTargetFor(called)); messages.push( `adding gateway target '${called.target}' to ${gatewayName}, for the boxed agent's calls ` + `to the gateway '${called.name}'`, diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index f5671d12d..85ab2d81e 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -706,7 +706,7 @@ describe("build routes the other gateways of the project for the boxed agent", ( name: "egress-gateway-tools", targetType: "passthrough", passthrough: { gateway: "tools", protocolType: "CUSTOM" }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, }); expect((await runtimeProfile(root)).mcp).toHaveProperty("tools"); expect(warnings.filter((warning) => warning.includes("passthrough.gateway"))).toEqual([]); diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index 58dbaf58a..a222ccbd2 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -625,7 +625,7 @@ describe("a passthrough target that names a gateway", () => { name, targetType: "passthrough", passthrough: { protocolType: "CUSTOM", ...passthrough }, - outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore", region: "us-west-2" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, }); const messages = (gateways: unknown[]) => { const result = ProjectSpecSchema.safeParse({ From 58a1168762dd1ec0461816e2bffc2af33db0143c Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 23 Nov 2026 13:19:32 -0800 Subject: [PATCH 17/22] fix(box): Stop build when a host takes again a target that a new gateway would get Review feedback on network.ts line 489: a host that takes again a target that build wrote before went into `owners` with no check. With `[egress.gateway-tools]` for `api.github.com`, one build, and then a gateway named `tools`, the next build rewrote `egress-gateway-tools` as the route to the gateway. The profile still sent `api.github.com` to that target, so the agent lost its GitHub route. Now each host that takes a target again goes through the check. When a gateway of the project gets the same target name, build stops with `TARGET_NAME_COLLISION` at the entry, and writes nothing. Tests that fail before this change: `network.test.ts`, "fails a gateway whose target has the name of the target that a host takes again", and `manager.boxNetwork.test.ts`, "stops, and keeps the route of a host, when a new gateway takes the name of its target", which does the steps of the review. --- src/core/project/boxNetwork/network.test.ts | 17 ++++++++++++ src/core/project/boxNetwork/network.ts | 16 +++++++++++- src/core/project/manager.boxNetwork.test.ts | 29 +++++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/core/project/boxNetwork/network.test.ts b/src/core/project/boxNetwork/network.test.ts index 5c03d956b..684ab65dc 100644 --- a/src/core/project/boxNetwork/network.test.ts +++ b/src/core/project/boxNetwork/network.test.ts @@ -1285,6 +1285,23 @@ describe("the gateways of the project", () => { expect(network.warnings).toEqual([]); }); + test("fails a gateway whose target has the name of the target that a host takes again", () => { + // An earlier build wrote egress-gateway-tools for [egress.gateway-tools]; then the gateway + // tools came, and build gives it that name too. + const held = passthrough("egress-gateway-tools", "https://api.github.com"); + const r = model( + "", + { "gateway-tools": { destinations: ["api.github.com"] } }, + { gateways: [TOOLS], targets: [held] }, + ); + + expect(r.failures()).toEqual([["TARGET_NAME_COLLISION", "gateway-tools"]]); + expect(r.reasons()[0]).toContain( + "takes the gateway target 'egress-gateway-tools' for api.github.com, and the target that " + + "build adds for the gateway 'tools' has that name.", + ); + }); + test("fails two gateways whose targets still have one name, as for two hosts", () => { // The target of "a--b" ends in the hash of its name, which a second gateway can have as a name. const hash = createHash("sha256").update("a--b").digest("hex").slice(0, 8); diff --git a/src/core/project/boxNetwork/network.ts b/src/core/project/boxNetwork/network.ts index 9ca3d2540..d02e02839 100644 --- a/src/core/project/boxNetwork/network.ts +++ b/src/core/project/boxNetwork/network.ts @@ -491,7 +491,21 @@ function hostTargets( } const describeHost = (host: MappedHost) => host.entry ? `${entryLabel(host.entry)} for ${host.authority}` : `the host ${host.authority}`; - for (const index of reused) owners.set(hosts[index]!.target!, describeHost(mapped[index]!)); + for (const index of reused) { + const name = hosts[index]!.target!; + const gateway = gatewayOf.get(name); + if (gateway !== undefined) { + // The host keeps its target, so the gateway cannot have that name. + failAt( + mapped[index]!, + "TARGET_NAME_COLLISION", + `takes the gateway target '${name}' for ${hosts[index]!.authority}, and the target that ` + + `build adds for the gateway '${gateway}' has that name. Rename the entry or the gateway.`, + ); + continue; + } + owners.set(name, describeHost(mapped[index]!)); + } mapped.forEach((host, index) => { const name = hosts[index]!.target; if (name === undefined || reused.has(index)) return; diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 85ab2d81e..29984f9bd 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -800,6 +800,35 @@ describe("build routes the other gateways of the project for the boxed agent", ( expect(built.warnings.filter((warning) => warning.includes("CUSTOM_JWT"))).toEqual([]); }); + test("stops, and keeps the route of a host, when a new gateway takes the name of its target", async () => { + const { manager, root, box } = await strandsProject({ + acceptsPassthroughGateway: true, + env: { GITHUB_TOKEN: "ghp_123" }, + }); + await editProfile(root, { + tables: + '\n[egress.gateway-tools]\ndestinations = ["api.github.com"]\nsecret.ref = "env://GITHUB_TOKEN"\n', + }); + box.answer = shows({ "gateway-tools": GITHUB }); + await build(manager, root); + const before = await text(root, SPEC); + expect(await targetNames(root)).toContain("egress-gateway-tools"); + await addToolsGateway(root); + const added = await text(root, SPEC); + + await expect(build(manager, root)).rejects.toThrow( + "takes the gateway target 'egress-gateway-tools' for api.github.com", + ); + + expect(await text(root, SPEC)).toBe(added); + expect(JSON.parse(before).agentCoreGateways[0].targets).toContainEqual( + expect.objectContaining({ + name: "egress-gateway-tools", + passthrough: { endpoint: "https://api.github.com", protocolType: "CUSTOM" }, + }), + ); + }); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); From 6deafe34983cf479f6da357ce66cc2a6e6ed550b Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 23 Nov 2026 13:20:06 -0800 Subject: [PATCH 18/22] fix(box): Stop build for a gateway with the name of a server that the policy denies Review feedback on gateway.ts line 88: an HTTP `[mcp.tools]` that the policy denies gets no route, so the rule left it out of `mcp`. The check of the gateway name then passed, and a gateway named `tools` took the name of the server. A policy rule with `context.input.server == "tools"` then applied to a different backend. The check now looks at the `[mcp]` table of the local profile too. A gateway with the name of a server there, with a route or not, stops build with `RUNTIME_GATEWAY_SERVER_NAME_TAKEN`. Test: `gateway.test.ts`, "stops for an HTTP server of the local profile with the gateway's name that the policy denies", fails before this change. --- .../project/runtimeProfile/rules/gateway.test.ts | 14 ++++++++++++++ src/core/project/runtimeProfile/rules/gateway.ts | 5 ++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/core/project/runtimeProfile/rules/gateway.test.ts b/src/core/project/runtimeProfile/rules/gateway.test.ts index b04f17ba9..9db14461a 100644 --- a/src/core/project/runtimeProfile/rules/gateway.test.ts +++ b/src/core/project/runtimeProfile/rules/gateway.test.ts @@ -762,6 +762,20 @@ describe("the gateway rule for a gateway of the project", () => { expect(Object.keys(result.table.mcp as TomlTable)).toEqual(["constructor"]); }); + test("stops for an HTTP server of the local profile with the gateway's name that the policy denies", () => { + const text = `${PROFILE_TEXT}\n[mcp.tools]\ntype = "http"\ndestinations = ["tools.example.com"]\n`; + // The policy denies the server's host, so the server gets no route and no [mcp] entry. + const denied = host("tools.example.com", server("tools", "tools.example.com")); + const result = apply(parse(text) as TomlTable, { + ...contextOf(text, [denied]), + projectGateways: [TOOLS], + }); + + expect(result.problems.map(({ code, key }) => [code, key])).toEqual([ + ["RUNTIME_GATEWAY_SERVER_NAME_TAKEN", ["mcp", "tools"]], + ]); + }); + test("stops for a server of the local profile with the gateway's name", () => { const text = `${PROFILE_TEXT}\n[mcp.tools]\ncommand = ["/usr/bin/tools"]\n`; diff --git a/src/core/project/runtimeProfile/rules/gateway.ts b/src/core/project/runtimeProfile/rules/gateway.ts index 45893ae08..487d636ea 100644 --- a/src/core/project/runtimeProfile/rules/gateway.ts +++ b/src/core/project/runtimeProfile/rules/gateway.ts @@ -99,9 +99,12 @@ export function apply(table: Readonly, context: RuntimeProfileContext } } + // A server of the local profile keeps its name, also one that gets no route here, because the + // policy names it; a gateway of the project cannot take that name. + const local = isTable(table.mcp) ? table.mcp : {}; const problems: RuntimeProfileProblem[] = []; for (const gateway of context.projectGateways ?? []) { - if (Object.hasOwn(mcp, gateway.name)) { + if (Object.hasOwn(mcp, gateway.name) || Object.hasOwn(local, gateway.name)) { problems.push({ code: "RUNTIME_GATEWAY_SERVER_NAME_TAKEN", key: ["mcp", gateway.name], From 3a2c57648d4defb15c72938cdeba0231e0c24066 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 23 Nov 2026 13:22:05 -0800 Subject: [PATCH 19/22] fix(box): Stop build, and write nothing, when it cannot check the CDK library Review feedback on projectGateways.ts line 75: `timed-out`, `failed`, `no-node`, and `not-installed` took the same path as `refuses`. Thus a transient failure removed each `egress-gateway-*` target, the `[mcp]` server, and the pack inputs, and a deploy then removed the tools of the agent. `not-installed` rewrote agentcore.json, and then stopped with "CDK dependencies are missing". Only `refuses` is an answer about the library, so only `refuses` lets build remove the targets. For each other reason, `applyBoxNetwork` stops the build or the deploy before it writes, with the reason and its fix: "Build stopped, and wrote nothing: build cannot tell if it can route the gateways 'tools' of this project for a boxed agent, because ...". I chose the stop, and not a warning that keeps the targets, because a stop changes nothing that the last build wrote, also when there was no earlier build. `docs/box-local-testing.md` says so. Tests: in `manager.boxNetwork.test.ts`, "stops, and keeps the target and agentcore.json, when the check gives ..." for `not-installed`, `no-node`, `timed-out`, and `failed` fail before this change. Each builds once with the target, then checks that agentcore.json and the Runtime profile do not change. --- docs/box-local-testing.md | 4 +- .../project/boxNetwork/projectGateways.ts | 31 +++++++++--- src/core/project/manager.boxNetwork.test.ts | 47 ++++++++++++++++++- src/core/project/manager.tsx | 25 +++++++++- 4 files changed, 98 insertions(+), 9 deletions(-) diff --git a/docs/box-local-testing.md b/docs/box-local-testing.md index 32759fa1f..3ed089a72 100644 --- a/docs/box-local-testing.md +++ b/docs/box-local-testing.md @@ -232,7 +232,9 @@ profile that names a pack `box/` fails: box refuses it and names the `@box box runtime, give one notice for it. You write nothing for them. A profile entry that signs for a gateway host with `aws://` stops build. Build writes these targets only when the `@aws/agentcore-cdk` in `agentcore/cdk` accepts `passthrough.gateway`: it asks that library - with `node`. Otherwise build writes none of them, and gives one warning. + with `node`. When the library refuses the field, build writes none of them, removes the ones it + wrote before, and gives one warning. When build cannot do the check (no `node_modules`, no `node`, + a check that takes more than 60 seconds, or one that fails), it stops and writes nothing. - **Outbound auth.** An `aws://` secret signs with the gateway's role, an `env://` secret sends an API key from AgentCore Identity, and an entry with no secret sends no credential. - **Failures.** A profile Box refuses stops build and deploy with box's own error. A wildcard host, diff --git a/src/core/project/boxNetwork/projectGateways.ts b/src/core/project/boxNetwork/projectGateways.ts index fd643e8d0..a46f44cd4 100644 --- a/src/core/project/boxNetwork/projectGateways.ts +++ b/src/core/project/boxNetwork/projectGateways.ts @@ -73,12 +73,9 @@ export function projectGatewaysOf( }); } if (!check.accepts && gateways.length > 0) { - const names = gateways.map(({ name }) => `'${name}'`); - const list = - names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names[0]; warnings.push( - `The gateways ${list} of this project get no route for a boxed agent on AgentCore ` + - `Runtime, because ${uncheckedBecause(check)}`, + `The gateways ${gatewayList(gateways.map(({ name }) => name))} of this project get no ` + + `route for a boxed agent on AgentCore Runtime, because ${uncheckedBecause(check)}`, ); return { gateways: [], warnings }; } @@ -102,7 +99,9 @@ export function projectGatewayTargetFor(gateway: BoxProjectGateway): AgentCoreGa } /** Why build writes no gateway target, from the check of the CDK library, and how to fix it. */ -function uncheckedBecause(check: Extract): string { +export function uncheckedBecause( + check: Extract, +): string { const library = "the @aws/agentcore-cdk in agentcore/cdk"; switch (check.reason) { case "refuses": @@ -124,6 +123,26 @@ function uncheckedBecause(check: Extract[], +): string[] { + const names = runtimes.flatMap((runtime) => + projectGatewaysOf(spec, runtime).gateways.map(({ name }) => name), + ); + return [...new Set(names)]; +} + +/** The quoted names of `names`, as a list in a sentence: `'a', 'b' and 'c'`. */ +export function gatewayList(names: readonly string[]): string { + const quoted = names.map((name) => `'${name}'`); + return quoted.length > 1 ? `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}` : quoted[0]!; +} + /** What `add gateway` or `add runtime` tells the user once about a `CUSTOM_JWT` gateway in a Box project. */ export function customJwtGatewayNotice(gatewayName: string): string { return ( diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 29984f9bd..caa8730d2 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -16,6 +16,7 @@ import { seedBoxCache } from "./backends/box-release-test-support"; import { BOX_RELEASE } from "./backends/boxRelease"; import { boxGatewayLogsNotice, FsProjectManager } from "./manager"; import { renderAwsMetadataPolicy } from "./templates/boxProfile"; +import type { PassthroughGatewayCheck } from "./backends/cdk/compatibility"; /** The golden files of this suite; `RECORD=1 bun test ` rewrites them, with no AWS call. */ const FIXTURES = join(import.meta.dir, "__fixtures__"); @@ -149,6 +150,8 @@ async function strandsProject( env?: NodeJS.ProcessEnv; /** What the probe of agentcore/cdk answers; it refuses passthrough.gateway when absent. */ acceptsPassthroughGateway?: boolean; + /** What the probe answers, in place of `acceptsPassthroughGateway`; a test can change it. */ + check?: { current: PassthroughGatewayCheck }; } = {}, ) { const directory = await temporary("agentcore-box-network-"); @@ -169,7 +172,10 @@ async function strandsProject( }, boxProfileResolver: box, cdkAcceptsPassthroughGateway: async () => - options.acceptsPassthroughGateway ? { accepts: true } : { accepts: false, reason: "refuses" }, + options.check?.current ?? + (options.acceptsPassthroughGateway + ? { accepts: true } + : { accepts: false, reason: "refuses" }), ...(options.backends && { backends: options.backends }), }); const { value: created, warnings: createWarnings } = await drain( @@ -829,6 +835,45 @@ describe("build routes the other gateways of the project for the boxed agent", ( ); }); + test.each([ + [ + { accepts: false, reason: "not-installed" }, + "build found no @aws/agentcore-cdk in agentcore/cdk. Run npm install in agentcore/cdk, then build again.", + ], + [ + { accepts: false, reason: "no-node" }, + "build cannot run node to check the @aws/agentcore-cdk in agentcore/cdk. Put node on PATH, then build again.", + ], + [ + { accepts: false, reason: "timed-out" }, + "the check of the @aws/agentcore-cdk in agentcore/cdk took more than 60 seconds. Build again.", + ], + [ + { accepts: false, reason: "failed", detail: "the library is broken" }, + "the check of the @aws/agentcore-cdk in agentcore/cdk failed: the library is broken. Build again.", + ], + ] as const)( + "stops, and keeps the target and agentcore.json, when the check gives %o", + async (answer, why) => { + const check: { current: PassthroughGatewayCheck } = { current: { accepts: true } }; + const { manager, root } = await strandsProject({ check }); + await addToolsGateway(root); + await build(manager, root); + const before = await text(root, SPEC); + const profile = await text(root, RUNTIME_PROFILE); + check.current = answer; + + await expect(build(manager, root)).rejects.toThrow( + "Build stopped, and wrote nothing: build cannot tell if it can route the gateways 'tools' " + + `of this project for a boxed agent, because ${why}`, + ); + + expect(await text(root, SPEC)).toBe(before); + expect(await text(root, RUNTIME_PROFILE)).toBe(profile); + expect(await targetNames(root)).toContain("egress-gateway-tools"); + }, + ); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 86cebdfb0..856272915 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -136,7 +136,12 @@ import { cdkAcceptsPassthroughGateway, type PassthroughGatewayCheck, } from "./backends/cdk/compatibility"; -import { customJwtGatewayNotice } from "./boxNetwork/projectGateways"; +import { + customJwtGatewayNotice, + gatewayList, + reachedGatewayNames, + uncheckedBecause, +} from "./boxNetwork/projectGateways"; import { resolveAwsAccount } from "./backends/cdk/environment"; import { pinnedVersion } from "./backends/cdk/dependencies"; import type { ProjectBackend } from "./backends/types"; @@ -1770,6 +1775,24 @@ export class FsProjectManager implements ProjectManager { unbound && boxed ? await this.cdkAcceptsPassthroughGateway(join(project.rootPath, "agentcore", "cdk")) : undefined; + // Only a library that refuses passthrough.gateway is an answer; build then removes the + // gateway targets. For each other reason, the command stops before it writes, so a transient + // failure keeps the targets that a deploy needs. + if ( + projectGatewayCheck && + !projectGatewayCheck.accepts && + projectGatewayCheck.reason !== "refuses" + ) { + const boxRuntimes = project.spec.runtimes.filter((runtime) => + runtimeRunsInBox(project.spec, runtime), + ); + const names = reachedGatewayNames(project.spec, boxRuntimes); + throw new ProjectStateError( + `${command === "build" ? "Build" : "Deploy"} stopped, and wrote nothing: build cannot ` + + `tell if it can route the gateways ${gatewayList(names)} of this project for a boxed ` + + `agent, because ${uncheckedBecause(projectGatewayCheck)}`, + ); + } const networks = await readBoxNetworks( project.spec, project.rootPath, From cccb0ecd5b2ca1c2ec17baf5d1084da522615fa3 Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 23 Nov 2026 13:24:55 -0800 Subject: [PATCH 20/22] perf(box): Load only dist/schema of the CDK library, and do the check only when a gateway needs it Review feedback on compatibility.ts line 46: the check loaded the whole `@aws/agentcore-cdk` package, with its constructs, on each build and deploy of a project with a box runtime and a gateway without `boundRuntime`. It did this also when no gateway could get a target: a `CUSTOM_JWT` gateway only, or a `PRIVATE_VPC` runtime. - The check script finds the package with `require.resolve` and loads `dist/schema` by path. It loads the whole package only when the package has no `dist/schema`. - `applyBoxNetwork` does the check only when a boxed runtime calls a gateway through its Box gateway (`reachedGatewayNames`), so the cases above start no `node`. Time of one check with `cdkAcceptsPassthroughGateway`, 5 runs on a MacBook with Node 26.12.1: before, 104 to 107 ms for the build of aws/agentcore-l3-cdk-constructs PR 478 and 102 to 160 ms for `@aws/agentcore-cdk` 1.1.0; after, 69 to 83 ms and 70 to 78 ms. With no compile cache, the load in `node` takes 0.10 to 0.11 s for the whole package and 0.05 to 0.06 s for `dist/schema`. This machine is faster than the one of the review, which measured 6 to 10 s and 2.6 s. Tests that fail before this change: `compatibility.test.ts`, "loads only dist/schema of the library, and not the constructs", with a package whose entry throws; and `manager.boxNetwork.test.ts`, "does not check the CDK library when no gateway gets a target" for a `CUSTOM_JWT` gateway only and for a `PRIVATE_VPC` runtime. --- .../backends/cdk/compatibility.test.ts | 19 +++++++++ .../project/backends/cdk/compatibility.ts | 15 +++++-- src/core/project/manager.boxNetwork.test.ts | 42 +++++++++++++++++++ src/core/project/manager.tsx | 17 ++++---- 4 files changed, 81 insertions(+), 12 deletions(-) diff --git a/src/core/project/backends/cdk/compatibility.test.ts b/src/core/project/backends/cdk/compatibility.test.ts index afaeb70da..c26f7d6ea 100644 --- a/src/core/project/backends/cdk/compatibility.test.ts +++ b/src/core/project/backends/cdk/compatibility.test.ts @@ -145,6 +145,25 @@ describe("cdkAcceptsPassthroughGateway", () => { }); }); + withNode("loads only dist/schema of the library, and not the constructs", async () => { + const directory = await mkdtemp(join(tmpdir(), "agentcore-cdk-passthrough-gateway-")); + tempDirectories.push(directory); + const packageDirectory = join(directory, "node_modules", "@aws", "agentcore-cdk"); + await mkdir(join(packageDirectory, "dist", "schema"), { recursive: true }); + await writeFile( + join(packageDirectory, "package.json"), + JSON.stringify({ name: "@aws/agentcore-cdk", version: "1.1.0", main: "./dist/index.js" }), + ); + // The entry of the package loads the constructs, which a check does not need. + await writeFile( + join(packageDirectory, "dist", "index.js"), + 'throw new Error("the check loaded the constructs");\n', + ); + await writeFile(join(packageDirectory, "dist", "schema", "index.js"), WITH_GATEWAY); + + expect(await cdkAcceptsPassthroughGateway(directory)).toEqual({ accepts: true }); + }); + withNode("says that the library is not installed", async () => { expect(await cdkAcceptsPassthroughGateway(await cdkDirectoryWithIndex(undefined))).toEqual({ accepts: false, diff --git a/src/core/project/backends/cdk/compatibility.ts b/src/core/project/backends/cdk/compatibility.ts index ee9983bf6..450c4db54 100644 --- a/src/core/project/backends/cdk/compatibility.ts +++ b/src/core/project/backends/cdk/compatibility.ts @@ -68,13 +68,22 @@ export async function cdkCompatibilityWarning(cdkDirectory: string): Promise { + let checks = 0; + const check = { + get current(): PassthroughGatewayCheck { + checks++; + return { accepts: true }; + }, + }; + const { manager, root } = await strandsProject({ check }); + await addToolsGateway(root); + const spec = JSON.parse(await text(root, SPEC)); + Object.assign( + spec.agentCoreGateways.find(({ name }: { name: string }) => name === "tools"), + gatewayFields, + ); + Object.assign(spec.runtimes[0], runtimeFields); + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + + await build(manager, root); + + expect(checks).toBe(0); + expect(await targetNames(root)).not.toContain("egress-gateway-tools"); + }, + ); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index 856272915..bf4213005 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -1768,11 +1768,14 @@ export class FsProjectManager implements ProjectManager { command: "build" | "deploy", region: string, ): Promise<{ project: Project; networks: BoxNetwork[]; events: ProjectEvent[] }> { - // Only a box runtime and a gateway without boundRuntime need the check of the CDK app. - const unbound = project.spec.agentCoreGateways.some(({ boundRuntime }) => !boundRuntime); - const boxed = project.spec.runtimes.some((runtime) => runtimeRunsInBox(project.spec, runtime)); + // Only a gateway that a boxed runtime calls through its Box gateway needs the check of the CDK + // app: none for a CUSTOM_JWT gateway or a PRIVATE_VPC runtime. + const boxRuntimes = project.spec.runtimes.filter((runtime) => + runtimeRunsInBox(project.spec, runtime), + ); + const reached = reachedGatewayNames(project.spec, boxRuntimes); const projectGatewayCheck = - unbound && boxed + reached.length > 0 ? await this.cdkAcceptsPassthroughGateway(join(project.rootPath, "agentcore", "cdk")) : undefined; // Only a library that refuses passthrough.gateway is an answer; build then removes the @@ -1783,13 +1786,9 @@ export class FsProjectManager implements ProjectManager { !projectGatewayCheck.accepts && projectGatewayCheck.reason !== "refuses" ) { - const boxRuntimes = project.spec.runtimes.filter((runtime) => - runtimeRunsInBox(project.spec, runtime), - ); - const names = reachedGatewayNames(project.spec, boxRuntimes); throw new ProjectStateError( `${command === "build" ? "Build" : "Deploy"} stopped, and wrote nothing: build cannot ` + - `tell if it can route the gateways ${gatewayList(names)} of this project for a boxed ` + + `tell if it can route the gateways ${gatewayList(reached)} of this project for a boxed ` + `agent, because ${uncheckedBecause(projectGatewayCheck)}`, ); } From 92a6db7f846e9aac219896cd8681371b589a2b6d Mon Sep 17 00:00:00 2001 From: Sai Abhishek Date: Mon, 23 Nov 2026 13:26:18 -0800 Subject: [PATCH 21/22] fix(remove): Remove only a target that build owns when the gateway that it names goes Review feedback on manager.tsx line 1306: `remove gateway` used `isManagedTarget`, which checks only the `egress-` prefix of the name. Thus `remove gateway tools` also removed a hand-written `egress-mine` target on an ordinary gateway `front` that names `tools`. The rule of the schema moves out of `superRefine` into the exported `isBuildOwnedTarget(spec, gateway, target)` in `projectSchemas/project.ts`: an `egress-` target on a gateway with `boundRuntime`, in a Box project. The schema and `remove gateway` both use it. `remove gateway` keeps a target of the user, and the schema refuses it with its name, so the user removes it. Test: `manager.boxNetwork.test.ts`, "remove gateway keeps an egress- target that the user wrote on an ordinary gateway", fails before this change. --- src/core/project/manager.boxNetwork.test.ts | 28 +++++++++++++++++++++ src/core/project/manager.tsx | 8 ++++-- src/projectSchemas/project.ts | 28 ++++++++++++++------- 3 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/core/project/manager.boxNetwork.test.ts b/src/core/project/manager.boxNetwork.test.ts index 03fb61145..52ea781a7 100644 --- a/src/core/project/manager.boxNetwork.test.ts +++ b/src/core/project/manager.boxNetwork.test.ts @@ -916,6 +916,34 @@ describe("build routes the other gateways of the project for the boxed agent", ( }, ); + test("remove gateway keeps an egress- target that the user wrote on an ordinary gateway", async () => { + const { manager, root } = await strandsProject({ acceptsPassthroughGateway: true }); + await addToolsGateway(root); + const spec = JSON.parse(await text(root, SPEC)); + spec.agentCoreGateways.push({ + name: "front", + authorizerType: "AWS_IAM", + protocolType: "None", + targets: [ + { + name: "egress-mine", + targetType: "passthrough", + passthrough: { gateway: "tools", protocolType: "CUSTOM" }, + outboundAuth: { type: "GATEWAY_IAM_ROLE", service: "bedrock-agentcore" }, + }, + ], + }); + await writeFile(path(root, SPEC), JSON.stringify(spec, undefined, 2)); + const before = await text(root, SPEC); + const project = (await manager.resolve({ filePath: root })) as Project; + + // The target is the user's, so remove keeps it, and the schema refuses it with its name. + await expect( + manager.removeResource(project, { resourceType: "gateway", name: "tools" }), + ).rejects.toThrow('Target "egress-mine" of gateway "front" names the gateway "tools"'); + expect(await text(root, SPEC)).toBe(before); + }); + test("writes no target and no server, and warns once, when it does not", async () => { const { manager, root } = await strandsProject({ acceptsPassthroughGateway: false }); await addToolsGateway(root); diff --git a/src/core/project/manager.tsx b/src/core/project/manager.tsx index bf4213005..75ef58d74 100644 --- a/src/core/project/manager.tsx +++ b/src/core/project/manager.tsx @@ -55,7 +55,7 @@ import { harnessApiKeyCredentialName, validateHarnessTemplateSource, } from "./templates/harness"; -import { boxGatewayIamWarnings, isManagedTarget, type BoxNetwork } from "./boxNetwork"; +import { boxGatewayIamWarnings, type BoxNetwork } from "./boxNetwork"; import { reservedBoxTargetNameProblem } from "./boxMemory"; import { boxNetworkFailureMessage, readBoxNetworks } from "./boxNetworkSource"; import { resolveRegion } from "../region"; @@ -100,6 +100,7 @@ import { boxGatewaySpec, isBoundGateway, isBoxProject, + isBuildOwnedTarget, ProjectSpecSchema, type ManagedBy, } from "../../projectSchemas/project"; @@ -1346,7 +1347,10 @@ export class FsProjectManager implements ProjectManager { ...gateway, targets: gateway.targets.filter( (target) => - !(isManagedTarget(target) && target.passthrough?.gateway === input.name), + !( + isBuildOwnedTarget(existingProjectSpec, gateway, target) && + target.passthrough?.gateway === input.name + ), ), })), }; diff --git a/src/projectSchemas/project.ts b/src/projectSchemas/project.ts index f318f5541..293db9f6a 100644 --- a/src/projectSchemas/project.ts +++ b/src/projectSchemas/project.ts @@ -41,6 +41,22 @@ export const isBoxProject = (spec: { projectType?: string }) => spec.projectType * target whose name has it, and no other. */ export const BOX_EGRESS_TARGET_PREFIX = "egress-"; +/** + * Whether build writes and removes `target` of `gateway`: a target whose name starts with + * {@link BOX_EGRESS_TARGET_PREFIX}, on the Box gateway of a runtime (a gateway with + * `boundRuntime`), in a project with `"projectType": "box"`. + */ +export function isBuildOwnedTarget( + spec: { projectType?: string }, + gateway: { boundRuntime?: string }, + target: { name: string }, +): boolean { + return ( + isBoxProject(spec) && + gateway.boundRuntime !== undefined && + target.name.startsWith(BOX_EGRESS_TARGET_PREFIX) + ); +} /** The suffix of each Box gateway name: the runtime `agent` gets the gateway `agent-box-egress`. */ export const BOX_GATEWAY_SUFFIX = "-box-egress"; /** @@ -187,18 +203,12 @@ export const ProjectSpecSchema = z } } // A passthrough target that names a gateway calls a gateway of this project. A gateway bound to - // a runtime belongs to that runtime, so no target of another gateway calls it. On the Box - // gateway of a runtime of a Box project, build writes and removes each target whose name starts - // with BOX_EGRESS_TARGET_PREFIX, so such a target that names no such gateway is not refused - // here: the next build removes it. - const buildOwns = (gateway: { boundRuntime?: string }, target: { name: string }) => - isBoxProject(spec) && - isBoundGateway(gateway) && - target.name.startsWith(BOX_EGRESS_TARGET_PREFIX); + // a runtime belongs to that runtime, so no target of another gateway calls it. A target that + // build owns and that names no such gateway is not refused here: the next build removes it. for (const gateway of spec.agentCoreGateways) { for (const target of gateway.targets) { const reached = target.passthrough?.gateway; - if (reached === undefined || buildOwns(gateway, target)) continue; + if (reached === undefined || isBuildOwnedTarget(spec, gateway, target)) continue; const named = spec.agentCoreGateways.find((other) => other.name === reached); const problem = named === undefined From db61a73dd6d03cd41d0273d74eff126bf5ee9a8e Mon Sep 17 00:00:00 2001 From: Varun Gunda Date: Mon, 23 Nov 2026 23:03:08 -0800 Subject: [PATCH 22/22] test(schema): Give the runtime of the Box-project fixture platformVersion V2 After box-integration PR 2879, every runtime of a Box project needs "platformVersion": "V2". The fixture of "a target that build owns" had no platformVersion, so the two "is accepted on the Box gateway of a Box project" cases failed with 'Runtime "agent" has no platformVersion'. The fixture now sets V2 only for a Box project. The other cases stay the same. --- src/projectSchemas/project.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/projectSchemas/project.test.ts b/src/projectSchemas/project.test.ts index a222ccbd2..8a21ccf07 100644 --- a/src/projectSchemas/project.test.ts +++ b/src/projectSchemas/project.test.ts @@ -678,7 +678,7 @@ describe("a passthrough target that names a gateway", () => { const result = ProjectSpecSchema.safeParse({ ...minimalProject, ...(projectType && { projectType }), - runtimes: [runtime], + runtimes: [projectType === "box" ? { ...runtime, platformVersion: "V2" } : runtime], agentCoreGateways: gateways, }); return result.success ? [] : result.error.issues.map(({ message }) => message);