1.4 Partner API Management & Token Monetization with Apigee X¶
In 1.3 The Private Front Door & Pluggable Gateways, we saw how internal workloads inside Garimpo's VPC call *.esmeralda.internal through the internal HTTPS load balancer (entrypoint), using the built-in direct backend by default. And in 2.1 Central Agent Gateway & Private PKI, we will see how every internal AI agent's outbound traffic is governed by Google's Central Agent Gateway using attested SPIFFE Agent Identities (principal://).
But what happens when the business wants to expose Camila Rocha's order support workflow to external B2B partners—such as resale marketplaces that list Garimpo's vintage stock, partner shipping and logistics apps, or external shopping assistants?
External partners sit outside our Google Cloud organization:
- They do not have internal SPIFFE identities or GCP IAM service accounts. They authenticate with commercial API keys (
x-api-key) or OAuth 2.0 client credentials provisioned through a developer portal. - They must never be allowed to call internal specialist agents or raw MCP tools directly. A partner app may call the front-door
support-assistant, or a curated read-only MCP tool (get_order), but must receive an immediateHTTP 403if it tries to invokeorder-ops-specialistdirectly or call administrative MCP tools. - They require contractual LLM token quotas and billing attribution. If a Bronze-tier partner is contracted for 10,000 Gemini tokens per minute, the gateway must parse Server-Sent Events (SSE) token usage in flight, deduct the exact prompt + candidate tokens consumed, and reject subsequent calls with
HTTP 429once the budget is exhausted—before invoking Vertex AI.
This section explains exactly how Apigee X works in Esmeralda from network plumbing down to XML policies, JavaScript callouts, SSE token extraction, and how it hands off seamlessly to GEAP Agent Identity and the Central Agent Gateway.
1. Division of Responsibilities: Apigee X vs. GEAP Agent Identity vs. Central Agent Gateway¶
Before diving into the proxy bundles, it is important to see how Apigee X, GEAP Agent Identity, and the Central Agent Gateway divide responsibilities without overlapping:
| Layer / Component | Traffic Direction | Primary Role | What It Enforces |
|---|---|---|---|
1. Apigee X (partner.esmeralda.internal, served on the entry point VIP) |
North–South (External / Partner Ingress) | Commercial & Partner API Management | • Verifies partner API Keys / OAuth tokens (VerifyAPIKey) against tiered API Products (bronze, silver, gold)• Enforces agent & MCP tool exposure allowlists ( kvm-partner-agents, kvm-partner-mcp)• Enforces per-partner LLM Token Quotas ( <LLMTokenQuota> EnforceOnly + CountOnly → HTTP 429)• Emits per-partner Monetization & Token Analytics ( DataCapture + PostClientFlow MessageLogging) |
2. GEAP Agent Identity & Auth Manager (agents.global.org-<ORG>.system.id.goog) |
End-to-End Cryptographic Identity | Workload & Delegated Human Identity | • Assigns each Reasoning Engine a unique X.509 SPIFFE ID (principal://)• Brokers 3-Legged OAuth (3LO) end-user tokens ( X-Esmeralda-User-Token) so downstream MCP tools can verify which human user authorized the call (esmeralda.mcp_authz) |
3. GEAP Central Agent Gateway (Google-managed; PSC attachment agw-egress-na-<env>) |
East–West (Internal Agent Egress) | Zero-Trust Runtime Policy Enforcement | • Enforces Agent Registry destination allowlists • Enforces per-target IAP roles/iap.egressor policies on each Agent Registry entry: only support-assistant is listed on order-ops-specialist, and only order-ops-specialist on the MCP servers (A2A calls through the generic Vertex AI endpoint are a known gap, see Security & IAM)• Runs optional Model Armor on unary MCP tool calls (the Semantic Governance (NLC) manifest is not enforced yet) |
2. End-to-End Architecture & Packet Flow¶
When an external partner app calls https://partner.esmeralda.internal/partner/v1/agents/support-assistant:streamQuery, the request traverses both the North–South Apigee X front door and the East–West GEAP Agent Identity + Central Agent Gateway loop:
sequenceDiagram
autonumber
participant Partner as External Partner App
participant EP as Entrypoint HTTPS ALB<br/>(partner.esmeralda.internal)
participant Apigee as Apigee X Runtime<br/>(partner-agents proxy)
participant Orch as support-assistant<br/>(SPIFFE Identity #1)
participant AGW as Central Agent Gateway<br/>(per-target IAP + Model Armor, optional)
participant Spec as order-ops-specialist<br/>(SPIFFE Identity #2 + 3LO)
participant MCP as Cloud Run MCP Servers<br/>(orders, customers, refunds)
Partner->>EP: POST /partner/v1/agents/support-assistant:streamQuery<br/>(x-api-key + X-Esmeralda-User-Token)
EP->>Apigee: Route via PSC NEG (neg-apigee-psc-<env>)
Note over Apigee: 1. VAK-Partner-Key (401 if invalid)<br/>2. KVM-Get-Agent-Config + JS-Validate-Agent (403 if not orchestrator)<br/>3. FC-Token-Quota-Enforce (429 if token quota exhausted)<br/>4. JS-Rewrite-Target-Path + mint GoogleAccessToken (sa-esmeralda-apigee-proxy)
Apigee->>Orch: POST /v1beta1/.../reasoningEngines/<id>:streamQuery?alt=sse
Note over Orch: Attests SPIFFE Identity #1 (principal://...)
Orch->>AGW: A2A Task to order-ops-specialist.esmeralda.internal
Note over AGW: Verify SPIFFE Identity #1 holds roles/iap.egressor on Specialist
AGW->>Spec: Route via Entrypoint direct PSC NEG
Note over Spec: Attests SPIFFE Identity #2 + Auth Manager 3LO user claims
Spec->>AGW: MCP tool calls (get_order, check_refund_eligibility)
Note over AGW: Verify SPIFFE Identity #2 holds roles/iap.egressor on each MCP server<br/>(+ Model Armor on tools/call when enabled)
AGW->>MCP: Forward with verified identity + 3LO user claims
MCP-->>Spec: Order ORD-2026-4102 details + refund eligibility
Spec-->>Orch: Order status summary
Orch-->>Apigee: SSE Stream chunks + usageMetadata token counts
Note over Apigee: 5. EventFlow + extract-tokens.js parses prompt/candidate/total tokens<br/>6. LTQ-count deducts tokens from partner product quota<br/>7. PostClientFlow logs ML-interaction JSON to Cloud Logging + Analytics
Apigee-->>EP: Governed SSE Stream
EP-->>Partner: HTTP 200 text/event-stream (or HTTP 429 on next turn if quota exceeded)
3. Private Networking & PSC Bridge (apigee/platform & entrypoint)¶
How does traffic get from our Shared VPC into Apigee X's Google-managed tenant project—and from Apigee X back to our private *.esmeralda.internal services—with zero public IP addresses?
flowchart LR
subgraph SharedVPC["Shared VPC (esm-<env>-net-host-<sfx>)"]
DNS["Cloud DNS Private Zone<br/>*.esmeralda.internal -> entry point VIP"]
ALB["Entrypoint Internal HTTPS ALB<br/>(ilb-esmeralda-rule-<env>, host partner.esmeralda.internal)"]
PSCNEG["Regional PSC NEG<br/>(neg-apigee-psc-<env>)"]
end
subgraph ApigeeTenant["Apigee X Tenant Project (esm-<env>-gateway-<sfx>)"]
SA_IN["Northbound PSC Service Attachment<br/>(google_apigee_instance.service_attachment)"]
INST["Apigee X Instance (us-central1)<br/>Environment: esmeralda-<env> (INTERMEDIATE)"]
EP_ATT["Southbound PSC Endpoint Attachment<br/>(*.esmeralda.internal)"]
end
subgraph Targets["Downstream Targets"]
VAI["Vertex AI Agent Runtime<br/>(us-central1-aiplatform.googleapis.com)"]
MCPS["Internal Entrypoint<br/>-> Cloud Run MCP Servers"]
end
DNS -.-> ALB
ALB -->|"backend-apigee-gateway-<env>"| PSCNEG
PSCNEG -->|"PSC tunnel"| SA_IN
SA_IN --> INST
INST -->|"GoogleAccessToken (sa-esmeralda-apigee-proxy)"| VAI
INST -->|"GoogleIDToken via PSC"| EP_ATT --> MCPS
- Apigee Organization & Instance (
infrastructure/modules/5-workloads/apigee/platform/): - Provisions (or adopts via
byo = true) thegoogle_apigee_organizationand regionalgoogle_apigee_instanceinesm-<env>-gateway-<sfx>. - Creates the Apigee environment
esmeralda-<env>(configurable tier:BASE,INTERMEDIATE, orCOMPREHENSIVE) and environment groupenvgroup-esmeralda-<env>listening onpartner.esmeralda.internal. - Creates a regional Private Service Connect (PSC) NEG (
neg-apigee-psc-<env>) pointing togoogle_apigee_instance.apigee_instance.service_attachment, wrapped in a regionalINTERNAL_MANAGEDHTTPS backend service (backend-apigee-gateway-<env>). - Partner host on the entry point:
- When
partner_access = "apigee"inenv.yaml, the Layer 5entrypointunit adds apartner.esmeralda.internalhost rule to its URL map withbackend-apigee-gateway-<env>as the backend. There is no separate partner IP or forwarding rule:partner.esmeralda.internalmatches the*.esmeralda.internalrecord and reaches the same entry point VIP and forwarding rule (ilb-esmeralda-rule-<env>, port 443) as every other host. Read that VIP withuv run esmeralda status --env <env> --unit layer-2-networking --output entrypoint_address. - Southbound to the entry point (
apigee/capabilities/partner-mcp): - A PSC service attachment (
sa-esmeralda-entrypoint-apigee-<env>, NAT subnetsb-esmeralda-psc-nat-apigee-<env>frompsc_nat_cidr) publishes the entry point forwarding rule; the Apigee endpoint attachmentea-esmeralda-mcp-<env>connects to it, and the target serverts-esmeralda-mcpreaches it asapigee-southbound.<domain>(private zoneapigee-southbound-<env>in the Shared VPC + Apigee DNS peering zonedz-esmeralda-mcp-<env>; the Apigee service agent getsroles/dns.peeron the host project). The unit runs afterentrypoint(Terragruntdependencies), so there is no cycle with the northbound path.partner-agentskeeps calling Vertex AI directly (ts-esmeralda-entrypoint).
4. Tiered API Products & Consumer Credentials (apigee/products)¶
Before any partner can call an agent or MCP tool, they must subscribe to an Apigee API Product provisioned by infrastructure/modules/5-workloads/apigee/products/ (live unit layer-5-workloads/apigee/products):
| API Product | Proxies Bound | Quota Attribute (llm_token_quota) |
Purpose |
|---|---|---|---|
agent-partner-bronze-<env> |
partner-agents |
10000/minute (configurable; 50/minute in quota exhaustion tests) |
Entry-level partner tier for B2B orchestrator queries. |
agent-partner-silver-<env> |
partner-agents |
100000/minute |
Mid-tier partner product for high-volume marketplace integrations. |
agent-partner-gold-<env> |
partner-agents |
1000000/minute |
Enterprise partner tier. |
mcp-partner-tools-<env> |
partner-mcp |
Standard request quota | Partner access to curated MCP tool endpoints (/partner/v1/mcp/<service>). |
The apigee/products unit also provisions a default smoke-test developer (partner-smoke-test@example.com), developer app (partner-smoke-test), and consumer credential subscribed to agent-partner-bronze-<env> and mcp-partner-tools-<env> so uv run esmeralda verify --env <env> --partner can run non-interactively out of the box.
5. Inside the Proxy & Shared Flow Bundles: Step-by-Step Policy Execution¶
Esmeralda's Apigee implementation is split into five independent, removable capability bundles under apps/apigee/: three API proxies (partner-agents, partner-mcp and llm-gateway) and two reusable shared flows (token-quota and usage-metering).
5.1 Proxy 1: partner-agents (apps/apigee/proxies/partner-agents/)¶
Exposes /partner/v1/agents/{agent_name}:streamQuery and /partner/v1/agents/{agent_name}:query for partner consumption.
flowchart TD
subgraph Req["Request Preflow (Northbound -> Southbound)"]
P1["1. AM-Capture-Request-Start<br/>Record client_received_start_ms & W3C traceparent"]
P2["2. VAK-Partner-Key (VerifyAPIKey)<br/>Validate x-api-key & load apiproduct.llm_token_quota"]
P3["3. EV-Agent-Name + KVM-Get-Agent-Config<br/>Read allowed_agents & orchestrator_engine_id from kvm-partner-agents"]
P4{"4. JS-Validate-Agent<br/>Is agent_name in allowed_agents?"}
P4_DENY["RF-Agent-Forbidden<br/>Return HTTP 403 (blocks internal specialists)"]
P5["5. FC-Token-Quota-Enforce<br/>Run shared flow token-quota (EnforceOnly)"]
P5_DENY["RF-Quota-Exceeded<br/>Return HTTP 429 before calling Vertex AI"]
P6["6. JS-Rewrite-Target-Path<br/>Rewrite to /v1beta1/.../reasoningEngines/<id>:streamQuery?alt=sse<br/>Set target.copy.pathsuffix = false"]
end
subgraph Target["HTTPTargetConnection (Vertex AI Agent Runtime)"]
T1["Southbound GoogleAccessToken<br/>(sa-esmeralda-apigee-proxy-<env>)<br/>https://us-central1-aiplatform.googleapis.com"]
end
subgraph Resp["EventFlow + Response Postflow + PostClientFlow"]
R1["7. EventFlow / JS-extract-tokens<br/>Parse SSE chunks for usageMetadata.{prompt,candidates,total}TokenCount<br/>Box counts as java.lang.Integer"]
R2["8. LTQ-count (LLMTokenQuota CountOnly)<br/>Deduct actual llm.totalTokenCount from partner quota"]
R3["9. FC-Usage-Metering (DataCapture)<br/>Populate dc_prompt_tokens, dc_candidates_tokens, dc_total_tokens, dc_llm_model"]
R4["10. PostClientFlow: ML-interaction<br/>Write structured JSON event to Cloud Logging<br/>(projects/<gateway>/logs/esmeralda-apigee-interactions)"]
end
P1 --> P2 --> P3 --> P4
P4 -- "No (e.g. order-ops-specialist)" --> P4_DENY
P4 -- "Yes (support-assistant)" --> P5
P5 -- "Bucket exhausted" --> P5_DENY
P5 -- "Within budget" --> P6 --> T1
T1 --> R1 --> R2 --> R3 --> R4
Key Implementation Details in partner-agents:¶
- Blocking Direct Access to Internal Specialists (
KVM-Get-Agent-Config+JS-Validate-Agent): The Terraform moduleinfrastructure/modules/5-workloads/apigee/partner-agents/populates an encrypted environment KeyValueMap (kvm-partner-agents) withallowed_agents = "support-assistant"andorchestrator_engine_id = "<numeric-id>". When a partner requests/partner/v1/agents/order-ops-specialist:streamQuery,validate-agent.jssetsagent.validation.Allowed = falseandRF-Agent-Forbiddenimmediately returnsHTTP 403 Forbidden. - Dynamic Vertex AI Reasoning Engine Target Rewriting (
JS-Rewrite-Target-Path): In Apigee X,<HTTPTargetConnection><URL>does not interpolate arbitrary path variables inside the XML tag. Instead,rewrite-target-path.jsruns in the Target Preflow, disables default path suffix copying (context.setVariable("target.copy.pathsuffix", false)), and rewritestarget.urlto the exact Vertex AI Reasoning Engine endpoint (https://us-central1-aiplatform.googleapis.com/v1beta1/projects/<project>/locations/us-central1/reasoningEngines/<engine_id>:streamQuery?alt=sse). - Two-Phase
<LLMTokenQuota>Enforcement (EnforceOnly+CountOnly): - Pre-request (
LTQ-enforce.xml): Checks the partner's remaining token budget againstverifyapikey.VAK-Partner-Key.apiproduct.llm_token_quotabefore forwarding the request to Vertex AI. - Post-response (
extract-tokens.js+LTQ-count.xml): ExtractsusageMetadata.totalTokenCountfrom the SSE stream (current.event.data) or JSON body, boxes it as a Java integer (new java.lang.Integer(Math.round(totalTokens))), and deducts the actual tokens consumed.
5.2 Proxy 2: partner-mcp (apps/apigee/proxies/partner-mcp/)¶
Exposes the MCP servers listed as partner-exposed in the module catalog (by default orders and notifications) at /partner/v1/mcp/{service}/mcp for external partner agents:
- API Key Verification (
VAK-Verify-Partner-Key): verifies the partner's API key and loads the API product'sallowed_mcp_toolsattribute. - Service allowlist (
KVM-Get-MCP-Config+JS-Enforce-Tool-Scope): readsallowed_mcp_servicesandapex_domainfromkvm-partner-mcp. A path whose service is not in the allowlist (an internal agent host,customers, or anything else behind the entry point) stops atRF-Not-Found(HTTP 404) and is never routed. - JSON-RPC tool scope (
JS-Enforce-Tool-Scope+RF-Tool-Forbidden): parses the JSON-RPC 2.0 body; fortools/call,params.namemust be in the product'sallowed_mcp_tools(<tool>,<service>:<tool>or*), otherwiseHTTP 403. Discovery (initialize,tools/list) is always allowed. The products list the real tools of the exposed servers:get_order(orders) andlist_notifications(notifications), plusget_shipment_statusandsend_customer_updateon the premium product. - Southbound path to the entry point (
targets/default.xml+AM-set-target-host): the MCP servers only accept traffic from internal load balancers, so the proxy reaches them through the internal entry point like any agent. Thepartner-mcpunit publishes the entry point forwarding rule to Apigee with a PSC service attachment (sa-esmeralda-entrypoint-apigee-<env>, own PSC NAT subnet) and an Apigee endpoint attachment; the target serverts-esmeralda-mcppoints atapigee-southbound.<domain>(a name covered by the entry point certificate that a private zone of the Shared VPC, DNS-peered to the Apigee organization, resolves to the endpoint attachment IP) and trusts the internal Root CA (keystoreks-esmeralda-internal-ca), with strict TLS (enforce, hostname verification).AM-set-target-hostsetstarget.header.hostto<service>.<domain>(with a target server, Apigee ignores a plainHostheader) and the request goes to/mcpwith a Google ID token of the proxy service account (<GoogleIDToken>with audiencehttps://<service>.<domain>, the Cloud Run custom audience). The proxy service account is the catalog callerapigee-partner-mcp, so it getsroles/run.invokeron the exposed servers only wherepartner_access = "apigee".
5.3 Shared Flows: token-quota and usage-metering¶
token-quota(apps/apigee/sharedflows/token-quota/): EncapsulatesAM-Resolve-Quota-Config(resolving product attributellm_token_quotainto count/interval/timeUnit) andLTQ-Enforce(<LLMTokenQuota>withEnforceOnly = true). Requires anINTERMEDIATEorCOMPREHENSIVEApigee environment.usage-metering(apps/apigee/sharedflows/usage-metering/): Provisions 5google_apigee_data_collectorDataCollectors (dc_prompt_tokens,dc_candidates_tokens,dc_total_tokens,dc_llm_model,dc_consumer_app) used byDataCapture, and ships the sharedML-interactiontemplate.
Usage records (ML-interaction)¶
Every proxy writes one esmeralda.usage record per request in PostClientFlow to projects/<gateway-project>/logs/esmeralda-apigee-interactions. The record follows the usage event contract (contracts/usage-event.schema.json), the same schema the esmeralda library emits from inside agents, so the BigQuery views join gateway and workload records on trace_id. Consumers select the records by jsonPayload.schema = "esmeralda.usage", never by log name.
A MessageLogging template can't compute values, omit empty fields or add numbers, so the JS-Usage-Context policy (usage-context.js, the same file in every bundle) prepares them: an RFC 3339 timestamp, latency_ms, the W3C trace_id from traceparent, the outcome (http, status, error_type) and the JSON fragments for caller, workload, tool and gen_ai. It runs after authentication, again at the end of the exchange (response PostFlow, final SSE event), and in a DefaultFaultRule (AlwaysEnforce), so rejected calls (401, 403, 429) are recorded too. Records never contain request or response bodies, credentials or API keys:
| Proxy | event |
caller.principal (verified: true) |
Extra fields |
|---|---|---|---|
partner-agents |
gateway.request |
verified cross-cloud iss#sub, else the Apigee developer app name |
workload = target agent, gen_ai.usage.* |
partner-mcp |
gateway.request |
same as partner-agents |
workload = MCP server, tool for tools/call |
llm-gateway |
llm.call |
the calling agent's Agent Identity principal:// (verified ID token sub; a service account's email for other callers) |
workload = calling agent, gen_ai.request.model, response.model, usage.* |
{
"schema": "esmeralda.usage",
"schema_version": 1,
"event": "llm.call",
"source": "gateway",
"timestamp": "2026-11-09T02:13:22.123Z",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"caller": {"principal": "principal://agents.global.org-<ORG_ID>.system.id.goog/resources/aiplatform/projects/<PROJECT_NUMBER>/locations/<REGION>/reasoningEngines/<ENGINE_ID>", "verified": true},
"workload": {"name": "support-assistant", "runtime": "agent_engine", "cloud": "gcp"},
"gen_ai": {
"system": "gcp.vertex_ai",
"operation.name": "generate_content",
"request.model": "gemini-2.5-flash",
"response.model": "gemini-2.5-flash-001",
"usage.input_tokens": 1200,
"usage.output_tokens": 120,
"usage.cached_tokens": 1024,
"usage.reasoning_tokens": 40
},
"http": {"request.method": "POST", "response.status_code": 200},
"status": "ok",
"gateway": {"product": "apigee", "name": "llm-gateway"},
"dimensions": {},
"latency_ms": 1834
}
usage.output_tokens includes reasoning tokens and usage.input_tokens includes cached tokens (OpenTelemetry GenAI semantics); Gemini reports thinking tokens apart from candidates, so the gateway adds them.
The agent sends the W3C traceparent of its current span with every model call, and the llm-gateway record names the calling agent as workload.name, so vw_usage_billable puts the gateway record and the agent's own llm.call record in the same billable unit (trace_id + agent) and counts the tokens once, from the gateway. The verified principal:// resolves to the agent's team through its principal_teams row (compiled from the catalog), so chargeback bills the calling team as verified.
5.4 Proxy 3: llm-gateway, the agent → model hop (apps/apigee/proxies/llm-gateway/)¶
The partner proxies govern traffic into the platform. The llm-gateway proxy governs the agents' own model egress: with model_gateway = "apigee", every Gemini call an agent makes goes through Apigee instead of straight to *-aiplatform.googleapis.com. Apigee then becomes the primary source of token usage and caller identity for chargeback, and enforces a token budget per agent.
sequenceDiagram
autonumber
participant Agent as support-assistant<br/>(google-genai via esmeralda.models)
participant AGW as Central Agent Gateway
participant EP as Entrypoint HTTPS ALB<br/>(apigee.esmeralda.internal)
participant Apigee as Apigee X Runtime<br/>(llm-gateway proxy)
participant Vertex as Vertex AI Gemini<br/>(<location>-aiplatform.googleapis.com)
Agent->>AGW: POST /llm/v1beta1/projects/<p>/locations/global/publishers/google/models/gemini-2.5-flash:streamGenerateContent?alt=sse<br/>Authorization: Bearer <unbound Agent Identity ID token, aud https://apigee.esmeralda.internal><br/>traceparent
AGW->>EP: Registered destination (catalog llm-gateway target, roles/iap.egressor for the agents)
EP->>Apigee: Route via PSC NEG
Note over Apigee: 1. KVM-Get-LLM-Gateway-Config (kvm-llm-gateway)<br/>2. DJ-Decode-Caller-Token + JS-Select-Token-Issuer: trusted issuer and JWKS<br/>3. VJ-Verify-Caller-Token: VerifyJWT, signature, issuer, audience (401)<br/>4. JS-Authorize-LLM-Call: caller, path, project, location, model (403 / 404)<br/>4b. JS-Validate-Run-Origin: agent factory run origin headers (flag, or 403 in enforce)<br/>5. LTQ-enforce: LLMTokenQuota per verified caller (429)<br/>6. AM-Strip-Caller-Credentials: the ID token stops here
Apigee->>Vertex: Same Vertex AI path, GoogleAccessToken (proxy service account)
Vertex-->>Apigee: SSE chunks with usageMetadata
Note over Apigee: 7. EventFlow: JS-extract-tokens per chunk<br/>8. Final chunk: LTQ-count, DC-capture-llm-metrics, JS-Usage-Context<br/>9. PostClientFlow: ML-interaction (esmeralda.usage llm.call)
Apigee-->>Agent: Unbuffered SSE stream
Agent side: ESMERALDA_MODEL_GATEWAY_URL¶
The agent Terraform units set ESMERALDA_MODEL_GATEWAY_URL = https://apigee.<domain>/llm only when governance.apigee.enabled and governance.capabilities.model_gateway = "apigee"; otherwise the variable is absent and nothing changes. esmeralda.create_app() calls esmeralda.models.route_models(root_agent), which replaces every Gemini model name in the agent tree with an ADK Gemini model that:
- uses the gateway as
base_url, so the request path stays the Vertex AI one and the proxy is a pass-through; - passes
project(GOOGLE_CLOUD_PROJECT) andlocation(MODEL_LOCATION, elseglobal) explicitly, because google-genai drops them from the path for a custom base URL otherwise; - authenticates with an ID token for the agent's runtime identity, audience
https://apigee.<domain>: on Agent Runtime, the agent's own Agent Identity, so the gateway verifies and meters each agent as itsprincipal://. It is never minted forSERVICE_ACCOUNT_EMAIL(the deprecated shared invoker), which would bill every agent to one identity. Like every ID tokenesmeralda.authmints, it is unbound (bind_id_token=False): the Central Agent Gateway and the entry point re-terminate TLS, so a certificate-bound token could not be checked behind them; - sends the W3C
traceparentof the current span, so the gateway's usage record joins the agent's own.
Model objects (Gemini(...), LiteLlm(...)) and inherited models are left as they are.
Reaching the gateway: the catalog llm-gateway target¶
The Central Agent Gateway denies every host that isn't in the Agent Registry. The model gateway is declared in the service catalog as a managed: false target, in the overrides of each environment that sets model_gateway = "apigee" (dev: catalog/environments/dev.yaml):
llm-gateway:
kind: http
owner_team: platform
deploy: { managed: false, endpoint: "https://apigee.{domain}/llm" }
gateway: apigee
callers:
support-assistant: {}
order-ops-specialist: {}
It compiles into an Agent Registry endpoint entry for apigee.<domain> with a roles/iap.egressor policy listing the two agents' principals (the iap-egress unit), and the same callers are the proxy's allowed_callers (the llm-gateway unit reads them from catalog_iap_egress). An agent missing from callers is stopped by the Agent Gateway (403) before Apigee, and by the proxy if it got there. make test-guards fails when the target and the capability disagree in an environment.
Why an ID token and VerifyJWT¶
Google OAuth2 access tokens are opaque: Apigee has no local policy that can verify them (VerifyAccessToken only accepts Apigee-issued tokens), so checking one would take a ServiceCallout to Google's tokeninfo endpoint on every model call. An ID token is a JWT that VerifyJWT checks locally against the issuer's cached JWKS (signature, iss, exp), and its audience binds it to this gateway, so it can't be replayed against another service. The agents already mint ID tokens the same way for MCP servers.
An agent's Agent Identity ID token is signed by its trust domain on Security Token Service: iss = https://sts.googleapis.com/v1/organizations/<ORG_ID>/locations/global/workloadIdentityPools/agents.global.org-<ORG_ID>.system.id.goog, JWKS at <iss>/openid/jwks, sub = spiffe://agents.global.org-<ORG_ID>.system.id.goog/... (no email). DJ-Decode-Caller-Token reads the token's iss without trusting it, and JS-Select-Token-Issuer picks the issuer and JWKS VerifyJWT checks against: the trust domain issuer when it is in the KVM's agent_issuers (derived from the agents' principals), else Google's (https://accounts.google.com, service account ID tokens such as the test VM's). A token from any other issuer fails VerifyJWT (401), and the JWKS URI is never built from an issuer outside the allowlist. JS-Authorize-LLM-Call turns the spiffe:// subject into the principal:// form the catalog and the usage views use.
Authorization and southbound call¶
kvm-llm-gateway, written by the capability module, holds the allowlists. All of them fail closed (an empty list is written as none; there are no wildcard callers):
| KVM entry | Live unit value |
|---|---|
audience |
https://apigee.<domain> |
allowed_callers |
the Agent Identity principals of the catalog llm-gateway target's callers, plus the test VM's service account |
agent_issuers |
the Security Token Service issuers of those principals' trust domains |
caller_workloads |
<principal>=<agent name>: the usage record's workload.name |
allowed_projects |
the CX and AI CoE agent projects (the project in the request path), as IDs and numbers: on Agent Runtime, GOOGLE_CLOUD_PROJECT is the project number |
allowed_locations |
the env region and global |
allowed_models |
gemini-* |
quota_limit, quota_timeunit |
tokens per caller per interval (default 1,000,000 per minute) |
caller_teams |
agent factory callers only: <service account>=<paying team>/<cost centre>\|<cost centre>/<owner team>, from the catalog principal_teams rows of the factory service accounts (none without the factory) |
run_origin_mode |
off | flag | enforce, from attribution.run_origin in env.yaml (dev: flag, prd: off) |
The southbound host is derived from the allowed location only (global → aiplatform.googleapis.com, otherwise <location>-aiplatform.googleapis.com), so a caller can't steer the proxy to another host. Only generateContent, streamGenerateContent and countTokens on publishers/google/models/* are served. The proxy calls Vertex AI with its own access token, so the module grants the proxy service account roles/aiplatform.user on the allowed projects.
streamGenerateContent is routed to a dedicated SSE target (response.streaming.enabled, EventFlow): tokens are read per event and metered on the final chunk (finishReason), and the stream is never buffered.
Agent factory run origin headers¶
Agent factory callers (the Scion integration's service accounts, listed in caller_teams) send the run they belong to with each model call. JS-Validate-Run-Origin runs right after JS-Authorize-LLM-Call; every other caller is exempt:
| Header | Usage record field | Check |
|---|---|---|
X-Esmeralda-Billed-Team |
billing.team |
must equal the paying team of the verified service account (payer_missing, payer_mismatch); the recorded team always comes from the service account, never from the header |
X-Esmeralda-Cost-Center |
billing.cost_center |
one of that team's cost centres (cost_center_invalid); absent: the team default, billing.cost_center_defaulted = true |
X-Esmeralda-Run, X-Esmeralda-Root-Run |
run.run, run.root_run |
at least one present (run_missing); ids [A-Za-z0-9][A-Za-z0-9._:-]{0,127} |
X-Esmeralda-Parent-Run, X-Esmeralda-Scion-Project |
run.parent_run, run.scion_project |
same id format |
X-Esmeralda-Origin |
run.origin |
ui, cli, api, schedule, trigger or trigger:<source> |
X-Esmeralda-Initiated-By |
run.initiated_by |
up to 256 characters, no control characters |
X-Esmeralda-Agent |
run.agent |
must equal the calling workload (caller_workloads) (agent_mismatch) |
X-Esmeralda-Issue |
run.issue |
[A-Za-z0-9][A-Za-z0-9._:/#-]{0,127} |
A malformed value is never recorded (attribution_malformed). run_origin_mode decides what a failed check does: flag lets the call through and records billing.status = rejected_would_be with billing.reason; enforce refuses it (RF-Run-Origin-Rejected, 403 {"error":"run_origin_rejected","reason":...}, before the token quota); off checks nothing. A call that passes is recorded with billing.status = catalog_checked. In every mode a factory caller's record also carries caller.team (its paying team) and workload.team (the agent's owner team), and the run id becomes gen_ai.conversation.id. AM-Strip-Caller-Credentials removes all X-Esmeralda-* run headers, so none of them reaches Vertex AI.
6. How to Enable, Remove, and Verify Apigee X (esmeralda CLI)¶
Every Apigee unit in Layer 5 is controlled declaratively by governance in infrastructure/live/<env>/env.yaml and includes a Terragrunt exclude block so it is automatically skipped when disabled:
governance = {
apigee = {
enabled = true
byo = false
environment_type = "INTERMEDIATE" # Required when token_quota = "apigee"
}
capabilities = {
egress_allowlist = "agent_gateway" # Internal East-West governed by Central Agent Gateway
content_safety = "agent_gateway" # Model Armor on Agent Gateway (governance.model_armor)
partner_access = "apigee" # Enables partner-agents, partner-mcp, and the partner.<domain> host rule on the entry point
token_quota = "apigee" # Enables token-quota shared flow (LLMTokenQuota)
usage_metering = "apigee" # Enables usage-metering shared flow & DataCollectors
cross_cloud = "apigee" # Required with partner_access: deploys the cross-cloud shared flow the partner proxies call
model_gateway = "apigee" # Agent -> model through llm-gateway (needs usage_metering and partner_access = "apigee", INTERMEDIATE+)
}
}
The partner proxies call the cross-cloud shared flow (FC-Cross-Cloud), and Apigee does not deploy a proxy whose shared flow is missing from the environment, so Layer 4 rejects partner_access = "apigee" without cross_cloud = "apigee". With no trusted issuers configured, the shared flow rejects every cross-cloud credential (fail closed); API-key partners are unaffected.
model_gateway takes "none" (default: agents call Vertex AI directly and the workload records are the only token source) or "apigee". Layer 4 rejects "apigee" unless usage_metering = "apigee" (the proxy writes to its data collectors), the environment is INTERMEDIATE or COMPREHENSIVE (LLMTokenQuota), and partner_access = "apigee" (the entry point only enables its Apigee backend for partner access; with model_gateway = "apigee" it also routes apigee.<domain>, already a hostname of the Apigee environment group, to that backend).
Setting model_gateway = "apigee" in an environment takes three things, all checked offline by make test-guards:
- the capability in
infrastructure/live/<env>/env.yaml(dev sets it; prd keeps"none"); - the catalog
llm-gatewaytarget incatalog/environments/<env>.yaml, with every agent as a caller (above), thenuv run esmeralda catalog resolve --env all --write; - the units:
layer-4-governance(capability contract),apigee/capabilities/llm-gateway,entrypoint(routesapigee.<domain>),iap-egress(Agent Registry entry androles/iap.egressor) and the agent units (ESMERALDA_MODEL_GATEWAY_URL). In a running environment, apply the agent units last: once they set the URL, every model call goes through the gateway, so the path must already be in place.
Model Armor's model_calls floor setting still screens the calls: it applies per agent project on Vertex AI, and the proxy keeps the agent's project in the request path.
Deploying & Running the Live Partner Conformance Probes¶
# 1. Inspect enabled Apigee units in your environment
uv run esmeralda units --env dev
# 2. Apply the Apigee platform, capability bundles, API products, and entrypoint
uv run esmeralda apply layer-5-workloads/apigee/platform --env dev
uv run esmeralda apply layer-5-workloads/apigee/capabilities/token-quota --env dev
uv run esmeralda apply layer-5-workloads/apigee/capabilities/usage-metering --env dev
uv run esmeralda apply layer-5-workloads/apigee/capabilities/partner-agents --env dev
uv run esmeralda apply layer-5-workloads/apigee/capabilities/partner-mcp --env dev
uv run esmeralda apply layer-5-workloads/apigee/capabilities/llm-gateway --env dev # model_gateway = "apigee"
uv run esmeralda apply layer-5-workloads/apigee/products --env dev
uv run esmeralda apply layer-5-workloads/entrypoint --env dev
# 3. Run the 5 live partner front-door conformance probes (including quota exhaustion)
ESMERALDA_TEST_QUOTA_EXHAUSTION=1 uv run esmeralda verify --env dev --partner
uv run esmeralda verify --env dev --partner resolves the test VM, the internal CA and the partner key (ESMERALDA_PARTNER_API_KEY, else the apigee/products consumer key secret) and executes the live probes from the private test VM against https://partner.esmeralda.internal (the entry point VIP, layer-2 output entrypoint_address). When Apigee is not deployed in the environment there is nothing to probe; the proxy bundles are checked offline by make test-apigee:
- Probe 1 (
HTTP 401): Unauthenticated partner request (nox-api-key) is rejected byVAK-Partner-Key. - Probe 2 (
HTTP 403): Partner request with a valid API key attempting to call internal specialist/partner/v1/agents/order-ops-specialist:streamQueryis blocked byJS-Validate-Agent. - Probe 3 (
HTTP 403): Partner request attempting to invoke an unallowlisted MCP tool via/partner/v1/mcp/ordersis blocked byJS-Validate-MCP-Tool. - Probe 4 (
HTTP 200): Partner request to/partner/v1/agents/support-assistant:streamQuerystreams Garimpo's order support response end-to-end (Apigee X →support-assistant→ GEAP Agent Identity → Central Agent Gateway →order-ops-specialist→ MCP servers) and records token metrics. - Probe 5 (
HTTP 429): Repeated partner calls exhaust thellm_token_quotabudget on the product and are rejected withHTTP 429 Too Many Requestsbefore reaching Vertex AI. - Probe 6 (
HTTP 200): MCPtools/liston/partner/v1/mcp/orders/mcpreturns the server's tools (get_order) through the southbound path. - Probe 7 (
HTTP 200): an allowed MCPtools/call(get_orderforORD-2026-4102) is answered byorders.
The probes are defined once, in the partner scenario catalog tests/partner/scenarios.py (every scenario with a probe number), and sent from the VM by tests/partner/probe.py (stdlib Python, no packages to install). Probe 5 only runs with ESMERALDA_TEST_QUOTA_EXHAUSTION=1.
7. Load Testing Through the Partner Front Door¶
make load-test-partner drives a steady, small partner workload through Apigee, for example to fill the Apigee Analytics dashboards and the token-quota and usage-metering views before a demo:
make load-test-partner ENV=dev # 2 users, 5 minutes
make load-test-partner ENV=dev USERS=1 DURATION=3m
make load-test-partner ENV=dev INCLUDE_QUOTA=1 # adds quota exhaustion (burns the product quota)
The CLI (esmeralda.ops.partner_load) resolves the test VM, the entry point, the internal CA and the partner key the same way as esmeralda verify --partner, and runs Locust on the test VM over IAP SSH (scripts/vm/partner_load.sh), because partner.esmeralda.internal only resolves inside the VPC. On first use it installs Locust on the VM in a cached virtual environment with uv, which needs outbound HTTPS from the VM (for example through Cloud NAT). The CSV and HTML reports are copied back to tests/load_test/.results/partner/ (gitignored).
The traffic mix is the same scenario catalog as the conformance probes: one weighted Locust task per scenario with weight > 0. A request counts as a success when its status is in the scenario's expected set, so the deliberate 401 and 403 rejections show up as successes under their own names, next to the real orchestrator answers:
| Scenario | Proxy | Expected | What the console shows |
|---|---|---|---|
agents-no-key, agents-invalid-key, mcp-no-key |
partner-agents, partner-mcp |
401 |
VerifyAPIKey faults in error code analysis |
agents-specialist-card-blocked, agents-specialist-stream-blocked |
partner-agents |
403/404 |
RF-Agent-Not-Allowed: internal specialists are never exposed |
mcp-restricted-tool-call |
partner-mcp |
403 |
RF-Tool-Forbidden: tool scope enforced at the gateway |
mcp-tools-list |
partner-mcp |
200 + get_order |
MCP discovery through the southbound path to the entry point |
mcp-tools-call-allowed |
partner-mcp |
200 + ORD-2026-4102 |
An allowed tool (get_order) answered by orders |
orchestrator-order-status, orchestrator-shipment, orchestrator-return-policy |
partner-agents |
200 |
SSE answers, time to first event and stream total, token counts |
orchestrator-quota-exhaustion (opt-in) |
partner-agents |
429 |
LLMTokenQuota rejections once the product budget is spent |
Each simulated user sends a synthetic end-user id (x-esmeralda-partner-user header and user_id in the query body), a W3C traceparent (logged by ML-interaction), and an x-esmeralda-load-run header with the run id. Keep the load small: the specialist runs a single instance and an answer takes about 25 seconds.
What to show in the Google Cloud console during a run (Apigee, environment esmeralda-<env>):
- Proxy development → API proxies →
partner-agents→ Debug: start a debug session, then open a200transaction to walk throughVAK-Verify-Partner-Key,LTQ-enforce, thessetarget and the EventFlow token extraction, and a403transaction that stops atRF-Agent-Not-Allowed. Onpartner-mcp, a403transaction stops atRF-Tool-Forbidden, and a200one (tools/listorget_order) showsKVM-Get-MCP-Config,JS-Enforce-Tool-Scope, thenAM-set-target-hostand the call to thets-esmeralda-mcptarget server. - Analytics → API metrics → API proxy performance: traffic and latency per proxy (
partner-agents,partner-mcp). Error code analysis splits the expected401/403from real errors. On pay-as-you-go organizations these dashboards need the environment's Analytics add-on: setgovernance.apigee.enable_analytics = trueinenv.yaml(on in dev, off in prd; it adds a per-call cost) and applyapigee/platform. Data appears after several minutes; Debug works without the add-on. - Analytics → Developer metrics → Developer apps: traffic attributed to the
partner-smoke-testapp. - Distribution → API products →
esmeralda-partner-standard: theallowed_mcp_tools(get_order,list_notifications) and LLM token quota attributes the gateway enforces. - Management → Environments →
esmeralda-<env>→ Target servers:ts-esmeralda-mcp(hostapigee-southbound.<domain>, TLS with the internal CA truststore); Management → Endpoint attachments showsea-esmeralda-mcp-<env>connected to the entry point service attachment, and Management → DNS peering the zonedz-esmeralda-mcp-<env>. - Logging → Logs Explorer: log
esmeralda-apigee-interactionsin the gateway project (logName="projects/<gateway-project>/logs/esmeralda-apigee-interactions"), oneesmeralda.usagerecord per partner call of both proxies with the verified caller (caller.principal, never the API key), the target workload, the MCP tool, the outcome and token counts.ML-interactionwrites with the proxy runtime service account (roles/logging.logWriter); its message template uses single-quoted literals ({firstnonnull(usage.latency_ms,'0')}), because a double-quoted literal makes the JSON payload invalid and Cloud Logging drops the entry. In BigQuery, the records land inesmeralda_usage_<env>and feedvw_partner_apigee_chargeback(partner chargeback by verified partner team) andvw_usage_billable.
make load-test(Locust against the Vertex AI API) bypasses Apigee: its traffic never appears in Apigee Analytics and does not consume partner token quota. Usemake load-test-partnerfor anything Apigee should see.
Adding a probe or a load scenario: append one Scenario to tests/partner/scenarios.py with its path, headers, body, expected statuses and weight (give it a probe number to also run it in esmeralda verify --partner, or destructive=True to keep it opt-in). Neither the probe runner, the Locust file nor the scripts change; make test-apigee checks the catalog offline.
Next Section: Now that we have seen how requests enter the platform—both internally via direct / envoy and externally via Apigee X—continue to 2.0 Governance, Identity & AgentOps — Overview & Release Lifecycle to see how the Central Agent Gateway, SPIFFE Agent Identity, and per-target IAP egress govern every internal hop.