How to Deploy Autonomous Agents with the Claude Agent SDK on Cloud Run

1. Introduction

Overview

AI agents are transitioning from simple conversational chatbots into autonomous systems capable of executing bash commands, running unit tests, querying APIs, and modifying source code. Running these workloads securely in production presents two core architectural challenges:

  1. Code Execution Safety: Untrusted code generated by an LLM shouldn't run directly on the host operating system or access platform secrets and credentials.
  2. State and Compute Lifecycle: Agent workflows can either require a persistent, dedicated workspace (such as long-lived developer environments, interactive terminals, or background dev servers) or a stateless, event-driven, scale-to-zero API (such as incoming webhooks or automated issue triage).

In this codelab, you build and deploy an autonomous AI agent using the official Claude Agent SDK (claude-agent-sdk) on Google Cloud Run, using Cloud Run Sandboxes with sandbox templates (Public Preview) for software-isolated gVisor code execution.

You can deploy your agent harness using either of two deployment models:

  • Path A: Cloud Run Instances (Public Preview - dedicated singleton host for up to 7 days, deterministic URL, persistent /workspace volume across turns, ~$11.40/month compute).
  • Path B: Cloud Run Services with concurrency=1 (Scale-to-zero serverless, pay-per-request, $0 idle compute cost, ephemeral execution).

Architecture: Brain vs. Hands Separation

To illustrate the security boundary, we use a "Brain vs. Hands" analogy (an illustrative mental model rather than official product terminology): both deployment paths enforce a strict invariant where The Brain (Host Container) is isolated from The Hands (Sandbox).

┌────────────────────────────────────────────────────────────────────────┐
│ Cloud Run Host Container (The Brain)                                   │
│ - FastAPI Web Server (POST /chat, IAM-authenticated by default)        │
│ - Claude Agent SDK (`claude-agent-sdk`, state in `/tmp/claude`)        │
│ - Calls Claude on Agent Platform using Cloud Run service account (ADC) │
│                                                                        │
│   │                                                                    │
│   ▼ Dispatches untrusted commands via In-Process MCP Tool              │
│                                                                        │
│ ┌──────────────────────────────────────────────────────────────────┐   │
│ │ Cloud Run Sandbox (The Hands)                                    │   │
│ │ - Spawned using `/usr/local/gcp/bin/sandbox do --template`       │   │
│ │ - Dedicated sibling container image (`sandboxes.templates`)      │   │
│ │ - Dedicated gVisor kernel; no access to host FS, env, or creds   │   │
│ │ - Writable per-sandbox overlay + configurable internet egress    │   │
│ └──────────────────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────────────────┘

What you'll learn

  • How to build an agent harness using the Claude Agent SDK and in-process Model Context Protocol (MCP) tools.
  • How to route untrusted shell commands into software-isolated Cloud Run Sandboxes via /usr/local/gcp/bin/sandbox.
  • How to choose between Cloud Run Instances and Cloud Run Services (concurrency=1) based on statefulness and cost goals.
  • How to authenticate the Claude Agent SDK with Agent Platform (CLAUDE_CODE_USE_VERTEX=1) using Application Default Credentials (ADC) — with no API keys to manage.
  • How to verify sandbox isolation and outbound network connectivity.

2. Instances vs. Services

Before deploying, review the decision matrix below to choose the path that best matches your target workload:

Architectural Metric

Path A: Cloud Run Instances

Path B: Cloud Run Services (concurrency=1)

Compute Model

Dedicated singleton container (runs continuously for up to 7 days)

Ephemeral auto-scaling container pool

Scaling & Max Instances

Single instance (1 instance)

Scales from 0 up to --max-instances (set to 5 in this codelab to cap maximum concurrent cost)

Idle Cost

~$11.40/month compute (2 vCPU / 2 GiB on shared CPU)

$0.00 (scales to 0 instances when idle)

Billing Granularity

Billed continuously while instance exists (Claude tokens billed separately)

Billed per request turn down to the millisecond (Claude tokens billed separately)

URL & Addressing

Dedicated URL per instance (https://INSTANCE_URL.run.app)

Service endpoint (https://SERVICE_URL.run.app); no session affinity by default (best-effort when enabled)

Routing Reliability

100% deterministic 1:1 instance routing

Load-balanced across auto-scaled Cloud Run service instances

Sandboxes & Host State

sandbox do --template runs per command and mounts a shared in-memory /workspace volume across turns (up to 7 days)

sandbox do --template runs ephemerally per command; instance scales to zero when idle

Background Processes

Supported on host or inside detached sandboxes (sandbox run --detach)

Throttled or suspended when request completes

Primary Use Cases

Personal agent assistant, IDE companion, coding bot

Webhook handlers, event-driven pipelines, automated issue triage

Which path should you choose?

  • Choose Path A (Instances) if you're building a single-owner coding partner or personal assistant that needs a persistent host workspace (up to 7 days) and long-running background dev servers. You also get a dedicated URL that works with tools and webhooks without custom routing headers.
  • Choose Path B (Services) if you are building a webhook endpoint (e.g., GitHub PR bot or Slack bot), an automated event-driven pipeline, or want zero idle cost where the service scales completely to zero between sporadic events (with --max-instances capping your maximum concurrent spend).

(You can also complete both paths using the same container image to compare their operational mechanics directly!)

3. Setup and Requirements

Google Cloud Project Setup & Required Roles

  1. Sign in to the Google Cloud Console.
  2. Select or create a Google Cloud Project with billing enabled.
  3. Verify your account has the following IAM roles on the project (included in Owner, or granted individually):
    • Cloud Run Developer (roles/run.developer) and Service Account User (roles/iam.serviceAccountUser) to deploy Instances and Services.
    • Service Account Admin (roles/iam.serviceAccountAdmin), Service Usage Admin (roles/serviceusage.serviceUsageAdmin), and Project IAM Admin (roles/resourcemanager.projectIamAdmin) to create the runtime service account, enable APIs, and grant IAM roles.
    • Consumer Procurement Entitlement Manager (roles/consumerprocurement.entitlementManager) to enable partner Claude models in Model Garden.

Open Cloud Shell

Activate Google Cloud Shell from the top navigation bar of the Cloud Console.

Authenticate your user credentials so gcloud auth print-identity-token can mint OpenID Connect (OIDC) identity tokens when testing your IAM-protected Cloud Run endpoint:

gcloud auth login

Set Environment Variables

Set your project ID, deployment region, and dedicated runtime service account name (re-run these export commands if your Cloud Shell session reconnects):

export PROJECT_ID="<YOUR_PROJECT_ID>"
export REGION="us-west1"
export SA_NAME="claude-agent-sa"
export RUN_SA="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud config set project ${PROJECT_ID}

Install gcloud beta (Local Terminal Only)

Cloud Shell already includes gcloud beta pre-installed (skip this step in Cloud Shell, where the component manager is disabled). If you're running from a local terminal instead, install and update beta:

gcloud components install beta --quiet
gcloud components update --quiet

Enable Required Google Cloud APIs

Enable the Cloud Run, Agent Platform (aiplatform.googleapis.com), IAM, Cloud Build, and Artifact Registry APIs:

gcloud services enable \
  run.googleapis.com \
  aiplatform.googleapis.com \
  iam.googleapis.com \
  cloudbuild.googleapis.com \
  artifactregistry.googleapis.com

4. Enable Claude on Agent Platform & Configure IAM

Instead of managing static Anthropic API keys, the Claude Agent SDK can authenticate directly against Agent Platform using your Cloud Run service account's Application Default Credentials (ADC).

1. Enable Claude Sonnet 5.5 in Model Garden

  1. Open the Model Garden in the Google Cloud Console.
  2. Search for Claude Sonnet 5.5 (claude-sonnet-5-5) - or Claude Opus 5.5 (claude-opus-5-5) - and click Enable to accept the Anthropic partner terms for your project.

2. Create a Dedicated Runtime Service Account

Create a dedicated runtime service account for your Cloud Run agent and grant it Agent Platform User (roles/aiplatform.user) so it can invoke Claude models:

gcloud iam service-accounts create "${SA_NAME}" \
  --display-name="Claude Agent Runtime Service Account" \
  --project="${PROJECT_ID}" \
  --quiet

export RUN_SA="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${RUN_SA}" \
  --role="roles/aiplatform.user"

3. Optional: Verify Claude Access Before Building

Send a quick test request to confirm claude-sonnet-5-5 is enabled on your project before building the container (remove | jq '{content}' if you want to inspect the full API response or an error body):

curl -sS --fail-with-body \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/publishers/anthropic/models/claude-sonnet-5-5:rawPredict" \
  -d @- << 'EOF' | jq '{content}'
{
  "anthropic_version": "vertex-2023-10-16",
  "max_tokens": 64,
  "messages": [
    {"role": "user", "content": "Reply with Hello! I'm Claude."}
  ]
}
EOF

Expected Output:

{
  "content": [
    {
      "type": "text",
      "text": "Hello! I'm Claude."
    }
  ]
}

5. Build the Agent Application Container

Create a clean directory for your agent source code:

mkdir -p claude-agent-app && cd claude-agent-app

Create five files in claude-agent-app using cat <<'EOF' commands so you can copy and run each block directly in Cloud Shell:

  1. sandbox_runner.py: Wraps /usr/local/gcp/bin/sandbox to dispatch shell commands into gVisor sandboxes.
  2. agent.py: Instantiates the Claude Agent SDK and configures the in-process bash execution MCP tool.
  3. server.py: A lightweight FastAPI web server serving POST /chat.
  4. requirements.txt: Python package dependencies.
  5. Dockerfile: Container definition packaging the FastAPI host runtime.

1. Create sandbox_runner.py

This module provides the execution bridge between the agent harness and the Cloud Run sandbox launcher:

cat <<'EOF' > sandbox_runner.py
"""Sandbox Runner utilizing Cloud Run Sandbox launcher."""

from __future__ import annotations

import logging
import os
import subprocess
from dataclasses import dataclass

logger = logging.getLogger("sandbox-runner")


@dataclass
class ExecutionResult:
    stdout: str
    stderr: str
    exit_code: int


def _env_bool(name: str, default: bool) -> bool:
    raw = os.environ.get(name)
    if raw is None:
        return default
    return raw.strip().lower() in ("1", "true", "yes", "on")


class CloudRunSandboxRunner:
    """Dispatches shell commands into isolated gVisor sandbox templates."""

    def __init__(
        self,
        sandbox_bin: str = "/usr/local/gcp/bin/sandbox",
        template: str | None = None,
        default_allow_egress: bool | None = None,
    ):
        self.sandbox_bin = sandbox_bin
        self.template = (
            template
            if template is not None
            else os.environ.get("SANDBOX_TEMPLATE", "code-sandbox").strip()
        )
        self.default_allow_egress = (
            default_allow_egress
            if default_allow_egress is not None
            else _env_bool("SANDBOX_ALLOW_EGRESS", True)
        )
        self.is_available = os.path.exists(sandbox_bin) and os.access(
            sandbox_bin, os.X_OK
        )

    def execute(
        self,
        command: str,
        timeout: int = 60,
        allow_egress: bool | None = None,
    ) -> ExecutionResult:
        """Executes a command inside an ephemeral templated sandbox."""
        if not self.is_available:
            return ExecutionResult(
                stdout="",
                stderr="Cloud Run Sandbox binary is unavailable on this host.",
                exit_code=1,
            )
        if not self.template:
            return ExecutionResult(
                stdout="",
                stderr=(
                    "SANDBOX_TEMPLATE must be set to launch a sandbox template."
                ),
                exit_code=1,
            )

        egress = (
            self.default_allow_egress if allow_egress is None else allow_egress
        )
        cmd = [
            self.sandbox_bin,
            "do",
            "--stdin=false",
            "--template",
            self.template,
        ]
        if egress:
            cmd.append("--allow-egress")
        cmd.extend(["--", "/bin/sh", "-c", command])

        try:
            res = subprocess.run(
                cmd, capture_output=True, text=True, timeout=timeout, check=False
            )
            return ExecutionResult(
                stdout=res.stdout, stderr=res.stderr.strip(), exit_code=res.returncode
            )
        except subprocess.TimeoutExpired:
            return ExecutionResult(
                stdout="", stderr=f"Command timed out after {timeout} seconds.", exit_code=124
            )
        except Exception as e:
            logger.exception("Unexpected error during sandbox execution")
            return ExecutionResult(stdout="", stderr=str(e), exit_code=1)
EOF

2. Create agent.py

Define the Claude Agent harness and register an in-process MCP tool named execute_bash that routes shell commands into the sandbox runner. Setting tools=[] disables Claude Code's built-in tools (Bash, Write, Edit, and others) so execute_bash is the only command tool. Each request runs one Claude Agent SDK session to completion using query():

cat <<'EOF' > agent.py
"""Claude Agent harness with in-process Cloud Run Sandbox tool."""

from __future__ import annotations

from typing import Any

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ResultMessage,
    create_sdk_mcp_server,
    query,
    tool,
)
from sandbox_runner import CloudRunSandboxRunner

runner = CloudRunSandboxRunner()


@tool(
    "execute_bash",
    "Execute shell commands inside an isolated sandbox with internet egress.",
    {"command": str},
)
async def execute_bash(args: dict[str, Any]) -> dict[str, Any]:
    """Executes a command inside the gVisor sandbox and returns the combined output."""
    result = runner.execute(args["command"])
    output = []
    if result.stdout:
        output.append(result.stdout)
    if result.stderr:
        output.append(f"[STDERR]\n{result.stderr}")
    output.append(f"[Exit Code: {result.exit_code}]")
    return {"content": [{"type": "text", "text": "\n".join(output)}]}


class ClaudeAgent:
    """Runs one Claude Agent SDK session per prompt."""

    def __init__(self, options: ClaudeAgentOptions):
        self.options = options

    async def run(self, prompt: str) -> str:
        """Runs the agent loop to completion and returns Claude's final answer."""
        async for message in query(prompt=prompt, options=self.options):
            if isinstance(message, ResultMessage):
                if message.is_error:
                    raise RuntimeError(message.result or message.subtype)
                return message.result or ""
        raise RuntimeError("Claude Agent SDK ended without a result.")


def create_claude_agent() -> ClaudeAgent:
    """Initializes the Claude Agent with the sandbox as its only execution tool."""
    system_prompt = (
        "You are an autonomous AI coding assistant running on Google Cloud Run. "
        "You have access to a secure bash tool called 'execute_bash'. "
        "All bash commands run inside an isolated gVisor sandbox with outbound internet access. "
        "If /workspace exists, store persistent project files there across turns. "
        "Use this tool to explore the environment, execute Python code, compile programs, or run tests."
    )
    options = ClaudeAgentOptions(
        # Swap to another enabled Model Garden ID (e.g., "claude-opus-5-5") as needed.
        model="claude-sonnet-5-5",
        system_prompt=system_prompt,
        mcp_servers={"sandbox": create_sdk_mcp_server("sandbox", tools=[execute_bash])},
        allowed_tools=["mcp__sandbox__execute_bash"],
        # Disable Claude Code's built-in tools (Bash, Write, Edit, ...) so the
        # only way to run commands is through the sandboxed execute_bash tool.
        tools=[],
    )
    return ClaudeAgent(options)
EOF

3. Create server.py

Create a clean FastAPI server exposing POST /chat:

cat <<'EOF' > server.py
"""FastAPI endpoint serving the Claude Agent."""

from __future__ import annotations

import logging
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

from agent import create_claude_agent

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("claude-service")

app = FastAPI(title="Claude Agent Cloud Run Service")
agent = create_claude_agent()


class ChatRequest(BaseModel):
    prompt: str


class ChatResponse(BaseModel):
    response: str


@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(req: ChatRequest):
    if not req.prompt.strip():
        raise HTTPException(status_code=400, detail="Prompt must not be empty.")
    try:
        result = await agent.run(req.prompt)
        return ChatResponse(response=str(result))
    except Exception as e:
        logger.exception("Error during agent processing")
        raise HTTPException(status_code=500, detail=str(e))
EOF

4. Create requirements.txt

cat <<'EOF' > requirements.txt
fastapi>=0.110.0
uvicorn>=0.28.0
pydantic>=2.0.0
claude-agent-sdk>=0.1.81
anthropic[vertex]>=0.40.0
EOF

5. Create Dockerfile

cat <<'EOF' > Dockerfile
FROM python:3.11-slim

ENV PYTHONUNBUFFERED=1
ENV PORT=8080
# Store Claude Agent SDK session files in /tmp on the host container
# (defense-in-depth alongside sandbox template file system isolation).
ENV CLAUDE_CONFIG_DIR=/tmp/claude

WORKDIR /app

# Ensure CA certificates are present for TLS connections
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8080

CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8080"]
EOF

6. Build and Push the Container Image

Create an Artifact Registry Docker repository (if agent-repo already exists in your project, skip to the build command below):

gcloud artifacts repositories create agent-repo \
  --repository-format=docker \
  --location=${REGION} \
  --description="Repository for Claude Agent containers"

Build and push the FastAPI host container image using Cloud Build:

export IMAGE_URI="${REGION}-docker.pkg.dev/${PROJECT_ID}/agent-repo/claude-agent:latest"

gcloud builds submit --tag ${IMAGE_URI}

6. Path A: Deploy to Cloud Run Instances

Follow this step if you chose Path A: Dedicated Singleton Host (up to 7 days). (Otherwise, jump to the next section for Path B).

1. Create instance.yaml

Create instance.yaml with a dedicated code-sandbox template and a shared in-memory /workspace volume:

cat <<EOF > instance.yaml
apiVersion: run.googleapis.com/v1
kind: Instance
metadata:
  name: claude-agent-instance
  annotations:
    run.googleapis.com/launch-stage: BETA
spec:
  serviceAccountName: ${RUN_SA}
  containers:
  - image: ${IMAGE_URI}
    ports:
    - containerPort: 8080
    resources:
      limits:
        cpu: "2"
        memory: 2Gi
    sandboxLauncher: true
    volumeMounts:
    - name: workspace
      mountPath: /workspace
    env:
    - name: CLAUDE_CODE_USE_VERTEX
      value: "1"
    - name: ANTHROPIC_VERTEX_PROJECT_ID
      value: "${PROJECT_ID}"
    - name: CLOUD_ML_REGION
      value: "global"
    - name: SANDBOX_TEMPLATE
      value: "code-sandbox"
  volumes:
  - name: workspace
    emptyDir:
      medium: Memory
  sandboxes:
    templates:
    - name: code-sandbox
      image: python:3.11-slim
      volumeMounts:
      - name: workspace
        mountPath: /workspace
EOF

2. Deploy the Cloud Run Instance

During Public Preview (run.googleapis.com/launch-stage: BETA), sandbox templates (sandboxes.templates) are configured declaratively using YAML rather than gcloud CLI flags. Deploy the instance from instance.yaml using gcloud beta run instances replace:

gcloud beta run instances replace instance.yaml --region ${REGION}

Key Parameter Breakdown

  • serviceAccountName: Runs the host container as your dedicated claude-agent-sa service account rather than the default Compute Engine service account.
  • sandboxLauncher: true: Injects /usr/local/gcp/bin/sandbox into the host container so it can supervise gVisor sandboxes.
  • sandboxes.templates & volumes: Defines the code-sandbox sibling container image (python:3.11-slim) and mounts a shared in-memory emptyDir volume (workspace at /workspace, counted against the instance's 2 GiB memory limit) on both the host container and code-sandbox. Each sandbox do --template code-sandbox call gets a fresh /tmp and root overlay, no access to /app or /tmp/claude, and persistent access to /workspace across turns for up to 7 days.
  • IAM authentication (default): Allocating containerPort: 8080 without disabling Invoker IAM checks creates a dedicated HTTPS URL protected by Cloud Run IAM, satisfying constraints/run.managed.requireInvokerIam.
  • env: Configures the Claude Agent SDK (CLAUDE_CODE_USE_VERTEX=1) to call Claude on Agent Platform (global) using the instance's service account credentials, and sets SANDBOX_TEMPLATE=code-sandbox.
# Optional (personal, non-enterprise projects only):
gcloud beta run instances update claude-agent-instance \
  --region ${REGION} \
  --public

3. Retrieve Your Instance URL

export INSTANCE_URL=$(gcloud beta run instances describe claude-agent-instance \
  --region ${REGION} \
  --format="value(status.urls[0])")

echo "Instance URL: ${INSTANCE_URL}"

7. Path B: Deploy to Cloud Run Services (Concurrency=1)

Follow this step if you chose Path B: Scale-to-Zero Serverless.

1. Create service.yaml

Create service.yaml with containerConcurrency: 1 and a dedicated code-sandbox template:

cat <<EOF > service.yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: claude-agent-service
  annotations:
    run.googleapis.com/launch-stage: BETA
spec:
  template:
    metadata:
      annotations:
        autoscaling.knative.dev/minScale: "0"
        autoscaling.knative.dev/maxScale: "5"
        run.googleapis.com/execution-environment: gen2
    spec:
      serviceAccountName: ${RUN_SA}
      containerConcurrency: 1
      timeoutSeconds: 900
      containers:
      - image: ${IMAGE_URI}
        ports:
        - containerPort: 8080
        resources:
          limits:
            cpu: "2"
            memory: 2Gi
        sandboxLauncher: true
        env:
        - name: CLAUDE_CODE_USE_VERTEX
          value: "1"
        - name: ANTHROPIC_VERTEX_PROJECT_ID
          value: "${PROJECT_ID}"
        - name: CLOUD_ML_REGION
          value: "global"
        - name: SANDBOX_TEMPLATE
          value: "code-sandbox"
      sandboxes:
        templates:
        - name: code-sandbox
          image: python:3.11-slim
EOF

2. Deploy the Cloud Run Service

During Public Preview (run.googleapis.com/launch-stage: BETA), sandbox templates (sandboxes.templates) are configured declaratively using YAML rather than gcloud beta run deploy flags. Deploy the service from service.yaml using gcloud beta run services replace:

gcloud beta run services replace service.yaml --region ${REGION}

Key Parameter Breakdown

  • serviceAccountName: Runs each Cloud Run service instance as your dedicated claude-agent-sa service account rather than the default Compute Engine service account.
  • containerConcurrency: 1: Ensures each Cloud Run service instance handles strictly one agent turn at a time so concurrent sandboxes don't contend for the instance's 2 vCPU / 2 GiB budget.
  • timeoutSeconds: 900: Extends the per-request HTTP timeout from the 5-minute default (300s) to 15 minutes (up to 3600s max) so multi-step agent runs don't time out mid-turn (Cloud Run Instances default to 60 minutes).
  • minScale: "0" & maxScale: "5": Scales to zero ($0.00 CPU billing when idle) while capping concurrent Cloud Run service instances to bound cost and Claude API quota usage.
  • execution-environment: gen2: Selects the second generation execution environment required for sandbox launching.
  • sandboxLauncher: true & sandboxes.templates: Launches each command in a dedicated python:3.11-slim sibling container (code-sandbox) with a writable per-sandbox overlay and no access to the host file system.
  • IAM authentication (default): Creating a new service with services replace leaves allUsers ungranted by default so only authorized callers can invoke your agent, satisfying constraints/iam.allowedPolicyMemberDomains.
  • env: Routes Claude Agent SDK calls (CLAUDE_CODE_USE_VERTEX=1) to Agent Platform (global) using the service account credentials, and sets SANDBOX_TEMPLATE=code-sandbox.
# Optional (personal, non-enterprise projects only):
gcloud run services add-iam-policy-binding claude-agent-service \
  --region ${REGION} \
  --member="allUsers" \
  --role="roles/run.invoker"

3. Retrieve Your Service URL

export SERVICE_URL=$(gcloud run services describe claude-agent-service \
  --region ${REGION} \
  --format="value(status.url)")

echo "Service URL: ${SERVICE_URL}"

8. Test Your Agent & Verify Sandbox Isolation

Set TARGET_URL by running only the block that matches the deployment path you completed (verify the printed URL isn't empty before running curl):

  • If you deployed Path A (Cloud Run Instances):
export TARGET_URL="${INSTANCE_URL}"
echo "Target URL: ${TARGET_URL}"
  • If you deployed Path B (Cloud Run Services):
export TARGET_URL="${SERVICE_URL}"
echo "Target URL: ${TARGET_URL}"

1. Verify Kernel & Sandbox Isolation

Ask the agent to check its kernel version and operating system environment, authenticating with a Google Cloud OIDC identity token:

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Run uname -a and cat /etc/os-release using bash and report the kernel and distro."}'

Expected Response:

{
  "response": "The kernel is 4.19.0-gvisor and the distro is Debian GNU/Linux 13 (trixie)."
}

The agent invokes the execute_bash tool inside the sandbox and reports a 4.19.0-gvisor sandbox kernel alongside the python:3.11-slim Debian distribution, confirming that commands run inside an isolated sandbox rather than on the host kernel.

2. Verify Outbound Network Egress

Ask the agent to verify network egress from within the python:3.11-slim sandbox using Python's standard library:

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use execute_bash to fetch https://www.google.com with Python urllib.request and report the HTTP status code."}'

Expected Response:

{
  "response": "The HTTP response status from https://www.google.com is 200."
}

Because SANDBOX_ALLOW_EGRESS defaults to true in CloudRunSandboxRunner, the sandbox can fetch dependencies, download git repositories, and query public APIs while remaining safely sandboxed (set SANDBOX_ALLOW_EGRESS=false to block outbound network access).

3. Verify Host File System, Environment, & Transcript Isolation

Instruct the agent to check whether it can see the host container's /app directory, /tmp/claude session files, or host environment variables inside the sandbox:

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Run ls -la /app, ls -la /tmp, and env inside bash and tell me if you can see /app, /tmp/claude, ANTHROPIC_VERTEX_PROJECT_ID, or CLAUDE_CODE_USE_VERTEX."}'

Expected Response:

{
  "response": "ls: cannot access '/app': No such file or directory. /tmp is empty (no /tmp/claude), and neither ANTHROPIC_VERTEX_PROJECT_ID nor CLAUDE_CODE_USE_VERTEX is set in env."
}

The agent reports that /app doesn't exist (No such file or directory), /tmp/claude is absent, and neither ANTHROPIC_VERTEX_PROJECT_ID nor CLAUDE_CODE_USE_VERTEX is present in the sandbox environment. Because --template code-sandbox runs each command inside a sibling container from its own python:3.11-slim image, the host container's file system, credentials, and session transcripts stay isolated inside The Brain.

4. Verify Persistent /workspace Across Requests (Path A: Instances)

If you deployed Path A (Cloud Run Instances), instance.yaml mounts an in-memory emptyDir volume at /workspace on code-sandbox. Send two separate HTTP requests to verify that files written to /workspace survive across ephemeral sandbox do invocations while /tmp is reset each time:

# Request 1: Write one file to /workspace and one file to /tmp
curl -X POST "${INSTANCE_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use bash to write the current UTC timestamp to /workspace/session_note.txt and also write ephemeral to /tmp/ephemeral.txt, then confirm both files exist."}'

# Request 2: Read both files in a new request (new sandbox do invocation)
curl -X POST "${INSTANCE_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use bash to check cat /workspace/session_note.txt and ls -la /tmp/ephemeral.txt and report which file persisted."}'

Expected Response (Request 2):

{
  "response": "/workspace/session_note.txt persisted with timestamp 2026-..., while /tmp/ephemeral.txt does not exist (No such file or directory)."
}

/workspace/session_note.txt persists across turns in memory (up to 7 days on the active Cloud Run Instance), while /tmp/ephemeral.txt was discarded as soon as Request 1's sandbox do container exited.

9. State & Sandboxing Nuances (Deep Dive)

Why containerConcurrency: 1 is Essential on Cloud Run Services

Standard stateless web applications handle 80+ concurrent requests per Cloud Run service instance. For AI agents running sandboxes, single-request concurrency matters:

  1. Shared Instance CPU & Memory Budget: Sandbox template containers run within the same Cloud Run service instance and share its 2 vCPU and 2 GiB memory allocation. Setting containerConcurrency: 1 ensures each active agent turn receives the full instance CPU and memory budget without contention from concurrent compilers or Python runtimes.
  2. Host-Side SDK Isolation: Keeps per-turn Claude Agent SDK execution isolated on the supervisor container so concurrent turns don't compete for host memory or scratch space.

Sandbox Templates, Endpoint Auth, & Multi-User Session Authorization

  • Dedicated Sandbox Root File System (sandboxes.templates): Running sandbox do --template code-sandbox launches each command in a dedicated sibling container (python:3.11-slim) with a writable per-sandbox overlay (--write=true by default). The sandbox has no access to the host container's file system, protecting /app, Secret Manager or Cloud Storage volume mounts, and /tmp/claude transcripts. You can define up to 10 distinct tool images in sandbox templates without adding compilers or CLIs to the FastAPI host container.
  • Endpoint-Level Access (Cloud Run IAM and IAP): Keeping Invoker IAM checks enabled ensures only authorized principals (or users behind Identity-Aware Proxy) can reach POST /chat. Path A (Instances) runs a single shared host environment for single-owner personal agents, not multi-tenant traffic.
  • Multi-User Session Ownership: If you extend POST /chat to accept a session_id for multi-turn resume, Cloud Run IAM and IAP only verify who can call the service. Bind each session_id to the authenticated caller's identity in your app before resuming a session.

State Persistence: Local Memory vs. Snapshot Rehydration

  • Path A (Instances) - Three Independent State Layers:
    1. Sandbox /workspace files: Persist across sandbox do turns for up to 7 days in the shared in-memory emptyDir volume (counted against the instance's 2 GiB memory limit), while /tmp and root overlay writes reset after every command.
    2. Long-running background processes: Because sandbox do exits after each command, dev servers or watchers inside a sandbox require a detached sandbox (sandbox run --detach with sandbox exec).
    3. Multi-turn conversation history: query() starts a fresh prompt turn by default. Pass resume (or ClaudeSDKClient) or persist transcripts to an external store to carry chat history across requests.
  • Path B (Services): Once a Cloud Run service instance scales to zero after traffic ceases, local disk and memory state are purged. Persist multi-turn files and session state to external storage (such as Cloud Storage, Firestore, or Cloud Spanner) and rehydrate at the start of each turn.

10. Clean Up

To avoid incurring ongoing Google Cloud charges (especially on Path A, which bills ~$11.40/month until deleted), delete the resources you created:

  • If you deployed Path A (Cloud Run Instances):
gcloud beta run instances delete claude-agent-instance --region ${REGION}
  • If you deployed Path B (Cloud Run Services):
gcloud run services delete claude-agent-service --region ${REGION}
  • Delete the Artifact Registry repository (both paths):
gcloud artifacts repositories delete agent-repo --location ${REGION}
  • Remove the dedicated service account and IAM binding (both paths):
gcloud projects remove-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${RUN_SA}" \
  --role="roles/aiplatform.user"
gcloud iam service-accounts delete "${RUN_SA}" --project="${PROJECT_ID}"

11. Congratulations

You have deployed an autonomous AI agent powered by Claude Sonnet 5.5 and the Claude Agent SDK on Google Cloud Run!

What you accomplished

  • Built a hardened agent harness using Brain versus Hands architectural separation.
  • Routed untrusted bash commands into software-isolated Cloud Run Sandboxes (sandboxes.templates) running gVisor.
  • Configured keyless Agent Platform authentication (CLAUDE_CODE_USE_VERTEX=1) using Application Default Credentials and the Agent Platform User (roles/aiplatform.user) role.
  • Explored the trade-offs between Cloud Run Instances (dedicated URL, persistent in-memory /workspace volume for up to 7 days, ~$11.40/mo compute) and Cloud Run Services (concurrency=1) (scale-to-zero, event-driven, capped with maxScale).