Allows interaction with PostgreSQL databases, providing tools for listing schemas, tables, describing table structures, querying relationships, and executing SQL queries.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PostgreSQL MCP Servershow me the structure of the users table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PostgreSQL MCP Server with OAuth
A PostgreSQL MCP server implementation with OAuth authentication support using the Model Context Protocol (MCP) Python SDK. This server enables AI agents to interact with PostgreSQL databases through a standardized interface, with secure multi-user authentication and cloud deployment capabilities.
✨ New Features
🔐 OAuth Authentication: Secure Google OAuth 2.0 integration
👥 Multi-tenant: Each user has their own database connection
☁️ Railway Ready: Optimized for Railway cloud deployment
🛡️ Production Safe: Session management, security controls, and health monitoring
Related MCP server: MCP PostgreSQL Server
Features
Core Database Operations
List database schemas with advanced filtering and pagination
List tables within schemas with pattern matching
Describe table structures and constraints
Discover table relationships (explicit foreign keys + implied relationships)
Execute SQL queries with safety controls
Typed tools with JSON/markdown output
Optional table resources and guidance prompts
Authentication & Security
Google OAuth 2.0: Secure user authentication
Session Management: Token-based sessions with expiration
User Isolation: Each user's database connections are separate
Read-only Mode: Optional query restrictions
Query Timeouts: Prevent runaway queries
Health Monitoring: Built-in health checks and metrics
Deployment Options
Local Development: Direct database connections
OAuth Mode: Multi-user authentication with personal database connections
Railway Cloud: One-click cloud deployment with managed PostgreSQL
Docker: Containerized deployment
🚀 Quick Start
Option 1: Traditional Mode (Direct Connection)
Option 2: OAuth Mode (Multi-user)
Option 3: Railway Cloud Deployment
📚 Documentation
OAUTH_SETUP.md - Complete OAuth setup guide
RAILWAY_DEPLOYMENT.md - Railway cloud deployment guide
Installation
Installing via Smithery
To install PostgreSQL MCP Server for Claude Desktop automatically via Smithery:
Manual Installation
Clone this repository:
Create and activate a virtual environment (recommended):
Install dependencies:
Usage
Authentication Flow (OAuth Mode)
Start the server in OAuth mode:
python postgres_server.py --oauth-only --transport streamable-http --port 8000Get authentication info (via MCP client like Claude):
User: "Show me information about the database server" Claude: [Calls auth_info tool, provides Google OAuth login URL]Complete OAuth flow:
Visit the provided login URL
Authenticate with Google
Receive session token
Configure database connection:
Browser: visit
http://localhost:8000/connection(uses your session cookie)API:
curl -X POST http://localhost:8000/connection/set \ -H "Authorization: Bearer YOUR_SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{"connection_string": "postgresql://user:pass@host:port/db"}'
Use database tools - all operations now work with your authenticated connection
Direct Mode (Traditional)
Available Tools
Core Database Tools
query: Execute SQL queries against the databaselist_schemas: List all available schemaslist_tables: List all tables in a specific schemadescribe_table: Get detailed information about a table's structureget_foreign_keys: Get foreign key relationships for a tablefind_relationships: Discover both explicit and implied relationships for a tabledb_identity: Show current db/user/host/port, search_path, and version
Authentication Tools (OAuth Mode)
auth_info: Get authentication status and login instructionsserver_info: Server configuration and capabilities
Typed Tools (Preferred)
run_query(input): Execute with typed input (sql,parameters,row_limit,format: 'markdown'|'json')run_query_json(input): Execute and return JSON-serializable rowslist_schemas_json(input): List schemas with filters (include_system,include_temp,require_usage,row_limit)list_schemas_json_page(input): Paginated listing with filters andname_likepatternlist_tables_json(input): List tables within a schema with filters (name pattern, case sensitivity, table_types, row_limit)list_tables_json_page(input): Paginated tables listing with filters
Example Tool Usage
Resources & Prompts
Resources (if supported by client):
table://{schema}/{table}for reading table rows. Fallback tools are available:list_table_resources(schema)→table://...URIsread_table_resource(schema, table, row_limit)→ rows JSON
Prompts (registered when supported; also exposed as tools):
write_safe_select/prompt_write_safe_select_toolexplain_plan_tips/prompt_explain_plan_tips_tool
Configuration
Claude Desktop Configuration
Traditional Mode
OAuth Mode (Local Development)
Railway Cloud Deployment
Environment Variables
Core Configuration
POSTGRES_CONNECTION_STRING: Direct database connection (traditional mode)MCP_TRANSPORT:stdio|sse|streamable-http(default:stdio)MCP_HOST: Host for HTTP transports (default:127.0.0.1)MCP_PORT: Port for HTTP transports (default:8000)
OAuth Configuration
GOOGLE_CLIENT_ID: Google OAuth client ID (required for OAuth mode)GOOGLE_CLIENT_SECRET: Google OAuth client secret (required for OAuth mode)SECRET_KEY: Session encryption key (32+ characters, required for OAuth mode)REDIRECT_URI: OAuth redirect URI (auto-configured for Railway)
Security & Performance
POSTGRES_READONLY:trueto allow only SELECT/CTE/EXPLAIN/SHOW/VALUES queriesPOSTGRES_STATEMENT_TIMEOUT_MS: Query timeout in milliseconds (e.g.,30000)
Railway Deployment (Auto-configured)
DATABASE_URL: Managed PostgreSQL connection stringPORT: Server port (Railway-provided)RAILWAY_PUBLIC_DOMAIN: Public domain for OAuth redirectsRAILWAY_ENVIRONMENT: Deployment environment
Running with Docker
Build the image:
Traditional mode:
OAuth mode:
HTTP Client Integration
Run the server with Streamable HTTP:
Health Check (OAuth service)
OAuth Endpoints (OAuth Mode)
GET /auth/login- Get Google OAuth authorization URLGET /auth/callback- OAuth callback endpointGET /auth/status- Check authentication statusPOST /connection/set- Set user's database connection string
Python MCP Client Example
Security Best Practices
Authentication & Authorization
OAuth Secrets: Keep Google OAuth credentials secure, never commit to git
Session Keys: Use strong SECRET_KEY (32+ characters minimum)
Token Rotation: Regularly rotate OAuth credentials
User Isolation: Each authenticated user has separate database connections
Database Security
Connection Strings: Use minimal privilege database connections
Read-only Mode: Enable
POSTGRES_READONLY=truewhen appropriateQuery Timeouts: Set
POSTGRES_STATEMENT_TIMEOUT_MSto prevent runaway queriesSSL Connections: Always use SSL for production database connections
Production Deployment
Environment Variables: Never expose secrets in code or logs
HTTPS: Use HTTPS for all OAuth flows (Railway provides this automatically)
Access Controls: Implement proper database user permissions
Connection Pooling: Use connection pooling for better resource management
Deployment Options
1. Local Development
Direct database connections
OAuth testing with localhost
Development environment variables
2. Railway Cloud (Recommended)
Managed PostgreSQL database
Automatic HTTPS and domain management
Environment variable management
Automatic deployments from GitHub
Built-in monitoring and logging
Cost: $5-20/month for most use cases
3. Custom Cloud Deployment
Any cloud provider supporting Python applications
Container-based deployment with Docker
Manual OAuth configuration
Custom domain and SSL setup
Migration Guide
From Traditional to OAuth Mode
Backup Current Setup: Save existing configuration files
Set Up OAuth: Follow OAUTH_SETUP.md guide
Update Server: Replace with OAuth-enabled version
Test Locally: Verify OAuth flow works
Deploy: Use Railway or custom deployment
Update Clients: Configure Claude Desktop with new server URL
Backwards Compatibility
Traditional mode still works with
--connparameterExisting MCP clients remain compatible
All original tools and functionality preserved
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Setup
Create a
.venvand install runtime deps:pip install -r requirements.txt(Optional) Install test deps:
pip install -r dev-requirements.txtSet up OAuth credentials for testing (see OAUTH_SETUP.md)
Run tests:
pytest -q
Development & Testing
Local Testing: Test both traditional and OAuth modes
Integration Tests: Test with actual PostgreSQL databases
OAuth Testing: Test complete authentication flow
Railway Testing: Test cloud deployment
Troubleshooting
Common Issues
OAuth not configured:
Verify
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRETare setCheck Google Cloud Console OAuth setup
Authentication required:
Complete OAuth flow via
/auth/loginendpointVerify session token is included in requests
Database connection errors:
Verify connection string format
Test database connectivity independently
Check firewall and network access
Railway deployment issues:
Check environment variables are set correctly
Verify OAuth redirect URIs match Railway domain
Monitor deployment logs in Railway dashboard
For detailed troubleshooting, see OAUTH_SETUP.md and RAILWAY_DEPLOYMENT.md.
Related Projects
Railway - Cloud deployment platform
Google OAuth 2.0 - Authentication provider
License
MIT License
Copyright (c) 2025 gldc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.