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

> Connect Claude to PostgreSQL with the official Postgres MCP server. Run natural language queries, explore schemas, and build an analytics agent. Includes Claude Desktop and Cursor setup, read-only SQL, and Next.js/Node.js agent patterns.

**Source:** https://mcpplaygroundonline.com/blog/postgres-mcp-claude-analytics-agent-recipe  
**Author:** Nikhil Tiwari  
**Published:** 2026-02-05  
**Updated:** 2026-02-05  
**Category:** Recipe  
**Reading time:** 18 min read

---

🍳 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](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres))
-   **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](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres). 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](/blog/build-ai-database-query-assistant-natural-language-sql) 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](/mcp-test-server), 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](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres) 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 →](/mcp-test-server)

## Related Recipes

-   [Build an AI Database Query Assistant (Supabase MCP)](/blog/build-ai-database-query-assistant-natural-language-sql)
-   [Build an AI GitHub PR Reviewer](/blog/build-ai-github-pr-reviewer-mcp-recipe)
-   [How to Set Up MCP in Claude Desktop](/blog/how-to-setup-mcp-claude-desktop)

## 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.

---

_Canonical page: https://mcpplaygroundonline.com/blog/postgres-mcp-claude-analytics-agent-recipe — MCP Playground (mcpplaygroundonline.com), the free browser-based tool for testing MCP servers and building AI agents._
