hybrid server
The server is able to function both locally and remotely, depending on the configuration or use case.
Integrations
Built on Bun runtime for high performance server execution, leveraging Bun's speed and JavaScript/TypeScript capabilities.
Allows AI agents to interact with multiple PostgreSQL databases, including running read-only queries, executing data-modifying statements, performing transactions, listing tables, and inspecting database schemas.
Implements end-to-end type-safety throughout the server with TypeScript, ensuring robust and error-resistant database interactions.
FastPostgresMCP 🐘⚡️ (Full-Featured Multi-DB MCP Server)
This project implements a blazing fast, type-safe, and full-featured Model Context Protocol (MCP) Server designed for AI Agents (like Cursor, Claude Desktop) to interact with multiple PostgreSQL databases, including listing tables and inspecting schemas.
It is built with Bun, TypeScript, postgres
, and leverages advanced features of the fastmcp
framework for building robust MCP servers.
Purpose: An MCP Server for AI Agents
This is not a library to be imported into your code. It is a standalone server application. You run it as a process, and MCP clients (like AI agents) communicate with it using the JSON-based Model Context Protocol (v2.0), typically over a stdio
connection managed by the client application (e.g., Cursor).
Troubleshooting and Development
Using the CLI for Testing
The package includes a built-in CLI command for testing the MCP server directly:
Testing with Built-in MCP Inspector
You can also use the MCP Inspector to visually test and debug:
Common Issues
If you see this error when running bunx postgres-mcp
:
followed by ping messages, it means:
- The MCP server started successfully
- The client connected successfully
- But the client is only sending ping requests and not properly negotiating capabilities
This usually indicates you need to use a proper MCP client. Try:
- Using
bun run cli
to test with the MCP CLI - Configuring the MCP server in Cursor or Claude Desktop as described in the Installation section
If you're developing a custom MCP client, make sure it properly implements the MCP protocol including capabilities negotiation.
✨ Core Features
- 🚀 Blazing Fast: Built on Bun and
fastmcp
. - 🔒 Type-Safe: End-to-end TypeScript with Zod schema validation.
- 🐘 Multi-Database Support: Connect to and manage interactions across several PostgreSQL instances defined in
.env
. - 🛡️ Secure by Design: Parameterized queries via
postgres
prevent SQL injection. - 🔑 Optional Authentication: Secure network-based connections (SSE/HTTP) using API Key validation (
fastmcp
'sauthenticate
hook). - 📄 Database Schema via MCP Resources:
- List Tables: Get a list of tables in a database via
db://{dbAlias}/schema/tables
. - Inspect Table Schema: Get detailed column info for a specific table via
db://{dbAlias}/schema/{tableName}
.
- List Tables: Get a list of tables in a database via
- 💬 Enhanced Tool Interaction:
- In-Tool Logging: Tools send detailed logs back to the client (
log
context). - Progress Reporting: Long-running operations report progress (
reportProgress
context).
- In-Tool Logging: Tools send detailed logs back to the client (
- 🧠 Session-Aware: Access session information within tool execution context (
session
context). - 📡 Event-Driven: Uses
server.on
andsession.on
for connection/session event handling. - 🔧 Modern Developer Experience (DX): Clear configuration, intuitive API, easy testing with
fastmcp
tools.
What's Included (fastmcp Features Leveraged)
FastMCP
Server Coreserver.addTool
(forquery_tool
,execute_tool
,schema_tool
, andtransaction_tool
)server.addResourceTemplate
(for listing tables and inspecting table schemas)server.start
(withstdio
focus, adaptable forsse
/http
)- Optional:
authenticate
Hook (for API Key validation) - Tool Execution
context
(log
,reportProgress
,session
) - Zod for Parameter Schema Validation
server.on
(for connection logging)- (Potentially)
session.on
for session-specific logic
📋 Prerequisites
- Bun (v1.0 or later recommended): Installed and in PATH.
- PostgreSQL Database(s): Access credentials and connectivity. User needs permissions to query
information_schema
.
⚙️ Installation
Option 1: NPM Package
The npm package is available at https://www.npmjs.com/package/postgres-mcp
Option 2: Clone Repository
- Clone the repository:Copy
- Install dependencies:Copy
🔑 Configuration (Multi-Database & Optional Auth)
Configure via environment variables, loaded from appropriate .env
files.
- Create environment files:
- For production:
cp .env.example .env
- For development:
cp .env.development.example .env.development
- For production:
- Environment file loading order:
The server loads environment variables from files in the following order of priority:
.env.<NODE_ENV>
(e.g.,.env.development
,.env.production
,.env.staging
).env.local
(for local overrides, not version controlled).env
(default fallback)
This allows different configurations for different environments.
- Edit the environment files to define database connections and authentication:
DB_ALIASES
- Comma-separated list of unique DB aliasesDEFAULT_DB_ALIAS
- Default alias if 'dbAlias' is omitted in tool calls- Database connection details for each alias (e.g.,
DB_MAIN_HOST
,DB_REPORTING_HOST
) - Optional API Key authentication (
ENABLE_AUTH
,MCP_API_KEY
)
🚀 Running the Server (as a Process)
Run this server directly using Bun. The AI Client (like Cursor) will typically start and manage this command for you.
Option 1: Using the globally installed package
- To run manually:
postgres-mcp
Option 2: Using the package in your project
- To run from your project:
npx postgres-mcp
- Or import programmatically:Copy
Option 3: From cloned repository
- To run manually (for testing):
bun run src/index.ts
- Manual Development Mode:
bun run --watch src/index.ts
Testing with fastmcp
CLI Tools
- Interactive Terminal:
bunx fastmcp dev src/index.ts
- Web UI Inspector:
bunx fastmcp inspect src/index.ts
💻 Using the Programmatic API (as a Library)
In addition to running as a standalone MCP server, postgres-mcp can also be used programmatically as a library in your Node.js/TypeScript applications.
Basic Usage
Direct Function Imports
For simpler use cases, you can import specific functions directly:
Configuration Options
For complete documentation on the programmatic API, see docs/programmatic-api.md.
🔌 Connecting with AI Clients (Cursor, Claude Desktop)
Configure your AI Agent (MCP Client) to execute this server script via its command/args mechanism.
Cursor AI - Detailed Example
- Open Cursor Settings/Preferences (Cmd+, or Ctrl+,).
- Navigate to "Extensions" -> "MCP".
- Click "Add MCP Server" or edit
settings.json
. - Add the following JSON configuration:Copy
- Save and Restart Cursor or "Reload MCP Servers".
- Verify connection in Cursor's MCP status/logs.
Claude Desktop
- Locate and edit
config.json
(see previous README for paths). - Add a similar entry under
mcpServers
, using the absolute path inargs
. - Restart Claude Desktop.
🛠️ MCP Capabilities Exposed
Authentication (Optional)
- Secures network transports (HTTP/SSE) via
X-API-Key
header matchingMCP_API_KEY
ifENABLE_AUTH=true
. stdio
connections (default for Cursor/Claude) generally bypass this check.
Resources
1. List Database Tables
- URI Template:
db://{dbAlias}/schema/tables
- Description: Retrieves a list of user table names within the specified database alias (typically from the 'public' schema).
- Resource Definition (
addResourceTemplate
):uriTemplate
:"db://{dbAlias}/schema/tables"
arguments
:dbAlias
: (string, required) - Alias of the database (from.env
).
load({ dbAlias })
: Connects to the database, queriesinformation_schema.tables
(filtered for base tables in the public schema, customizable in implementation), formats the result as a JSON string array["table1", "table2", ...]
, and returns{ text: "..." }
.
Example Usage (AI Prompt): "Get the resource db://main/schema/tables
to list tables in the main database."
2. Inspect Table Schema
- URI Template:
db://{dbAlias}/schema/{tableName}
- Description: Provides detailed schema information (columns, types, nullability, defaults) for a specific table.
- Resource Definition (
addResourceTemplate
):uriTemplate
:"db://{dbAlias}/schema/{tableName}"
arguments
:dbAlias
: (string, required) - Database alias.tableName
: (string, required) - Name of the table.
load({ dbAlias, tableName })
: Connects, queriesinformation_schema.columns
for the specific table, formats as JSON string array of column objects, returns{ text: "..." }
.
Example Usage (AI Prompt): "Describe the resource db://reporting/schema/daily_sales
."
Example Response Content (JSON String):
Tools
Tools receive context
object (log
, reportProgress
, session
).
1. query_tool
Executes read-only SQL queries.
- Description: Safely execute read-only SQL, get results, with execution logging/progress.
- Parameters:
statement
(string),params
(array, opt),dbAlias
(string, opt). - Context Usage:
log.info/debug
, optionalreportProgress
, accesssession
. - Returns: JSON string of the row array.
Example Request:
Example Response Content (JSON String):
2. execute_tool
Executes data-modifying SQL statements.
- Description: Safely execute data-modifying SQL, with execution logging.
- Parameters:
statement
(string),params
(array, opt),dbAlias
(string, opt). - Context Usage:
log.info/debug
, accesssession
. - Returns: String indicating rows affected.
Example Request:
Example Response Content (String):
3. schema_tool
Retrieves detailed schema information for a specific table.
- Description: Get column definitions and details for a database table.
- Parameters:
tableName
(string),dbAlias
(string, opt). - Context Usage:
log.info
, accesssession
. - Returns: JSON string array of column information objects.
Example Request:
Example Response Content (JSON String):
4. transaction_tool
Executes multiple SQL statements atomically.
- Description: Execute SQL sequence in a transaction, with step logging/progress.
- Parameters:
operations
(array of {statement, params}),dbAlias
(string, opt). - Context Usage:
log.info/debug/error
,reportProgress
, accesssession
. - Returns: JSON string summarizing success/failure:
{"success": true, "results": [...]}
or{"success": false, "error": ..., "failedOperationIndex": ...}
.
Example Request:
Example Success Response Content (JSON String):
Example Error Response Content (JSON String):
Server & Session Events
- Uses
server.on('connect'/'disconnect')
for logging client connections. - Can use
session.on(...)
for more granular session event handling if needed.
🔒 Security Considerations
- SQL Injection: Mitigated via parameterized queries. No direct input concatenation.
- Database Permissions: Critical. Assign least privilege to each
DB_<ALIAS>_USER
, including read access toinformation_schema
for schema/table listing resources. - SSL/TLS: Essential for production (
DB_<ALIAS>_SSL=require
or stricter). - Secrets Management: Protect
.env
file (add to.gitignore
). Use secure secret management for production environments (Vault, Doppler, cloud secrets). - Authentication Scope:
authenticate
hook primarily secures network transports.stdio
security relies on the execution environment. - Data Sensitivity: Be aware of data accessible via connections/tools.
- Resource Queries: The queries used for listing tables (
information_schema.tables
) and schemas (information_schema.columns
) are generally safe but rely on database permissions. Ensure the configured users have appropriate read access. Customize the table listing query (e.g., schema filtering) if needed for security or clarity.
📜 License
This project is licensed under the MIT License. See the LICENSE file for details.
📋 Changelog
1.0.0
- Initial release
- Full-featured MCP Server for PostgreSQL
- Support for multiple database connections
- Tools for queries, execution, schema inspection, and transactions
- Resources for schema introspection
- Comprehensive documentation and examples
You must be authenticated.
A blazing fast MCP server that enables AI agents to interact with multiple PostgreSQL databases, providing functionality to list tables, inspect schemas, execute queries, and run transactions.
- Purpose: An MCP Server for AI Agents
- Troubleshooting and Development
- ✨ Core Features
- What's Included (fastmcp Features Leveraged)
- 📋 Prerequisites
- ⚙️ Installation
- 🔑 Configuration (Multi-Database & Optional Auth)
- 🚀 Running the Server (as a Process)
- 💻 Using the Programmatic API (as a Library)
- 🔌 Connecting with AI Clients (Cursor, Claude Desktop)
- 🛠️ MCP Capabilities Exposed
- 🔒 Security Considerations
- 📜 License
- 📋 Changelog