Back to Blog
RecipeFeb 5, 202618 min read

PostgreSQL MCP: Build a Claude Analytics Agent (Setup + Examples)

NT

Nikhil Tiwari

MCP Playground

🍳 MCP Recipe

  • What you'll build: A Claude (or Cursor) agent that talks to PostgreSQL via natural language—queries, schema exploration, and analytics
  • MCP server: @modelcontextprotocol/server-postgres (archived from the official modelcontextprotocol/servers repo to servers-archived)
  • Time to complete: 20–30 minutes
  • Difficulty: Intermediate

The PostgreSQL MCP server gives your AI assistant read-only access to a Postgres database. Claude (or Cursor) can list tables, inspect schemas, and run SELECT queries from natural language—no SQL required from you. This recipe shows how to set it up and use it for ad-hoc analytics, reporting, and as the data layer for an analytics-style agent.

What the Postgres MCP Server Provides

The server was originally part of the modelcontextprotocol/servers repo and is now in servers-archived. The npm package still works. It exposes:

Capability Description
query (tool) Run read-only SQL. All queries execute inside a READ ONLY transaction—no INSERT/UPDATE/DELETE.
Table schemas (resources) Automatically discovered schema for each table: column names, types. The AI uses these to generate correct SQL.

So: you ask in plain English, the model uses schema context + the query tool, and you get results. Perfect for dashboards, reports, and analytics agents.

For large databases, consider limiting accessible schemas or views (e.g. a dedicated reporting schema) to reduce context size and improve query accuracy.

Prerequisites

PostgreSQL database

Local or remote; any version supported by Node pg

Connection string

postgresql://user:password@host:5432/dbname

MCP client

Claude Desktop or Cursor

Step 1: Get Your Connection String

Format:

postgresql://USER:PASSWORD@HOST:PORT/DATABASE_NAME

Examples:

  • Local: postgresql://postgres:secret@localhost:5432/mydb
  • Cloud (e.g. Neon, Supabase, RDS): use the URL from your provider (often with SSL). Example: postgresql://user:pass@ep-xxx.region.aws.neon.tech/neondb?sslmode=require

Security

Use a database user with read-only rights (e.g. GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;). Never put production credentials in version control; use env vars or a secret manager when possible.

Step 2: Install and Configure Postgres MCP

Claude Desktop

Edit your config (e.g. ~/Library/Application Support/Claude/claude_desktop_config.json on macOS). Add the server with the connection string as the first argument:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:password@localhost:5432/mydb"]
    }
  }
}

To avoid putting the password in the config file, use an environment variable. Claude Desktop does not always inherit shell env vars, so prefer one of these:

  • Wrapper script: Create a small script that sets POSTGRES_URL and runs your MCP client, or
  • Load .env into the command: e.g. env $(grep -v '^#' .env | xargs) npx -y @modelcontextprotocol/server-postgres $POSTGRES_URL (use the path to your .env and ensure POSTGRES_URL is defined there).

Keep the connection string in a local .env that is not committed.

Cursor

In Cursor: Settings → Tools & MCP → Add MCP server. Choose STDIO and set:

Field Value
Name postgres
Type stdio
Command npx
Args -y @modelcontextprotocol/server-postgres postgresql://user:password@localhost:5432/mydb

Replace the connection string with your own. Restart Claude Desktop or Cursor after saving.

Step 3: Verify and Explore Interactively

In Claude or Cursor, try these prompts to confirm the server is connected and to see how the agent uses the tools:

  1. "What Postgres tools or resources do you have?" — You should see a query tool and resources listing table schemas.
  2. "List the tables in the database and describe their columns." — The model will use the schema resources and summarize.
  3. "How many rows are in the [table_name] table?" — It will run a SELECT COUNT(*) via the query tool.

Example Prompts: Analytics Agent Use Cases

Once connected, you can use natural language for analytics. Adapt these to your schema.

Ad-hoc analytics

  • "What were our top 10 products by revenue last month?"
  • "Show me daily signups for the last 14 days."
  • "Compare this week's support ticket count to last week."

Schema exploration

  • "Describe the orders table and its relationships to other tables."
  • "Which tables contain a created_at column?"

Reporting

  • "Summarize monthly revenue by product category as a markdown table."
  • "List the 5 most active users by number of orders and their total spend."

Using This Pattern in a Next.js or Node.js Analytics Agent

The same idea—natural language → Postgres MCP → SQL → results—can power an app or API:

  • Backend agent: A Node.js (or Next.js API route) service can run an LLM with the MCP SDK, attaching the Postgres MCP server. Users send questions (e.g. from a chat UI); the backend returns SQL results or generated summaries/charts. The Postgres MCP server runs in the same process as your app.
  • Claude + API: Some setups use Claude Desktop (or another MCP host) for ad-hoc use, and a separate Next.js front end that calls a REST API that executes pre-defined or parameterized queries. The "agent" is then the combination of Claude for exploration and the app for shared dashboards.

Architecture in short: User → Next.js/Node API → LLM with Postgres MCP → read-only SQL → formatted response (JSON, table, or chart data). The MCP server stays read-only; write operations go through your own application logic and migrations. This pattern works especially well for internal analytics tools, admin dashboards, and support teams who need answers without SQL access.

Difference From Supabase MCP

If you use Supabase, you can also use Supabase MCP for natural language queries (it uses your Supabase project's Postgres). The official @modelcontextprotocol/server-postgres works with any Postgres (local, Neon, RDS, Supabase, etc.) and is ideal when you already have a connection string and want a minimal, read-only analytics agent.

Important Notes

  • Read-only: The server runs queries in a READ ONLY transaction. It cannot modify data.
  • STDIO only: This server runs locally (STDIO). You cannot connect to it from MCP Playground, which expects HTTP/SSE. Use Claude Desktop or Cursor to try it.
  • Package: The npm package @modelcontextprotocol/server-postgres was moved to the servers-archived repo. The npm package still works via npx but is no longer actively updated.

Test Remote MCP Servers (Supabase, GitHub, etc.)

Postgres MCP is local-only. For cloud DBs with HTTP MCP, try Supabase MCP in the playground.

Open MCP Playground →

Related Recipes

Frequently Asked Questions

Can I use Postgres MCP with a cloud database (Neon, RDS, Supabase)?
Yes. Use the provider's connection string (including SSL params if required, e.g. ?sslmode=require). Create a read-only user for the MCP server when possible.
Why read-only? Can the AI insert or update data?
The official server is designed for read-only access so that AI-generated SQL cannot accidentally modify or delete data. For writes, use your app's API or migrations; you can still ask the AI to suggest INSERT/UPDATE statements and run them yourself.
How do I build a Next.js analytics dashboard with this?
Use a backend (Next.js API route or a separate Node service) that runs an LLM with the MCP SDK and the Postgres MCP server. The front end sends natural language questions; the backend returns query results or chart data. Alternatively, use parameterized queries in your API and let the LLM help with exploration and ad-hoc questions in Claude/Cursor.
NT

Written by Nikhil Tiwari

15+ years in product development. AI enthusiast building developer tools that make complex technologies accessible to everyone.