Skip to main content
Glama
chncaesar

pg-semantic-mcp

db-semantic-mcp

English | 简体中文

A multi-backend MCP server for AI coding agents — supports both PostgreSQL and SQL Server.

Exposes your database schema — table names, column types, comments, and bounded sample data — as MCP tools. Includes semantic search powered by any OpenAI-compatible LLM, enriched by a user-authored semantic layer document.

No SQL execution. Read-only. No vector database required.

Backends

Backend

Scheme

Driver

Required Extras

PostgreSQL

postgresql://...

asyncpg

(built-in)

SQL Server

sqlserver://...

pymssql

[sqlserver]

The backend is auto-detected from DATABASE_URL. Everything else works the same.

Related MCP server: dbecho

Features

  • list_tables — discover all tables with comments

  • describe_table — inspect column names, types, nullability, and comments

  • sample_data — fetch example rows from any table

  • search_schema — semantic keyword search across tables and columns using LLM

Install

# PostgreSQL only
pip install db-semantic-mcp

# With SQL Server support
pip install "db-semantic-mcp[sqlserver]"

Requires Python 3.11+.

Quick Start

# PostgreSQL
export DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"

# SQL Server (Kingdee ERP or any MSSQL instance)
export DATABASE_URL="sqlserver://user:pass@host:1433?database=mydb&encrypt=disable"

export LLM_API_KEY="sk-..."          # required only for search_schema
pg-semantic-mcp

Configuration

Variable

Required

Default

Description

DATABASE_URL

yes

PostgreSQL or SQL Server connection string

SEMANTIC_FILE

no

Path to your semantic layer markdown

LLM_BASE_URL

no

https://api.openai.com/v1

OpenAI-compatible endpoint

LLM_API_KEY

no

Required for search_schema

LLM_MODEL

no

gpt-4o-mini

LLM model name

CACHE_REFRESH_MINUTES

no

30

Background cache refresh interval

CACHE_SCHEMAS

no

all

Comma-separated schema names to cache

CACHE_TABLE_PREFIX

no

Comma-separated table name prefixes to cache

SAMPLE_DATA_LIMIT

no

5

Default row count for sample_data

SAMPLE_DATA_MAX_ROWS

no

20

Hard maximum rows returned by sample_data

SAMPLE_DATA_MAX_BYTES

no

50000

Approximate hard maximum serialized response bytes for sample_data

SAMPLE_DATA_ALLOW_COLUMNS

no

all

Comma-separated case-insensitive glob patterns for columns that may be returned

SAMPLE_DATA_DENY_COLUMNS

no

Comma-separated case-insensitive glob patterns for columns that must be omitted

SAMPLE_DATA_REDACT_COLUMNS

no

built-in sensitive patterns

Comma-separated case-insensitive glob patterns for columns whose values are replaced with [REDACTED]

You can also use a .env file in the working directory.

sample_data Security Boundary

sample_data is read-only, but it is not metadata-only: it can expose actual business data from the connected database. Treat it as a small data-plane tool.

The tool applies these response controls before returning rows to the MCP client:

  • limit must be greater than 0 and is hard-capped by SAMPLE_DATA_MAX_ROWS.

  • The response is reduced until its serialized size is within SAMPLE_DATA_MAX_BYTES.

  • SAMPLE_DATA_ALLOW_COLUMNS limits returned columns when set.

  • SAMPLE_DATA_DENY_COLUMNS omits matching columns and takes precedence over allow rules.

  • SAMPLE_DATA_REDACT_COLUMNS masks matching values with [REDACTED].

Column policies use case-insensitive glob patterns. For example:

SAMPLE_DATA_ALLOW_COLUMNS="id,name,email,created_at"
SAMPLE_DATA_DENY_COLUMNS="*password*,*token*"
SAMPLE_DATA_REDACT_COLUMNS="*email*,*phone*,*secret*"

The response shape is intentionally short to save model context:

{
  "rows": [
    {"id": 1, "email": "[REDACTED]"}
  ],
  "_meta": {
    "table": "public.customers",
    "returned": 1,
    "truncated": false
  }
}

Register with OpenCode

Add to your opencode.jsonc:

{
  "mcp": {
    "pg-data": {
      "type": "local",
      "command": "pg-semantic-mcp",
      "environment": {
        "DATABASE_URL": "postgresql://user:pass@host:5432/dbname",
        "SEMANTIC_FILE": "/path/to/SCHEMA.md",
        "LLM_API_KEY": "sk-..."
      }
    }
  }
}

Same config format works for Claude Code, Cursor, and any MCP-compatible agent.

Semantic Layer

Create a SCHEMA.md file describing your database — naming conventions, business term mappings, design decisions. See SCHEMA.md.example for a template.

This document is loaded at startup and included in the search_schema LLM prompt. It is the main way to teach the agent about your specific domain.

Compatible LLMs

search_schema calls any OpenAI-compatible endpoint:

  • OpenAI (gpt-4o-mini, gpt-4o, …)

  • DeepSeek (deepseek-v4, set LLM_BASE_URL=https://api.deepseek.com/v1)

  • Anthropic via proxy

  • Local models via Ollama or LM Studio

License

MIT

Available Tools

4 tools
describe_tableB

Return column metadata for a table.

ParametersJSON Schema
NameRequiredDescriptionDefault
tableYesTable name in "schema.table" format (e.g. "ods.bd_customer") or bare table name (defaults to "public"/"dbo" schema).

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.3/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 simply states 'Return column metadata' without mentioning whether the operation is safe/read-only, whether it requires special permissions, how errors are handled, or any side effects. The minimal description leaves behavioral expectations unclear.

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, direct sentence that immediately conveys the tool's purpose. There is no wasted words or unnecessary repetition, front-loading the core action.

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?

The tool is simple, has a fully documented parameter schema, and an output schema exists, so return values need not be explained. However, the description lacks any usage context or mention of when to choose this tool over siblings. It is minimally sufficient but leaves the agent without guidance on applicability.

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%: the 'table' parameter already has a detailed description explaining schema.table format and default schema behavior. The tool description adds no additional parameter semantics, so the baseline of 3 applies.

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 tool's function: 'Return column metadata for a table.' It uses a specific verb ('return') and resource ('column metadata'), and it is distinct from sibling tools like list_tables (which lists tables) and sample_data (which returns data rows).

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. It does not mention any prerequisites, exclusions, or reference sibling tools. There is no explicit context for choosing describe_table over list_tables or search_schema.

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

list_tablesA

List all tables in the database with their comments.

ParametersJSON Schema
NameRequiredDescriptionDefault
schemaNoOptional schema name to filter by (e.g. "ods", "dw"). If omitted, all non-system schemas are returned.

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A3.6/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. It discloses the list operation, the inclusion of comments, and via the parameter description, the default behavior of returning all non-system schemas when no filter is given. However, it does not mention potential permissions, output ordering, or any limits, leaving some behavioral ambiguity.

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, front-loaded sentence with no wasted words. It efficiently conveys the tool's core function.

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

Completeness4/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, the presence of an output schema, and the parameter's full documentation in the schema, the description is nearly complete. It could explicitly state that this is a read-only operation, but the word 'List' implies no side effects. Minor gap: no direct statement about system schema exclusion if a specific schema is provided, but the parameter description already covers this.

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 provides a complete description for the single optional 'schema' parameter, including examples and default behavior. The tool description itself adds no additional parameter-related meaning, so the baseline of 3 applies.

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 tool's function: listing all tables in the database. The addition 'with their comments' specifies the output detail, distinguishing it from sibling tools that describe single tables or sample data.

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 its siblings. It merely states what it does, without mentioning alternatives or exclusions. The parameter description offers some behavior context (filtering by schema) but does not address tool selection.

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

sample_dataB

Return sample rows from a table.

ParametersJSON Schema
NameRequiredDescriptionDefault
limitNoNumber of rows to return. Defaults to SAMPLE_DATA_LIMIT env var (default 5). Hard-capped by SAMPLE_DATA_MAX_ROWS.
tableYesTable name in "schema.table" format or bare table name.

Output Schema

ParametersJSON Schema
NameRequiredDescription

No output 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 full responsibility for behavioral disclosure. It only states 'return sample rows,' implying a read operation, but reveals nothing about limits, randomness, or side effects. The parameter schema covers limit constraints, but the description adds no behavioral context.

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

Conciseness4/5

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

The description is a single concise sentence that is easy to parse and front-loads the action. It is appropriately sized for a simple tool, though it omits useful context that could be added without becoming verbose.

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?

The tool is simple and an output schema exists, but the description lacks usage context and does not clarify how sampling works (e.g., random vs. first N rows). It also provides no guidance on when to use this tool relative to siblings, making it incomplete for an agent to fully understand its role.

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 fully documents both parameters (limit and table) with descriptions, achieving 100% schema coverage. The description does not add meaning beyond the schema's parameter descriptions, so the baseline score of 3 applies.

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 tool's function with a specific verb ('return') and resource ('sample rows from a table'). It is distinct from sibling tools like list_tables and describe_table, which handle schema or metadata rather than actual data rows.

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. It does not mention any context, exclusions, or refer to sibling tools, leaving the agent without direction on choosing this tool.

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

search_schemaA

Semantically search tables and columns by keyword using LLM.

Combines the in-memory schema cache and the semantic layer markdown (if configured) into a prompt, then calls the configured LLM to find relevant tables and columns.

ParametersJSON Schema
NameRequiredDescriptionDefault
typeNoOptional filter — "table" to match tables only, "column" to match columns only. Omit to search both tables and columns.
keywordYesNatural language search term (e.g. "customer receivables", "WIP inventory", "应收账款").

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.1/5.0
Behavior4/5

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

The description goes beyond a generic statement by explaining the internal process: it combines the in-memory schema cache and semantic layer markdown into a prompt, then calls the LLM. Since no annotations are provided, this contextual detail about the tool's behavior is valuable and clarifies that results are LLM-based, not exact matches.

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 two sentences and immediately states the tool's purpose, followed by a concise explanation of how it works. There is no redundancy or filler.

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

Completeness5/5

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

With a simple two-parameter schema and an output schema present, the description sufficiently covers what the tool does and how it operates. It does not need to explain return values because the output schema exists, and there are no hidden behaviors or complex side effects.

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 already describes both parameters fully: 'keyword' as a natural language search term and 'type' as an optional filter. The description adds little beyond the schema's coverage, so the baseline score of 3 is appropriate.

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 states a specific verb ('search') and resource ('tables and columns'), and clarifies it's semantic search using an LLM. This distinguishes it from sibling tools like list_tables, describe_table, and sample_data.

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 the tool is for finding relevant tables/columns by meaning, but it does not explicitly state when to use it versus alternatives, nor does it mention any exclusions or prerequisite conditions. The usage intent is implicit rather than explicit.

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

TDQS

A3.7/5.0
Disambiguation5/5

Each tool has a clearly distinct purpose: list_tables for enumeration, describe_table for schema details, sample_data for row previews, and search_schema for semantic discovery. There is no ambiguity or overlap between them.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern using snake_case (list_tables, describe_table, sample_data, search_schema). The naming is predictable and follows standard database exploration terminology.

Tool Count5/5

With 4 tools, the server is well-scoped for its purpose of schema exploration and semantic search. Each tool adds unique value without unnecessary bloat, fitting comfortably in the ideal 3-15 tool range.

Completeness4/5

The core schema exploration lifecycle (list, describe, sample, search) is covered completely. Minor gaps exist such as no direct schema listing or database-level information, but these are not essential for the server's apparent purpose.

Maintenance

ActivityMaintained
ResponsivenessSyncing

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    A read-only PostgreSQL MCP server that enables AI agents to perform schema introspection and execute SELECT-only queries. It supports secure database connections through SSL and SSH tunnels while offering a structure-only mode to restrict query access.
    26
    MIT
  • A
    license
    A
    quality
    B
    maintenance
    An MCP server that gives AI agents direct read-only access to PostgreSQL databases, enabling natural language analytics through tools for schema exploration, querying, trend analysis, and data quality checks.
    11
    5
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    A zero-config, read-only PostgreSQL MCP server that enforces read-only access at the database level using READ ONLY transactions, allowing AI agents to safely explore schemas and run SELECT queries without risk of mutation.
    49
    MIT

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/chncaesar/db-semantic-mcp'

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