How to Do a Postgres Database Connection on Claude Code
The fastest way to connect Claude Code to a Postgres database is via the Model Context Protocol (MCP) using the official @modelcontextprotocol/server-postgres package. Once configured, Claude can inspect your schema, run queries, and help debug data issues without you ever leaving your terminal. It takes under 5 minutes to set up for local databases, and works with remote databases too via a connection string.
- Works with local Postgres, Supabase, Railway, Render, and any DSN-accessible instance
- Claude gets read access to schema metadata and can run SQL queries directly in-context
- Configuration lives in a single JSON file: no plugins, no extensions, no IDE required
What is MCP and why use it for Postgres?
The Model Context Protocol is an open standard from Anthropic that lets Claude connect to external tools and data sources. Instead of copy-pasting schema dumps or query results into a chat window, MCP gives Claude a live, structured interface to your database. You ask questions in plain English and Claude translates them to SQL, executes against the real DB, and returns results in context.
For developers working on data-heavy features, debugging migrations, or reverse-engineering a poorly documented schema, this eliminates a significant amount of context switching. Claude sees the same data your application does.
How to connect Postgres to Claude Code step by step
Step 1: Install the Postgres MCP server
The official package is @modelcontextprotocol/server-postgres. You do not need to install it globally. Claude Code can run it via npx automatically. If you prefer, you can install it once:
npm install -g @modelcontextprotocol/server-postgres
Step 2: Add the MCP server to your Claude Code config
Claude Code MCP configuration is stored in ~/.claude.json (global) or .claude/settings.json (per-project). To add a Postgres connection, run the following command, replacing the connection string with your own:
claude mcp add postgres -- npx -y @modelcontextprotocol/server-postgres \
"postgresql://username:password@localhost:5432/mydatabase"
This registers the server under the name postgres in your MCP configuration. You can verify it was added with:
claude mcp list
Alternatively, you can edit your ~/.claude.json directly and add the entry under mcpServers:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"postgresql://username:password@localhost:5432/mydatabase"
]
}
}
}
Step 3: Start Claude Code and verify the connection
Launch Claude Code from your project directory:
claude
Once inside, you can ask Claude to confirm the connection is live:
> List all tables in the database
Claude will use the MCP tool to query information_schema.tables and return your schema. If you see your tables listed, the connection is working.
Step 4: Scope access per project (recommended)
For team projects or when working with production databases, use a project-scoped config in .claude/settings.json rather than the global ~/.claude.json. This lets each project use a different connection string and prevents accidentally running destructive queries against the wrong database. You can also use environment variables in your connection string to avoid committing credentials to version control:
"postgresql://$DB_USER:$DB_PASS@$DB_HOST:5432/$DB_NAME"
What Claude can do with a live Postgres connection
Once connected, Claude has access to a set of database tools it can invoke automatically based on your prompts. Common workflows include:
- Schema inspection: "Show me all foreign keys on the orders table" or "What indexes exist on this database?"
- Query generation and execution: "Find all users who signed up in the last 30 days but never made a purchase"
- Migration debugging: "Why is this migration failing? Here's the error" (Claude can check existing schema constraints live)
- Data validation: "Are there any orphaned rows in the line_items table?"
- Performance analysis: "Generate an EXPLAIN ANALYZE for this slow query and suggest indexes"
This is significantly faster than the traditional loop of running a query, copying output, pasting into a chat, getting a suggestion, running again. The entire cycle happens within a single Claude Code session.
Connecting to remote databases (Supabase, Railway, Render)
The setup is identical for any PostgreSQL-compatible database that exposes a standard DSN. Examples:
- Supabase: Use the connection string from your Supabase project settings under "Database" (use the direct connection, not the pooler, for MCP sessions)
- Railway: Copy the
DATABASE_URLfrom your Railway service variables - Render: Use the "External Database URL" from your Render Postgres dashboard
- Neon: Use the connection string from the Neon console; Neon supports standard Postgres connections
For production databases, create a read-only role and use those credentials in your MCP config. The Postgres MCP server does support write operations, so limiting privileges is a sensible safeguard:
CREATE ROLE claude_readonly LOGIN PASSWORD 'yourpassword';
GRANT CONNECT ON DATABASE mydatabase TO claude_readonly;
GRANT USAGE ON SCHEMA public TO claude_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;
Troubleshooting common connection issues
MCP server not found
Run claude mcp list to confirm your server is registered. If the list is empty, re-run the claude mcp add command. Check that npx is available in your PATH.
Authentication failed
Verify the connection string format: postgresql://user:password@host:port/dbname. Special characters in passwords must be URL-encoded (e.g., @ becomes %40).
Connection refused on localhost
Confirm Postgres is running (pg_isready) and that the port matches (default is 5432). If you're using Docker, make sure the container port is exposed to the host.
SSL errors with remote databases
Some hosted providers require SSL. Append ?sslmode=require to your connection string:
postgresql://user:pass@host:5432/dbname?sslmode=require
Checking your usage while working with databases
Database sessions tend to run long. Schema exploration, migration debugging, and iterative query refinement burn through Claude Code usage faster than most tasks. If you hit your usage limit mid-session, you're locked out for up to 5 hours, right when you were in the middle of debugging that migration.
You can check remaining usage at any time using the /usage slash command inside Claude Code, or by visiting claude.ai/settings/usage. For a less disruptive option, Usagebar sits in your macOS menu bar and shows your remaining Claude Code usage at a glance, with alerts at 50%, 75%, and 90% so you know when to wrap up a session before hitting the wall. Credentials are stored securely in macOS Keychain. It's free for students, and pay-what-you-want for everyone else.
If you're doing intensive database work, also check out the Claude Max plan for higher usage limits.
Key takeaways
- Install the Postgres MCP server with
claude mcp add postgres -- npx -y @modelcontextprotocol/server-postgres "your-connection-string" - Use project-scoped configs (
.claude/settings.json) and read-only DB roles for safety - Works with any standard Postgres DSN: local, Supabase, Railway, Render, Neon
- For SSL-required hosted databases, append
?sslmode=requireto your connection string - Monitor usage during long database sessions with
/usageor Usagebar to avoid mid-task lockouts
Related guides
- How to do API testing on Claude Code
- How to set up Claude Code hooks
- How to use CLAUDE.md on Claude Code
- Best Claude Code skills to install
- How long until Claude Code resets
Sources
Track Your Claude Code Usage
Never hit your usage limits unexpectedly. Usagebar lives in your menu bar and shows your 5-hour and weekly limits at a glance.
Get Usagebar