Skip to main content
Glama
melihbirim

PostgreSQL MCP Server

by melihbirim

PostgreSQL MCP Server

A Model Context Protocol (MCP) server that enables AI assistants to interact with PostgreSQL databases using natural language queries. This server provides secure, read-only access to database schemas and allows for natural language to SQL translation.

Features

  • πŸ”’ Secure: Read-only operations only (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH)

  • πŸ—„οΈ Schema Inspection: List tables, describe structures, view relationships

  • πŸ” Query Execution: Execute SQL queries with safety checks and result limits

  • 🌐 Natural Language: Enables AI assistants to convert natural language to SQL

  • ⚑ Fast: Built with TypeScript and the official MCP SDK

Related MCP server: PostgreSQL MCP Server

Available Tools

Database Connection

  • connect_database - Connect to a PostgreSQL database

  • disconnect_database - Disconnect from the current database

Schema Inspection

  • list_tables - List all tables in the current database

  • describe_table - Get detailed information about a table's structure

  • get_schema - Get an overview of the database schema and relationships

Query Execution

  • execute_query - Execute read-only SQL queries with safety checks

Quick Test with Docker

1. Start Test Database

npm run docker:up

2. Run Tests

npm run test

3. Try Manual Testing

npm run test:manual

4. Clean Up

npm run docker:down

Installation

Prerequisites

  • Node.js 16 or higher

  • PostgreSQL database access

  • Claude for Desktop (for testing with AI assistant)

Setup

  1. Clone and build:

    git clone https://github.com/melihbirim/pg-mcp.git
    cd pg-mcp
    npm install
    npm run build
  2. Configure Claude for Desktop: Edit your Claude configuration file:

    # macOS
    code ~/Library/Application\ Support/Claude/claude_desktop_config.json
    
    # Windows
    code %APPDATA%\\Claude\\claude_desktop_config.json
  3. Add server configuration:

    {
      "mcpServers": {
        "postgresql": {
          "command": "node",
          "args": ["/ABSOLUTE/PATH/TO/pg-mcp/build/index.js"]
        }
      }
    }
  4. Restart Claude for Desktop

Usage Examples

Once connected to Claude for Desktop, you can use natural language to query your database:

Connect to Database

"Connect to my PostgreSQL database named 'inventory' on localhost with username 'admin'"

Schema Exploration

  • "What tables are in this database?"

  • "Describe the users table structure"

  • "Show me the database schema"

Natural Language Queries

  • "How many users are in the system?"

  • "Show me all products with price greater than $100"

  • "What are the top 5 customers by order count?"

  • "Find all orders placed in the last 30 days"

Security Features

  • Read-only operations: Only SELECT, SHOW, DESCRIBE, EXPLAIN, and WITH statements allowed

  • Query validation: Automatic checking for dangerous operations

  • Result limits: Automatic LIMIT clauses added to prevent large result sets

  • Error handling: Secure error messages without exposing sensitive information

Development

Project Structure

pg-mcp/
β”œβ”€β”€ src/
β”‚   └── index.ts          # Main MCP server implementation
β”œβ”€β”€ build/                # Compiled JavaScript output
β”œβ”€β”€ .github/
β”‚   └── copilot-instructions.md
β”œβ”€β”€ .vscode/
β”‚   └── mcp.json          # VS Code MCP configuration
β”œβ”€β”€ package.json
β”œβ”€β”€ tsconfig.json
└── README.md

Building

npm run build

Running Locally

npm run dev

Testing

The server communicates via stdio, so you can test it by running:

echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0.0"}}}' | node build/index.js

Environment Variables

You can optionally set these environment variables:

  • PG_HOST - PostgreSQL host (default: localhost)

  • PG_PORT - PostgreSQL port (default: 5432)

  • PG_DATABASE - Default database name

  • PG_USER - Default username

  • PG_PASSWORD - Default password

Contributing

  1. Fork the repository

  2. Create a feature branch

  3. Make your changes

  4. Add tests if applicable

  5. Submit a pull request

License

ISC License

Troubleshooting

Claude for Desktop Issues

  • Check Claude's logs: ~/Library/Logs/Claude/mcp*.log

  • Ensure absolute paths in configuration

  • Restart Claude for Desktop after config changes

Database Connection Issues

  • Verify PostgreSQL is running

  • Check connection credentials

  • Ensure network access to database host

Permission Issues

chmod +x build/index.js

Available Tools

6 tools
connect_databaseC

Connect to a PostgreSQL database

ParametersJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
hostNoDatabase host (default: localhost)
passwordNoDatabase password
portNoDatabase port (default: 5432)
sslNoUse SSL connection (default: false)
usernameYesDatabase username

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full burden but only states the basic action. It lacks critical behavioral details: whether this establishes a persistent connection, requires authentication, has side effects (e.g., opening network ports), error handling, or what 'connect' means in context (e.g., returns a connection object).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero wasted words. It's appropriately sized for a tool with a straightforward purpose and well-documented schema, making it easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a connection tool with no annotations and no output schema, the description is inadequate. It doesn't explain what happens after connecting (e.g., state changes, returned handles), error conditions, or dependencies on other tools. Given the complexity of database connections, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so parameters are fully documented in the schema. The description adds no parameter-specific information beyond implying PostgreSQL context, which doesn't enhance understanding of individual parameters. Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Connect to') and resource ('a PostgreSQL database'), making the purpose unambiguous. However, it doesn't differentiate from sibling tools like 'disconnect_database' or explain what 'connect' entails operationally, preventing a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing a database instance), when to reconnect, or how it relates to siblings like 'execute_query' or 'disconnect_database'.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

describe_tableB

Get detailed information about a table's structure, columns, and constraints

ParametersJSON Schema
NameRequiredDescriptionDefault
tableNameYesName of the table to describe

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states this is a read operation ('Get detailed information'), which is clear, but it doesn't cover aspects like permissions needed, error handling, or what the output format looks like (e.g., structured data or raw text). This leaves gaps for an agent to understand the tool's behavior fully.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose without any wasted words. It is appropriately sized for a simple tool with one parameter, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's low complexity (1 parameter, no annotations, no output schema), the description is adequate but incomplete. It covers the basic purpose but lacks details on usage context, behavioral traits, and output expectations, which are needed for full agent understanding in a database environment.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, with the single parameter 'tableName' documented as 'Name of the table to describe'. The description adds no additional meaning beyond this, such as format examples or constraints, so it meets the baseline of 3 where the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Get detailed information') and resource ('table's structure, columns, and constraints'), making the purpose specific and understandable. It distinguishes from siblings like 'list_tables' (which lists names) and 'get_schema' (which might cover broader schema info), though it doesn't explicitly name these alternatives.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'get_schema' or 'execute_query', nor does it mention prerequisites such as needing an active database connection. It implies usage for table details but lacks explicit context or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

disconnect_databaseB

Disconnect from the current PostgreSQL database

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Disconnect' implies a state-changing operation, it doesn't specify whether this is reversible, what cleanup occurs, whether it affects other operations, or what happens on success/failure. The description is too minimal for a tool that likely has important side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that communicates the essential action without any wasted words. It's perfectly front-loaded with the core purpose and doesn't include unnecessary elaboration. Every word earns its place in this minimal but complete statement.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool that performs a state-changing operation (disconnecting from a database) with no annotations and no output schema, the description is inadequate. It doesn't explain what 'disconnect' entails, what gets cleaned up, whether this affects subsequent operations, what the response looks like, or error conditions. Given the complexity of database connection management, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters with 100% schema description coverage, so the schema already fully documents the parameter situation. The description appropriately doesn't waste space discussing nonexistent parameters, maintaining focus on the tool's purpose. A baseline of 4 is appropriate for zero-parameter tools.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Disconnect from') and target resource ('the current PostgreSQL database'), making the purpose immediately understandable. However, it doesn't explicitly differentiate this tool from its siblings like 'connect_database' beyond the obvious opposite action, missing an opportunity to clarify the relationship between connection management tools.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives or what prerequisites might be needed. It doesn't mention whether a database connection must be active first, what happens if no connection exists, or how this relates to sibling tools like 'connect_database' in a workflow.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

execute_queryA

Execute a read-only SQL query (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH statements only)

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNoMaximum number of rows to return (default: 100)
queryYesSQL query to execute (read-only operations only)

TDQS

A3.9/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It clearly states the read-only constraint and acceptable statement types, which is valuable. However, it doesn't mention important behavioral aspects like error handling, timeout behavior, result format, or authentication requirements that would be helpful for an agent.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that communicates the essential information with zero waste. It's appropriately sized and front-loaded with the core purpose, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a query execution tool with no annotations and no output schema, the description provides adequate but minimal information. It covers the read-only constraint and acceptable statement types, but doesn't address result format, error conditions, or performance characteristics that would help an agent use it effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already fully documents both parameters. The description adds no additional parameter information beyond what's in the schema descriptions. The baseline of 3 is appropriate when the schema does all the parameter documentation work.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'execute' and resource 'SQL query', specifying it's for read-only operations with explicit statement types (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH). It distinguishes from siblings like describe_table and get_schema by focusing on arbitrary query execution rather than metadata retrieval.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use this tool (for read-only SQL queries) and implicitly distinguishes it from siblings by not being for connection management or schema inspection. However, it doesn't explicitly state when NOT to use it or name specific alternatives for different query types.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_schemaB

Get an overview of the database schema including tables and their relationships

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.4/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It describes what the tool does ('Get an overview') but lacks details on behavioral traits such as whether it's read-only (implied but not stated), performance characteristics (e.g., if it's slow for large schemas), error handling, or output format. For a tool with zero annotation coverage, this is a significant gap, though it's not misleadingβ€”just insufficient.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence that efficiently conveys the tool's purpose without any wasted words. It's front-loaded with the main action ('Get an overview') and specifies the scope ('database schema including tables and their relationships'), making it easy to understand at a glance. Every part of the sentence earns its place, achieving optimal conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (simple read operation with no parameters) and the lack of annotations and output schema, the description is adequate but not complete. It explains what the tool does but doesn't cover behavioral aspects like output format or potential limitations. For a tool in this context, it meets minimum viability but could benefit from more detail to fully guide an agent, scoring a 3.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters, and schema description coverage is 100% (since there are no parameters to describe). The description doesn't need to add parameter semantics, so it meets the baseline of 4 for tools with no parameters. It appropriately focuses on the tool's purpose without unnecessary parameter details.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Get') and resource ('database schema'), specifying it includes 'tables and their relationships'. It distinguishes from siblings like 'list_tables' (which might just list names) and 'describe_table' (which focuses on a single table). However, it doesn't explicitly differentiate from potential alternatives like 'execute_query' for schema queries, keeping it at 4 rather than 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage when needing an overview of the database structure, which suggests context for database exploration or query planning. However, it doesn't explicitly state when to use this tool versus alternatives like 'list_tables' (for just table names) or 'describe_table' (for detailed info on a specific table), nor does it mention prerequisites such as needing a connected database first. This leaves some ambiguity, scoring a 3 for implied but incomplete guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

list_tablesB

List all tables in the current database

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

TDQS

B3.1/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It states the action but does not disclose behavioral traits such as whether this is a read-only operation, if it requires authentication, potential rate limits, or the format of the returned list. This leaves significant gaps in understanding how the tool behaves.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence that directly states the tool's purpose without any unnecessary words. It is front-loaded and efficiently conveys the essential information, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete. It does not explain what the output looks like (e.g., list format, pagination) or address behavioral aspects like error handling. For a tool with no structured metadata, more context is needed to fully guide the agent.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters, and the input schema has 100% description coverage (though empty). The description does not need to add parameter details, so it appropriately avoids redundancy. A baseline score of 4 is given since no parameters are present, and the description does not mislead about inputs.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('List') and resource ('tables in the current database'), making the purpose immediately understandable. However, it does not explicitly differentiate from sibling tools like 'get_schema' or 'describe_table', which might also provide table-related information, so it falls short of a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives such as 'get_schema' or 'describe_table'. It lacks context about prerequisites (e.g., needing a database connection) or exclusions, leaving the agent to infer usage based on tool names alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 6 tool updatesv1.0.0
    • First observedconnect_database
    • First observeddescribe_table
    • First observeddisconnect_database
    • First observedexecute_query
    • First observedget_schema
    • First observedlist_tables

TDQS

A3.5/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose with no overlap: connect/disconnect manage connections, list_tables enumerates tables, describe_table provides table details, get_schema shows relationships, and execute_query runs read-only SQL. An agent can easily distinguish between these functions.

Naming Consistency5/5

All tools follow a consistent verb_noun pattern with snake_case naming (e.g., connect_database, describe_table, execute_query). The naming is predictable and readable throughout the set.

Tool Count4/5

With 6 tools, the count is reasonable for a PostgreSQL server focused on schema exploration and read-only queries. It's slightly lean but covers core database interaction needs without bloat.

Completeness3/5

The tools cover connection management, schema inspection, and read-only queries well, but there are notable gaps: no write operations (INSERT, UPDATE, DELETE) or administrative functions (e.g., create/drop tables). This limits the server to read-only use cases, which may cause agent failures for broader database tasks.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.
    63
    Apache 2.0
  • A
    license
    Not graded
    quality
    Not graded
    maintenance
    Provides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.
    1
    -
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.
    2
    -

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/melihbirim/pg-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server