Kanji
・Cloud engineer / freelance ・Born in 1993 ・From Ehime / Living in Shibuya, Tokyo ・5 years AWS experience Profile details
Table of Contents
vertexai.preview.extensions
google-genai
“All our Vertex AI extension endpoints are throwing 410 Gone errors…!”
On the afternoon of November 26, 2026, my team’s autonomous infrastructure diagnostic agent suddenly triggered a storm of alerts in Cloud Monitoring. Inspecting the execution logs, I found that every single tool call utilizing Google Cloud’s vertexai.preview.extensions —which connected our agents to Cloud SQL and internal operations APIs—had crashed with the following unyielding exception:
google.api_core.exceptions.NotFound: 404/410 The extension resource projects/xxxxxxxx/locations/us-central1/extensions/ext-ops-toolset was not found or has been permanently discontinued.
As foreshadowed in Google Cloud’s official deprecation announcement on May 26, 2026, following a 6-month sunset window, Vertex AI Extensions (including prebuilt Code Interpreter / Vertex AI Search extensions and custom OpenAPI extensions) reached its hard shutdown on November 26, 2026 . Although I had marked the announcement on my calendar months ago, watching live production endpoints evaporate in real time still caused an immediate surge of adrenaline across our engineering team.
Vertex AI Extensions had previously offered a remarkably easy managed tool framework: you simply uploaded an OpenAPI (Swagger) schema to Google Cloud, and Gemini could automatically trigger API calls via Function Calling. However, as our operations scaled, I continuously struggled with the structural limitations of relying on a proprietary cloud vendor extension:
stdio
SSE
HTTP Stream
min-instances=0
“If I merely shift to another proprietary GCP feature like Agent Engine, I’ll eventually face the same vendor lock-in cycle when specs change again. The only future-proof path right now is to re-architect our entire tool layer around Model Context Protocol (MCP) running on serverless Cloud Run , universally accessible by Gemini 4, Claude Code, and OpenCode alike.”
With that resolution, I spent that evening and the following morning completely refactoring our toolsets into stateless Remote MCP services deployed to Cloud Run. In this article, I share the concrete migration architecture, production-ready implementation code, and the thorny pitfalls I personally stepped on during migration.
▲ Complete migration architecture from Vertex AI Extensions to Cloud Run × FastMCP, securing tool execution via Google Cloud IAM OIDC tokens and exposing unified tools to Gemini 4 and multi-agent runners
The core architecture I chose couples “stateless containerized MCP servers built with FastMCP” with “Google Cloud Run’s zero-trust IAM authentication” .
--allow-unauthenticated
Authorization: Bearer <ID_TOKEN>
vertexai.preview
▲ Cloud Run management console displaying the deployed Remote MCP service with unauthenticated ingress blocked and minimal IAM service account roles
Under legacy Vertex AI Extensions, we were required to author static OpenAPI 3.0 YAML/JSON manifests. With FastMCP, we can express tools cleanly using standard Python type hints and Pydantic v2 validation.
Below is the production MCP server implementation ( server.py ) I built to replace our deprecated extension tools:
server.py
""" Stateless Remote MCP Server running on Cloud Run (FastMCP) Migrated from deprecated Vertex AI Extensions OpenAPI specifications """ import os import logging from typing import Dict, Any, List from mcp.server.fastmcp import FastMCP from pydantic import BaseModel, Field # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger("remote-mcp-ops") # Initialize FastMCP instance (binds to Cloud Run's PORT environment variable) mcp = FastMCP( name="GCP-Infrastructure-Ops-MCP", host="0.0.0.0", port=int(os.environ.get("PORT", 8080)), dependencies=["pydantic", "google-cloud-monitoring", "google-cloud-logging"] ) class ResourceFilter(BaseModel): project_id: str = Field(..., description="Target Google Cloud Project ID") severity: str = Field("ERROR", description="Log severity threshold (INFO, WARNING, ERROR, CRITICAL)") limit: int = Field(10, ge=1, le=100, description="Maximum number of records to retrieve") @mcp.tool() def get_service_health(service_name: str, environment: str = "production") -> Dict[str, Any]: """ Retrieves the current health status, error rates, and p99 latency for a given Cloud Run or GKE service. """ logger.info(f"Health check requested for {service_name} in {environment}") # Realistic mock response (in production, queries Cloud Monitoring API) return { "service": service_name, "environment": environment, "status": "HEALTHY", "latency_p99_ms": 142.5, "error_rate_percent": 0.02, "active_instances": 4, "checked_at": "2026-11-29T07:00:00Z" } @mcp.tool() def list_active_incidents(filter_params: ResourceFilter) -> List[Dict[str, Any]]: """ Lists active system incidents and critical firing alerts within the specified project. """ logger.info(f"Listing incidents for {filter_params.project_id} (severity: {filter_params.severity})") return [ { "incident_id": "INC-20261126-001", "summary": "Vertex AI Extensions endpoint discontinued - 410 Gone", "severity": filter_params.severity, "status": "RESOLVED", "impacted_service": "vertexai.preview.extensions" } ] if __name__ == "__main__": # Run using Cloud Run's recommended Streamable HTTP transport (or transport="sse") transport_mode = os.environ.get("MCP_TRANSPORT", "streamable-http") logger.info(f"Starting Remote MCP Server with transport={transport_mode}...") mcp.run(transport=transport_mode)
To minimize container startup latency on Cloud Run, I used python:3.13-slim without unnecessary build tools or system caches:
python:3.13-slim
FROM python:3.13-slim WORKDIR /app ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ PORT=8080 RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY server.py . EXPOSE 8080 CMD ["python", "server.py"]
Deploying to Cloud Run with gcloud CLI enforces zero-trust unauthenticated blocking:
# 1. Create a dedicated runtime Service Account gcloud iam service-accounts create sa-agent-mcp-runner \ --display-name="Service Account for AI Agent MCP Runner" # 2. Deploy to Cloud Run (Strictly disallowing unauthenticated traffic) gcloud run deploy remote-mcp-ops \ --source . \ --region us-central1 \ --platform managed \ --no-allow-unauthenticated \ --min-instances 0 \ --max-instances 5 \ --cpu 1 \ --memory 512Mi \ --timeout 300s \ --service-account "sa-agent-mcp-runner@${PROJECT_ID}.iam.gserviceaccount.com" # 3. Grant invocation rights (roles/run.invoker) strictly to the calling agent identity gcloud run services add-iam-policy-binding remote-mcp-ops \ --region us-central1 \ --member="serviceAccount:sa-antigravity-caller@${PROJECT_ID}.iam.gserviceaccount.com" \ --role="roles/run.invoker"
A crucial security principle here is privilege separation : the calling agent requires only roles/run.invoker to hit the Cloud Run URL. The actual permissions to read logs or inspect database instances are attached strictly to the server’s own identity ( sa-agent-mcp-runner ), preventing prompt-injection attacks on the agent from directly hijacking backend cloud permissions.
roles/run.invoker
sa-agent-mcp-runner
Unlike legacy code where vertexai.preview.extensions.Extension.from_hub() acted as a proprietary middleman, the modern google-genai SDK supports passing an official mcp ClientSession directly into tools=[session] for seamless autonomous tool discovery and invocation:
vertexai.preview.extensions.Extension.from_hub()
mcp
ClientSession
tools=[session]
Below is the client implementation using streamablehttp_client with OIDC Bearer authentication and binding the ClientSession directly to google-genai :
streamablehttp_client
""" Client integration executing Remote MCP tools on Cloud Run using Gemini 4 Carbon and google-genai """ import asyncio import os import subprocess from google import genai from google.genai import types from mcp import ClientSession from mcp.client.streamable_http import streamablehttp_client def get_google_oidc_token(target_audience: str) -> str: """ Retrieves a valid Google Cloud OIDC ID token targeting the Cloud Run audience. In containerized production environments, use google.auth.transport.requests. """ cmd = ["gcloud", "auth", "print-identity-token", f"--audiences={target_audience}"] result = subprocess.run(cmd, capture_output=True, text=True, check=True) return result.stdout.strip() async def run_agent_with_remote_mcp(): cloud_run_url = os.environ.get("CLOUD_RUN_MCP_URL", "https://remote-mcp-ops-xxxxxxxx-uc.a.run.app") mcp_endpoint = f"{cloud_run_url.rstrip('/')}/mcp" # Generate OIDC identity token for Cloud Run authentication id_token = get_google_oidc_token(target_audience=cloud_run_url) headers = {"Authorization": f"Bearer {id_token}"} print(f"Connecting to Remote MCP at {mcp_endpoint} with OIDC token...") # Establish Streamable HTTP MCP session with Cloud Run async with streamablehttp_client(mcp_endpoint, headers=headers) as (read_stream, write_stream, _): async with ClientSession(read_stream, write_stream) as session: await session.initialize() # Initialize modern google-genai client client = genai.Client() # Pass MCP ClientSession directly into tools=[session] for Gemini 4 Carbon response = await client.aio.models.generate_content( model="gemini-4-carbon", contents="Inspect the health status of payment-service running in our production Cloud Run environment.", config=types.GenerateContentConfig( tools=[session], temperature=0.2 ) ) print("Gemini Final Report:\n", response.text) if __name__ == "__main__": asyncio.run(run_agent_with_remote_mcp())
While writing the replacement code took less than half a day, I hit three nasty snags during testing that every engineer following this path must guard against.
The most insidious bug occurred roughly 60 minutes into continuous agent operations: tool requests suddenly failed with 401 Unauthorized .
401 Unauthorized
Google Cloud OIDC ID tokens enforce a strict 3,600-second (1-hour) maximum lifespan . Because my initial script cached the token obtained during startup, once the hour lapsed, Cloud Run’s IAM gateway promptly dropped every request.
Resolution : Never store the ID token statically. I built an auth interceptor that decodes the exp claim before every outgoing request and refreshes the token automatically if fewer than 5 minutes remain.
exp
When running FastMCP in Server-Sent Events (SSE) mode, complex reasoning tasks from Gemini 4 Carbon frequently required 60 to 90 seconds of continuous thinking. During this time, Cloud Run’s infrastructure assumed the idle TCP connection had hung and severed the stream.
While Cloud Run allows up to a 300-second request timeout, intermediary edge proxies often terminate idle TCP streams after 60 seconds without data.
Resolution : Configure FastMCP to emit periodic comment heartbeats ( : ping\n\n ) every 15 seconds, keeping the streaming connection alive regardless of long LLM inference times.
: ping\n\n
Our legacy OpenAPI 3.0 specifications made heavy use of polymorphic schemas ( oneOf , anyOf , and nullable: true ). When blindly translated into nested Pydantic v2 models, the auto-generated tool declaration produced schema depths that Gemini’s Function Calling parser could not reliably bind.
oneOf
anyOf
nullable: true
Resolution : Flatten tool parameter schemas. Stick strictly to primitive types ( str , int , float , bool ) and single-level structured models, avoiding deeply nested polymorphic unions in tool arguments.
str
int
float
bool
▲ Live execution trace of Gemini 4 Carbon invoking Remote MCP tools via google-genai ClientSession and automated pytest verification of all three production guardrails
Over three consecutive days of testing with roughly 500 tool calls per day, the telemetry showed:
To be completely transparent, the architecture described here has been validated across personal lab environments and internal staging clusters. The following scenarios remain unverified in large-scale production :
us-central1
When I received Google’s deprecation notice for Vertex AI Extensions, my initial reaction was frustration at having to rewrite working pipelines. Yet, embracing the transition has turned out to be an immense net positive:
The era of locking agent tool definitions into vendor-specific extensions is over. By hosting Model Context Protocol servers on serverless container infrastructure, cloud engineers can build robust, standardized tool ecosystems that survive the rapid evolution of foundation models.
Real-time AI quant analysis of earnings reports, corporate filings, and momentum indicators for global equities and Japanese stocks.
Master conversation skills with realistic AI phone training and 5-axis feedback. Includes 16-lesson interactive academy and studio AI portraits.
Effortlessly snap receipts for instant AI itemization. Integrated with LINE for seamless group expense tracking and pain-free settlement.
Interactive AI personas (Fortune Teller, Butler, Bartender) host real-time games, challenges, and conversation starters for unforgettable gatherings.
Unbiased healthcare database featuring zero-additive filters and active ingredient cost performance metrics.