Command Palette

Search for a command to run...

UnylyUnyly
Весь каталог

PgSQL

БесплатноНе проверен

A local MCP server for PostgreSQL that provides tools for SQL execution, metadata inspection, performance diagnostics, and database management through natural l

GitHubEmbed

Описание

A local MCP server for PostgreSQL that provides tools for SQL execution, metadata inspection, performance diagnostics, and database management through natural language.

README

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_query solo acepta consultas read-only (SELECT, WITH, SHOW, EXPLAIN, VALUES, TABLE).
  • execute_nonquery bloquea DDL.
  • Operaciones DDL/destructivas requieren confirm=true.
  • statement_timeout default: 30 s.
  • lock_timeout default: 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_procedure y recompile_all_procedures devuelven advertencia NOT_APPLICABLE.
  • clear_plan_cache devuelve advertencia NOT_APPLICABLE.
  • database_files reporta tamanos de bases, no archivos MDF/LDF.
  • tempdb_usage usa pg_stat_database.temp_files/temp_bytes.
  • create_or_alter usa CREATE OR REPLACE cuando aplica.
  • get_sql_agent_jobs, start_job y job_history usan pg_cron si esta instalado; sin esa extension devuelven advertencia.
  • list_linked_servers lista foreign servers/FDW. execute_on_linked no tiene pass-through generico equivalente a SQL Server linked servers.
  • cdc_status y replication_status reportan logical replication, publications, slots, subscriptions y senders.
  • snapshot_database/restore_snapshot usan CREATE 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_context
  • list_databases
  • execute_query con parametro @x
  • list_schemas
  • server_info
  • DDL/DML sobre tabla descartable: create, schema, bulk insert, count, upsert, sample, indexes y drop.

from github.com/OscarByron69/mcp-pgSQL

Установка PgSQL

У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.

▸ github.com/OscarByron69/mcp-pgSQL

FAQ

PgSQL MCP бесплатный?

Да, PgSQL MCP бесплатный — установка в пару кликов через Unyly без оплаты.

Нужен ли API-ключ для PgSQL?

Нет, PgSQL работает без API-ключей и переменных окружения.

PgSQL — hosted или self-hosted?

Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.

Как установить PgSQL в Claude Desktop, Claude Code или Cursor?

Открой PgSQL на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.

Похожие MCP

Compare PgSQL with

Не уверен что выбрать?

Найди свой стек за 60 секунд

Автор?

Embed-бейдж для README

Похожее

Все в категории data