Apigee Agent Gateway Governance
GoogleOfficialPublished by Google
- Skill
- Workflow
- Automation and integrations
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill automates the configuration of an Apigee API proxy to act as a service extension for a Google Cloud Agent Gateway. It enables inspection of LLM traffic to perform token metering, caller identity extraction, prompt screening via Model Armor, and semantic caching. The skill follows a structured deployment process using AFT templates and gcloud commands, ensuring the proxy is correctly wired to intercept and evaluate agent requests without acting as a backend router.
What it does
- Stands up an inspect-only Apigee proxy for LLM traffic governance.
- Configures token metering per model and enforces usage quotas.
- Integrates Model Armor for prompt screening and semantic caching.
- Manages gateway network connectivity and AuthzPolicy configuration.
- Provides automated deployment scripts for consistent environment setup.
- Supports both development and production modes with defined contract schemas.
When to use it
- When you need to meter or govern LLM token usage for agents.
- When you require prompt screening or semantic caching for agent egress.
- When you need to extract caller identity from agent traffic.
- When you are wiring Apigee as an AI gateway behind a Google Cloud Agent Gateway.
Advantages
- Centralized governance for agent model egress.
- Version-controlled proxy configuration via AFT templates.
- Automated handling of complex network and service extension dependencies.
- Non-intrusive inspection architecture that does not require backend routing.
Usage examples
- “Set up Apigee governance for my existing Agent Gateway in dev mode.”
- The agent will assess the current environment, apply default configurations for metering and identity, and generate a deployment plan for approval.
- “Deploy the Apigee proxy using my production configuration file.”
- The agent will validate the provided contract file, execute the deployment sequence, and verify the proxy is reporting as EXTENSIBLE.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/google/apigee-agent-gateway-governance/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip apigee-agent-gateway-governance.zip -d .agents/skills
Documentation by Google
Apigee as an Agent Gateway Service Extension
Wires an Apigee proxy in as an ext-proc callout on a GCP Agent Gateway. The proxy is a processor, not an API proxy: it has no backend, inspects the LLM request and response the gateway hands it, and returns a verdict.
Usage Attribution
MUST READ: Before executing any gcloud, REST API, or MCP command, you
MUST read and follow the instructions in
Usage Attribution.
You build the proxy; the user does not.
Two modes, one schema. Decide which before anything else, and say which.
Input file present → prod mode: it is the contract, every value comes from
it, and a missing or malformed field is a refusal, not a default. No input file
and the user is describing an outcome → dev mode: apply the documented
defaults, show a plan with durations and get approval, start with identity and
metering only, write apigee-agent-gateway-governance.yaml at the end as the
handoff. assets/apigee-agent-gateway-governance.example.yaml documents the
schema both modes use.
Modes, defaults, durations, cost disclosure and the interlocks that bind both:
references/modes.md. Read it before you start.
Colour the plan's ACTION column — green REUSE, cyan CREATE/RESERVE,
yellow APPEND/MODIFY; full palette in references/modes.md. Yellow is the
one that earns its place: it is the only signal that a resource the user already
owns is being changed. Rendered plain, the one row that modifies something is
indistinguishable from the dozen that do not — which is exactly the row the
approval exists for.
Prerequisite: where the agent runs
Check this before building anything. It decides whether traffic can reach the gateway at all, and it is silent when wrong — every step below still succeeds while nothing arrives.
Use Agent Runtime, created with agent_gateway_config /
agent_to_anywhere_config. It is the supported path and the orchestrator builds
the client-side PSC, routing, DNS and cert trust for you. There is no gcloud
surface for this and no console path — it is SDK-only, at agent creation time.
See
Route traffic through Agent Gateway
for the binding, and references/networking-psc.md for a worked example.
Set GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES: "False" in the
agent's env_vars, or every invocation 401s on the agent's own
sessions.create, before user code runs. Deploy-time invisible. Full symptom
and isolation: references/gotchas.md, Agent Gateway.
Where the agent runs is otherwise settled — the premise is a working gateway and
a working agent. Do not explain how to build one or list unsupported compute
unprompted; references/networking-psc.md has the constraints if it turns out
to matter.
Tool versions
Do not assume these are installed or current.
| Tool | Minimum | Why |
|---|---|---|
gcloud | 588.0.0 | apigee apis import --from-template is on the GA track at this version; older SDKs need gcloud beta |
google-cloud-aiplatform[agent_engines,adk] | >=2.1,<3 | Agent Runtime client used to bind the agent to the gateway |
google-adk | >=2.9,<3 | only if you build the test agent with ADK |
On gcloud >= 588.0.0: every feature must keep its uid, and the template must
never declare endpoints or targets. All six features set uid today and
the template declares neither, so the shipped bundle is correct — but both are
load-bearing now, and breaking either one still compiles, still deploys, and
reports nothing. Mechanism and symptoms: references/gotchas.md, under
Authoring (AFT).
gcloud version | head -1 # confirm >= 588.0.0
gcloud components update # if older
pip install "google-cloud-aiplatform[agent_engines,adk]>=2.1,<3" "google-adk>=2.9,<3"scripts/compile_check.py needs PyYAML and names the interpreter if it is
missing. pip install pyyaml, or run it with a Python 3 that has it; gcloud's
bundled interpreter does not, and the SDK's vendored yaml is Python 2.
python3 scripts/compile_check.py assets/apigee-proxy-template.yamlExecution model
Three layers, and the choice between them is not stylistic:
| Layer | Used for | Why |
|---|---|---|
| AFT YAML template | the proxy itself | version-controlled, reviewable, diffable |
gcloud | PSC, DNS, AuthzExtension, AuthzPolicy | native commands exist |
REST (curl) | env properties, envgroups, deployments, debug sessions | no gcloud equivalent today |
The customer owns one input file
(assets/apigee-agent-gateway-governance.example.yaml). It is the
version-controlled artifact. Never hand-edit the generated proxy: regenerate it.
Run the Apigee-side sequence with the script, not by hand. Steps 1, 3 and 4
below are order-dependent and each fails in a way that reads as a different
problem. scripts/deploy_proxy.sh does all three, preserves the properties
map, polls the async operation, and exits non-zero if the deployment does not
come up EXTENSIBLE:
scripts/deploy_proxy.sh --org "$ORG" --env "$ENV" --proxy "$PROXY" \
--template assets/apigee-proxy-template.yaml [--service-account "$SA"] --yes \
[--index-endpoint-id ID --index-id ID --sc-project P --sc-region R --embeddings-model M]Run it without --yes first: it prints the plan and changes nothing. Show that
plan, then re-run with --yes once the user agrees.
The vector-search flags are the one exception to "edit the default in every
feature that declares it". Those three ids are substituted at deploy time
and checked for leftovers; hand-editing them into feature-semantic-cache.yaml
deploys fine, skips the check, and makes the file single-use.
scripts/ensure_gateway_connectivity.sh is the same idea for the gateway leg
(step 0). It is the only part of this skill that modifies a resource the user
already owns, so it applies nothing without --yes.
The steps are written out below so you can diagnose a failure, not so you can retype them.
Inputs you must resolve first
Environment prerequisites: references/setup.md — gcloud SDK (588+),
project, billing, gcloud services enable, region, credentials, IAM. Nothing
below creates any of it.
Prod: from the input file, then environment, then ask — never invent. Dev: apply
the references/modes.md defaults, and ask only for what has none.
project,regionapigee.org,apigee.environment,apigee.envgroup,apigee.hostname,apigee.proxynetwork.vpc,network.subnet,network.networkAttachmentgateway.name,gateway.matchPaths(a list, one entry per wire shape),gateway.manageNetworkConfig
matchPaths drives TWO artifacts; write both from the same list. The
AuthzPolicy paths[].suffix gets one suffix per entry, verbatim with
leading punctuation kept — it decides what the gateway routes to Apigee. The
template's LLM_URI_MATCH gets one (request.uri Like "*<entry>*") clause
per entry, OR-ed, leading : or / stripped — it decides what the proxy
acts on once it arrives. The shipped two-entry default gives:
((request.uri Like "*generateContent*") or (request.uri Like "*chat/completions*"))The AuthzPolicy is the outer gate and wins: a suffix list narrower than
matchPaths means the missing shape never reaches Apigee at all. Derive both
from the input file and never from the default when the file disagrees — the
file is the reviewable contract and a mismatch is invisible once deployed.
A one-entry list is legitimate and governs one shape. Dropping an entry
governs one fewer silently — deploys clean, zero transactions for the shape
dropped — and narrows feature-normalize, Model Armor and the cache together.
references/gotchas.md, Runtime.
semanticCache is a KNOWN ISSUE whenever it is on — warn, then build it.
The key is the prompt embedding alone: no caller, no model, no shape. A hit
therefore crosses callers — similar prompts share an answer — and one model
behind one shape does not make it safe. With more shapes the first model to
answer answers for the other too: empty HTTP 200 across shapes, wrong-model
body within one. Warn whenever the cache is on, not only on multi-shape, then
build. Wording: references/modes.md; mechanism: references/gotchas.md.
Each entry is a SUFFIX match. You write these, not the user — derive them
from which endpoint their agent actually calls, and do not ask them to reason
about suffixes. Vertex's OpenAI-compatible endpoint and api.openai.com need
different entries, and getting it wrong governs nothing silently; the forms and
the evidence are in references/gotchas.md, Runtime.
There is no apiShape field. Metering does not depend on the wire shape —
the count is normalised in JS across both — so the field selected nothing and
was removed. Adding a shape is an || branch in extract-model.js plus an
entry in matchPaths.
Three places carry the callout hostname and all three must match — the
Apigee envgroup, the AuthzExtension authority/service, and the private DNS A
record. You set all three from one value: a build invariant to hold, not a
question for the user. It becomes a topic only when a callout never lands, and
then it is the first check. Build order matters alongside it — the
AuthzExtension is inert until the host resolves and the proxy is deployed, so
"the extension exists" is not evidence that leg works. references/gotchas.md,
Runtime.
Workflow
0. Gateway: give it a route into the VPC
A gateway with no networkConfig has no route into the customer's VPC and
cannot resolve the callout hostname. This skill builds it — network
attachment, egress and DNS peering — so its absence is a build step, not a
blocker, and should be reported that way. Do not open with an alarm about a
resource you are about to create.
One thing here does need the user, and it is the reason this is step 0 rather than a silent prerequisite: attaching egress is one-way and affects traffic they already run. Settle it in the plan, before anything executes — see "Confirm everything up front" below. Capturing a known-good agent turn first is worth doing when they are nervous about a production gateway, because it separates "never worked" from "we broke it"; it is a precaution to offer, not a step to impose.
gcloud network-services agent-gateways describe "$GATEWAY" \
--location="$REGION" --project="$PROJECT" --format='value(networkConfig)'
gcloud network-security authz-policies list \
--location="$REGION" --project="$PROJECT"A console-created gateway already has a CUSTOM AuthzPolicy — an IAP
REQUEST_AUTHZ one, which coexists with ours and is not needed for the egress
JWT. You never create the gateway, so assess it rather than assuming.
references/gotchas.md, Agent Gateway.
Empty networkConfig output means missing, and it is easy to miss: the gateway
still serves ordinary agent traffic perfectly, because that path goes to public
Google endpoints and never enters the VPC. Only the Apigee callout fails.
If it is missing, behaviour depends on gateway.manageNetworkConfig:
true— run the script below. It creates the network attachment, then read-modify-writes the gateway to add the egress attachment and DNS peering. Agreement for this is taken in the plan, not here;--yescarries it.false— the user has said they want to make this change themselves. Print the script invocation and let them run it. Do not modify the gateway.
scripts/ensure_gateway_connectivity.sh \
--gateway "$GATEWAY" --project "$PROJECT" --region "$REGION" \
--vpc "$VPC" --subnet "$SUBNET" --attachment "$ATTACHMENT" \
--domain "$DNS_DOMAIN" # add --yes only after the user agreesEither way networkConfig has to exist before the Apigee work starts — not
because its absence is an error, but because every later step then succeeds and
governs nothing.
Use the script, not the raw commands: import is a whole-resource upsert and a
hand-built YAML silently drops the gateway's registries and protocols. Why,
and the etag and PROTOCOL_UNSPECIFIED handling: references/gotchas.md.
1. Apigee: enable the environment
The env must carry apigee-service-extension-enabled=true. No gcloud flag
exists; PATCH the properties map.
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENV"The PATCH replaces the whole map. Read it first and re-send every property you intend to keep, or you will silently drop them.
curl -X PATCH -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
"https://apigee.googleapis.com/v1/organizations/$ORG/environments/$ENV?updateMask=properties" \
-d '{"properties":{"property":[{"name":"apigee-service-extension-enabled","value":"true"}]}}'This does not disable Apigee Analytics — the two coexist; if analytics looks
missing it is the separate per-environment add-on. references/gotchas.md.
Use a dedicated environment, attached to exactly one envgroup. An
environment in two makes the gateway 404 every request with the extension never
invoked. It also leaves the / base path free, which is what the proxy ships
with.
scripts/ensure_apigee_environment.sh creates the environment, attaches it to
the regional runtime instance, and creates and attaches the envgroup — so step 2
is already done when it succeeds. It creates billable resources and applies
nothing without --yes; that agreement is taken in the plan, not here.
scripts/ensure_apigee_environment.sh \
--org "$ORG" --env "$ENV" --region "$REGION" \
--envgroup "$ENVGROUP" --hostname "$HOSTNAME" # add --yes to applyIt is idempotent and resumable, and refuses with exit 2 when the environment is
already in another envgroup or the envgroup exists on a different hostname. It
also handles three things a runbook tends to get wrong — the omitted type on
create, the four-minute instance attachment that locks the environment, and
polling the operation rather than a GET that succeeds too early.
2. Apigee: envgroup on the callout hostname
Done already if step 1's script ran. Verify, or do it by hand for an envgroup that already exists. The hostname must be exactly the callout host, and the group must be attached to the env.
curl -s -H "Authorization: Bearer $TOKEN" \
"https://apigee.googleapis.com/v1/organizations/$ORG/envgroups/$ENVGROUP/attachments"How many envgroups is the environment in? More than one and the callout
never lands. deploy_proxy.sh enforces this before touching anything and exits
2 naming them; assess_integration.sh reports it. Read the failure literally if
it fires — the environment is wrong, not the script.
3. Build the proxy from the template
gcloud apigee apis import organizations/$ORG/apis/$PROXY \
--from-template=assets/apigee-proxy-template.yamlEach features: entry resolves relative to the template file's own
directory, never the working directory, so a bare filename must sit beside the
template (a subpath like features/feature-identity.yaml works too). assets/
is flat by convention, not compiler demand — but moving a file without updating
features: fails the import with a bare FileNotFoundError.
If you get Permission denied on resource ... (or it may not exist) on an org
you demonstrably have access to, it is the credential, not the access. With
context-aware access enabled the default gcloud credential is rejected. Pass the
ADC token instead:
CLOUDSDK_AUTH_ACCESS_TOKEN=$(gcloud auth application-default print-access-token) \
gcloud apigee apis import ...To change a parameter, edit the default in every FEATURE that declares it
— not in the template. gcloud apigee apis import passes an empty
caller-parameter map, so each feature resolves its own default and the
template's declaration of the same name is never read. Editing the template
changes nothing, silently, and the compile still passes. Measured: setting
MA_CONTINUE_ON_ERROR to DRY_RUN in the template shipped ENFORCE on a
fail-closed policy. LLM_URI_MATCH is declared in four features and all four
must agree. scripts/compile_check.py fails on any disagreement. There is no
--parameters flag.
Enable an optional recipe by adding its feature to the template's features
list. See references/recipes.md.
tokenMetering.models in the input file is NOT generative. It documents
which buckets exist; it does not create them. A bucket is real only when it has
an LLMTokenQuota step in feature-token-metering.yaml and a matching
*_TOKEN_LIMIT parameter. Three exist: gemini-pro, gemini-flash and other
— the catch-all for any model whose name contains neither pro nor flash.
Adding a fourth entry to the list meters nothing, and omitting other
silently unmeters every non-Gemini model: the count is extracted and then
discarded, with no ratelimit reference anywhere in the transaction. Adding a
model is a feature-file edit, not a config change.
4. Deploy
Deploy to the service-extension env, then confirm the deployment reports
proxyDeploymentType: EXTENSIBLE.
curl -s -H "Authorization: Bearer $TOKEN" \
".../environments/$ENV/deployments"STANDARD means it will not govern the agent's off-Apigee tool egress.
If any policy calls a Google API — Model Armor, embeddings, Vector Search —
deploy with a service account or the deploy is rejected with
MISSING_SERVICE_ACCOUNT:
curl -X POST -H "Authorization: Bearer $TOKEN" \
".../apis/$PROXY/revisions/$REV/deployments?override=true&serviceAccount=$DEPLOY_SA"5. Networking
This is the gateway → Apigee leg only. PSC endpoint to the Apigee instance
service attachment, plus a private DNS A record. See
references/networking-psc.md. The Apigee instance consumerAcceptList must
include your project or the connection never reaches ACCEPTED.
The agent → gateway leg is the prerequisite above, and is not built here.
6. Bind the gateway
AuthzExtension then AuthzPolicy — in that order, and only once the host resolves and the proxy is deployed. The extension is inert until then.
Both document bodies ship as assets. Copy and substitute; do not invent them
— assets/authz-extension.example.yaml and assets/authz-policy.example.yaml.
They carry the fields that are load-bearing and have no obvious default:
wireFormat: EXT_PROC_GRPC, failOpen, the authority/service pair, the
metadata body flags, and the policy's customProvider / httpRules nesting.
gcloud service-extensions authz-extensions import $AUTHZ_EXT \
--source=authz-extension.yaml --location=$REGION --project=$PROJECT
gcloud beta network-security authz-policies import $AUTHZ_POLICY \
--source=authz-policy.yaml --location=$REGION --project=$PROJECTThe policy's resource paths take the project NUMBER, not the ID — both
target.resources and customProvider.authzExtension.resources. Resolve it
yourself; narrating two numbers at the user does not help. The trap, for when a
callout never lands: the number in the gateway's
serviceExtensionsServiceAccount is the Google-managed tenant project, not
theirs, and it is the only one on screen, so it is the natural thing to copy. A
wrong number imports cleanly and targets nothing. Copy the slots from
assets/authz-policy.example.yaml.
7. Verify
You cannot test with curl — the host is internal and the proxy expects the
gateway's IAP-egress JWT. Run scripts/read_debug_session.sh --arm, drive a
turn, read it back with --session. Expect one transaction per turn per
governed shape under a suffix list this narrow; zero alone does not mean the
callout is dead — the script prints the probe that settles it.
Hard rules
Gate every step — how urgently depends on your AuthzPolicy. An ungated
continueOnError="false" policy faults on any call that carries no prompt, and
that breaks the agent's turn. Historically the most common failure here.
A narrow suffix list routes only the model call to Apigee, so the trap mostly
does not fire. Broaden the policy and it fires at once: the ext-proc then sees
every agent egress — session create/read, appendEvent, OpenTelemetry exports —
measured at 12 calls for one single-question turn, of which one was the model
call. Gate the steps regardless; a condition is cheap and it is what makes the
policy safe to widen later. Full measurement: references/gotchas.md.
model call:
(request.uri Like "*generateContent*")
Never fail-close on your own metering. Keep continueOnError="true" on the
JavaScript and quota policies so a metering bug cannot break LLM traffic.
This skill meters by default and can enforce on request. Enforcement is
assets/feature-token-enforce.yaml: request-flow EnforceOnly policies sharing
each SharedName with the response-flow CountOnly half. Add it to the
template's feature list. Verified live on ext-proc traffic — the over-budget
caller gets a 429, model never called.
Never offer CountOnly=false as a substitute: in the response flow it cannot
gate (the answer is already on the wire) and it freezes the counter, losing the
metering too.
State two things whenever you offer it. It is one request late — the turn
that crosses the limit completes, because a token cost is not known until the
model answers. And it buckets on the requested model, which under an OpenAI
alias can differ from the resolved model the counting side bills. The two traps
that both present as "it never refuses": references/gotchas.md.
Normalize the model to a bucket. With an OpenAI-compatible endpoint the
model is an alias in the request body and the resolved name is in the response
body (google/gemini-2.5-pro). Exact-matching a raw name fails on the response
path.
jsonPath needs its third argument true so it returns a scalar. Without
it the quota policy receives a node it cannot parse.
References
references/modes.md— read first. How to answer "what can you do", dev vs prod, the defaults, durations, cost disclosure, the interlocks, and reading an assess reportscripts/assess_integration.sh— read-only. Setup Status Summary then a per-check table;--jsoncarries both. Lead with the summary and read out the Enforcement row. Run it before planning: it decides CREATE vs REUSE.TODOis a build step, not a failure; onlyFAILexits non-zeroreferences/networking-psc.md— both network legs, PSC, DNS, acceptancereferences/recipes.md— Model Armor and semantic cachereferences/verify.md— debug sessions and the checklist scriptreferences/setup.md— SDK, project, billing, APIs, region, auth, IAMreferences/gotchas.md— 63 failure modes and their symptomsassets/apigee-agent-gateway-governance.example.yaml— the input contractassets/apigee-proxy-template.yaml— the AFT template. Features merge bypriorityand all sit beside it:feature-identity.yaml(10),feature-normalize.yaml(15),feature-model-armor.yaml(20),feature-semantic-cache.yaml(30),feature-token-metering.yaml(50).assets/authz-extension.example.yaml,assets/authz-policy.example.yaml— the step-6 bodies. Copy and substitute; paths take the project numberAnything read out of the request body is normalised once, at priority 15, not inside whichever feature needs it first.
LLM_URI_MATCHis shared, so widening it arms every feature gated on it simultaneously — including Model Armor, which fails closed. Model Armor and the cache both readagw.user_prompt; the quotas readagw.total_tokens, set on the response path by the metering feature's own JS for the same reason.scripts/ensure_apigee_environment.sh— create the environment, attach it to the instance, create and attach the envgroup. Idempotent,--yesgatedscripts/ensure_gateway_connectivity.sh— route the gateway into the VPC. Read-modify-write;--yesgatedscripts/ensure_vector_search.sh— only whensemanticCacheis enabled: build index and endpoint, deploy one on the other, read back the domain.--yesgated, ~34 min, bills continuouslyscripts/teardown_vector_search.sh— the only thing that STOPS that charge. Refuses until the revision dropsSCL-lookup.--yesgatedscripts/deploy_proxy.sh— the Apigee-side sequence, idempotent,--dry-runscripts/read_debug_session.sh—--arma session (printing when it actually closes) and read it back as theverify.mdchecklist, instead of parsing the transaction JSON by handscripts/compile_check.py— compile the template offline, no org needed
Files
- ATTRIBUTION.mdAdded by AutoGineer880 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md26.1 KiB
- assets/apigee-agent-gateway-governance.example.yaml20.8 KiB
- assets/apigee-proxy-template.yaml9.4 KiB
- assets/authz-extension.example.yaml1.7 KiB
- assets/authz-policy.example.yaml2.1 KiB
- assets/feature-identity.yaml6.0 KiB
- assets/feature-model-armor.yaml3.5 KiB
- assets/feature-normalize.yaml4.0 KiB
- assets/feature-semantic-cache.yaml7.9 KiB
- assets/feature-token-enforce.yaml16.3 KiB
- assets/feature-token-metering.yaml14.9 KiB
- references/attribution.md1.9 KiB
- references/gotchas.md43.7 KiB
- references/modes.md46.5 KiB
- references/networking-psc.md10.0 KiB
- references/recipes.md9.4 KiB
- references/setup.md7.2 KiB
- references/verify.md14.3 KiB
- scripts/assess_integration.shScript35.5 KiB
- scripts/compile_check.pyScript9.9 KiB
- scripts/deploy_proxy.shScript23.7 KiB
- scripts/ensure_apigee_environment.shScript17.8 KiB
- scripts/ensure_gateway_connectivity.shScript21.2 KiB
- scripts/ensure_vector_search.shScript19.0 KiB
- scripts/read_debug_session.shScript15.5 KiB
- scripts/teardown_vector_search.shScript9.0 KiB
assets/apigee-agent-gateway-governance.example.yaml
# THE customer-owned, version-controlled input -- and the schema for BOTH modes.
#
# PROD mode reads this file as the contract and reconciles the setup to it,
# refusing rather than defaulting when a required field is absent. DEV mode
# WRITES this same shape at the end of a conversational setup, so what it emits
# can be committed and fed straight back in. One schema, two entry points --
# see references/modes.md.
#
# Commit it; review it; roll it back. The skill reads it, rewrites the AFT
# template/feature parameter defaults from it, compiles the proxy through
# `gcloud apigee apis import --from-template`, and runs the gcloud/REST
# steps for the pieces AFT does not cover.
#
# Do not hand-edit the generated proxy bundle. Change this file and regenerate,
# or the committed artifact stops matching what is deployed.
#
# SCOPE LIMIT, STATED PLAINLY: AFT YAML covers the proxy only. The environment
# property, envgroup, PSC endpoint, DNS record, AuthzExtension and AuthzPolicy
# are driven imperatively from the values below. They are reproducible from
# this file, but they are not themselves declarative Apigee config.
apiVersion: apigee.googleapis.com/v1alpha1
kind: AgentGatewayGovernance
metadata:
name: agent-gateway-governance
description: Meter LLM tokens per model on the agent gateway's egress.
spec:
project: my-project
region: us-central1
apigee:
org: my-project
# MUST BE DEDICATED TO THIS PROXY, and attached to exactly ONE envgroup --
# the one named below. An environment sitting in two envgroups makes the
# gateway return 404 for every agent request, with the extension never
# invoked and no error reported anywhere. Do not share an environment to
# save creating one.
#
# CREATED BY THE SKILL if absent, and attached to the runtime instance in
# `region`, by scripts/ensure_apigee_environment.sh. That script creates
# billable resources, so it prints a plan and does nothing without --yes.
# It is idempotent and resumable, so a partial run is safe to repeat.
#
# An EXISTING environment is reused only after the skill counts its
# envgroups and finds at most this one. If it is already in another, the
# skill stops rather than continuing, because every later step would
# otherwise succeed and govern nothing.
#
# Two things it handles that bite when done by hand: on a SUBSCRIPTION_2021
# org `type` must be omitted from the create, and attaching to the instance
# takes around four minutes during which the environment is LOCKED -- a
# property PATCH in that window fails looking like a permissions problem.
#
# The skill WILL set the environment property
# apigee-service-extension-enabled=true on it -- that property is what lets
# the environment host a service-extension proxy, and without it the proxy
# deploys STANDARD and never sees the agent's traffic.
# Note the property PATCH replaces the environment's whole property map, so
# the skill reads the existing properties first and re-sends them.
# This does NOT disable Apigee Analytics; the two are unrelated.
environment: agent-gateway-govern
# CREATED BY THE SKILL if absent, on `hostname` below, and attached to
# `environment` -- same script, same --yes gate as the environment above.
#
# An existing envgroup is reused ONLY if it already carries `hostname`
# exactly. If it exists on a different hostname the skill stops rather than
# rewriting it: the group may carry someone else's routing, and a hostname
# that does not match the AuthzExtension authority means the callout never
# lands and nothing errors.
envgroup: agent-gateway-govern-group
# An internal hostname you choose. It does not need to be registered
# anywhere public and nothing resolves it outside your VPC.
#
# The skill writes this same string into THREE places it creates, and they
# must stay byte-identical or the callout silently never lands and nothing
# errors:
# 1. the Apigee envgroup hostname
# 2. the private DNS A record
# 3. the AuthzExtension authority/service
# You give the value once, here. network.dns.record below repeats it only
# because the DNS zone is described separately; keep the two identical.
hostname: agent-gateway-callout.internal.example.local
proxy: agent-gateway-governance
# YOU CREATE THIS BEFOREHAND. The skill does not create it and does not
# grant it anything.
#
# Required only if an enabled feature calls a Google API. With just
# identity + tokenMetering, leave it as "" -- naming a service account that
# does not exist, or that you cannot act as, fails the deploy.
#
# Roles the service account itself needs, by feature:
# modelArmor roles/modelarmor.user
# semanticCache roles/aiplatform.user (embeddings + Vector Search)
# And the identity running the deploy needs iam.serviceAccounts.actAs on
# this service account, or the deploy is rejected even though the roles
# above are correct.
#
# Omitting it when a feature does need it fails with
# MISSING_SERVICE_ACCOUNT.
deploymentServiceAccount: ""
network:
# BOTH MUST ALREADY EXIST. The skill does not create them.
#
# This must be the VPC the Agent Gateway egresses into -- the one named in
# the gateway's network attachment -- not simply any VPC in the project.
# If they differ, everything below builds successfully and the gateway
# still cannot reach Apigee.
#
# The subnet must be in `region` above, which must also be the region of
# the Apigee runtime instance. All three are the same region: the gateway,
# the subnet the private endpoint is reserved in, and the Apigee instance.
vpc: agent-network
subnet: agent-subnet
# PSC-interface network attachment the Agent Gateway egresses through to
# reach your VPC. CREATED BY THE SKILL in `subnet` above if it does not
# already exist; reused as-is if it does.
#
# This is what gives the gateway a route to the Apigee PSC endpoint. A
# gateway without one serves ordinary agent traffic perfectly well -- that
# path never enters your VPC -- and silently fails only the Apigee callout.
networkAttachment: agent-gateway-egress-attachment
dns:
# CREATED BY THE SKILL: a private zone visible to `vpc`, plus an A record
# pointing at the private endpoint it reserves for the Apigee instance.
# The gateway must also be able to resolve this zone -- that comes from
# the gateway's own DNS peering config, which is out of scope here.
zone: agent-gateway-callout-zone
# Must be the parent domain of `record`, with the trailing dot.
domain: internal.example.local.
# MUST equal apigee.hostname above, character for character.
record: agent-gateway-callout.internal.example.local
gateway:
# MUST ALREADY EXIST. The skill does not create the Agent Gateway. It can
# add missing network connectivity to one -- see manageNetworkConfig below
# -- but only with your confirmation. Use the short name, not the full
# resource path. List what you have with:
# gcloud network-services agent-gateways list \
# --location=$REGION --project=$PROJECT
#
# Two things about that gateway decide whether any of this works, and
# NEITHER is visible from the gateway name:
#
# 1. networkConfig.egress.networkAttachment -- a PSC-interface network
# attachment into `network.vpc` below. Without it the gateway has no
# route into your VPC and can never reach Apigee.
# 2. networkConfig.dnsPeeringConfig -- forwards `network.dns.domain` to
# your VPC. Without it the gateway cannot resolve `hostname`.
#
# A gateway missing these still passes every earlier check and still serves
# ordinary agent traffic to public Google endpoints, because that path does
# not enter your VPC. It is only the callout to Apigee that fails, and it
# fails silently. Check before you start -- empty output means missing:
# gcloud network-services agent-gateways describe $GATEWAY \
# --location=$REGION --project=$PROJECT --format='value(networkConfig)'
name: my-agent-gateway
# What the skill does when that networkConfig is missing.
#
# true -- add it for you: create network.networkAttachment if needed,
# then read-modify-write the gateway to add the egress
# attachment and DNS peering for network.dns.domain. The skill
# prints the exact before/after diff and waits for you to
# confirm. It never applies silently.
# false -- leave the gateway untouched and stop, printing the commands to
# run yourself. Choose this if the gateway is shared, owned by
# another team, or under IaC that would revert the change.
#
# Either way the skill refuses to continue while networkConfig is absent,
# because every later step would succeed and govern nothing.
manageNetworkConfig: true
# Path suffixes identifying a real model call. ONE ENTRY PER WIRE SHAPE
# you want governed; list both to govern both from a single proxy.
#
# gemini -> :generateContent
# openai -> /chat/completions
#
# These compile to the template's LLM_URI_MATCH as an OR of "*<entry>*"
# conditions. Two entries give:
#
# ((request.uri Like "*generateContent*") or
# (request.uri Like "*chat/completions*"))
#
# DELETING AN ENTRY SILENTLY STOPS GOVERNING THAT SHAPE. The proxy still
# deploys clean and reports nothing -- no fault, no error, just zero
# transactions for the shape you dropped. The same condition also gates
# Model Armor and the semantic cache, so narrowing this narrows all three
# at once. See references/gotchas.md, Runtime.
#
# The AuthzPolicy binds on path SUFFIX, which is why the OpenAI entry has
# NO leading /v1. /v1/chat/completions is LITERAL-OPENAI ONLY: Vertex's
# OpenAI-compatible endpoint ends openapi/chat/completions, so that
# pattern never matches it. Measured -- 0 transactions across two
# successful agent turns, 1 after switching to /chat/completions.
# See references/gotchas.md.
#
# Metering does not depend on this list. The token count is normalised in
# JS across both shapes, which is why there is no longer an apiShape
# field: it selected nothing and said so in its own comment.
matchPaths:
- ":generateContent"
- "/chat/completions"
timeout: 5s
# Each feature below compiles to a named set of Apigee policies. The values
# you set here become those policies' configuration fields, so the policy
# reference is the authority on what each one accepts and how it behaves.
#
# feature Apigee policies it generates
# ------------------- ----------------------------------------------------
# identity VerifyJWT, AssignMessage
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/verify-jwt-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/assign-message-policy.md.txt
# tokenMetering Javascript, LLMTokenQuota (one per model), AssignMessage
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/llm-token-quota-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/javascript-policy.md.txt
# modelArmor SanitizeUserPrompt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-user-prompt-policy.md.txt
# (response-side equivalent, not generated today:
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/sanitize-llm-response-policy.md.txt)
# semanticCache SemanticCacheLookup, SemanticCachePopulate
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/semantic-cache-lookup-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/semantic-cache-populate-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/parse-payload-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/verify-api-key-policy.md.txt
# https://docs.cloud.google.com/apigee/docs/api-platform/reference/policies/quota-policy.md.txt
#
# Field-by-field mapping, including which parameter drives which policy
# element: references/recipes.md.
features:
# ---- always on ---------------------------------------------------------
identity:
enabled: true
# Fallback when the gateway's IAP-egress JWT is absent. An absent header
# skips verification entirely; only a present-but-invalid token fails
# closed.
defaultClientId: anonymous
tokenMetering:
enabled: true
#
# COUNT_ONLY | ENFORCE. Same shape as modelArmor.mode below, and the
# same question: does this observe, or does it refuse?
# COUNT_ONLY meters every call and blocks nothing. `limit` is the
# denominator you measure against, for alerts and
# chargeback. This is the default.
# ENFORCE also refuses a caller that has spent its budget, with a
# 429, before the model is called. Adds
# feature-token-enforce.yaml. Verified live on ext-proc
# traffic.
#
# ENFORCEMENT IS ONE REQUEST LATE BY CONSTRUCTION: the turn that crosses
# the limit completes, because its cost is not known until the model
# answers, and the caller's NEXT request is refused. A token budget
# cannot be checked before the tokens exist. Say this when offering it.
#
# Do NOT try to get enforcement by making the response-flow quotas
# blocking. Verified on a live gateway, it fails in both directions:
# - It cannot deny. The quota runs on the RESPONSE, because the token
# count does not exist until the model has answered. The bytes are
# already going back to the caller by then -- Apigee aborts and emits
# 429, and the caller still gets the full answer.
# - It breaks the metering you already had. A blocking quota will not
# count the request that violated it, so the counter sticks at the
# limit for the rest of the window.
# That is a property of that placement, not of the policy.
#
# One caveat specific to ENFORCE: it buckets on the REQUESTED model,
# because the resolved name only exists in the response. Under an
# OpenAI-compatible alias a call can be enforced against one bucket and
# counted against another. Everything is still counted and still checked.
mode: COUNT_ONLY
interval: 1
timeUnit: hour
# THESE THREE BUCKETS ARE THE THREE THAT EXIST. The list is not
# generative: each bucket must also have an LLMTokenQuota step in
# feature-token-metering.yaml and a matching template parameter, so
# adding a fourth here on its own meters nothing.
models:
- bucket: gemini-pro
limit: 10000
- bucket: gemini-flash
limit: 40000
# Catch-all: every model whose name contains neither "pro" nor
# "flash" -- gpt-oss, Llama, Qwen, DeepSeek. Without it those calls
# consume no quota at all: the token count is extracted correctly and
# then discarded, with zero ratelimit references in the transaction
# and nothing reporting the gap.
- bucket: other
limit: 40000
# ---- optional recipes --------------------------------------------------
modelArmor:
enabled: false
# REQUIRED when enabled -- there is deliberately no default. A shipped
# default either names a template that does not exist in your project
# (the deploy fails for a reason that reads like a permissions problem)
# or, worse, silently points at a real template that screens nothing you
# chose. Prod mode refuses with the field named, as it does for
# semanticCache without deployedIndexId.
template: ""
# Needs roles/modelarmor.user on deploymentServiceAccount.
#
# ENFORCE | DRY_RUN. One of two policies here that can refuse a request;
# the other is tokenMetering.mode: ENFORCE. With Model Armor off or in
# DRY_RUN and metering at COUNT_ONLY, nothing here blocks anything.
# ENFORCE a filter match faults the policy; the caller gets a 400.
# DRY_RUN the scan still runs and the verdict is still in the trace,
# but the fault is swallowed and the turn continues.
# DRY_RUN is NOT "off": removing the feature means no evaluation at all.
# Use it to watch what a template would have blocked before letting it.
#
# Defaults to ENFORCE on purpose. A security control that silently does
# not protect is worse than one that visibly blocks, and silent
# non-protection is the failure class this whole skill exists to prevent.
# Toggling requires a redeploy (~2 min) -- deliberate, which suits a
# change that decides whether live agent turns can be refused.
mode: ENFORCE
semanticCache:
# A CACHE HIT CROSSES CALLER BOUNDARIES. The key is the embedding of the
# prompt and nothing else -- no caller, no model, no wire shape, no
# tenant. One model and one wire shape does NOT make this safe: two
# callers whose prompts are merely SIMILAR share an answer, so anything
# caller-specific leaks from whoever asked first. Identity is on by
# default and agw.client_id is available, but the cache policies accept
# no discriminator, so it cannot be scoped.
#
# Enable this only where every caller is entitled to every other
# caller's answer for the same question.
#
# Two further effects once more than one model answers here. Across wire
# shapes the cached body is in the wrong format, the client parses
# nothing, and the turn returns an EMPTY SUCCESS rather than an error --
# which reads as "the agent stopped working" and sends you into the agent
# code, the one place the cause is not. Reproduced across three
# consecutive runs. Within one shape it is quieter and worse: the body
# parses, and only model_version differs.
#
# KNOWN ISSUE, NOT A BLOCK. The skill builds the cache and warns rather
# than refusing, and it warns whenever the cache is enabled -- not only
# when matchPaths carries more than one entry. The defect is upstream and
# a fix is expected. See references/gotchas.md (Runtime) for mitigations
# and the upstream bug.
enabled: false
threshold: 0.95
ttlSeconds: 60
# PICK THIS BEFORE YOU BUILD THE INDEX, NOT AFTER. The policy takes only
# a URL, so the model's native width is what the index must be, and index
# width is fixed at creation. Changing it later is an index rebuild, not
# a config edit. Measured widths:
#
# gemini-embedding-001 3072 stronger; 4x storage
# text-embedding-005 768 <- default, supported
# text-multilingual-embedding-002 768
# text-embedding-004 768 still serves, but has dropped
# off the supported-models list
#
# 768 is ample for cache duty. Use gemini-embedding-001 only if you
# deliberately want the stronger model and a 3072 index to match.
embeddingsModel: text-embedding-005
# <DeployedIndexID> -- all-caps ID. DeployedIndexId fails validation.
# Lowercase, digits and underscores only; hyphens are rejected.
deployedIndexId: agent_gateway_llm_cache
# CREATED BY THE SKILL if absent: scripts/ensure_vector_search.sh builds
# the index and endpoint, deploys one onto the other, and prints these
# ids as JSON. It is --yes gated and resumable, which matters because the
# deploy step alone takes about 34 minutes.
#
# THIS IS THE ONLY PART OF THE SKILL THAT BILLS CONTINUOUSLY: a deployed
# index costs per node-hour for as long as it is deployed, with or
# without traffic. To stop the cost, undeploy it -- see the teardown
# order the script prints, which matters because SCL-lookup is
# fail-closed and undeploying underneath a live proxy faults every
# request.
#
# There is deliberately no field for the endpoint's domain. It cannot be
# derived from either id, so deploy_proxy.sh reads it back at deploy
# time from --index-endpoint-id.
indexEndpointId: ""
indexId: ""
# Needs roles/aiplatform.user on deploymentServiceAccount.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs a command-line tool, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Publisher
- Google (Official)
- Source
- google/skills · skills/cloud/apigee-agent-gateway-governance · commit 2194d3b
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download apigee-agent-gateway-governance.zip