Folio Rancher PostgreSQL MCP How-To

Folio Rancher PostgreSQL MCP How-To

Overview

PostgreSQL MCP is a Model Context Protocol server that connects your AI assistant (Claude, GitHub Copilot, Cursor, etc.) directly to the PostgreSQL instance running inside a Folio Rancher environment. It gives your AI a full DBA toolkit — you can query data, inspect schemas, analyze query plans, find missing indexes, check locks, manage roles, and much more — all from a natural-language chat, without leaving your IDE.

The server is deployed as a Kubernetes workload inside every Rancher project that has pg_mcp_server = true in its Terraform configuration. It is protected by a Bearer token stored in the db-credentials Kubernetes secret of that project.


Architecture

Your IDE / AI Client │ │ HTTPS (Authorization: Bearer <token>) ▼ ALB (shared group) │ ▼ Ingress → pg-mcp Service → pg-mcp Pod │ │ asyncpg ▼ PostgreSQL (embedded Bitnami or AWS RDS Aurora)

Endpoint pattern:

https://<cluster-name>-<project-name>-pg-mcp.ci.folio.org/sse

Examples: - https://folio-snapshot-pg-mcp.ci.folio.org/sse - https://folio-testing-pg-mcp.ci.folio.org/sse


Prerequisites

  • Access to the Rancher UI for the target environment or kubectl configured for that cluster/namespace

  • VS Code with GitHub Copilot, Claude Desktop, Cursor, or any other MCP-compatible AI client

  • The DB_MCP_TOKEN for the target environment (see Step 1 below)


Step 1: Retrieve the Bearer Token

The token is generated by Terraform and stored in the db-credentials Kubernetes secret of the target project namespace. There are two ways to retrieve it.

Option A — Rancher UI

  1. Log in to https://rancher.ci.folio.org

  2. Navigate to your cluster → Projects/Namespaces → select the project (e.g. snapshot)

  3. In the left sidebar go to Storage → Secrets

  4. Find the secret named db-credentials

  5. Click it, then click the eye icon next to DB_MCP_TOKEN to reveal the value

  6. Copy the raw value — this is your Bearer token

Option B — kubectl

Run the following command, replacing <namespace> with your project name (e.g. snapshot, testing):

kubectl get secret db-credentials -n <namespace> \ -o jsonpath='{.data.DB_MCP_TOKEN}' | base64 -d

The decoded string (32 alphanumeric characters) is your Bearer token. Store it somewhere safe — treat it like a password.


Step 2: Configure Your MCP Client

VS Code (GitHub Copilot / Copilot Chat)

Open VS Code settings with Cmd+Shift+P → Open User Settings JSON and add the following block, replacing the placeholders:

{ "mcp": { "servers": { "pg-mcp-snapshot": { "type": "sse", "url": "https://<cluster-name>-<project-name>-pg-mcp.ci.folio.org/sse", "headers": { "Authorization": "Bearer <your_token>" } } } } }

You can add multiple servers for different environments:

{ "mcp": { "servers": { "pg-mcp-snapshot": { "type": "sse", "url": "https://folio-snapshot-pg-mcp.ci.folio.org/sse", "headers": { "Authorization": "Bearer <snapshot_token>" } }, "pg-mcp-testing": { "type": "sse", "url": "https://folio-testing-pg-mcp.ci.folio.org/sse", "headers": { "Authorization": "Bearer <testing_token>" } } } } }

Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json:

{ "mcpServers": { "pg-mcp-snapshot": { "type": "sse", "url": "https://folio-snapshot-pg-mcp.ci.folio.org/sse", "headers": { "Authorization": "Bearer <your_token>" } } } }

Restart Claude Desktop after saving.

Cursor

In Cursor open Settings → MCP and add a new server entry with the same url and headers as above.


Step 3: Start Using It

Once configured, open your AI chat and start talking to your database naturally. The AI will automatically choose and call the right tool based on your request.

Example prompts to get started:

  • "List all databases in this PostgreSQL cluster"

  • "Show me all tables in the public schema of folio_modules"

  • "Describe the loan table — columns, indexes, constraints"

  • "Explain this query: SELECT * FROM loan WHERE status = 'Open'"

  • "Are there any long-running queries right now?"

  • "Find tables with missing indexes"

  • "What is the buffer cache hit ratio?"

  • "Show me all blocked sessions and what's blocking them"

  • "Vacuum analyze the item table"

  • "How big are all my databases?"


Available Tools

Tool

Category

What it does

Example prompt

Tool

Category

What it does

Example prompt

execute_query

SQL

Execute any SQL — SELECT by default; pass allow_write=true for DML/DDL

"Insert a test row into the config table"

explain_query

SQL

EXPLAIN or EXPLAIN ANALYZE with optional buffer stats and JSON output

"Explain analyze this query: SELECT * FROM holdings WHERE permanent_location_id = '...'"

list_databases

Schema

List all databases in the cluster

"What databases exist?"

list_schemas

Schema

List schemas in a database

"List schemas in folio_modules"

list_tables

Schema

List tables, views, and sequences in a schema

"Show all tables in the public schema"

describe_table

Schema

Full table description: columns, types, nullability, defaults, constraints, indexes

"Describe the loan table"

table_stats

Stats

pg_stat_user_tables stats — seq scans, row counts, dead tuples, last vacuum

"Show stats for the item table"

index_stats

Stats

pg_stat_user_indexes — index scans and usage per index

"Show index usage for the public schema"

active_locks

Monitoring

Currently held locks joined with blocking/waiting sessions

"Are there any lock conflicts right now?"

long_running_queries

Monitoring

Queries running longer than N seconds (default 30s)

"List all queries running more than 60 seconds"

connection_stats

Monitoring

Connection counts grouped by state and user

"How many connections are open?"

kill_query

Monitoring

Terminate a backend by PID (pg_terminate_backend) or cancel it (pg_cancel_backend)

"Kill PID 12345"

vacuum_table

Maintenance

VACUUM, VACUUM ANALYZE, or VACUUM FULL on a table

"Vacuum analyze the holdings table"

analyze_table

Maintenance

ANALYZE a specific table or entire database

"Analyze all tables in folio_modules"

reindex_table

Maintenance

REINDEX TABLE

"Reindex the loan table"

table_bloat

Health

Estimate dead-tuple bloat using pg_stat_user_tables

"Which tables have the most bloat?"

missing_indexes

Health

Suggest missing indexes based on sequential scan statistics

"Find tables that need indexes"

unused_indexes

Health

List indexes that have zero or very few scans

"Show me indexes that are never used"

cache_hit_ratio

Health

Buffer cache hit ratio for tables and indexes

"What is the cache hit ratio?"

checkpoint_stats

Health

pg_stat_bgwriter checkpoint and WAL write statistics

"Show checkpoint and WAL stats"

database_sizes

Health

Size of every database in the cluster

"How big are all the databases?"

table_sizes

Health

Table + TOAST + index size per table in a schema

"What are the largest tables in public schema?"

replication_status

Replication

pg_stat_replication and pg_replication_slots

"Show replication lag"

list_roles

Roles

List all PostgreSQL roles and users

"List all database users"

create_role

Roles

Create a new role with optional password, LOGIN, SUPERUSER, CREATEDB

"Create a read-only user called analytics"

drop_role

Roles

Drop a role

"Drop the role old_service"

create_database

Databases

Create a new database with optional owner

"Create a database called feature_test owned by postgres"

drop_database

Databases

Drop a database; optionally force-terminate connections first

"Drop the database scratch_test"

list_extensions

Databases

List installed extensions; optionally also list available ones

"What extensions are installed? Any useful ones available?"


Authentication Notes

  • The server uses Bearer token authentication — every request (except /health) must carry the header Authorization: Bearer <token>.

  • The token is a 32-character alphanumeric string generated by Terraform (random_password) and stored in the db-credentials Kubernetes secret. It never leaves the cluster except when you explicitly retrieve it.

  • The token is environment-specific — each Rancher project has its own independent token. A token from snapshot will not work against testing.

  • The comparison is performed with secrets.compare_digest — it is timing-safe and not vulnerable to timing attacks.

  • The server connects to PostgreSQL using the postgres superuser credentials from db-credentials. All operations run with full DBA privileges — use write operations carefully in shared environments.

  • /health is exempt from auth so Kubernetes liveness/readiness probes work without a token.


Troubleshooting

Problem

Solution

Problem

Solution

401 Unauthorized

The Authorization header is missing or malformed. Ensure it is exactly Bearer <token> with a single space and no extra characters.

403 Forbidden

The token is wrong. Re-fetch it from the db-credentials secret (Step 1) — it may have been rotated by a Terraform apply.

SSE connection drops immediately

The server pod may be restarting. Check pod status: kubectl get pods -n <namespace> \| grep pg-mcp

Tool returns a database error

The target database or schema may not exist. Use list_databases and list_schemas first to confirm names.

execute_query refuses DML

DML/DDL requires allow_write: true in the tool arguments. Explicitly ask the AI: "run this INSERT, allow writes".

vacuum_table with full: true hangs

VACUUM FULL holds an exclusive lock and rewrites the table. Only run during a maintenance window on live environments.

Pod not deployed in a project

The project may have pg_mcp_server = false in its Terraform tfvars, or it is the sprint project (always excluded).

Cannot find the secret in Rancher UI

Ensure you are in the correct project → namespace. The secret is named db-credentials, not db-mcp.