GCP Infrastructure MCP Server
by nsachin08
README.md
# GCP Infrastructure MCP Server
A **Model Context Protocol (MCP)** server that provides **30+ read-only tools** for querying Google Cloud Platform infrastructure. Designed for AI assistants, Terraform workflow support, and any MCP-compatible client.
Each user authenticates with their own **base64-encoded GCP service account key** — no credentials are stored on the server.
---
## Table of Contents
- [Features](#features)
- [Architecture](#architecture)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Running the Server](#running-the-server)
- [Authentication Setup](#authentication-setup)
- [MCP Client Configuration](#mcp-client-configuration)
- [Available Tools](#available-tools)
- [Terraform Integration](#terraform-integration)
- [Adding New Tools](#adding-new-tools)
- [Security Considerations](#security-considerations)
---
## Features
- **30+ infrastructure tools** covering Compute, Networking, GKE, DNS, Load Balancers, and Cloud Asset Inventory
- **Multi-tenant** — each user provides their own service account key as a Bearer token
- **SSE transport** — works with any MCP client that supports URL + token
- **Async** — GCP API calls run in a thread pool to keep the event loop responsive
- **Terraform-friendly** — fetch real infrastructure state to generate or validate `.tf` files
- **Docker-ready** — ship as a single container
---
## Architecture
```
MCP Client
│
│ Authorization: Bearer <base64_sa_key>
▼
┌──────────────────────────────────────┐
│ main.py (Starlette ASGI app) │
│ ├── GET /sse → SSE stream │
│ ├── POST /messages/ → MCP messages │
│ └── GET /health → health check │
│ │
│ src/auth.py → decode token, set ctx │
│ src/server.py → shared FastMCP instance │
│ │
│ src/tools/compute.py (5 tools) │
│ src/tools/networking.py (17 tools) │
│ src/tools/gke.py (4 tools) │
│ src/tools/regions.py (4 tools) │
│ src/tools/inventory.py (3 tools) │
│ │
│ src/gcp_clients.py → client factories│
└──────────────────────────────────────┘
│
▼
Google Cloud APIs (Compute, Container, DNS, Asset Inventory)
```
---
## Prerequisites
| Requirement | Minimum Version |
|---|---|
| Python | 3.10+ |
| pip | latest |
| GCP Service Account | with read-only roles |
| Docker *(optional)* | 20+ |
---
## Installation
### Option A — Local (virtualenv)
```bash
cd gcpmcp
# Create and activate a virtual environment
python -m venv venv
# Linux / macOS
source venv/bin/activate
# Windows (PowerShell)
.\venv\Scripts\Activate.ps1
# Install dependencies
pip install -r requirements.txt
```
### Option B — Docker
```bash
docker build -t gcp-mcp-server .
```
---
## Running the Server
### Local
```bash
python main.py
```
| Flag | Default | Description |
|---|---|---|
| `--host` | `0.0.0.0` | Bind address |
| `--port` | `8080` | Listen port |
| `--log-level` | `info` | `debug` / `info` / `warning` / `error` |
Example:
```bash
python main.py --host 127.0.0.1 --port 9000 --log-level debug
```
### Docker
```bash
docker run -p 8080:8080 gcp-mcp-server
```
### Health Check
```bash
curl http://localhost:8080/health
# {"status":"healthy","server":"gcp-infrastructure-mcp"}
```
---
## Authentication Setup
### 1. Create a GCP Service Account
```bash
PROJECT_ID=your-project-id
# Create the service account
gcloud iam service-accounts create mcp-reader \
--display-name="MCP Infrastructure Reader"
# Grant read-only roles
for ROLE in roles/compute.viewer roles/container.viewer \
roles/dns.reader roles/cloudasset.viewer; do
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:mcp-reader@${PROJECT_ID}.iam.gserviceaccount.com" \
--role="$ROLE"
done
# Download the JSON key
gcloud iam service-accounts keys create sa-key.json \
--iam-account=mcp-reader@${PROJECT_ID}.iam.gserviceaccount.com
```
### 2. Base64-Encode the Key
**Linux / macOS:**
```bash
TOKEN=$(base64 -w 0 < sa-key.json)
echo "$TOKEN"
```
**Windows (PowerShell):**
```powershell
$TOKEN = [Convert]::ToBase64String([IO.File]::ReadAllBytes("sa-key.json"))
Write-Output $TOKEN
```
### 3. Required IAM Roles
| Role | Purpose |
|---|---|
| `roles/compute.viewer` | VMs, disks, VPCs, subnets, firewalls, LBs, routes |
| `roles/container.viewer` | GKE clusters and node pools |
| `roles/dns.reader` | Cloud DNS zones and records |
| `roles/cloudasset.viewer` | Cloud Asset Inventory searches |
---
## MCP Client Configuration
Set your MCP client to connect with:
- **URL:** `http://<server-host>:8080/sse`
- **Token:** the base64-encoded service account key
### Example — Generic MCP Client
```json
{
"mcpServers": {
"gcp-infrastructure": {
"url": "http://localhost:8080/sse",
"token": "<BASE64_ENCODED_SERVICE_ACCOUNT_KEY>"
}
}
}
```
### Example — Production (HTTPS)
```json
{
"mcpServers": {
"gcp-infrastructure": {
"url": "https://mcp.example.com/sse",
"token": "<BASE64_ENCODED_SERVICE_ACCOUNT_KEY>"
}
}
}
```
> **Note:** Different users can connect simultaneously, each with their own token pointing to a different GCP project.
---
## Available Tools
### Compute Engine (5 tools)
| Tool | Description |
|---|---|
| `list_compute_instances` | List VMs (all zones or specific zone) |
| `get_compute_instance` | Get full details of a specific VM |
| `list_disks` | List persistent disks |
| `list_instance_templates` | List instance templates |
| `list_machine_types` | List available machine types in a zone |
### Networking (7 tools)
| Tool | Description |
|---|---|
| `list_vpcs` | List VPC networks |
| `get_vpc` | Get VPC details (peerings, routing) |
| `list_subnets` | List subnets (all regions or specific) |
| `get_subnet` | Get subnet details (CIDR, gateway) |
| `list_firewalls` | List firewall rules |
| `get_firewall` | Get firewall rule details |
| `list_routes` | List all routes |
### IP Addresses (1 tool)
| Tool | Description |
|---|---|
| `list_addresses` | List reserved / static IPs |
### Load Balancers (6 tools)
| Tool | Description |
|---|---|
| `list_forwarding_rules` | Regional LB frontends |
| `list_global_forwarding_rules` | Global HTTP(S)/SSL/TCP LB frontends |
| `list_backend_services` | LB backend services |
| `list_url_maps` | HTTP(S) LB URL routing |
| `list_target_pools` | Classic network LB backends |
| `list_health_checks` | Health checks |
### SSL (1 tool)
| Tool | Description |
|---|---|
| `list_ssl_certificates` | SSL certificates for HTTPS LBs |
### DNS (2 tools)
| Tool | Description |
|---|---|
| `list_dns_zones` | Cloud DNS managed zones |
| `list_dns_records` | DNS record sets in a zone |
### GKE — Google Kubernetes Engine (4 tools)
| Tool | Description |
|---|---|
| `list_gke_clusters` | List GKE clusters |
| `get_gke_cluster` | Cluster details (networking, add-ons, security) |
| `list_gke_node_pools` | Node pools for a cluster |
| `get_gke_server_config` | Supported K8s versions & image types |
### Regions & Zones (4 tools)
| Tool | Description |
|---|---|
| `list_regions` | All GCP regions |
| `get_region` | Region details (quotas, zones) |
| `list_zones` | All GCP zones |
| `get_zone` | Zone details (status, CPU platforms) |
### Cloud Asset Inventory (3 tools)
| Tool | Description |
|---|---|
| `search_cloud_resources` | Full-text search across all resources |
| `list_cloud_assets` | List assets by type |
| `get_infrastructure_summary` | Resource counts by type (quick audit) |
---
## Terraform Integration
This server is purpose-built for infrastructure-as-code workflows:
1. **Audit** — Use `get_infrastructure_summary` to see what's deployed.
2. **Explore** — Drill into VPCs, subnets, firewalls, GKE clusters.
3. **Generate** — Feed real infrastructure data to an AI to produce accurate `.tf` files.
4. **Validate** — Compare `terraform plan` output against live state.
### Example Workflow
```text
User: "List all VPCs and generate Terraform for them"
AI: → calls list_vpcs → gets 3 VPCs with auto-subnets
→ calls list_subnets → maps CIDRs per region
→ generates google_compute_network + google_compute_subnetwork resources
```
---
## Adding New Tools
1. Pick the right file (`src/tools/compute.py`, `src/tools/networking.py`, etc.) or create a new `src/tools/<name>.py` module.
2. Import `mcp` from `src.server` and credentials helpers from `src.auth`.
3. Decorate your function with `@mcp.tool()`.
4. If you create a new module, import it in `main.py` so the tools get registered.
```python
# src/tools/storage.py (example)
from src.server import mcp
from src.auth import get_credentials, get_project_id
from src.gcp_clients import run_sync, format_response
@mcp.tool()
async def list_storage_buckets(project_id=None, max_results=100):
"""List Cloud Storage buckets."""
credentials = get_credentials()
project = project_id or get_project_id()
# ... call GCS API ...
```
Then add to `main.py`:
```python
import src.tools.storage # noqa: F401
```
---
## Project Structure
```
gcpmcp/
├── main.py # Entry point — HTTP server + route handlers
├── src/
│ ├── __init__.py
│ ├── server.py # Shared FastMCP instance
│ ├── auth.py # Token decoding + per-session credential mgmt
│ ├── gcp_clients.py # GCP client factories + proto-to-dict helpers
│ └── tools/
│ ├── __init__.py
│ ├── compute.py # Compute Engine tools (5)
│ ├── networking.py # VPC / firewall / DNS / LB tools (17)
│ ├── gke.py # GKE tools (4)
│ ├── regions.py # Region & zone tools (4)
│ └── inventory.py # Cloud Asset Inventory tools (3)
├── requirements.txt # Python dependencies
├── Dockerfile # Container image
└── README.md # This file
```
---
## Security Considerations
| Concern | Mitigation |
|---|---|
| **Token in transit** | Use HTTPS (TLS) in production — the Bearer token is a full credential. |
| **Least privilege** | Grant only `viewer` / `reader` roles — never `editor` or `owner`. |
| **Key rotation** | Rotate service account keys regularly; delete unused keys. |
| **Network access** | Restrict the MCP server to trusted networks (VPN, firewall rules). |
| **Secrets in VCS** | Never commit `sa-key.json` or base64 tokens to version control. |
| **Server hardening** | Run as a non-root user in Docker; pin dependency versions. |
---
## License
MIT
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues