pg-semantic-mcp
pg-semantic-mcp is a read-only MCP server for AI coding agents that exposes database schema information for PostgreSQL or SQL Server without executing SQL. Core capabilities: list tables with comments, describe columns (names, types, nullability), fetch sample rows, and perform semantic schema search using natural language via any OpenAI-compatible LLM (optionally enhanced by a user-authored semantic layer document). The server requires no vector database and operates entirely read-only.
Can use local LLM models served by Ollama for semantic schema search.
Uses OpenAI-compatible LLM APIs, including GPT models, to power semantic search across the database schema.
Exposes PostgreSQL database schema (tables, columns, comments) and sample data as MCP tools, with semantic search over the schema.
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., "@pg-semantic-mcpShow me the schema for the orders 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.
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 |
| asyncpg | (built-in) |
SQL Server |
| pymssql |
|
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-mcpConfiguration
Variable | Required | Default | Description |
| yes | — | PostgreSQL or SQL Server connection string |
| no | — | Path to your semantic layer markdown |
| no |
| OpenAI-compatible endpoint |
| no | — | Required for |
| no |
| LLM model name |
| no |
| Background cache refresh interval |
| no | all | Comma-separated schema names to cache |
| no | — | Comma-separated table name prefixes to cache |
| no |
| Default row count for |
| no |
| Hard maximum rows returned by |
| no |
| Approximate hard maximum serialized response bytes for |
| no | all | Comma-separated case-insensitive glob patterns for columns that may be returned |
| no | — | Comma-separated case-insensitive glob patterns for columns that must be omitted |
| no | built-in sensitive patterns | Comma-separated case-insensitive glob patterns for columns whose values are replaced with |
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:
limitmust be greater than 0 and is hard-capped bySAMPLE_DATA_MAX_ROWS.The response is reduced until its serialized size is within
SAMPLE_DATA_MAX_BYTES.SAMPLE_DATA_ALLOW_COLUMNSlimits returned columns when set.SAMPLE_DATA_DENY_COLUMNSomits matching columns and takes precedence over allow rules.SAMPLE_DATA_REDACT_COLUMNSmasks 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, setLLM_BASE_URL=https://api.deepseek.com/v1)Anthropic via proxy
Local models via Ollama or LM Studio
License
MIT
Available Tools
4 toolsdescribe_tableB
Return column metadata for a table.
| Name | Required | Description | Default |
|---|---|---|---|
| table | Yes | Table name in "schema.table" format (e.g. "ods.bd_customer") or bare table name (defaults to "public"/"dbo" schema). |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| schema | No | Optional schema name to filter by (e.g. "ods", "dw"). If omitted, all non-system schemas are returned. |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Number of rows to return. Defaults to SAMPLE_DATA_LIMIT env var (default 5). Hard-capped by SAMPLE_DATA_MAX_ROWS. | |
| table | Yes | Table name in "schema.table" format or bare table name. |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
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.
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.
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.
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.
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.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| type | No | Optional filter — "table" to match tables only, "column" to match columns only. Omit to search both tables and columns. | |
| keyword | Yes | Natural language search term (e.g. "customer receivables", "WIP inventory", "应收账款"). |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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
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.
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.
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.
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
Related MCP Connectors
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Xata MCP server lets AI agents interact with your Xata projects, and Postgres database branches.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceA 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.26MIT
- AlicenseAqualityBmaintenanceAn 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.115MIT
- FlicenseNot gradedqualityFmaintenanceA read-only MCP server that enables AI agents to explore database schemas and execute safe queries on PostgreSQL and MySQL.
- AlicenseNot gradedqualityBmaintenanceA 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.49MIT
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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