Claude Code PostgreSQL MCP Setup Guide
Connect Claude Code to PostgreSQL through a local or remote MCP server. Includes scopes, read-only roles, datamcp setup, testing, and fixes.
Quick setup
Claude Code can connect to PostgreSQL through a local stdio MCP server or a remote HTTP MCP server.
For a hosted datamcp PostgreSQL link:
claude mcp add --transport http \
--header "Authorization: Bearer YOUR_DATAMCP_API_KEY" \
datamcp-postgres \
"https://api.datamcp.app/api/mcp/YOUR_CONNECTION_ID"
Then verify it:
claude mcp list
claude mcp get datamcp-postgres
Open Claude Code and run:
/mcp
Start with schema inspection, run one narrow read-only query, and test a denied write before using production data.
Anthropic's current Claude Code MCP documentation recommends HTTP for remote cloud services. Local stdio is appropriate when the MCP package and database access must run on the developer machine. Remote SSE is deprecated when HTTP is available.
For general MCP installation, .mcp.json, scope precedence, and non-database examples, use the Claude Code MCP setup guide. This page owns the PostgreSQL-specific Claude Code workflow.
Claude Code PostgreSQL MCP options
| Option | Best for | PostgreSQL credential | Operations owner |
|---|---|---|---|
Local stdio server | One developer and a local or development database | Developer machine | Developer or team |
| Provider MCP server | Supabase or Neon projects, branches, migrations, and platform tools | Provider identity or configured credential | Database provider |
| Self-hosted HTTP server | Internal shared access with complete infrastructure control | Your server environment | Your platform team |
| datamcp hosted link | Standard PostgreSQL shared across clients or users | Stored on datamcp connection | datamcp |
Choose local when the useful capability and database are genuinely local. Choose a provider server when Claude Code must manage provider projects or branches. Choose remote HTTP when several repositories, machines, or users need a stable endpoint and database credentials should not be distributed to each client.
Use the database MCP server guide for the broad architecture decision and the PostgreSQL MCP comparison for current implementations.
Requirements
For the hosted datamcp path, confirm:
- Claude Code is installed and authenticated
- PostgreSQL 12 or newer is reachable from datamcp
- a dedicated PostgreSQL role exists for Claude Code access
- the role has only the required schema and table grants
- the datamcp connection and MCP link are active
- you have the generated remote MCP URL and a datamcp API key
For a local server, replace the last two items with a maintained package, supported runtime, and secure local credential mechanism.
Do not use a PostgreSQL owner, migration, replication, or administrator account merely because the MCP server advertises read-only behavior. The database role should remain the final permission boundary.
How to connect Claude Code to PostgreSQL with MCP
Step 1: create a dedicated PostgreSQL role
Create a separate login for the Claude Code workflow. For analytics or schema exploration, grant only connection, schema usage, and SELECT on the required objects.
The exact SQL depends on your schemas, ownership, default privileges, and tenant model. Review grants with the database owner rather than pasting a universal role script into production.
Use a recognizable name such as:
claude_code_analytics_readonly
Keep development, staging, and production identities separate. A role created for one repository should not silently inherit access to every database in the organization.
Step 2: choose local or remote MCP
Use local stdio when:
- one developer owns the configuration
- the database is local or disposable
- the package needs machine-local access
- the team accepts per-machine credentials and updates
Use remote HTTP when:
- the PostgreSQL database is already remote
- several projects or people need access
- client authentication should be separate from the database role
- credentials, policy, revocation, and runtime updates should be centralized
Remote does not automatically mean secure, and local does not automatically mean private. Compare the complete credential path and operating model in the hosted vs local MCP guide.
Step 3: add PostgreSQL to datamcp
Full disclosure: datamcp is our product.
Create a PostgreSQL connection with the dedicated role, host, port, database, password, and applicable TLS settings. Test the connection and review the discovered schema.
datamcp encrypts PostgreSQL credentials at rest with AES-256-GCM. The credential remains on the datamcp connection rather than being placed in Claude Code configuration.
datamcp currently supports PostgreSQL 12+. It does not provide native MySQL, MongoDB, SQL Server, Oracle, or SQLite connections.
Step 4: create a read-only MCP link
Create a separate MCP link for Claude Code and start with Read Only.
| Link policy | PostgreSQL operations |
|---|---|
| Read Only | SELECT |
| Read, Write & Delete | SELECT, INSERT, UPDATE, and DELETE; no DDL |
| Full Access | Operations allowed by the effective PostgreSQL role |
| Custom | Selected table-level operations, bounded by PostgreSQL grants |
Separate links allow Claude Code access to be revoked without changing links used by Cursor, ChatGPT, VS Code, or another teammate.
The effective permission is the intersection of Claude Code access, datamcp client authentication, the MCP link policy, and the PostgreSQL role.
Step 5: add the remote server to Claude Code
From the repository where Claude Code should use PostgreSQL, run:
claude mcp add --transport http \
--header "Authorization: Bearer YOUR_DATAMCP_API_KEY" \
datamcp-postgres \
"https://api.datamcp.app/api/mcp/YOUR_CONNECTION_ID"
Local scope is the default. It loads only in the current project and remains private in the project entry inside ~/.claude.json.
For a secret-free project definition shared through .mcp.json, use environment expansion:
{
"mcpServers": {
"datamcp-postgres": {
"type": "http",
"url": "${DATAMCP_MCP_URL}",
"headers": {
"Authorization": "Bearer ${DATAMCP_API_KEY}"
}
}
}
}
Each developer supplies DATAMCP_MCP_URL and DATAMCP_API_KEY through the approved environment or secret workflow. Do not commit real values.
Project-scoped MCP definitions require user approval after cloning. Review the URL, headers, tools, and repository trust before accepting them.
Step 6: verify the server and tools
Run:
claude mcp list
claude mcp get datamcp-postgres
Inside Claude Code, open /mcp and confirm that the server is connected. datamcp's PostgreSQL MCP surface includes:
get_permissionsget_schemaget_table_detailsget_schema_changesresync_schemaquery
Begin without reading table data:
Use datamcp-postgres to show my effective permissions and list the schemas I can access. Do not run a data query.
Then inspect one table and verify that Claude Code selected the expected MCP server and tool.
Step 7: test a query and a denial
Run a bounded read:
Inspect the orders table, explain the relevant columns, then count completed orders by month for the last six months. Do not modify data.
For a Read Only link, request a forbidden write:
Attempt to update one order status, but do not work around any permission denial.
The write should fail. Review the denied operation in datamcp activity and confirm the PostgreSQL role would also reject the operation.
A successful query proves connectivity. A denied write, excluded table, and revoked credential demonstrate more important access boundaries.
Use a local PostgreSQL MCP server instead
Anthropic's current documentation uses DBHub as its PostgreSQL stdio example:
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
--dsn "postgresql://readonly:password@localhost:5432/analytics"
Use a local server when it matches the workflow, but do not copy a real production connection string into shell history, repository files, or documentation. Follow the selected server's current secret mechanism and pin a reviewed version for repeatable team use.
Do not start a new setup with @modelcontextprotocol/server-postgres. That reference package is deprecated and archived. Existing installations should follow the server-postgres migration guide and preserve the old read-only boundary while rotating credentials.
A local tuning server may be better than datamcp when the primary requirement is query-plan analysis, hypothetical indexes, or database health checks. datamcp does not provide automated PostgreSQL tuning.
Claude Code MCP scopes for PostgreSQL
| Scope | Loads in | Shared | Recommended PostgreSQL use |
|---|---|---|---|
| Local | Current project | No | Private experiment or one developer's database link |
| Project | Current project | Yes, through .mcp.json | Reviewed secret-free endpoint definition for a team repository |
| User | All projects | No | Personal utility database intentionally used across repositories |
Prefer local scope for the first production test. Move to project scope only when the endpoint belongs to the repository and every developer receives an independently managed credential or link.
Avoid user scope for a powerful production database unless it genuinely belongs in every project. Broad scope makes accidental tool selection and unrelated repository access harder to reason about.
Claude Code PostgreSQL prompts
Understand an unfamiliar schema
Inspect the schema and identify tables related to users, subscriptions, invoices, and payments. Explain relationships and likely join keys. Do not query row data.
Investigate an application bug
Read the repository code that writes subscription status, inspect the relevant PostgreSQL table definitions, and explain where the application and database model disagree. Do not modify code or data yet.
Build a reviewed analytics query
Draft a query for monthly recurring revenue by plan. Explain the tables, filters, and assumptions before executing it. Limit the result to the last 12 months.
Prepare a migration without applying it
Inspect the current table and indexes, then draft the SQL migration needed for the new field. Do not execute DDL. Include rollback SQL and application compatibility notes.
Claude Code can reason about a write or migration without receiving permission to execute it. Keep the link read-only when review and code generation are sufficient.
Troubleshooting Claude Code PostgreSQL MCP
Server is missing
- Run
claude mcp listfrom the intended repository. - Confirm whether the definition is local, project, or user scoped.
- Check the root
mcpServersobject andtype: "http"in.mcp.json. - Ensure required environment variables are set before Claude Code starts.
- Check organization allowlists, denylists, or managed MCP configuration.
Remote server returns 401 or 403
- Confirm the datamcp API key is active.
- Verify the
Authorization: Bearer ...header. - Confirm the MCP link was not deleted.
- Remove a stale duplicate definition at a higher-precedence scope.
- Re-add the server after changing URL or authentication.
Schema works but query fails
- Use
get_permissionsto inspect the MCP link. - Check the PostgreSQL role's grants.
- Confirm the table is allowed by a Custom link.
- Reduce result size and query complexity.
- Review the denied operation in datamcp activity.
Claude Code chooses the wrong database server
- Give each environment a distinct server name.
- Remove duplicate URLs or names across local, project, and user scopes.
- Name the intended server in the prompt.
- Disable unrelated database tools for the project.
Output is too large
- Add a date range,
LIMIT, aggregation, or narrower columns. - Inspect schema before requesting data.
- Split exploration into several bounded queries.
- Avoid increasing Claude Code's MCP output limit until the query itself is constrained.
Claude Code PostgreSQL FAQ
Can Claude Code connect to PostgreSQL?
Yes. Claude Code can start a local PostgreSQL MCP server through stdio or connect to a remote HTTP server that exposes PostgreSQL tools.
What is the Claude Code PostgreSQL MCP command?
For a remote endpoint, use claude mcp add --transport http NAME URL with the provider's authentication header or OAuth flow. For a local package, use claude mcp add --transport stdio NAME -- COMMAND ARGS.
Should PostgreSQL MCP be local or remote?
Use local for one trusted developer and a local or development database. Use remote when several users, machines, or repositories need stable access and the database credential should remain behind a shared service.
Where does Claude Code store MCP configuration?
Local and user scopes are stored in ~/.claude.json. Project scope is stored in .mcp.json at the repository root and can be shared after removing fixed secrets.
Can Claude Code use read-only PostgreSQL access?
Yes. Combine a read-only MCP policy with a dedicated PostgreSQL role that lacks write and administrative privileges. Test a denied write before relying on the configuration.
Does Claude Code see the PostgreSQL password with datamcp?
No. Claude Code receives the remote MCP URL and datamcp client credential. The PostgreSQL connection credential remains encrypted on the datamcp connection.
Does datamcp support databases other than PostgreSQL?
Not for database connections. datamcp currently supports PostgreSQL 12+. OpenAPI 3.x is a separate source type for REST APIs, not another database engine.
Next, review the Claude PostgreSQL integration, compare PostgreSQL MCP servers, or create one PostgreSQL connection and one Read Only MCP link on the Free plan.
Related articles
Claude Desktop MCP Setup for PostgreSQL (2026)
Connect Claude Desktop or Claude on the web to PostgreSQL through MCP, with a separate Claude Code path, permissions, OAuth, testing, and troubleshooting.
TutorialClaude Code MCP Setup Guide: Config, Servers, Scopes
Add MCP servers to Claude Code with the CLI or .mcp.json. Covers HTTP and stdio, local/project/user scopes, OAuth, API keys, testing, and fixes.
Ready to connect an AI client?
Create a hosted MCP link for a supported PostgreSQL or OpenAPI source.
Create MCP linkExplore the Claude integration · Questions? Read the docs or view pricing.