mcp-pgSQL
A local MCP server for PostgreSQL that provides tools for SQL execution, metadata inspection, performance diagnostics, and database management through natural language.
README
MCP de PostgreSQL (Python)
Servidor MCP local para PostgreSQL usando psycopg y FastMCP.
Es el equivalente operativo del proyecto C:\Users\PCBYRON\mssql-python-mcp,
adaptado a catalogos y semantica de PostgreSQL. Mantiene el contrato de
respuesta uniforme:
{
"success": true,
"data": {},
"warnings": []
}
En error:
{
"success": false,
"error": {
"code": "SQL_ERROR",
"sql_state": "42601",
"message": "...",
"hint": "..."
}
}
Configuracion default
La conexion default usa:
HOST = "localhost"
PORT = 5432
USER = "postgres"
PASSWORD = "pgSQL"
DEFAULT_DATABASE = "postgres"
DEFAULT_SCHEMA = "public"
Instalacion
Con el Python global de este equipo:
cd C:\Users\PCBYRON\Documents\mcp-pgSQL
C:\Python310\python.exe -m pip install --user -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org
C:\Python310\python.exe -m py_compile server.py
Para ejecutar como MCP por stdio:
C:\Python310\python.exe C:\Users\PCBYRON\Documents\mcp-pgSQL\server.py
Tambien puedes usar:
run.bat
Configuracion en Codex/Claude Desktop
Ejemplo:
{
"mcpServers": {
"pgsql": {
"command": "C:\\Python310\\python.exe",
"args": ["C:\\Users\\PCBYRON\\Documents\\mcp-pgSQL\\server.py"]
}
}
}
Parametros
Las tools SQL aceptan parametros por nombre estilo @nombre; internamente se
convierten a placeholders seguros de psycopg.
{
"sql": "select * from public.clientes where id = @id",
"params": [
{"name": "id", "type": "int", "value": 123}
]
}
Tambien acepta params como objeto:
{
"sql": "select @x::int + 1 as y",
"params": {"x": 41}
}
Tools incluidas
El servidor registra 165 tools: las 106 tools nominales del MCP MSSQL original mas utilidades propias de PostgreSQL para observabilidad, MVCC, indices, JSONB, particiones, RLS, extensiones, replicacion, FDW y desarrollo. Grupos principales:
- Conexion:
connect_server,disconnect_server,list_connections,is_connected,use_database,set_default_schema,current_context. - Metadata:
list_databases,list_schemas,list_objects,get_table_schema,get_indexes,get_foreign_keys,get_constraints,get_triggers,get_dependencies,get_object_definition,search_in_definitions,get_table_dependencies_graph,find_identity_columns. - Ejecucion SQL:
execute_query,execute_query_paged,execute_scalar,execute_nonquery,execute_script,execute_dry_run,stream_query,call_procedure,call_function,call_tvf. - Compatibilidad:
query,execute,describe. - Transacciones:
begin_transaction,commit_transaction,rollback_transaction,savepoint,rollback_to_savepoint,get_open_transactions. - DDL:
create_or_alter,drop_object,rename_object,alter_column,clone_table,truncate_table. - Locks/performance:
list_sessions,get_active_requests,get_blocking_chains,kill_session,get_locks,get_wait_stats,get_query_plan,explain_query,get_query_stats,analyze_table. - Seguridad:
list_logins,list_users,list_roles,list_permissions,grant_permission,revoke_permission,check_effective_permissions. - Schema repo/db:
export_schema,import_schema,diff_schema,sync_schema. - Datos:
count_rows,sample_data,column_stats,find_duplicates,check_referential_integrity,find_identity_gaps,bulk_insert,bulk_upsert. - Diagnostico:
server_info,database_files,tempdb_usage,memory_usage,get_mcp_logs,get_connection_pool_stats,clear_plan_cache,table_sizes,vacuum_analyze,list_extensions,create_extension. - PostgreSQL-first:
get_database_health,get_table_bloat,get_autovacuum_status,get_slow_queries,recommend_indexes,index_usage_report,find_missing_foreign_key_indexes,inspect_jsonb_column,list_partitions,rls_status,role_audit,extension_recommendations,replication_slot_risk,fdw_health_check,generate_table_ddl_full,export_pg_dump_schema.
Seguridad operacional
execute_querysolo acepta consultas read-only (SELECT,WITH,SHOW,EXPLAIN,VALUES,TABLE).execute_nonquerybloquea DDL.- Operaciones DDL/destructivas requieren
confirm=true. statement_timeoutdefault: 30 s.lock_timeoutdefault: 5000 ms.- Resultsets se limitan a 1000 filas por default y 10000 como hard limit.
Equivalencia contra SQL Server
Cobertura nominal: 106/106 tools MSSQL presentes.
Equivalencia funcional estimada: 90-93%. Las areas core estan portadas con implementacion PostgreSQL real. Algunas tools conservan el nombre y contrato, pero devuelven advertencias o equivalentes aproximados cuando el motor no tiene una funcion 1:1.
Expansion PostgreSQL-first: 52 tools nuevas agregadas en 5 bloques, orientadas a capacidades donde PostgreSQL tiene ventajas o necesidades propias.
Diferencias contra SQL Server
Algunas tools del MCP MSSQL eran intrinsecamente de SQL Server. En PostgreSQL:
recompile_procedureyrecompile_all_proceduresdevuelven advertenciaNOT_APPLICABLE.clear_plan_cachedevuelve advertenciaNOT_APPLICABLE.database_filesreporta tamanos de bases, no archivos MDF/LDF.tempdb_usageusapg_stat_database.temp_files/temp_bytes.create_or_alterusaCREATE OR REPLACEcuando aplica.get_sql_agent_jobs,start_jobyjob_historyusanpg_cronsi esta instalado; sin esa extension devuelven advertencia.list_linked_serverslista foreign servers/FDW.execute_on_linkedno tiene pass-through generico equivalente a SQL Server linked servers.cdc_statusyreplication_statusreportan logical replication, publications, slots, subscriptions y senders.snapshot_database/restore_snapshotusanCREATE DATABASE ... WITH TEMPLATE; no son snapshots copy-on-write como SQL Server.
Pruebas realizadas
Validado localmente contra PostgreSQL 17.10 en localhost con usuario
postgres:
C:\Python310\python.exe -m py_compile server.py
Y pruebas directas de:
- conexion
postgres/pgSQL current_contextlist_databasesexecute_querycon parametro@xlist_schemasserver_info- DDL/DML sobre tabla descartable: create, schema, bulk insert, count, upsert, sample, indexes y drop.
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.