clouddb-mcp
# clouddb-mcp
> **Local-first, guardrailed Model Context Protocol (MCP) server for read-only PostgreSQL diagnostics and AWS infrastructure auditing.**
[](https://github.com/Manishp16/clouddb-mcp/actions/workflows/ci.yml)
[](https://www.python.org/)
[](https://modelcontextprotocol.io/)
[](https://www.postgresql.org/)
[](https://github.com/floci-dev/floci)
AI agents connected to databases and cloud APIs can generate **destructive SQL** (e.g., `WITH d AS (DELETE ... RETURNING *) SELECT * FROM d`), **expensive queries**, **large data reads**, and expose PII or secrets in LLM context windows.
`clouddb-mcp` applies SQL validation, read-only database transactions, query timeouts, row limits, and selected PII/secret redaction. These controls reduce risk but are not a replacement for least-privilege database/IAM permissions or a security review.
---
## Architecture
```mermaid
flowchart LR
Agent["LLM / SRE Agent<br/>(Gemini 3.5 Flash-Lite / Claude / MCP Inspector)"]
MCP["clouddb-mcp Server<br/>(MCP Python SDK v2 — stdio / streamable-http)"]
subgraph Guardrails["Defense-in-Depth Guardrails"]
AST["sqlglot AST Validator<br/>- Blocks DDL/DML & CTE writes<br/>- Blocks DoS funcs & multi-stmt<br/>- Enforces LIMIT cap"]
Redactor["PII & Secret Redactor<br/>- Sensitive column masking<br/>- Regex: AKIA, JWT, sk_*, DSN, Email, Phone"]
Audit["Structured JSONL Audit Log<br/>logs/audit.jsonl + audit://recent/{limit}"]
end
subgraph Infra["$0 Local Infrastructure (Docker Compose)"]
PG["PostgreSQL 16<br/>SET TRANSACTION READ ONLY<br/>statement_timeout = 3000ms"]
Floci["Floci AWS Emulator (:4566)<br/>EC2, RDS, CloudWatch Logs, S3"]
end
Agent <-->|"JSON-RPC"| MCP
MCP --> AST --> PG
MCP --> Floci
PG --> Redactor --> MCP
Floci --> Redactor --> MCP
MCP --> Audit
```
---
## MCP Capabilities
### Tools (8)
| Tool | Target | Guardrail / Behavior |
| :--- | :--- | :--- |
| `pg_inspect_schema` | PostgreSQL | Lists tables, columns, data types, nullability, and indexes |
| `pg_safe_query` | PostgreSQL | `sqlglot` AST read-only validation, `LIMIT` cap, `READ ONLY` txn, PII redaction |
| `pg_explain_query` | PostgreSQL | Runs `EXPLAIN` or `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` inside a read-only txn |
| `pg_health_diagnostics` | PostgreSQL | Reports `seq_scan` vs `idx_scan`, dead tuples, and unused indexes |
| `aws_ec2_security_audit` | AWS / Floci | Flags Security Groups exposing `0.0.0.0/0` or `::/0` on critical ports (`22`, `3389`, `5432`, `3306`, `6379`) |
| `aws_rds_health` | AWS / Floci | Checks RDS status, public accessibility, storage encryption, and Multi-AZ |
| `aws_cloudwatch_recent_errors` | AWS / Floci | Fetches recent CloudWatch error logs and redacts leaked secrets/PII |
| `aws_s3_security_audit` | AWS / Floci | Audits S3 buckets for default encryption, Block Public Access, public bucket policies, and ACL grants |
### Resources & Prompts
- **Resource:** `audit://recent/{limit}` — Returns recent guardrail decisions, latency, and redaction counts (`application/json`).
- **Prompt:** `diagnose_slow_query(table_name)` — Guided SRE workflow for diagnosing missing indexes without executing DDL.
---
## Red-Team Security Evaluation
Every guardrail rule is verified by automated tests (`tests/test_sql_guard.py`, `tests/test_pii_redactor.py`, `tests/test_mcp_e2e.py`, `tests/test_integration_live.py`):
| Attack / Risk Vector | Example Input / Payload | Result |
| :--- | :--- | :--- |
| **DDL / DML Mutation** | `DROP TABLE customers;`, `DELETE FROM orders ...` | Blocked by AST (`FORBIDDEN_EXPRESSIONS`) |
| **Sneaky Write CTE** | `WITH d AS (DELETE FROM orders RETURNING *) SELECT * FROM d` | Blocked by AST tree walk |
| **Multi-Statement Injection** | `SELECT 1; DROP TABLE orders;` | Blocked (single-statement enforcement) |
| **DoS / File Read Functions** | `SELECT pg_sleep(10);`, `SELECT pg_read_file('/etc/passwd');` | Blocked (`FORBIDDEN_FUNCTIONS`) |
| **System Credential Tables** | `SELECT * FROM pg_shadow;`, `SELECT * FROM pg_catalog.pg_tables;` | Blocked (`BLOCKED_TABLES` / `BLOCKED_SCHEMAS`) |
| **Unbounded Row Exfiltration** | `SELECT id FROM orders LIMIT 5000` | Rewritten to `LIMIT 100` |
| **Leaked Secrets & PII** | `AKIA...`, `postgresql://...`, JWTs, `sk_live_...`, `api_key`, emails, phones | Masked with `[REDACTED_*]` tokens |
| **Legitimate String Literals** | `SELECT * FROM orders WHERE status = 'DELETE_REQUESTED'` | **Allowed** (no false positive on string literals) |
---
## Zero-Cost Local Quickstart
### Prerequisites
- Python `>= 3.11` & [`uv`](https://docs.astral.sh/uv/)
- Docker & Docker Compose
- Free Google AI Studio API key (`GEMINI_API_KEY`) for the example agent (optional for running `pytest`)
> **Safety:** The Docker stack and seeded AWS findings are for local demonstration only. The AWS endpoint defaults to Floci, but changing it can direct audit calls to a real AWS account. Use appropriately restricted credentials and do not treat this project as production-ready without your own review.
### 1. Configure & Install
```bash
git clone https://github.com/Manishp16/clouddb-mcp.git
cd clouddb-mcp
cp .env.example .env
# Edit .env: add your GEMINI_API_KEY and set GEMINI_MODEL=gemini-3.5-flash-lite
uv sync --all-groups
```
### 2. Start Local PostgreSQL 16 + Floci AWS
```bash
docker compose up -d
uv run python scripts/seed_floci.py
```
`scripts/seed_postgres.sql` creates `customers` (1,000 rows) and `orders` (50,000 rows without a `customer_id` index). `scripts/seed_floci.py` seeds an exposed Security Group (`0.0.0.0/0` on ports `22` & `5432`), an S3 bucket with public-access blocking disabled and a public-read bucket policy, and CloudWatch error logs containing intentionally synthetic examples of a leaked AWS key, DB URI, and email.
### 3. Run Security, Protocol & Integration Tests ($0 API Cost)
```bash
uv run ruff check src tests scripts examples
uv run pytest -v
```
### 4. Run the Interactive SRE Agent
```bash
uv run python examples/gemini_agent.py
```
<details>
<summary>Sample verified SRE agent session (AWS audit, secret redaction, EXPLAIN ANALYZE & guardrail block)</summary>
```text
SRE> Run an EC2 security audit and S3 audit, and summarize any CRITICAL exposure risks.
[tool] aws_ec2_security_audit({})
[tool] aws_s3_security_audit({})
-> Flags prod-db-exposed-sg (0.0.0.0/0 on ports 22 & 5432) and prod-ops-public-backups (PUBLIC_ACCESS_BLOCK_INCOMPLETE, PUBLIC_BUCKET_POLICY).
SRE> Check recent errors in /aws/eks/prod-api/app and tell me if any secrets were redacted.
[tool] aws_cloudwatch_recent_errors({'log_group': '/aws/eks/prod-api/app'})
-> Redacts 3 sensitive fields before LLM context: [REDACTED_EMAIL], [REDACTED_AWS_KEY], [REDACTED_DB_URI].
SRE> Check why querying orders by customer_id = 42 is slow using EXPLAIN ANALYZE, and recommend an exact index.
[tool] pg_inspect_schema({'schema_name': 'public'})
[tool] pg_explain_query({'analyze': True, 'sql': 'SELECT * FROM orders WHERE customer_id = 42;'})
-> Identifies Seq Scan on orders (49,950 rows filtered out, ~34ms) and recommends:
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
SRE> Execute this SQL via pg_safe_query: WITH d AS (DELETE FROM orders RETURNING *) SELECT * FROM d
[tool] pg_safe_query({'sql': 'WITH d AS (DELETE FROM orders RETURNING *) SELECT * FROM d'})
-> Blocked by sqlglot AST guardrail (status: blocked_by_guardrail).
```
</details>
### 5. (Optional) Inspect Visually with MCP Inspector
```bash
uv run mcp dev src/clouddb_mcp/server.py
```TDQS
Scored across 8 tools
Each tool targets a distinct resource+action: schema inspection, read-only querying, EXPLAIN plans, and health diagnostics are clearly separated within the PostgreSQL family, and the AWS tools map to distinct services (EC2, RDS, CloudWatch, S3). The pg_safe_query vs pg_explain_query boundary is clear from descriptions (execute vs explain a validated SELECT). No overlaps that would cause misselection.
Names follow a predictable provider_resource_action pattern (pg_* and aws_*) in consistent snake_case throughout. Minor deviations exist in the action vocabulary (inspect, safe_query, health_diagnostics, health), so it is not perfectly uniform but remains highly readable.
Eight tools are well-scoped for a cloud database auditing server, with four PostgreSQL tools and four AWS audit tools each earning their place. No redundant or filler tools.
The read-only auditing surface is coherent and covers schema inspection, querying, planning, and key AWS security checks. Minor gaps exist (no schema/database listing, no CloudWatch metrics beyond errors), but agents can work around them for the stated audit purpose.