A specialized MCP (Model Context Protocol) server for PostgreSQL database operations, built with TypeScript. This server enables AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.
get_database_schema- Inspect database schemas, tables, and structureexecute_sql_query- Execute SQL queries with multiple output formats (table, JSON, CSV)execute_ai_generated_sql- Execute AI-generated SQL queries with explanationsnatural_language_query- Convert natural language questions to SQL and execute them
- ποΈ Multi-Schema Support - Works with complex database structures
- π Safe Query Execution - Built-in SQL injection protection
- π Multiple Output Formats - Table, JSON, and CSV output options
- π Google Cloud SQL Support - Direct and Cloud SQL Proxy connections
- π Connection Pooling - Efficient database connection management
- π― Natural Language Processing - Convert English questions to SQL
This server follows a clean, modular architecture that evolved from a monolithic structure:
src/
βββ main.ts # MCP server entry point
βββ config/
β βββ database.ts # Database configuration management
βββ database/
β βββ manager.ts # Connection pool and lifecycle management
β βββ query-service.ts # High-level database operations
βββ tools/
β βββ database-tools.ts # MCP tool implementations
βββ types/
β βββ database.ts # TypeScript type definitions
βββ utils/
βββ query-utils.ts # Query formatting and utilities
- Single Responsibility - Each module has a focused purpose
- Type Safety - Comprehensive TypeScript coverage
- Error Handling - Robust error management throughout
- Testability - Modular design enables thorough testing
Configure your PostgreSQL connection using environment variables in .env:
# PostgreSQL Connection DB_HOST=127.0.0.1 DB_PORT=5432 DB_NAME=your-database-name DB_USER=your-username DB_PASSWORD=your-password # Google Cloud SQL (optional) INSTANCE_CONNECTION_NAME=your-project:region:instance-name # SSL Configuration (recommended for production) DB_SSL=false # Google Cloud Project (for IAM authentication) GOOGLE_CLOUD_PROJECT=your-project-id
β Returns all tables and their structures
AI: "Show me the schema for the customers table" β Returns detailed schema for specific table
#### 2. Execute SQL Queries
AI: "Execute SQL: SELECT COUNT(*) FROM customers.customer_t WHERE country_code = 'SE'" β Executes the query and returns results in table format
AI: "Run this query in JSON format: SELECT cutomer_id, customer_code FROM customers.customer_t LIMIT 5" β Returns results in JSON format
#### 3. Natural Language Queries
AI: "How many active customers are there for Sweden?" β Converts to SQL and executes: finds active customers for SE market
AI: "Show me all customer types in the database" β Automatically generates and runs appropriate SQL query
#### 4. AI-Generated SQL
AI: "Generate SQL to find all customers that expire in the next 7 days" β Creates appropriate SQL query with explanation and executes it
### Supported Output Formats
- **table** (default) - Formatted table output
- **json** - JSON array format
- **csv** - Comma-separated values
### Database Features
- **Schema Discovery** - Automatically discover all schemas, tables, and columns
- **Multiple Output Formats** - Table, JSON, or CSV output
- **Natural Language Processing** - Convert questions to SQL queries
- **Google Cloud SQL Support** - Native support for Cloud SQL with private IP
- **Connection Pooling** - Efficient database connection management
- **Error Handling** - Comprehensive error handling and reporting
## οΏ½ Installation & Setup
### Prerequisites
- **Node.js** 18+
- **PostgreSQL** database (local or cloud)
- **TypeScript** (installed globally or via npm)
### Quick Start
1. **Clone and install dependencies:**
```bash
git clone <repository-url>
cd mcp-test
npm install
- Configure environment:
# Create .env file with your database configuration touch .env # Edit .env with your PostgreSQL connection details
- Build and test:
# Build the project npm run build # Test database connection npm run test:db # Start the server npm start
- Development mode:
# Watch mode with auto-rebuild
npm run devCreate a .env file with your database connection details:
# PostgreSQL Configuration DB_HOST=localhost DB_PORT=5432 DB_NAME=your-database-name DB_USER=your-username DB_PASSWORD=your-password # Connection Pool Settings DB_MAX_CONNECTIONS=5 # SSL Configuration (recommended for production) DB_SSL=false # Google Cloud SQL Configuration (optional) INSTANCE_CONNECTION_NAME=your-project:region:instance-name GOOGLE_CLOUD_PROJECT=your-project-id
The project includes comprehensive testing scripts:
# Test database connection npm run test:db # Test database schema discovery npm run test:schema # Test MCP client integration npm run test:client # Run all tests npm test
# Direct database connection test node scripts/test-direct-db.js # Schema validation node scripts/test-db-schema.js # Get schema statistics node scripts/get-schema-count.js
- ποΈ Modular Design: Clean separation of concerns with dedicated modules for database, tools, and utilities
- π Single Responsibility: Each component has a clear, focused purpose
- π Type Safety: 100% TypeScript coverage prevents runtime errors
- π‘οΈ Error Handling: Comprehensive error management throughout the stack
- ποΈ PostgreSQL Specialized: Optimized for PostgreSQL databases with advanced features
- π Connection Pooling: Efficient database connection management
- π Google Cloud SQL: Native support for Cloud SQL with private IP connections
- π Schema Discovery: Automatic discovery of all schemas, tables, and columns
- π‘οΈ SQL Security: Protection against SQL injection with query validation
- π― Clear Structure: Easy to understand and navigate codebase
- π Hot Reload: Development mode with automatic rebuilding
- π Better Debugging: Source maps and proper error stack traces
- π Linting: Consistent code style and best practices
- π§ͺ Comprehensive Testing: Unit and integration tests ensure stability
- β‘ Performance: Optimized queries and connection management
- π Multiple Formats: Support for table, JSON, and CSV output
- π§ Configuration Management: Environment-specific settings centralized
- π Documentation: Clear interfaces and comprehensive guides
Add to your Claude Desktop configuration (~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"sql-assistant-server": {
"command": "node",
"args": ["/absolute/path/to/mcp-test/build/main.js"]
}
}
}This project is configured for VS Code with:
- MCP Configuration (
.vscode/mcp.json) - For VS Code MCP integration - Tasks - Build and run tasks accessible via
Ctrl+Shift+Pβ "Tasks: Run Task" - Debug Configuration - Press
F5to debug
Build MCP Server- Compile TypeScriptStart MCP Server- Build and runWatch and Build- Development mode
mcp-test/
βββ .vscode/ # VS Code configuration
β βββ mcp.json # MCP server config
β βββ tasks.json # Build tasks
β βββ launch.json # Debug config
βββ src/ # Source code (TypeScript)
β βββ main.ts # Main server entry point
β βββ config/ # Configuration management
β β βββ database.ts # Database configuration
β βββ database/ # Database layer
β β βββ manager.ts # Connection management
β β βββ query-service.ts # Query operations
β βββ tools/ # MCP tools implementation
β β βββ database-tools.ts # Database tools
β βββ types/ # TypeScript type definitions
β β βββ database.ts # Database-related types
β βββ utils/ # Utility functions
β βββ query-utils.ts # Query formatting and analysis
βββ build/ # Compiled JavaScript output
βββ scripts/ # Utility scripts
β βββ setup-dev.sh # Development setup
β βββ test-direct-db.js # Database connection test
β βββ test-db-schema.js # Database schema testing
β βββ test-client.js # MCP client testing
βββ .env # Environment variables (create from template above)
βββ Dockerfile # Docker configuration
βββ package.json
βββ tsconfig.json
βββ README.md
The project includes comprehensive testing scripts:
# Test database connection npm run test:db # Test database schema npm run test:schema # Test MCP client integration npm run test:client # Run all tests npm test
// In src/tools/database-tools.ts server.tool( "your_database_tool", { query: z.string().describe("SQL query or natural language request"), format: z.enum(["table", "json", "csv"]).default("table") }, { title: "Your Database Tool", description: "Custom database operation" }, async (args) => { const queryService = DatabaseManager.getInstance().getQueryService(); const results = await queryService.executeQuery(args.query); return { content: [{ type: "text", text: formatResults(results, args.format) }] }; } );
Create a .env file with your database connection details:
# PostgreSQL Configuration DB_HOST=localhost DB_PORT=5432 DB_NAME=your-database-name DB_USER=your-username DB_PASSWORD=your-password # Connection Pool Settings DB_MAX_CONNECTIONS=5 # SSL Configuration (recommended for production) DB_SSL=false # Google Cloud SQL Configuration (optional) INSTANCE_CONNECTION_NAME=your-project:region:instance-name GOOGLE_CLOUD_PROJECT=your-project-id
Build and run the server in Docker:
# Build image docker build -t mcp-postgres-server . # Run container docker run -p 3000:3000 --env-file .env mcp-postgres-server
MIT License - feel free to use and modify!