postgres-mcp-server
Provides read-only access to PostgreSQL databases, allowing AI agents to list databases, schemas, tables, describe table structure, and execute SELECT queries.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
postgres-mcp-server
A read-only by default MCP server for PostgreSQL databases, built with .NET 11 and the official ModelContextProtocol C# SDK.
Connect any MCP-compatible AI agent to your PostgreSQL server and let it explore databases, schemas, tables, and run read-only queries — all through natural language. Writes are optional, off by default, and always confirmed by a human.
Features
Connect to any PostgreSQL server (host, port, username, password)
List all databases on the server
List schemas within a database
List tables within a schema
Describe table structure: columns, types, nullability, primary keys, foreign keys
Execute read-only
SELECT/WITHqueries inside aREAD ONLYtransaction that is always rolled backPer-client connections: each
Connectreturns its ownconnectionId, so clients never share credentialsBearer token authentication on the MCP endpoint
Paged results with a row and character budget per page, plus a command timeout
Optional writes (
INSERT,UPDATE,DELETE) with an allow list, a row limit, human confirmation through MCP elicitation or a signed webhook, before image and inverse SQL/healthendpoint for Docker, Portainer or monitoringLightweight Docker container with no persistent state
Compatible with Claude Desktop, Claude Code, Cursor, Windsurf, and any MCP-compatible client
Related MCP server: postgres-mcp
Quick Start
git clone https://github.com/GuerthCastro/postgres-mcp-server.git
cd postgres-mcp-server
echo "MCP_API_TOKEN=$(openssl rand -hex 32)" > .env
docker compose up -dThe server starts on port 3100 by default and exposes the MCP endpoint at /mcp.
MCP Tools
Tool | Description |
| Connects to a PostgreSQL server (host, port, username, password, optional default database) and returns a |
| Forgets the credentials of a |
| Lists all non-template databases on the connected server |
| Lists all user-defined schemas in a given database |
| Lists all base tables in a given schema |
| Describes columns, data types, nullability, primary keys, and foreign keys |
| Executes a single read-only |
Every tool except Connect takes the connectionId returned by Connect. Idle connections
expire after 60 minutes by default.
ExecuteWrite and ConfirmWrite are registered only when writes are enabled (see Writes).
Paging
ExecuteQuery returns one page per call. A page starts at offset (default 0) and ends at
the first of these limits:
MCP_PAGE_MAX_ROWSrows (default200)MCP_PAGE_MAX_CHARACTERScharacters of row data (default20000)
The first line of every response describes the page:
rows 201-400 · nextOffset: 400 · hasMore: trueTo read the next page, send the same SQL again with
offsetset tonextOffset.offset > 0requires anORDER BYin the outer query, otherwise the query is rejected: without a stable order the database may return rows in a different order on each call and pages could overlap or skip rows. Order by a unique key.Every page re-executes the query and skips
offsetrows. For totals useCOUNT,SUMorGROUP BYinstead of reading every row. For very long walks prefer keyset pagination (WHERE id > last_id ORDER BY id) withoffset0.A row longer than
MCP_PAGE_MAX_CHARACTERSis returned alone, cut at the limit and marked[ROW TRUNCATED: showing N of M characters].nextOffsetstill moves past it.Pages are not a consistent snapshot. If the data changes between calls, rows can be repeated or missed.
The SQL is never rewritten. The server stops reading once the page is full and cancels the rest of the result.
Writes (optional)
Writes are off by default. With MCP_WRITE_MODE=on and a confirmation method configured,
two extra tools are registered. With writes off, they do not exist for the client.
Tool | Description |
| Prepares a single |
| Applies a prepared write after a human confirms it, and returns the before image and the inverse SQL to revert it |
How a write flows
The agent calls
ExecuteWrite(connectionId, database, sql).The server validates the statement. It then runs the statement inside a
SERIALIZABLEtransaction withSET TRANSACTION READ WRITE(so it also works for roles withdefault_transaction_read_only = on), captures the before image (aSELECTwith the sameWHERE), counts the rows and rolls back.A human confirms the write, either in the MCP client (elicitation) or by reading a 6-digit code that is delivered only to the confirmation webhook.
The agent calls
ConfirmWrite(writeId, code, connectionId). The statement runs again. If it affects a different number of rows than prepared, it is rolled back and aborted. Otherwise it is committed, and the response includes the inverse SQL to revert it.
Rules
Only a single
INSERT,UPDATEorDELETEon one table of the target database.UPDATEandDELETEwithoutWHEREare rejected. DDL,TRUNCATE,DROP,GRANT, role administration and multiple statements are always rejected.Not supported:
ON CONFLICT,RETURNING,UPDATE ... FROM,DELETE ... USING, table aliases, row-constructor assignments,E'...'strings and dollar quoting.At most
MCP_WRITE_MAX_ROWSrows per write (default50).Writes are allowed on any database the connection can reach. Protection relies on the human confirmation and the privileges of the database user.
The table needs a primary key, or a unique index on
NOT NULLcolumns. That key identifies the rows in the inverse SQL. Tables without a reliable key are rejected, and key columns cannot be updated.The target database must have
standard_conforming_strings = on. It is checked on every write.A
writeIdexpires after 5 minutes, can be used once, and is bound to the hash of the SQL, theconnectionIdand the database. Three wrong codes invalidate it.The
INSERTstatement is rewritten. To build the inverseDELETE, the server needs the keys of the rows that were actually inserted, so it appendsRETURNING <key columns>to yourINSERT. Statements that already containRETURNINGare rejected. The inverse SQL for anINSERTis returned byConfirmWrite, because generated keys only exist after the real insert.The inverse SQL restores the before image captured at commit time. It does not undo trigger side effects, and it does not rewind identity or sequence values.
Write configuration
Variable | Default | Description |
|
|
|
|
|
|
|
| Maximum rows a single write may affect |
| Required for | |
| Required for |
The server fails at startup when the write configuration is invalid.
With elicitation, the client must support MCP elicitation. If it does not, ExecuteWrite and
ConfirmWrite fail closed and nothing is written.
Confirmation webhook
For every prepared write, the server sends one POST with a JSON body:
{
"event": "write.confirmation_requested",
"server": "postgres-mcp-server",
"writeId": "9f2c4d1e8a7b6c5d4e3f2a1b0c9d8e7f",
"code": "482915",
"timestamp": 1790000000,
"expiresAt": "2026-09-21T14:05:00.0000000+00:00",
"target": { "host": "db.example.internal", "port": 5432, "database": "app" },
"operation": "UPDATE",
"table": "public.orders",
"rows": 3,
"sql": "UPDATE orders SET status = 'cancelled' WHERE id IN (101, 102, 103)"
}Headers:
Header | Value |
| Unix time in seconds; also present in the body |
|
|
To verify a request, the receiver should:
Read the raw body before parsing it.
Compute the HMAC-SHA256 of
{X-Timestamp}.{raw body}with the shared secret and compare it withX-Signaturein constant time.Reject timestamps older or newer than 5 minutes, and
writeIdvalues it has already seen (replay protection).Deliver the code to the human, and answer
2xxonly after that. Any other status, or no answer within 10 seconds, makesExecuteWritefail and nothing is prepared.
The code appears only in the webhook body. It is never included in tool responses or in the server logs.
Minimal receiver, Python standard library only. deliver_to_human is a placeholder for your
notification channel:
import hashlib, hmac, json, os, time
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["MCP_WRITE_CONFIRM_WEBHOOK_SECRET"].encode()
seen_write_ids = set()
def deliver_to_human(message: str) -> None:
raise NotImplementedError("Send the message through a channel only the human can read")
class ConfirmationReceiver(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers["Content-Length"]))
timestamp = self.headers.get("X-Timestamp", "")
expected = "sha256=" + hmac.new(SECRET, timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, self.headers.get("X-Signature", "")):
return self.reply(401)
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
return self.reply(401)
payload = json.loads(body)
if payload["writeId"] in seen_write_ids:
return self.reply(409)
seen_write_ids.add(payload["writeId"])
deliver_to_human(f"{payload['operation']} on {payload['table']} ({payload['rows']} rows)\n"
f"{payload['sql']}\nConfirmation code: {payload['code']}")
self.reply(204)
def reply(self, status: int) -> None:
self.send_response(status)
self.end_headers()
HTTPServer(("0.0.0.0", 8080), ConfirmationReceiver).serve_forever()Warning. The confirmation channel must not be readable by the AI agent. If the agent can read the mailbox, chat, log files or notification feed where the code arrives, for example through another MCP server or a connected integration, it can confirm its own writes and the human approval step is gone. Use a channel that only the human can see, and do not log the code in the receiver.
Audit log
Every write event is logged at Information level with the timestamp, database, operation, row
count and writeId: prepared, committed, aborted, failed, cancelled, invalid_code and
invalidated. Credentials, the full SQL and the confirmation code are never logged.
Configuration
Settings are read from environment variables. With Docker Compose, put them in a .env file
next to docker-compose.yml (the file is git-ignored).
Variable | Required | Default | Description |
| Yes | Bearer token clients must send. Generate with | |
| No |
| Timeout for every database command |
| No |
| Maximum rows per |
| No |
| Maximum characters of row data per |
| No |
| Minutes before an unused |
| No | Optional writes, off by default. See Write configuration |
Database credentials are not configured here: they are sent at runtime through Connect and
kept in memory only. To change the exposed port, edit the ports mapping in docker-compose.yml.
Client Setup
Claude Desktop
Add the following to your claude_desktop_config.json:
{
"mcpServers": {
"postgresqlServer": {
"type": "http",
"url": "http://localhost:3100/mcp",
"headers": {
"Authorization": "Bearer YOUR_MCP_API_TOKEN"
}
}
}
}Claude Code
claude mcp add --transport http postgresqlServer http://localhost:3100/mcp \
--header "Authorization: Bearer YOUR_MCP_API_TOKEN"Generic MCP Client
Point your client to the HTTP endpoint and send the header Authorization: Bearer YOUR_MCP_API_TOKEN:
http://localhost:3100/mcpExample Conversation
You: Connect to my database at 192.168.1.10, user postgres, password secret
Claude: Connected to PostgreSQL 16.2 at 192.168.1.10:5432 (connectionId: 3f9c...)
You: What databases are available?
Claude: Found 3 databases:
- myapp
- analytics
- postgres
You: Show me the schemas in myapp
Claude: Found 2 schemas in myapp:
- audit
- public
You: List the tables in public
Claude: Found 4 tables in public:
- orders
- products
- users
- categories
You: Describe the users table
Claude: Table: public.users
--------------------------------------------------------------------------------
Column Type Nullable PK FK References
--------------------------------------------------------------------------------
id bigint NO YES NO
email character varying NO NO NO
name character varying YES NO NO
role_id integer YES NO YES roles.id
created_at timestamp with... NO NO NO
You: How many users were created in the last 30 days?
Claude: SELECT COUNT(*) FROM users WHERE created_at >= NOW() - INTERVAL '30 days'
rows 1-1 · nextOffset: 1 · hasMore: false
count
--------
142Security
ExecuteQueryis read-only, enforced by PostgreSQL. Every query runs inside aSET TRANSACTION READ ONLYtransaction that is always rolled back. A keyword guard also rejects multiple statements,SELECT ... INTO, DML/DDL keywords and dangerous functions such aspg_terminate_backendorset_configbefore they reach the database.Use a read-only database role anyway. Defense in depth: connect with a role that only has
SELECTprivileges.Authenticated endpoint. Requests to
/mcprequireAuthorization: Bearer <MCP_API_TOKEN>. Only/healthis public.Isolated connections. Each client gets its own
connectionId; credentials are held in memory only, never written to disk or logs, and expire when idle.Bounded output. Results are paged by row and character budgets and every command has a timeout. The server stops reading once a page is full and cancels the rest of the result instead of loading every row.
Writes are opt-in and human-confirmed. Write tools exist only with
MCP_WRITE_MODE=on, and every write needs a human confirmation through a channel the agent cannot read. Use a dedicated database user with the minimum write privileges.Local network recommended. Do not expose the port to the internet without TLS and an additional authentication layer.
Requirements
Docker (for container deployment)
Any MCP-compatible client (Claude Desktop, Claude Code, Cursor, Windsurf, etc.)
A running PostgreSQL server accessible from the container
Building from source
cd Mcp.PostgreSQL
dotnet runThe server starts on http://localhost:5000 by default when running locally.
Architecture
postgres-mcp-server/
└── Mcp.PostgreSQL/
├── Configuration/
│ ├── RuntimeOptions.cs # Server settings read from environment variables
│ ├── WriteOptions.cs # Write settings
│ └── ServerConfiguration.cs # Immutable record holding connection parameters
├── Services/
│ ├── DatabaseService.cs # Per-connectionId registry of connection configs
│ ├── QueryGuard.cs # Pre-validation of ExecuteQuery input and paging
│ ├── ResultPager.cs # Reads one page of an ExecuteQuery result
│ ├── SqlText.cs # Comment, quoting and top-level SQL lexer
│ ├── WriteGuard.cs # Validation and parsing of ExecuteWrite statements
│ ├── WriteCatalog.cs # Table, column and unique key lookup for writes
│ ├── WriteSql.cs # Before image, key capture and inverse SQL
│ ├── WriteService.cs # Prepare, confirm, commit and audit of writes
│ ├── PendingWriteStore.cs # writeId registry: expiry, binding and codes
│ ├── ConfirmationWebhook.cs # Signed confirmation webhook
│ └── PostgreSQLQueries.cs # SQL constants and security policy
├── Tools/
│ ├── ConnectTool.cs # MCP tools: connect, disconnect
│ ├── ListDatabasesTool.cs # MCP tool: listDatabases
│ ├── ListSchemasTool.cs # MCP tool: listSchemas
│ ├── ListTablesTool.cs # MCP tool: listTables
│ ├── DescribeTableTool.cs # MCP tool: describeTable
│ ├── ExecuteQueryTool.cs # MCP tool: executeQuery
│ └── WriteTools.cs # MCP tools: executeWrite, confirmWrite (writes enabled only)
└── Program.cs # ASP.NET Core bootstrapThe DatabaseService keeps one configuration per connectionId, so concurrent clients are
isolated from each other. The server uses
ModelContextProtocol.AspNetCore
with HTTP transport.
Stack
Component | Technology |
Runtime | |
MCP SDK | |
PostgreSQL driver | |
Container |
Contributing
Contributions are welcome. Please read CONTRIBUTING.md before submitting a pull request.
Changelog
See CHANGELOG.md for a history of changes.
License
This project is licensed under the MIT License.
Built by Guerth Castro
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- AlicenseAqualityCmaintenanceAn MCP server that gives AI agents direct read-only access to PostgreSQL databases, enabling natural language analytics through tools for schema exploration, querying, trend analysis, and data quality checks.115MIT
- AlicenseNot gradedqualityDmaintenanceA production-ready MCP server for PostgreSQL — built for Claude Desktop, Claude Code, and any MCP-compatible AI agent.Apache 2.0
- AlicenseNot gradedqualityDmaintenanceA read-only MCP server for PostgreSQL that enables safe database introspection and querying via natural language.MIT
- FlicenseNot gradedqualityDmaintenanceA read-only MCP server that enables AI agents to explore database schemas and execute safe queries on PostgreSQL and MySQL.-