PG Sheets MCP
Provides tools to list spreadsheet tabs, read ranges, find rows by column value, and optionally append or update rows when write mode is enabled.
Provides read-only tools to inspect PostgreSQL tables and schemas and run guarded, capped single SELECT queries with allow-lists, timeouts, and audit logging.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PG Sheets MCP show me the top 5 customers by revenue last quarter"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PG Sheets MCP — mcp-postgres-sheets
Let your AI assistant answer questions from your database and spreadsheets, safely, with read-only defaults and a full audit log.
An open-source Model Context Protocol server for PostgreSQL and Google Sheets, for Claude Desktop, Claude Code, Cursor and ChatGPT. Local over stdio, or remote over Streamable HTTP behind your own OAuth identity provider.
Live demo: uvx mcp-postgres-sheets · Docs site · Architecture · Security model · Results
uvx mcp-postgres-sheetsWhat it does
Ask your assistant "Who were our top 5 customers by revenue last quarter?" and it uses these tools:
Tool | Type | Scope | What it does |
| read |
| Tables and views in the allowed schemas, with row estimates and comments |
| read |
| Columns, types, primary/foreign keys (both directions) and column comments |
| read |
| One |
| read |
| Tabs of a spreadsheet and their sizes |
| read |
| Values of an A1 range |
| read |
| Rows where a column matches a value, keyed by header |
| write |
| Append rows — only registered when |
| write |
| Overwrite a range — only registered when |
Security model
Five independent layers; the bottom one alone prevents any database write:
OAuth scopes (remote mode) — bearer JWTs from your IdP, validated against its JWKS; each tool needs its scope.
Allow-lists —
ALLOWED_SCHEMAS,ALLOWED_TABLES,ALLOWED_SHEET_IDS.SQL check — parsed with sqlglot: a single
SELECTonly; no DML/DDL, multiple statements, data-modifying CTEs,SELECT INTO,FOR UPDATE, system catalogs or unsafe functions (pg_sleep,pg_read_file,dblink,set_config, …).Read-only transaction —
BEGIN READ ONLY,statement_timeout, restrictedsearch_path, row cap through a server-side cursor.Read-only database role — the server connects as a role with
SELECTon the allowed schemas only (deploy/sql/001_readonly_role.sql). This is the main guarantee.
Write tools are not registered when READ_ONLY=true (the default), so the AI never sees them. Every tool call — including rejected, invalid and unknown ones — writes one JSON audit line with caller, tool, redacted arguments, duration, row count and outcome. Database writes are not supported, by design: an assistant that can only read can't be talked into damaging data.
Related MCP server: PostgreSQL MCP Server
Results
From the committed evaluation (eval/results.md, reproduce with make eval):
Measure | Result |
Safety suite: attack and misuse attempts stopped | 70 / 70 (DDL/DML, multi-statement, CTE tricks, comment injection, |
Natural-language tasks completed (Gemini Flash, tool calling) | pending — needs a free |
Latency p50 / p95, slowest tool ( | 26 ms / 30 ms (in-process MCP session, sample DB) |
Latency p50 / p95, top-5-revenue join query | 12 ms / 15 ms |
Remote mode end-to-end (real Keycloak) | 13 / 13 checks ( |
Tests | 236 pytest (unit, integration on real Postgres, MCP protocol, stdio subprocess, HTTP+OAuth) · 18 Playwright |
Architecture
flowchart LR
C[Claude Desktop / Claude Code / Cursor / ChatGPT] -->|stdio or Streamable HTTP + OAuth| S[MCP server<br/>FastMCP]
S --> AUTH{Bearer token + scope check<br/>remote only<br/>per-caller rate limit}
AUTH --> T[Tool layer<br/>Pydantic validation, allow-lists]
T --> Q[SQL guard<br/>sqlglot: single SELECT only] --> PG[(Postgres<br/>read-only role, READ ONLY txn,<br/>timeout, row cap)]
T --> GS[Google Sheets API<br/>allowed sheet IDs, retries]
T --> A[Audit log<br/>JSON lines, redacted args]
IDP[(Entra ID / Keycloak / any OIDC)] -. JWKS .-> AUTHModule map and request flow: docs/architecture.md.
Stack & why
Component | Choice | Why |
Protocol | Official MCP Python SDK (FastMCP) | Tracks the spec; stdio and Streamable HTTP from one codebase |
Postgres | psycopg 3 + pool | Native async, server-side cursors for the row cap; no ORM — the server owns no tables |
SQL check | sqlglot | A real parser tells a single |
Sheets | google-api-python-client + service account | Official client; no browser OAuth flow for local use; idempotency markers via developer metadata |
Validation | Pydantic v2 | Typed tool inputs that become the JSON schema the AI reads |
Remote auth | OAuth 2.1 resource server (PyJWT + JWKS) | What the MCP authorization spec requires; works with Entra ID, Auth0, Okta, Keycloak |
Local IdP for tests | Keycloak ( | Test remote mode with real tokens and no account |
Packaging | uv → PyPI (trusted publishing), Docker image on GHCR |
|
Website | Next.js static export + shadcn/ui | Same front-end stack as the other repos; tools reference generated from |
Production | Azure Container Apps + Key Vault + managed identity + App Insights (Bicep) | Stateless scale-out, no secrets in app settings, logs where enterprises already look |
Every decision with its alternative: docs/DECISIONS.md.
Quick start
1. Try it with the sample database (Docker + uv):
git clone https://github.com/hamza533/mcp-postgres-sheets && cd mcp-postgres-sheets
docker compose up -d db --wait # synthetic shop: 500 customers, 1,500 orders + a read-only role
cp .env.example .env # points at it; add SHEETS_BACKEND=memory for a demo spreadsheet2. Add it to your AI client — full guides for each client in docs/clients.md:
{
"mcpServers": {
"postgres-sheets": {
"command": "uvx",
"args": ["mcp-postgres-sheets", "--env-file", "/absolute/path/to/mcp-postgres-sheets/.env"]
}
}
}3. Ask "What tables do we have, and who are our top 5 customers by revenue?" — then try "Delete all cancelled orders" and watch it refuse.
Prefer to poke at it by hand? make inspector opens the MCP Inspector (docs/inspector.md).
Configuration
All settings are environment variables, documented in .env.example (also rendered on the website's Configuration page). The essentials:
Variable | Default | Meaning |
| — | Connection string for the read-only role |
|
| What the AI may query |
|
| Per-query limits |
| — | Sheets access (share each sheet with the service account) |
|
|
|
|
|
|
| stderr / | Audit destination and argument redaction |
Keep secrets out of client config files: pass --env-file pointing at a file only you can read.
Google Sheets setup: create a Google Cloud service account, enable the Sheets API, download a JSON key, then make a copy of the demo pipeline sheet — create a new Google Sheet and import sample_data/sheets/leads.csv, targets.csv and notes.csv as tabs named Leads, Targets, Notes — and share it with the service account's email. Put its ID (from the URL) in ALLOWED_SHEET_IDS.
Evaluation
make eval-safety # 70 attack/misuse cases through a real MCP session (no API key)
make eval-latency # p50/p95 per tool against the sample database
make eval # + 20 natural-language tasks run by Gemini Flash (needs GEMINI_API_KEY in .env)The task eval plays an AI assistant with Gemini's tool calling against the real server; expected answers are computed live from the database and sheet, so they stay correct whenever the sample data was seeded. Requests are throttled for the free tier and cached in eval/.cache/. Results are written to eval/results.md and eval/results.json and committed. CI runs the safety suite on every push and fails below 100 %.
Costs
Development: $0. Everything runs locally in Docker; the eval uses Gemini's free tier (synthetic data only — free-tier prompts may be used by Google).
Per tool call: no LLM cost — the server never calls an LLM. You pay only for where it runs and for your existing database.
Self-hosted (stdio): free.
Azure production profile: about $10–15 / month at 100,000 tool calls/month, see below.
Production deployment
The production profile runs remote mode on Azure Container Apps, authenticated by Microsoft Entra ID, defined in Bicep in deploy/azure/main.bicep (validated in CI; deployed by deploy-azure.yml, which is disabled by default).
flowchart LR
U[AI clients<br/>Claude, ChatGPT, Cursor] -->|HTTPS + Entra ID bearer token| ACA[Azure Container Apps<br/>mcp-postgres-sheets, 1–5 replicas]
ENTRA[Microsoft Entra ID] -. JWKS / tokens .- U
ENTRA -. JWKS .-> ACA
ACA -->|managed identity| KV[Key Vault<br/>database-url, service-account key]
ACA -->|private network / VNet| PG[(Client's PostgreSQL<br/>read-only role)]
ACA -->|HTTPS| GS[Google Sheets API]
ACA -->|stdout JSON + audit lines| LA[Log Analytics +<br/>Application Insights]Deploy:
Entra ID — App registrations → New registration
mcp-postgres-sheets. Expose an API: set the Application ID URI and add scopesdb.read,sheets.read,sheets.write(Entra doesn't allow:; the server accepts both spellings). In the manifest setrequestedAccessTokenVersion: 2. Note the client ID →oauthAudience. For app-only callers, define app roles with the same names (they arrive inroles).Database — run
deploy/sql/001_readonly_role.sqlon the client's Postgres.Infrastructure —
az deployment group create -g <rg> -f deploy/azure/main.bicep -p deploy/azure/main.bicepparam(setimageto a released tag andoauthAudience).Secrets —
az keyvault secret set --vault-name <kv> --name database-url --value '<read-only DSN>'and--name google-service-account-json --file sa.json. The app reads them with its managed identity; no secret is in app settings or the repo.Connect clients to the
mcpUrloutput (https://<app>.<env>.azurecontainerapps.io/mcp, or your custom domain).
Network notes: pass infrastructureSubnetId to put the Container Apps environment in a VNet and reach Postgres over a private endpoint or VNet peering (Azure Database for PostgreSQL Flexible Server with private access, or on-prem via VPN/ExpressRoute). Without it, allow the environment's static outbound IP in the database firewall and require TLS (sslmode=verify-full). Ingress is HTTPS-only; for a strict global rate limit or WAF, put Azure Front Door / API Management in front.
Monthly cost estimate (Azure list prices, consumption plan, one region; verify with the Azure pricing calculator). Assumptions: 100,000 tool calls/month, 1 always-on replica (0.5 vCPU, 1 GiB) scaling to 2 at peaks, ~1 GB of logs/month; the client's existing Postgres is not included.
Resource | Estimate |
Container Apps (mostly idle-rate billing, free monthly grant applied) | $8–12 |
Log Analytics / Application Insights (~1 GB; first 5 GB/month free per billing account) | $0–3 |
Key Vault (~50,000 secret operations) | < $1 |
Microsoft Entra ID (app registration, free tier) | $0 |
Total | ≈ $10–15 / month |
At ~2 million calls/month with 2–3 busy replicas, expect roughly $60–100/month, still dominated by Container Apps compute.
Scaling: the server is stateless (JSON responses, no sessions), so replicas scale on concurrent HTTP requests (rule: 50 per replica, 1–5 replicas by default). Keep replicas × DB_POOL_MAX_SIZE under the read-only role's CONNECTION LIMIT (20 by default), or put PgBouncer in front for more. The per-caller rate limit is enforced per replica.
Security summary: Entra ID bearer tokens validated against JWKS (signature, issuer, audience, expiry; asymmetric algorithms only) · per-tool scopes · read-only role + READ ONLY transactions + sqlglot check + allow-lists · secrets only in Key Vault via managed identity · non-root container with pinned base image and Trivy scan in CI · HTTPS-only ingress · structured audit log with redacted arguments in Log Analytics · CodeQL, Dependabot, trusted publishing, SBOM and provenance in the supply chain.
Self-hosting elsewhere: render.yaml runs remote mode on Render with a read-only role on Neon and any OIDC provider (Auth0, Entra ID, Keycloak). There is no hosted public endpoint: it would need an always-on identity provider, which doesn't fit a $0 budget.
Limitations & next steps
Postgres only. MySQL / SQL Server would be a welcome contribution (the safety layers map directly).
No database writes, by design.
Idempotency of Sheets appends relies on Sheets developer metadata: the append and the marker are two API calls, and Google caps metadata per spreadsheet — fine for assistant-driven writes, not for bulk loading.
Rate limit is per replica; use a gateway for a strict global limit.
HubSpot and other SaaS sources belong in separate servers.
Next: a natural-language task-success number in the README (run
make evalwith a Gemini key), and MCP Registry listing on the first release.
License
MIT.
Available Tools
3 toolspostgres_describe_tableDescribe a Postgres tableARead-onlyIdempotent
Describe one table or view: columns with types, nullability, defaults and comments, the primary key, foreign keys to other tables, and foreign keys from other tables (use these to write correct JOINs). Call before writing a query against a table you haven't seen.
Inputs: table (required), schema. Returns: kind, name, columns, comment, +5 more
postgres_list_tablesList Postgres tablesARead-onlyIdempotent
List the tables and views the AI may query in the allowed schemas (public), with approximate row counts and table comments. Call this first to discover what data exists, then postgres_describe_table for column details.
Inputs: schema. Returns: tables, row_count
postgres_queryRun a read-only SQL queryARead-onlyIdempotent
Run ONE read-only PostgreSQL SELECT and return the rows as JSON objects. Only tables in the allowed schemas (public) can be read. Rejected: anything that is not a single SELECT (INSERT/UPDATE/DELETE/DDL, multiple statements, SELECT INTO, FOR UPDATE), system catalogs (pg_*), and unsafe functions (pg_sleep, pg_read_file, dblink, set_config…). Results are capped at 500 rows (truncated=true means more rows exist) and the query is cancelled after 5000 ms, so aggregate in SQL (GROUP BY, ORDER BY … LIMIT) rather than fetching raw rows. Use postgres_describe_table first to get exact column names.
Inputs: sql (required), max_rows. Returns: rows, columns, max_rows, row_count, +2 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 3 tools
The three tools form a clean discovery→inspection→execution pipeline with no overlap: one lists tables, one describes a single table's schema, and one runs queries. Descriptions explicitly state the ordering and dependencies, so an agent cannot reasonably confuse them.
All names are snake_case with a consistent postgres_ prefix, and list/describe follow a verb_noun pattern. postgres_query deviates slightly by using a bare noun rather than an explicit verb like postgres_run_query, but the family is clearly recognizable.
Three tools is lean but each is essential to the read-only workflow, so nothing feels padded. A slightly richer surface (e.g. listing schemas or explaining a query plan) could exist, but the minimal set matches the narrow purpose.
For a read-only Postgres bridge the loop is closed: discover tables, inspect columns/keys, then query with corrective hints on ordering and aggregation. No write operations exist, but that is a deliberate scope choice; only minor conveniences like schema enumeration or query-plan inspection are absent.
Maintenance
Related MCP Connectors
Connect AI assistants to Google Sheets through controlled tools for reading and updating rows.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Connect assistants to your company tools with per-person, per-action grants and a full audit log.
Connect an AI assistant to your Google Sheets, Drive, Docs, PDFs, BigQuery and Gmail.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases using natural language queries, providing secure read-only access to database schemas and SQL translation capabilities.6ISC
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-
- AlicenseBqualityDmaintenanceEnables AI assistants to read and edit Excel files and perform PostgreSQL queries, streamlining data analysis workflows.12ISC
- AlicenseNot gradedqualityBmaintenanceEnables AI assistants to securely interact with PostgreSQL databases, offering 30+ tools, role-based access control, and security guardrails.2MIT