Labsco
chan00012 logo

PostgreSQL MCP Server

โ˜… 1

from chan00012

An MCP server that provides tools to interact with PostgreSQL databases.

๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅโœ“ VerifiedFreeQuick setup

PostgreSQL MCP Server

A Model Context Protocol (MCP) server that provides tools to interact with PostgreSQL databases. Built using the official Kotlin MCP SDK for robust and standardized protocol compliance.

Features

  • ๐Ÿ”’ Safe Query Execution: Only SELECT queries are allowed for security
  • ๐Ÿ—„๏ธ Schema Inspection: Get detailed table schemas and column information
  • ๐Ÿ“‹ Table Listing: List all tables in the database
  • ๐Ÿ”— Relationship Discovery: Discover foreign keys, primary keys, and table relationships
  • ๐Ÿ”„ JOIN Suggestions: Get intelligent JOIN query suggestions based on relationships
  • ๐ŸŒ Multi-Environment Support: Connect to staging, release, and production databases
  • โšก HikariCP Connection Pooling: Enterprise-grade connection management
  • ๐Ÿ“Š Real-time Monitoring: Built-in connection pool statistics and health monitoring

Available Tools

Tool NameDescriptionRequired ParametersOptional ParametersReturns
postgres_queryExecute SELECT queries against the databasesql (string)environment (staging/release/production)Query results in table format
postgres_list_tablesList all tables in the databaseNoneenvironment (staging/release/production)List of table names
postgres_get_table_schemaGet detailed schema information for a tabletable_name (string)environment (staging/release/production)Column details with data types, constraints, and relationship indicators
postgres_get_relationshipsGet table relationships (FK, PK, constraints)table_name (string)environment (staging/release/production)Primary keys, foreign keys, referenced by, unique constraints
postgres_suggest_joinsSuggest JOIN queries based on relationshipstable_name (string)environment (staging/release/production)Suggested JOIN conditions and example queries
postgres_get_database_infoGet database name and connection informationNoneenvironment (staging/release/production)Database name, version, driver info, and connection details
postgres_connection_statsGet connection pool statistics and health infoNoneNoneHikariCP pool status, metrics, and health information

Safety Features

  • ๐Ÿ”’ Read-Only Access: Only SELECT queries are permitted
  • ๐Ÿ›ก๏ธ SQL Injection Protection: Uses parameterized queries where possible
  • ๐Ÿ“ Row Limiting: Configurable limits prevent overwhelming responses
  • โœ… Connection Validation: Built-in connection testing and validation

Building

The build system requires a jarSuffix parameter to create database-specific JAR files:

# Build JAR for specific database system
./gradlew shadowJar -PjarSuffix=incidents
./gradlew shadowJar -PjarSuffix=users
./gradlew shadowJar -PjarSuffix=analytics
./gradlew shadowJar -PjarSuffix=payroll

This creates JAR files with descriptive names:

  • build/libs/postgres-mcp-tool-incidents.jar
  • build/libs/postgres-mcp-tool-users.jar
  • build/libs/postgres-mcp-tool-analytics.jar
  • build/libs/postgres-mcp-tool-payroll.jar

Note: The jarSuffix parameter is required. Running ./gradlew shadowJar without it will fail with a clear error message.

Multi-Database Workflow

This naming convention enables you to manage multiple database systems efficiently:

  1. Configure your database.properties for the target database system
  2. Build the JAR with a descriptive suffix: ./gradlew shadowJar -PjarSuffix=incidents
  3. Repeat for other database systems (users, analytics, payroll, etc.)
  4. Deploy multiple MCP servers, each with its own JAR and database configuration
  5. Distinguish easily between different database connections in your AI agent

Example Workflow:

# Configure database.properties for incidents database
# Build incidents JAR
./gradlew shadowJar -PjarSuffix=incidents

# Update database.properties for users database
# Build users JAR
./gradlew shadowJar -PjarSuffix=users

# Update database.properties for analytics database
# Build analytics JAR
./gradlew shadowJar -PjarSuffix=analytics

Environment-Based Database Routing

All tools support environment-based database routing with an optional environment parameter:

  • staging (default) - Routes to staging database
  • release - Routes to release database
  • production - Routes to production database

Natural Language Support

AI agents automatically extract environment information from user prompts:

  • "Query the production database for user statistics" โ†’ environment: "production"
  • "List tables in staging" โ†’ environment: "staging"
  • "Show me the schema for users table in release" โ†’ environment: "release"

Architecture

This server is built using:

  • Kotlin MCP SDK v0.5.0: Official Model Context Protocol implementation
  • HikariCP: High-performance JDBC connection pooling
  • PostgreSQL JDBC Driver: Database connectivity
  • Kotlinx Serialization: JSON handling
  • Kotlinx Coroutines: Asynchronous operations

Connection Management (HikariCP)

  • Enterprise-Grade Pooling: Battle-tested connection management
  • Automatic Health Monitoring: Built-in connection validation and health checks
  • Connection Leak Detection: Automatically detects and reports connection leaks
  • Optimized Performance: Fastest connection pool available for Java/Kotlin
  • Thread-Safe Operations: Concurrent access is properly managed

Project Structure

postgres-mcp-tool/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ main/
โ”‚   โ”‚   โ”œโ”€โ”€ kotlin/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ PostgreSqlMcpServer.kt         # Main MCP server implementation
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ PostgreSqlRepository.kt        # Database operations and queries
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ HikariConnectionManager.kt     # Connection pool management
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ DatabaseConnectionConfig.kt    # Database configuration DTO
โ”‚   โ”‚   โ””โ”€โ”€ resources/
โ”‚   โ”‚       โ””โ”€โ”€ database.properties            # Database configuration
โ”‚   โ””โ”€โ”€ test/kotlin/
โ”‚       โ”œโ”€โ”€ PostgreSqlMcpServerTest.kt         # Integration tests
โ”‚       โ”œโ”€โ”€ DatabaseConnectionConfigTest.kt    # DTO unit tests
โ”‚       โ””โ”€โ”€ DatabaseConfigurationTest.kt       # Configuration integration tests
โ”œโ”€โ”€ build.gradle.kts                           # Build configuration
โ”œโ”€โ”€ docker-compose.yml                         # Docker setup for testing
โ”œโ”€โ”€ init.sql                                   # Sample database schema
โ””โ”€โ”€ README.md                                 # This documentation

Migration to Kotlin MCP SDK

๐ŸŽ‰ Updated: This server has been migrated from a custom JSON-RPC implementation to use the official Kotlin MCP SDK, providing:

Benefits of the Migration

  • Better Protocol Compliance: Full adherence to the MCP specification
  • Improved Error Handling: Standardized error responses and better debugging
  • Cleaner Code Structure: More maintainable and readable codebase
  • Future-Proof Compatibility: Automatic updates with MCP protocol changes
  • Enhanced Performance: Optimized transport layer and message handling

What Changed

  • Server Implementation: Now uses Server class from the official SDK
  • Tool Registration: Tools are registered using server.addTool() method
  • Transport Layer: Uses StdioServerTransport with proper kotlinx.io integration
  • Message Handling: Automatic JSON-RPC protocol handling by the SDK

What Stayed the Same

  • All existing functionality: Every tool and feature has been preserved
  • Database operations: HikariCP connection management unchanged
  • Configuration: Clean database.properties with simplified format
  • API compatibility: All tool parameters and responses remain identical

Technical Details

  • SDK Version: Using Kotlin MCP SDK v0.5.0
  • Transport: STDIO transport with buffered kotlinx.io streams
  • Capabilities: Tools with listChanged support
  • Error Handling: Standardized MCP error responses

This migration ensures the server remains compatible with all MCP clients while benefiting from the official SDK's improvements and future updates.