Kanji
・Cloud engineer / freelance ・Born in 1993 ・From Ehime / Living in Shibuya, Tokyo ・5 years AWS experience Profile details
Table of Contents
When I began integrating AI coding agents like Antigravity and Claude Code into internal infrastructure and development workflows in late 2025, one of my top priorities was hosting remote Model Context Protocol (MCP) servers to allow agents to interact with proprietary databases, BigQuery datasets, and internal automation scripts.
At the time, the dominant transport in the MCP ecosystem was stateful Server-Sent Events (SSE) over HTTP. On a local development machine running against localhost , everything worked flawlessly. However, the moment I packaged the server into a container and deployed it onto Google Cloud Run, things started unraveling.
localhost
Cloud Run is fundamentally a serverless compute platform: it dynamically scales container instances from zero to dozens based on concurrent traffic, and promptly terminates idle instances (scale-to-zero). The legacy MCP specification, however, mandated an initial initialize handshake, returning a stateful Mcp-Session-Id that clients had to attach to subsequent tools/call and resources/read requests.
initialize
Mcp-Session-Id
tools/call
resources/read
This mismatch created severe production friction:
404 Session Not Found
min-instances: 1
The release of the MCP 2026-07-28 specification completely resolved this tension by stripping stateful constraints from the protocol core.
▲ High-level architecture: Secure zero-trust access from local AI agents to stateless MCP servers on Cloud Run via Google Cloud IAM
The defining feature of the 2026-07-28 specification is the complete statelessness of the protocol core . The differences compared to previous iterations are summarized below:
2026-07-28
_meta
Mcp-Method
Mcp-Name
MRTR is a game-changer for serverless tool hosting. Often, an agent executing an infrastructure action requires human approval or supplementary parameters (e.g., confirming a production database deletion or approving paid API invocations).
In legacy streaming transports, the server had to keep the socket alive while waiting for human input. Under MRTR, when a tool requires input, the server simply returns an input_required status with a continuation_token and cleanly terminates the HTTP request .
input_required
continuation_token
Once the operator responds, the agent sends a follow-up POST request containing the user’s answer and the continuation token. Even if this request reaches a completely different container (Instance B), the context is restored from the token, completing the workflow without persistent state.
Exposing remote MCP endpoints using static API keys passed in X-Api-Key headers is a major security vulnerability. Static keys frequently end up hardcoded in agent configuration files ( mcp_config.json ) and run the risk of leaking into version control.
X-Api-Key
mcp_config.json
By hosting your server on Cloud Run, you can enforce zero-trust authentication through Google Cloud IAM ( roles/run.invoker ) and OIDC identity tokens .
roles/run.invoker
--no-allow-unauthenticated
https://<service-name>-<hash>-an.a.run.app
Authorization: Bearer <ID_TOKEN>
Google Cloud’s edge infrastructure validates the cryptographic signature and expiration of the token before traffic ever reaches your container.
# 0. Grant least-privilege roles/run.invoker to the caller identity gcloud run services add-iam-policy-binding mcp-secops-server \ --region=asia-northeast1 \ --member="user:developer@example.com" \ --role="roles/run.invoker" # 1. Fetch Cloud Run Service URL SERVICE_URL=$(gcloud run services describe mcp-secops-server --region asia-northeast1 --format 'value(status.url)') # 2. Generate an OIDC ID token matching the specific service audience ID_TOKEN=$(gcloud auth print-identity-token --audiences="${SERVICE_URL}") # 3. Send a stateless request using Mcp-Method header and Bearer token curl -s -X POST "${SERVICE_URL}/mcp" \ -H "Authorization: Bearer ${ID_TOKEN}" \ -H "Mcp-Method: tools/list" \ -H "Content-Type: application/json" \ -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' | jq .
▲ Cloud Run service security: Denying unauthenticated requests and enforcing least-privilege roles/run.invoker
Below is the production-tested minimal implementation of a stateless MCP server adhering to the MCP 2026-07-28 specification, using Express:
// src/server.ts import express, { Request, Response } from 'express'; const app = express(); app.use(express.json()); // Startup probe endpoint for Cloud Run app.get('/healthz', (_req: Request, res: Response) => { res.status(200).send('OK'); }); // MCP 2026-07-28 Stateless Endpoint app.post('/mcp', async (req: Request, res: Response) => { const mcpMethod = req.header('Mcp-Method') || req.body?.method; const requestId = req.body?.id ?? 1; // 1. Tool discovery if (mcpMethod === 'tools/list' || req.body?.method === 'tools/list') { return res.json({ jsonrpc: '2.0', id: requestId, result: { tools: [ { name: 'query_security_audit_logs', description: 'Queries Cloud Logging for critical security events', inputSchema: { type: 'object', properties: { hoursAgo: { type: 'number', description: 'Lookback window in hours' }, severity: { type: 'string', enum: ['WARNING', 'ERROR', 'CRITICAL'] } }, required: ['severity'] } } ] } }); } // 2. Tool invocation (tools/call) if (mcpMethod === 'tools/call' || req.body?.method === 'tools/call') { const { name, arguments: args } = req.body.params; if (name === 'query_security_audit_logs') { const severity = args?.severity || 'ERROR'; const mockLogs = [ { timestamp: new Date().toISOString(), severity: severity, resource: 'projects/my-prod-project/instances/db-01', message: 'IAM authorization check failed' } ]; return res.json({ jsonrpc: '2.0', id: requestId, result: { content: [ { type: 'text', text: JSON.stringify(mockLogs, null, 2) } ], isError: false } }); } return res.status(404).json({ jsonrpc: '2.0', id: requestId, error: { code: -32601, message: `Tool ${name} not found` } }); } return res.status(400).json({ jsonrpc: '2.0', id: requestId, error: { code: -32600, message: `Unsupported method: ${mcpMethod}` } }); }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`[MCP Server] Stateless Remote MCP listening on port ${PORT}`); });
# Multi-stage build for Minimal Stateless MCP Server FROM node:22-alpine AS builder WORKDIR /app COPY package*.json tsconfig.json ./ RUN npm ci COPY src ./src RUN npm run build FROM node:22-alpine AS runner WORKDIR /app ENV NODE_ENV=production COPY package*.json ./ RUN npm ci --only=production COPY --from=builder /app/dist ./dist USER node EXPOSE 8080 CMD ["node", "dist/server.js"]
PROJECT_ID="your-gcp-project-id" REGION="asia-northeast1" SERVICE_NAME="mcp-secops-server" gcloud run deploy "${SERVICE_NAME}" --source . --region "${REGION}" --project "${PROJECT_ID}" --no-allow-unauthenticated --min-instances 0 --max-instances 10 --cpu 1 --memory 512Mi --concurrency 80 --timeout 60s
To connect an AI agent to the Cloud Run endpoint using authenticated identity tokens:
{ "mcpServers": { "cloudrun-secops": { "command": "node", "args": [ "/usr/local/bin/cloudrun-mcp-proxy.js", "--url", "https://mcp-secops-server-xyz-an.a.run.app/mcp" ], "env": { "CLOUD_RUN_AUDIENCE": "https://mcp-secops-server-xyz-an.a.run.app" } } } }
Alternatively, during local testing, you can run the built-in Cloud Run authentication proxy via gcloud run services proxy mcp-secops-server --region=asia-northeast1 --port=8080 , which automatically injects OIDC identity tokens for local requests to http://localhost:8080/mcp .
gcloud run services proxy mcp-secops-server --region=asia-northeast1 --port=8080
http://localhost:8080/mcp
▲ Verification log demonstrating dynamic token generation via gcloud auth and successful invocation of stateless MCP tools
--min-instances 1
gcloud auth print-identity-token
Authorization: Bearer <TOKEN>
X-Upstream-Authorization
The release of the MCP 2026-07-28 specification marks the maturity of agent tool protocols for cloud-native deployment. By removing in-memory session requirements, we can finally host remote MCP servers on Cloud Run with full autoscaling, scale-to-zero efficiency, and enterprise-grade Google Cloud IAM protection.
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.