Back to Hub
Certification Study Notes · v2.0

Agent Platform: Build, Retrieve & Run

Gemini Enterprise Agent Platform end-to-end engineering reference: the three build paths (Agent Studio, Managed Agents API + Skill Registry, and code-first ADK / LangGraph with agent-starter-pack & agents-cli), Agent Runtime vs. Cloud Run vs. GKE, Context Engineering (Sessions, Memory Bank, Example Store), Code Execution sandboxing, enterprise grounding & MCP servers, 2-step user simulation & environment simulation, Agent Registry observability & dual-attribution audit logs, failure cluster analysis & prompt optimization, and FinOps quota controls.

Author: Michaël Bettan
Updated: October 2026 (v2.0)
Track: Google Cloud / Agentic AI Architect
Test Yourself: Agent Platform Practice Quiz →
00

Overview & Mental Model

Definition

Gemini Enterprise Agent Platform is the evolution of Vertex AI for building, scaling, governing, and optimizing production agents on Google Cloud. This guide covers the build, retrieve, run, and optimize half: choosing among Agent Studio, the Managed Agents API, and code-first ADK / open frameworks, hosting agents on Agent Runtime (formerly Agent Engine), managed Sessions, Memory Bank, Example Store, and the Code Execution sandbox, choosing between Agent Runtime, Cloud Run, and GKE, enterprise retrieval and MCP tooling, 2-step user simulation and environment simulation, Agent Registry observability, programmatic prompt optimization, and FinOps quota management.

Companion Architecture Guides

Cryptographic Agent Identity, IAM, Principal Access Boundary (PAB), VPC Service Controls, Model Armor, Sensitive Data Protection, and Agent Gateway policies live in Agent Platform Security & Governance. Code-level ADK patterns live in the ADK guide; cross-agent wire protocols and A2UI/AP2 in A2A & Interoperability; vendor-neutral RAG in RAG; Gemini 4 Argon and Model Garden in Gemini & Google Models.

Mental model — 5-part agent anatomy on Google Cloud

The model (Gemini 4 Argon, Gemini 3.8 Flash…) is the reasoning brain; the orchestration layer (ADK, LangGraph, Managed Agents harness, or Agent Studio) wires the Think → Act → Observe loop; Agent Runtime is the managed body keeping long-running tasks alive; Sessions are short-term working memory for one conversation while Memory Bank is consolidated long-term memory across conversations; MCP servers, retrieval services, and the Code Execution sandbox are the hands and library; Evaluation + Observability + Agent Optimizer form the continuous AgentOps quality flywheel.

Rule 0 — managed by default

Choose the most managed component that meets the requirement. Move down the stack (Managed Agents API / Agent Studio → Agent Runtime → Cloud Run → GKE) only for a concrete engineering need: custom orchestration code, hosting stateless Streamable HTTP MCP servers, non-Python stacks, GPUs/self-hosted open weights, or kernel-level isolation.

Naming, preview status and limits evolve

Product names, preview status, quotas, and regional availability change frequently. Items marked Preview are Pre-GA without GA SLAs. Verify current limits and pricing in official Google Cloud documentation before production commitment.

01

1. Platform Map: Naming, Pillars & Build Paths

PillarWhat it coversKey components
BuildCreate agents, mount skills/tools, and connect to enterprise dataADK (Python, Go, Java, TS), Agent Studio (low-code), Managed Agents API + Interactions API Preview, Skill Registry, Agent Garden, Model Garden (200+ models), RAG Engine, Agent Search, Agent Retrieval, agent-starter-pack, agents-cli
ScaleRun stateful, multi-step agents reliably in productionAgent Runtime (reasoningEngines), Sessions, Memory Bank, Example Store Preview, Code Execution sandbox, A2A Agent Hosting Preview
GovernControl identity, discovery, egress, and security policyAgent Registry, Agent Identity (SPIFFE), Agent Gateway, Model Armor, governance policies → see Security guide
OptimizeSimulate, evaluate, observe, and continuously improve qualityGen AI Evaluation Service (2-step user simulation, environment simulation, adaptive rubrics, trajectory metrics, Online Monitors), Agent Registry Observability, Failure Cluster Analysis, Prompt Optimization / Agent Optimizer

Billing model: Agent Platform uses pay-as-you-go developer consumption (tokens, runtime vCPU/GiB-seconds, deployed index node-hours) with optional Provisioned Throughput (GSUs); the Gemini Enterprise app (formerly Agentspace) is a separate per-seat subscription workspace where business users discover and invoke published agents.

Build PathBuilder & Control LevelLoop, State & Sandbox OwnershipBest Fit
1. Agent Studio (low-code)Domain experts & rapid prototypersVisual canvas configuring Gemini model, system prompt, grounding data stores, MCP tools, and sub-agents; 1-click deploy to Agent Runtime or Gemini Enterprise Workflow BuilderDepartmental assistants, rapid enterprise RAG validation before pro-code handoff
2. Managed Agents API PreviewDevelopers wanting a declarative REST/SDK harnessPairs Agents API + mounted Skill Registry bundles with stateful Interactions API (previous_interaction_id, background=true). Google runs the loop, restarts, artifacts, and an isolated Linux sandbox with no network egress by default (powers Antigravity Agent & Deep Research).Autonomous coding, file/spreadsheet processing, and multi-hour synthesis with zero harness ops
3. Code-first ADK & Open FrameworksSoftware & AI engineers needing deterministic code controlAuthor custom control flow and callbacks in ADK, LangGraph, CrewAI, AG2, or LlamaIndex; scaffold Terraform + CI/CD eval gates via agent-starter-pack & agents-cli; deploy to Agent Runtime, Cloud Run, or GKEComplex multi-agent graphs, strict compliance guardrails, custom hybrid A2A meshes
Current nameFormer nameExam / API note
Gemini Enterprise Agent PlatformVertex AIEvolution of the same platform; IAM permissions still use aiplatform.*
Gemini Enterprise (end-user app)Google AgentspaceUnified enterprise search + multi-agent hub supporting A2A and A2UI
Agent RuntimeAgent Engine / Reasoning EngineThe REST/gRPC resource remains projects/…/locations/…/reasoningEngines/<id>
Agent SearchVertex AI SearchTurnkey managed search/RAG (discoveryengine) with connectors and native ACLs
Agent RetrievalVector Search 2.0Collections-based, self-tuning vector store with schema & auto-embeddings
Vector Search 1.0Matching EngineHigh-scale ScaNN ANN index-as-a-service
Workflow Builder (Gemini Enterprise)Agent DesignerNo-code builder for chat agents and scheduled workflows in Gemini Enterprise
Gemini 4 Argon / Gemini 3.xGemini 1.5 / PaLM 2Active frontier (gemini-4-argon) and agentic workhorse (gemini-3.8-flash)

Model Garden pointer

Model Garden catalogs Google first-party (Gemini 4 Argon, Gemini 3.8 Flash, Nano Banana 2.1, Gemini Omni 1.1 Flash, Veo 3.1, Lyria 3.5, Chirp 3), partner MaaS (Anthropic Claude, Mistral, DeepSeek), and open-weight models (Gemma 4, Gemma 3n, Llama). Model selection and tuning live in the Google guide. Gemini itself is served exclusively through managed Google endpoints — you cannot self-host Gemini on Cloud Run or GKE; open models such as Gemma 4 can be self-hosted there.

02

2. Agent Runtime & Production Tooling

Agent Runtime is a fully managed, opinionated compute runtime for stateful agents: sub-second cold starts, long-running and multi-day asynchronous workflows, optional min_instances for warm capacity, IAM and VPC Service Controls enforcement, private VPC/on-prem egress through a Private Service Connect (PSC) interface network attachment, cryptographic Agent Identity, and built-in integration with Sessions, Memory Bank, Example Store, Code Execution, A2A, and OpenTelemetry.

Framework & protocol support

  • First-class native integration: ADK (Python: adk deploy agent_engine or agents-cli; Go via adkgo; Java & TypeScript via containers)
  • SDK templates: LangChain, LangGraph, AG2, LlamaIndex Preview
  • Custom Python class: CrewAI or any custom class implementing query / async_query / stream_query
  • A2A agent hosting: native A2aAgent wrapper Preview exposing an AgentCard and task store on Agent Runtime
  • Any language: custom Dockerfile or Artifact Registry image conforming to the runtime HTTP contract

SDK, agent-starter-pack & agents-cli

  • Agent Platform SDK: google-cloud-agentplatform exposes agentplatform.Client(project=…, location=…) with client.runtimes, client.sessions, client.sandboxes, and client.memory_banks (replacing legacy agent_engines).
  • agent-starter-pack & agents-cli: scaffolds production Terraform IaC, Cloud Build / GitHub Actions CI/CD with automated agents-cli eval regression gates, OpenTelemetry spans, and BigQuery feedback sinks.
  • Managed Agents API Preview: declarative Agents API + Skill Registry + stateful Interactions API running in an isolated Linux container with no network access by default.
Deployment methodLanguagesBest for
Developer Connect (Git repository)PythonGitOps CI/CD — builds and deploys directly from a connected Git repo
Source files (inline directory)PythonAutomated CI/CD pipelines and Terraform; no Cloud Storage staging bucket needed
DockerfileAnyCustom OS packages or non-Python agents (Go, Java, TypeScript)
Container image (Artifact Registry)AnyPre-built, vulnerability-scanned images promoted across environments; lowest deployment latency
SDK object (in-memory)PythonNotebooks/Colab prototyping; the agent object must be serializable

Common trap — reserved environment variables

Do not set platform-managed variables such as GOOGLE_CLOUD_PROJECT or PORT in your deployment config, and avoid the GOOGLE_CLOUD_AGENT_ENGINE prefix for custom variables (except documented flags like GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY=true).

Exam tip

Agent Runtime hosts stateful agent orchestrators, not standalone MCP tool servers. Deploy custom Streamable HTTP MCP servers on Cloud Run or GKE, register them in Agent Registry, and call them from your agent.

03

3. Choosing a Runtime: Agent Runtime vs. Cloud Run vs. GKE

CriterionAgent RuntimeCloud RunGKE
Best fitStateful Python/ADK/LangGraph/A2A agents; fastest path to productionPolyglot containerized agents, webhook services, and Streamable HTTP MCP serversSelf-hosted open weights (Gemma 4 on GPUs/TPUs), dense K8s fleets, custom kernel isolation
Ops overheadLowest (fully managed agent harness)Low (serverless containers)Highest (you manage cluster & node lifecycle)
StateBuilt-in Sessions, Memory Bank, Example Store, Code ExecutionStateless — externalize to Agent Platform Sessions, Memorystore, Firestore, or Cloud SQLStatefulSets, local SSDs, or external managed stores
Scaling & durationManaged autoscaling; min_instances for warm capacity; multi-day workflowsScale to zero; HTTP timeout up to 60 minutes; Services, Jobs, Worker poolsFull control (HPA/VPA, node pools, GPU sharing)
Isolation & securityIAM, VPC-SC, PSC interface, Agent Identity, Code Execution sandboxIAM, Direct VPC egress, built-in Agent Identity & Agent Registry integrationWorkload Identity Federation, GKE Sandbox (gVisor), NetworkPolicies
Hosts MCP servers?NoYes (Streamable HTTP)Yes
Weak spotNo custom GPUs; non-Python stacks need a custom containerEphemeral in-process memory lost on scale-to-zeroOperational & platform engineering burden
01

Python/ADK, minimal ops, managed memory

→ Agent Runtime (or Managed Agents API for zero-code harness).

02

Already standardized on Cloud Run or GKE

→ Reuse existing platform investments where ops tooling is mature.

03

Any language, scale-to-zero, or MCP servers

→ Cloud Run (Streamable HTTP MCP servers & event-driven webhooks).

04

GPUs, Gemma 4 weights, gVisor isolation

→ GKE with accelerator node pools and fine-grained NetworkPolicies.

05

Tiered model routing

Route easy steps to Gemini 3.5 Flash-Lite, loops to 3.8 Flash, hard plans to 4 Argon.

Common trap — "stateless Cloud Run remembers"

A Cloud Run instance can be replaced or scaled to zero at any moment. Conversation state kept in process RAM vanishes. Persist it in Agent Platform Sessions (--session_service_uri agentengine://<id>), Memorystore, Firestore, or Cloud SQL.

04

4. Context Engineering: Sessions, Memory Bank & Example Store

Production agents apply context engineering — assembling only relevant recent events, compacted summaries, scoped long-term user facts, and top-k dynamic examples per turn to prevent context rot and runaway token spend.

AbstractionScopeLifetime
SessionChronological append-only sequence of events (messages, thoughts, tool calls/outputs) for one interactionOne conversation (apply sliding-window compaction on long threads)
StateMutable key-value scratchpad attached to a session (temp:, session, user:, app: prefixes in ADK)Current turn or current conversation
Memory BankLLM-extracted, consolidated semantic facts & preferences about a user/entityPersistent across sessions (governed by TTL & revisions)

Sessions: ADK agents deployed to Agent Runtime get managed sessions automatically. Outside Agent Runtime (Cloud Run, GKE, local), point ADK at the managed service with --session_service_uri agentengine://<id>.

Memory Bank

Common trap — persistent memory poisoning

Untrusted external tool outputs (emails, web pages, tickets) processed during memory extraction can plant malicious instructions into Memory Bank that replay across future sessions. Screen inputs with Model Armor, constrain Memory Topics, and audit memory revisions (Security guide).

Example Store Preview

Stores curated few-shot input→trajectory/output demonstrations and injects only the most semantically relevant ones dynamically at inference time. The embedding model (e.g., text-embedding-005, text-multilingual-embedding-002, or gemini-embedding-001) is immutable after instance creation; changing embedding models requires creating a new instance. Default quota: 50 instances per project per region.

NeedRight Component
Remember what this user said three turns ago in the chatSession events / scratchpad state
Remember user preferences and recurring project context next monthMemory Bank
Steer complex tool trajectories or output schemas with dynamic few-shot exemplarsExample Store Preview
Answer grounded in 50,000 permissioned enterprise documentsAgent Search / Retrieval (Section 06)
05

5. Code Execution Sandbox

The Code Execution sandbox runs untrusted, model-generated Python inside an isolated container: sub-second startup/execution, file I/O up to 100 MB, and stateful sandbox files/variables persisting up to 14 days (configurable TTL). ADK's AgentEngineSandboxCodeExecutor binds one sandbox per session so DataFrames and generated charts carry across turns — and can be invoked even when your agent runs on Cloud Run or GKE. Similarly, the Managed Agents API Linux sandbox blocks outbound network egress by default while mounting approved Skill Registry assets.

Mental model — runtime vs. sandbox

The runtime executes trusted orchestration code you wrote and reviewed (holding IAM/MCP credentials). The sandbox executes untrusted code synthesized by the model at runtime. Never run LLM-generated code via exec() inside the agent's own container.

Common trap — over-provisioning the sandbox

Injecting service-account tokens or opening unrestricted internet egress inside a code sandbox defeats containment. Pass input data strictly as scoped files and read sanitized outputs back.

06

6. Grounding, Retrieval & MCP Tooling on Google Cloud

ServiceTypeChoose whenWatch out for
Agent Search (formerly Vertex AI Search)Turnkey managed search/RAGEnterprise corpora (Drive, SharePoint, Confluence, Jira, GCS, BigQuery) needing built-in parsing, hybrid search, reranking, and native document-level ACLsLess low-level control over custom chunking or bespoke embeddings
RAG EngineCode-first managed RAG pipelineYou want explicit control over parsers (Document AI Layout Parser, LLM parser), chunking, embeddings, and vector DB (RagManagedDb, Agent Retrieval, Vector Search 1.0, Pinecone, Weaviate; the choice depends on the deployment mode)Check regional & model matrix (gemini-4-argon is not directly bound as a RAG Engine generator; Agent Retrieval corpora require supported regions + cosine metric)
Vector Search 1.0ScaNN ANN index-as-a-serviceTens of millions to billions of custom vectors (text or multimodal embeddings you compute yourself) at single-digit-ms latencyDeployed index endpoints bill continuously even when idle
Agent Retrieval (formerly Vector Search 2.0)Self-tuning collection storeSchema-aware collections of Data Objects with managed auto-embeddings or BYO embeddingsExact KNN up to ~100k objects; create an ANN Collection Index beyond ~100k
Grounding with Google Search / Maps / WebLive public-index groundingFresh public facts, places/geospatial context, or enterprise web grounding (Parallel, Exa)Must render required Search Suggestions & attribution metadata
BigQuery (VECTOR_SEARCH)In-warehouse SQL vectorsAnalytical batch enrichment, warehouse joins, and offline evaluation pipelinesMulti-second startup latency — not a sub-100ms interactive chat store
AlloyDB / Cloud SQL (pgvector / ScaNN)Operational OLTP vectorsLow-latency vector similarity filtered alongside live transactional SQL rowsYou manage sizing, pooling (MCP Toolbox), and index tuning

RAG Engine pipeline

Ingestion (local files, Cloud Storage, Google Drive, Slack/Jira connectors) → transformation (chunking via default parser, LLM parser, or Document AI Layout Parser) → embedding → corpus index → retrieval → generation. Vector store options depend on the deployment mode: Spanner mode offers RagManagedDb (default), Agent Retrieval, Vector Search 1.0, Pinecone, and Weaviate; Serverless mode defaults to an Agent Retrieval collection (Pinecone and Weaviate as alternatives). Both modes support VPC-SC; only Spanner mode supports CMEK.

Precision & citation verification

  • Ranking API (semantic-ranker-default@latest): stateless cross-encoder reranker applied to top-N candidates from any retriever.
  • Check Grounding API: scores claim-by-claim factual support against supplied context chunks to block hallucinations.
  • Grounding metadata: webSearchQueries, searchEntryPoint, groundingChunks, groundingSupports — render verifiable citations.
  • Agent Search grounding: attach up to 10 data stores per request; IAM roles roles/discoveryengine.viewer / editor.

ADK built-in retrieval tools: google_search (web grounding), VertexAiSearchTool (Agent Search data store), VertexAiRagRetrieval (RAG Engine corpus), VertexAiRagMemoryService (RAG-backed memory).

Google Cloud MCP servers & enterprise tool integrations

Common trap — wrong distance metric

When an Agent Retrieval / Vector Search index backs a RAG Engine corpus, configure the distance metric as COSINE. RAG Engine queries using cosine distance, so leaving the index at default DOT_PRODUCT fails with FAILED_PRECONDITION.

Vector Search 1.0 vs. Agent Retrieval vs. RAG Engine

When the matrix above leaves two vector options close, compare them on these dimensions.

DimensionVector Search 1.0Agent RetrievalRAG Engine
Object modelDatapoints (ID, embedding, optional filter metadata) in an index deployed to an endpoint; source records live in a separate storeJSON Data Objects (payload fields plus one or more vector fields) inside a schema-validated CollectionRagCorpus and RagFile resources; vectors go to a backing vector database
Embedding pipelineBring your own dense (and, for hybrid, sparse) vectors before upsertingYour own vectors, or automatic fill from a vertex_embedding_config (model ID, text template over payload fields, task type) when a Data Object arrives without that vectorParses, chunks, and embeds files for you at import time
Hybrid search and rerankingDense plus sparse index fused with Reciprocal Rank Fusion (RRF), weighted by rrf_ranking_alpha; you build sparse vectors (for example TF-IDF)Semantic plus built-in keyword text search through RRF; optional Ranking API rerankReranking in RagRetrievalConfig (rank_service or llm_ranker); hybrid_search.alpha applies only with Weaviate
Agent and MCP integrationCustom function tool or your own MCP serverGoogle-managed remote MCP server (Preview, read-only tools)Corpus attached to Gemini requests as a vertex_rag_store retrieval tool
Scaling and costDeployed index endpoints bill by node-hour, even when idleBrute-force KNN with no index; add a Collection Index near 100,000 Data Objects or when KNN latency is too high; usage-based or resource-based pricingDepends on the deployment mode (see below)

RAG Engine deployment modes

One RAG API routes to whichever mode the project has active; corpora created under the other mode stay stored but hidden until you switch back.

  • Serverless mode: no tier management, autoscales, and by default provisions an Agent Retrieval collection in your project as the vector database (Pinecone and Weaviate are alternatives; RagManagedDb is not offered). Storage is not isolated and CMEK is not supported.
  • Spanner mode (default when no mode is chosen): dedicated Spanner instance at the Basic tier (default, fixed low compute) or the Scaled tier (autoscaling, production volumes); the Unprovisioned tier deletes the instance and its data. Isolates storage and performance, supports CMEK, and offers RagManagedDb (default), Agent Retrieval, Vector Search 1.0, Pinecone, and Weaviate.
  • Both modes support VPC Service Controls.

When to choose and CMEK

  • Vector Search 1.0: existing pipelines with your own embedders and tuned, always-on ANN endpoints.
  • Agent Retrieval: a new custom agent store that keeps payload and vectors together, with auto-embeddings, keyword plus semantic search, and an MCP server.
  • RAG Engine Serverless mode: the fastest managed document RAG when CMEK is not required.
  • RAG Engine Spanner mode (or a CMEK-enabled Agent Retrieval collection): when policy demands CMEK or isolated storage and performance.
  • CMEK on Agent Retrieval: set the Cloud KMS key (same region as the collection) at Collection creation (--kms-key). An existing collection cannot be switched; export its Data Objects to Cloud Storage and import them into a new CMEK collection.

Anti-pattern: Serverless mode under a CMEK mandate

Serverless mode has no CMEK option, so a key-management policy rules it out. Pick Spanner mode before importing data, because corpora do not carry over between modes.

Managed remote MCP servers agents use most

Google-hosted HTTPS endpoints; callers need roles/mcp.toolUser (mcp.tools.call) plus IAM on the underlying resources.

Server (endpoint host)What the agent can doAuth notes
BigQuery (bigquery.googleapis.com)Discover datasets and tables, read schemas, run SQL over warehouse data without copying tables into the promptIAM principal; BigQuery row/column controls still apply
Cloud SQL (sqladmin.googleapis.com)Create, manage, and query MySQL, PostgreSQL, and SQL Server instances (execute_sql, execute_sql_readonly)IAM principal; prefer the read-only tool for analysis agents
AlloyDB / Spanner / FirestoreManage resources and run queries or document operations against operational dataIAM principal; AlloyDB regional endpoints are Preview
Cloud Storage (storage.googleapis.com/storage/mcp)List buckets and read or write objects such as reports and artifactsIAM principal plus bucket IAM
Agent Retrieval (vectorsearch.googleapis.com) PreviewInspect collections and indexes; run vector, semantic, hybrid, and text search (nine read-only tools, no write tools)IAM principal; the client sends routing headers (such as the target project) on every tools/call
Cloud Logging / Monitoring / TraceQuery logs, metrics, and traces while troubleshooting agentsIAM principal with observability viewer roles
Developer Knowledge and Maps Grounding LiteSearch Google developer documentation; look up places and location factsGoogle (non-Cloud) servers: API key or OAuth, no roles/mcp.toolUser, and not controllable through IAM policies

Check the supported products list

The catalog grows quickly and launch stages differ per server and per endpoint. Check the public Supported products list for Google Cloud MCP servers before you design around a specific server.

Integration layer decision table

Pick the thinnest integration layer that still gives the agent narrow, governed tools.

OptionCustom logicOps burdenTypical authChoose when
Managed remote MCP serverNone (Google-defined tool schemas)None (Google-hosted)Agent identity, service account, or user OAuth; IAM on roles/mcp.toolUser + resource rolesStandard access to Google Cloud data and infrastructure with no server to run
MCP Toolbox for DatabasesDeclarative (tools.yaml parameterized SQL)Low to medium (you run the container on Cloud Run or GKE)IAM database auth or per-tool OAuth/OIDCAgents must run only vetted, parameterized queries against your databases
Custom MCP server on Cloud RunFull (any language, multi-API composition)Medium (image, scaling, patching)Service account or agent identity; IAP in frontProprietary business workflows or internal services with no managed server
OpenAPI tool (ADK OpenAPIToolset)Lives in the existing REST serviceLow when a spec already existsAPI key, OAuth, or service accountWrapping a well-documented REST API without standing up an MCP server
Application Integration connectorsVisual flows and data mappingLow (managed connectors)Managed connector auth profilesSaaS ERPs/CRMs (SAP, Workday, ServiceNow) without a native MCP endpoint

Anti-pattern: one generic run_any_sql tool

Handing the model unrestricted SQL turns every prompt injection into a database incident. Prefer read-only tools, parameterized Toolbox tools, or narrow custom tools.

How Agent Registry records MCP servers

  • Google and Google Cloud servers register automatically when the API is enabled, tools included. The McpServer resource exists only in global; regional endpoints appear in its interfaces field, so query with --location=global (a regional query returns NOT_FOUND).
  • Custom servers on Cloud Run register automatically when deployed with gcloud beta run deploy --functional-type=mcp-server (services only; Cloud Run jobs can't be MCP servers). --identity-type (beta) selects agent-identity or service-account (default).
  • Custom servers on GKE register automatically from the registry.gke.io/functional-type: "MCP_SERVER" label plus modelcontextprotocol.info/* annotations; GKE fetches the tool spec from the running server.
  • External servers, and cross-project servers without a management boundary, need manual registration (gcloud agent-registry services create … --mcp-server-spec-type=tool-spec) with an uploaded toolspec.json (MCP tool schema, 10 KB max) listing tool names, descriptions, and annotations such as readOnlyHint or destructiveHint.
  • Data residency: register manually in a specific region when registry metadata must stay there. Role: registering requires roles/agentregistry.editor on the governance project.

Transports and identity choice

  • Transport: stdio runs the server as a local child process on the same machine (IDEs, CLIs, local Toolbox); Streamable HTTP over HTTPS is required for remote and production servers on Google infrastructure, Cloud Run, or GKE.
  • Identity: a service account or agent identity acts on the agent's own authority (recommended for production so permissions and logs are scoped to the agent); end-user OAuth runs and logs actions as the user, needed when downstream tools enforce per-user ACLs (brokered through Auth Manager).
  • Stateless MCP: Google Cloud remote servers support MCP version 2026-07-28, which drops the initialize handshake and Mcp-Session-Id; each request carries what it needs in HTTP headers or _meta, so load balancers route without parsing bodies.
  • Agent identity vs. service account: agent identities are SPIFFE-based, not shared across workloads by default, can't be impersonated, and don't allow long-lived keys.
  • Security controls (Agent Gateway egress policies, IAP tool-level authorization, Model Armor screening of MCP traffic) are covered in the Security guide.

Skill Registry lifecycle Preview

Skill Registry is the Agent Platform repository for agent skills in the open Agent Skills layout: a SKILL.md file plus optional scripts/, references/, and assets/ folders. Agents load a skill only when the task calls for it. Agent Registry can also hold the same packages as standalone skills, with its own API, roles, and tighter payload limits, so keep the two paths apart.

StageSkill Registry (Agent Platform API)Agent Registry standalone skills
AuthorSKILL.md front matter: name (required, max 64 characters, lowercase letters, digits, and hyphens, no leading or trailing hyphen), description (required, max 1,024 characters), optional license. Body max 500,000 characters. The skill ID (1 to 63 characters, starts with a letter) stays reserved after deletion; the gcp- prefix is reserved for built-in skillsSame SKILL.md at the zip root with valid front matter per the Agent Skills specification
Publish and validateCreateSkill long-running operation (REST v1beta1 or client.skills.create) with a base64 zip. Validation rejects a zip over 10 MB, over 500 MB unzipped, over 10,000 entries, nested deeper than 8 folders, compression ratio over 100, any symbolic link, duplicate names, .. or absolute paths, or a missing SKILL.mdgcloud alpha agent-registry skills create with --payload or --gcs-source-uri. Limits: 500 KB compressed, 10 MB uncompressed, 1 MB per file, 8 folder levels. The ID gets a private- prefix; a Cloud Storage import needs the Agent Registry service agent to hold storage.objects.get
RevisionsEvery create or update stores an immutable skill revision; GetSkill returns the latest, and ListSkillRevisions / GetSkillRevision expose historyNew skills start DISABLED; set the default revision and switch the target state to Active before agents can discover it
DiscoverListSkills returns name, display name, and description; RetrieveSkills runs semantic search over them. The built-in gcp-skill-registry skill lets an agent create, search, and manage skills itselfAgent Registry search across agents, MCP servers, and skills
AuthorizeInherits project IAM: roles/aiplatform.user to manage skills, roles/aiplatform.viewer for read-only accessroles/agentregistry.viewer (discover and read), roles/agentregistry.user (plus create, update, delete skills and revisions), roles/agentregistry.editor (plus agents, MCP servers, endpoints), roles/agentregistry.admin (plus bindings and skill IAM policies)
Govern at runtimeSemantic governance policies (Preview) intercept the ADK skill tools and judge each call against natural language constraints (NLCs)Same policies apply, because loading a skill is itself a tool call

Progressive disclosure through four ADK skill tools

  • list_skills shows the model only the catalog of skill names and descriptions.
  • load_skill pulls one skill's full instructions and tools into context.
  • load_skill_resource fetches a referenced file or asset on demand.
  • run_skill_script executes the skill's bundled code. Each tool is a point where a policy can return a verdict.

Compliance and runtime controls

  • Compliance: Access Transparency and US/EU data residency are supported; CMEK, VPC Service Controls, and HIPAA are not. Regions: us-central1, europe-west4, us-east5.
  • Tainted-session control: an NLC can deny load_skill for any skill that sends messages or writes externally once the history contains web, email, or uploaded content.
  • Supply-chain control: an NLC can inspect the arguments of an install tool triggered by skill instructions and deny packages outside an allowlist.
  • Caveat: semantic governance uses an LLM, so verdicts are probabilistic. Keep IAM and network egress controls as the deterministic layer.

Anti-pattern: registry admin roles on agents

Granting roles/agentregistry.admin or roles/agentregistry.editor to an agent identity lets a compromised agent alter tool definitions or enroll a malicious agent. On the standalone-skills path, give consuming agents roles/agentregistry.viewer and publishers or CI pipelines roles/agentregistry.user; on the Skill Registry path, use roles/aiplatform.viewer for consumers and roles/aiplatform.user for publishers.

Anti-pattern: IAM as the only skill control

IAM decides who may publish or read a package, but an authorized agent can still be steered by injected content into loading a powerful skill. Pair IAM with semantic governance policies.

07

7. Caching & External State

StoreRole in an agent system
Gemini Context CachingImplicit caching (on by default, zero storage fee; the only cache mode supported on gemini-4-argon) and Explicit caching (cachedContents with TTL + hourly storage on eligible Gemini 2.5/3.x base models) for large repeated instructions/corpora
Memorystore for Redis / ValkeySub-millisecond hot cache, rate-limit/budget counters, idempotency locks, and semantic response caching via Redis HNSW/FLAT vector search
FirestoreServerless document store for real-time client state sync, HITL approval queues, and user profiles
Cloud SQL / AlloyDBACID relational state; backs ADK DatabaseSessionService when SQL querying over sessions is required
Agent Platform SessionsZero-ops managed session/event persistence for ADK and Agent Runtime
BigQueryLong-term analytics, audit/trace sinks, failure-cluster mining, and offline evaluation datasets — never hot-path turn state

Semantic cache pattern: embed incoming query → vector lookup in Memorystore → if similarity ≥ threshold within the caller's ACL partition, return cached answer; otherwise invoke the agent and store with TTL.

Common trap — caching across permission boundaries

A global semantic cache shared across users can leak answers synthesized from restricted HR/finance documents to unauthorized callers. Always partition semantic cache keys by tenant/role/ACL scope or skip response caching for permission-sensitive corpora.

Choosing data services by agent data need

Split agent data by access pattern rather than putting everything in one database. Each row names the default pick and the usual fallback.

Data needDefault serviceCommon alternativeWhy the default fits
Conversation sessions (events + state)Agent Platform Sessions via VertexAiSessionServiceCloud SQL or AlloyDB via DatabaseSessionServiceNo schema to own; reachable from Agent Runtime, Cloud Run, GKE, or a laptop; feeds Memory Bank generation
Long-term user memoryMemory BankYour own facts table with vectors in AlloyDB/Cloud SQL (pgvector) or Firestore vector searchManaged LLM extraction, consolidation, identity-scoped similarity retrieval, TTL, and revisions
Semantic cacheMemorystore for Redis vector search (Redis 7.2; HNSW approximate or FLAT exact)AlloyDB vector indexIn-memory lookups with native key expiry, so repeated or paraphrased prompts skip the model call
Rate-limit and budget countersMemorystore (Redis/Valkey atomic increments with TTL)Firestore counters (higher latency, lower write rate per document)Atomic in-memory operations suit per-user or per-agent throttling on the hot path
Transactional data that tools read and writeCloud SQL or AlloyDBSpanner (global scale) or Firestore (document model)ACID transactions, joins, and vector columns next to live rows; reachable through managed MCP servers or MCP Toolbox
Analytics and agent telemetryBigQueryCloud Logging Log AnalyticsServerless SQL over prompt/response logs, traces, eval results, and token cost; never the per-turn state store
Documents, media, and artifactsCloud Storage (ADK GcsArtifactService for agent outputs)BigQuery object tables (SQL metadata over Cloud Storage objects)Durable, cheap object storage that also feeds Agent Search, RAG Engine, and Agent Retrieval ingestion
Vector embeddingsAgent Retrieval or Vector Search 1.0AlloyDB/Cloud SQL pgvector, Firestore vector search, BigQuery VECTOR_SEARCHPurpose-built ANN and hybrid search; pick the operational database when vectors must be filtered with live transactional rows

ADK session service options

The SessionService backend decides whether conversation state survives restarts and scale-out.

SessionServiceWhere data livesSurvives restart / scale-outUse for
InMemorySessionServiceProcess memoryNo (lost on restart; not shared across replicas)Local development, unit tests, adk web demos
DatabaseSessionServiceSQL database you operate (SQLite locally; PostgreSQL or MySQL such as Cloud SQL or AlloyDB in production)YesSelf-hosted agents on Cloud Run or GKE that need sessions in your own database for residency, private networking, or custom SQL reporting
VertexAiSessionServiceAgent Platform Sessions (managed, tied to an Agent Runtime resource)YesDefault on Agent Runtime; also usable from Cloud Run, GKE, or local code; pairs with VertexAiMemoryBankService

Rule of thumb

Use InMemorySessionService only until the first deployment. Any multi-replica or serverless deployment needs DatabaseSessionService or VertexAiSessionService.

Service trade-offs

Latency, consistency, cost model, and operational burden for the stores agents use most.

ServiceLatency profileConsistencyCost modelOps burden
Agent Platform Sessions + Memory BankAPI calls on the hot path; memory generation runs asynchronouslySession reads/writes are immediate; memories converge after background consolidationManaged usage-based pricingLowest
FirestoreLow (serverless document reads/writes)Strong, with ACID transactionsPer operation + storageVery low (scales to zero)
MemorystoreSub-millisecond in-memoryStrong on the primary; replicas are asynchronousProvisioned capacity per hourLow to medium (capacity sizing)
Cloud SQLLow within the VPCStrong relational ACIDProvisioned vCPU/RAM + storageMedium (instances, backups, indexes)
AlloyDBLow, with accelerated vector and analytical queriesStrong relational ACIDProvisioned primary and read pool nodesLow to medium
BigQuerySeconds per queryStrong after commitPer data scanned or reserved slots + storageVery low
Cloud StorageTens of milliseconds to first byteStrong read-after-writePer GB-month by class + operations + egressLowest
Agent Retrieval / Vector SearchLow-latency ANNNear real time for streaming updatesUsage-based (Agent Retrieval) or deployed node-hours (Vector Search 1.0)Low

Latency labels are directional

Benchmark with your own payload sizes and regions before committing to an SLO.

Reference architectures

Four agent shapes and the services each one typically combines.

ComponentCustomer support agentData analysis agentHigh-QPS public FAQ agentRegulated-industry agent
RuntimeAgent RuntimeAgent RuntimeCloud Run (autoscaled)GKE private cluster inside a VPC-SC perimeter
SessionsVertexAiSessionServiceVertexAiSessionServiceFirestore or Memorystore (short-lived state)DatabaseSessionService on AlloyDB with CMEK and private connectivity
MemoryMemory Bank (device history, preferences)Memory Bank (analyst preferences)None (anonymous traffic)Memory Bank with strict topics and TTL, or none
Knowledge and vectorsPolicy PDFs in Cloud Storage indexed by Agent Search or Agent RetrievalBigQuery tables through the BigQuery MCP serverAgent Retrieval behind a Memorystore semantic cacheAlloyDB vectors with row-level security next to transactional rows
Tools and transactionsOrder and refund lookups in Cloud SQL via MCP ToolboxCode Execution sandbox for Python; charts saved with GcsArtifactServiceMemorystore rate limits per IP or API keyNarrow custom MCP tools behind Agent Gateway
TelemetryCloud Trace + BigQuery eval sinkBigQuery cost and eval analyticsCloud Monitoring cache hit rate + BigQuery logsAudit logs to BigQuery; locked Cloud Storage retention bucket

Common trap: Memorystore as the system of record

A cache or counter store can evict or lose keys during failover. Keep authoritative orders, approvals, and audit data in Cloud SQL, AlloyDB, Spanner, or Firestore, and treat Memorystore entries as rebuildable.

08

8. Optimize Part 1: Evaluation, 2-Step Simulation & Golden Flywheels

The Gen AI Evaluation Service (client.evals.evaluate() / agents-cli eval) grades both final response quality and multi-step tool trajectories.

Metric familyWhat it doesRepresentative metrics
Adaptive rubrics (recommended)Autorater dynamically generates prompt-specific pass/fail tests per eval case, then scores the agent response against themGENERAL_QUALITY
Static rubricsApplies fixed organization-wide pass/fail rules to every promptCustom brand tone / regulatory disclaimer rubrics
Agent & faithfulness metricsSpecialized LLM-as-judge autoraters for grounded agent turnsFINAL_RESPONSE_QUALITY, HALLUCINATION, TOOL_USE_QUALITY
Trajectory metricsDeterministically compares actual tool-call sequence/args against expected reference stepstrajectory_exact_match, trajectory_in_order_match, trajectory_any_order_match, precision/recall
Computation metricsFast, deterministic programmatic checksJSON Schema validation, SQL AST check, exact match, ROUGE/BLEU

2-Step Agent Simulation & Environment Simulation

  • Prerequisite: requires an immutable Agent Registry version snapshot so multi-turn experiments are reproducible.
  • 2-Step User Simulation: (1) inspects agent instructions & tool schemas to synthesize a Starting Prompt + hidden Conversation Plan (persona, goal, edge-case constraints); (2) runs a simulated user LLM across multi-turn sessions to produce full traces.
  • Environment Simulation: intercepts tool calls during evals to inject deterministic faults (HTTP 503, 429, timeout spikes, mocked edge-case payloads) without mutating live production APIs.

Online Monitors & Golden-Dataset Flywheel

  • Online Evaluation (OnlineEvaluator): continuously samples live production OpenTelemetry GenAI traces and runs async autoraters to alert on quality regressions.
  • Production-to-Golden Flywheel: export thumbs-down user feedback, HITL escalations, and low-scoring online traces to BigQuery → redact PII via Sensitive Data Protection (SDP) → curate expected trajectories → append to the CI/CD golden regression suite (agents-cli eval).

Exam tip

Final-answer metrics alone miss "right answer, wrong path" compliance bugs (e.g., issuing a refund without calling verify_eligibility first). Always pair outcome rubrics with trajectory metrics (trajectory_in_order_match / trajectory_exact_match) when tool ordering matters.

Common trap — over-permissive online monitors

Online evaluation monitors run under a platform service agent with access to trace payloads and judge quota; restrict IAM permissions to create or edit monitors to prevent unauthorized trace inspection.

09

9. Optimize Part 2: Observability, Audit & Prompt Optimization

OpenTelemetry & 8 Agent Registry Views

  • Telemetry flags: set GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY=true (exports traces, metrics, and logs without raw prompt text) + OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental. Raw payload capture is opt-in: set OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=EVENT_ONLY and keep ADK_CAPTURE_MESSAGE_CONTENT_IN_SPANS=false (the value true is invalid with the latest conventions and collects nothing), paired with SDP de-identification and restricted log buckets (roles/logging.privateLogViewer).
  • 8 Agent Registry Observability tabs: Overview, Evaluation, Models, Tools (per-tool & per-MCP-server p95 latency + "no-tool interactions"), Usage, Logs, Traces (waterfall/DAG), and Topology (live graph of agents, A2A peers, models, and MCP servers) + native Model Armor spans.

Dual-Attribution Audit, Failure Clusters & Optimizer

  • Dual-Attribution Cloud Audit Logs (is_agentic=true): records both the cryptographic SPIFFE Agent Identity and the initiating human user principal to eliminate confused-deputy audit blind spots.
  • Failure Cluster Analysis: automatically groups failing simulation and production traces into root-cause clusters (e.g., ambiguous tool arg schemas, premature loop exits).
  • Prompt Optimization (Agent Optimizer): closed-loop programmatic optimizer that mutates system prompts/examples and validates candidates against your golden evalset via client.evals before rollout.
Production SymptomFirst Diagnostic View & Fix
Slow p95 turn responsesTraces waterfall → check whether thinking_level=HIGH decode, serial MCP calls, or retrieval dominates
Agent hallucinates instead of calling a toolTools tab ("no-tool interactions") → sharpen tool docstring/schema + add trajectory eval
Recurring errors or quality drop after model migrationFailure Cluster Analysis + Evaluation tab → run programmatic Prompt Optimization against golden evals
Unexpected token spend spikeModels / Usage tabs → compact long session histories and align static prompt prefixes for implicit caching

Common trap — logging raw prompts by default

Setting OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=EVENT_ONLY writes raw user prompts and tool payloads into logs, risking PII exposure. Keep content capture disabled by default or pair it with SDP de-identification and restricted log buckets (Security guide).

10

10. Cost, Quotas & Capacity

Error / situationMeaningArchitectural fix
429 RESOURCE_EXHAUSTED on Standard PayGoShared regional pool contention or project TPM/QPM quota exceededRoute stateless calls to the global endpoint, use exponential backoff with jitter, enable Priority PayGo for critical bursts, or reserve Provisioned Throughput (GSUs; spills over to PayGo by default unless X-Vertex-AI-LLM-Request-Type: dedicated is set)
"Region temporarily at capacity" deploying to Agent RuntimePhysical regional compute pool saturation — not a project quota capDeploy to an alternate region, request smaller per-instance CPU/memory, or retry off-peak

Agent Runtime representative default quotas (per project per region; verify current docs): query/streamQuery 90/min, session writes 100/min, append events 300/min, session reads 10,000/min, max 100 agent resources, Memory Bank writes 100/min and reads 300/min, sandbox executions 1,000/min.

Six FinOps levers: (1) tiered routing (3.5 Flash-Lite → 3.8 Flash → 4 Argon); (2) right-size thinking_level; (3) byte-identical static prompt prefixes for zero-storage-cost implicit caching; (4) session compaction & tool-output masking; (5) right-size min_instances and undeploy idle Vector Search 1.0 endpoints; (6) sample 1–5% of live traffic for OnlineEvaluator and run bulk offline evals on Flex PayGo or Batch inference.

Common trap — quota increase for a capacity error

Filing an IAM/project quota increase ticket will never resolve "Region temporarily at capacity". Switch region, reduce instance sizing, or retry instead.

11

11. Failure Modes & Exam Traps

TrapWhy it's wrongCorrect move
Hosting a custom MCP server on Agent RuntimeAgent Runtime hosts stateful agents (reasoningEngines)Deploy Streamable HTTP MCP servers on Cloud Run or GKE
Keeping chat history in Cloud Run memoryServerless instances scale to zero or recycleExternalize to Agent Platform Sessions, Memorystore, Firestore, or Cloud SQL
Self-hosting Gemini 4 Argon / 3.8 Flash on GKEProprietary Gemini weights are served only via managed endpointsCall managed Gemini APIs; self-host open models (Gemma 4) if weights are needed
Running generated Python inside the agent containerExposes IAM credentials and VPC accessUse the Code Execution sandbox or GKE Sandbox (gVisor)
Building custom RAG when SharePoint/Drive ACL sync is requiredRe-implements brittle connector & permission logicUse Agent Search with native ACL enforcement
Default DOT_PRODUCT index under RAG EngineRAG Engine queries cosine distance → FAILED_PRECONDITIONConfigure index metric as COSINE
Quota increase ticket for "region at capacity"Physical pool exhaustion, not a project quota capAlternate region, smaller CPU/RAM, or retry
Grading compliance agents only on final-answer qualityMisses skipped verification tools ("right answer, wrong path")Add trajectory metrics (trajectory_in_order_match)
Fault-testing resilience against live production APIsTriggers real side effects & non-reproducible statesUse Environment Simulation + 2-Step Agent Simulation
Global semantic cache over ACL-protected documentsLeaks confidential answers across usersPartition cache keys by ACL/tenant scope
Querying an auto-registered Google Cloud MCP server with --location=us-central1Auto-registered McpServer resources exist only in global, so the call returns NOT_FOUNDQuery with --location=global, or register the server manually in the region when metadata residency matters
Registering an external MCP server without a toolspec.jsonManual registration records only the endpoint; the registry does not inspect the server, so no tools are discoverableUpload a toolspec.json (MCP tool schema, 10 KB max) during registration
Shipping with InMemorySessionService on Cloud RunSessions vanish on restart and are not shared across replicasSwitch to VertexAiSessionService or DatabaseSessionService before the first deployment
12

12. Glossary, Related Guides & Practice Quiz

Agent Runtime
Managed stateful agent hosting (formerly Agent Engine); API resource reasoningEngines.
Managed Agents API Preview
Declarative Agents API + Skill Registry + stateful Interactions API with an isolated no-egress Linux sandbox.
Session / Event / State
One conversation, its ordered event log, and its mutable key-value scratchpad.
Memory Bank
Async LLM-extracted, consolidated, user-scoped long-term memory with TTL & revisions.
Example Store Preview
Dynamic few-shot trajectory/example retrieval (embedding model locked at creation).
Code Execution sandbox
Sub-second isolated Python container (100 MB I/O, up to 14-day TTL) for untrusted generated code.
Agent Search vs. RAG Engine
Turnkey connector + native-ACL enterprise search vs. code-first modular corpus RAG pipeline.
2-Step & Environment Simulation
Multi-turn user simulator (Starting Prompt + Conversation Plan) and deterministic tool-fault injector.
Dual-Attribution Audit Log
Cloud Audit Log (is_agentic=true) recording both SPIFFE Agent Identity and human principal.
Failure Clusters & Agent Optimizer
Root-cause clustering of failed traces paired with automated closed-loop prompt optimization.
Provisioned Throughput
Reserved model capacity bought in GSUs for predictable latency & throughput.
Google Cloud remote MCP server
Google-hosted HTTPS MCP endpoint for a Cloud service, enabled with the service API, auto-registered in Agent Registry, and gated by roles/mcp.toolUser plus resource IAM.
MCP Toolbox for Databases
Open-source MCP server (googleapis/mcp-toolbox) with prebuilt database tools and parameterized custom tools defined in tools.yaml.
toolspec.json
Tool specification file (MCP tool schema, 10 KB max) uploaded when manually registering an external MCP server in Agent Registry.
Streamable HTTP vs. stdio
Remote HTTPS MCP transport for cloud servers vs. local child-process transport for servers on the same machine.
ADK session services
VertexAiSessionService (managed Agent Platform Sessions), DatabaseSessionService (SQL database you operate), and InMemorySessionService (non-persistent process memory).
Skill Registry Preview
Agent Platform repository that validates, versions, and serves SKILL.md-based skill packages; inherits project IAM (roles/aiplatform.*).
Skill revision
Immutable snapshot of one version of a skill; agents load the default revision unless a specific revision is requested.
gcp-skill-registry
Google-managed built-in skill that lets an agent create, search, and manage skills in Skill Registry.
Semantic governance policy Preview
LLM-evaluated natural language constraint that can allow or deny skill tool calls such as load_skill and run_skill_script.
RAG Engine Serverless vs. Spanner mode
Zero-tier, autoscaled backend without CMEK vs. dedicated Spanner instance with Basic or Scaled tiers, isolation, and CMEK.
Collection / Data Object
Agent Retrieval container with a schema (similar to a table) and the individual JSON record it stores alongside its vector fields.
Semantic cache
Vector-indexed response cache (for example Memorystore for Redis vector search) serving stored answers to semantically similar prompts; partition keys by tenant or ACL scope.

Related guides

Audio Deep Dive & Study Downloads

Listen to the 71-minute Agent Platform audio deep dive, open the 21-slide architectural deck and sketchnote infographic in the Hub Viewer, or drill scenario-based questions on build paths (Agent Studio vs. Managed Agents API vs. ADK), Agent Runtime, Memory Bank, 2-step simulation, and prompt optimization.

Agent Platform: Build, Retrieve, Run & Optimize (Podcast)
Open Slide Deck & Infographic in Hub Viewer Launch Agent Platform Practice Quiz →

Sources