Postgres MCP
Überblick
Postgres MCP Pro ist ein Open-Source-MCP-Server (Model Context Protocol), der Sie und Ihre KI-Agenten während des gesamten Entwicklungsprozesses unterstützt – von der ersten Codierung über Tests und Bereitstellung bis hin zur Produktionsoptimierung und Wartung.
Postgres MCP Pro kann viel mehr als nur eine Datenbankverbindung umschließen.
Zu den Features gehören:
🔍 Datenbankintegrität – Analysieren Sie die Indexintegrität, die Verbindungsauslastung, den Puffercache, die Vakuumintegrität, Sequenzgrenzen, Replikationsverzögerung und mehr.
⚡ Index-Tuning – erkunden Sie Tausende möglicher Indizes, um mithilfe leistungsstarker Algorithmen die beste Lösung für Ihre Arbeitslast zu finden.
📈 Abfragepläne – validieren und optimieren Sie die Leistung, indem Sie EXPLAIN-Pläne überprüfen und die Auswirkungen hypothetischer Indizes simulieren.
🧠 Schema Intelligence – kontextsensitive SQL-Generierung basierend auf einem detaillierten Verständnis des Datenbankschemas.
🛡️ Sichere SQL-Ausführung – konfigurierbare Zugriffskontrolle, einschließlich Unterstützung für den schreibgeschützten Modus und sicheres SQL-Parsing, wodurch es sowohl für die Entwicklung als auch für die Produktion nutzbar wird.
Postgres MCP Pro unterstützt sowohl den Standard Input/Output (stdio)- als auch den Server-Sent Events (SSE) -Transport und sorgt so für Flexibilität in unterschiedlichen Umgebungen.
Weitere Hintergrundinformationen zu den Gründen für die Entwicklung von Postgres MCP Pro finden Sie in unserem Blogbeitrag zur Produkteinführung .
Related MCP server: Postgres MCP Pro
Demo
Von unbrauchbar zu blitzschnell
Herausforderung: Wir haben mithilfe eines KI-Assistenten eine Film-App erstellt, aber der SQLAlchemy-ORM-Code lief quälend langsam.
Lösung: Mit Postgres MCP Pro mit Cursor haben wir die Leistungsprobleme innerhalb von Minuten behoben.
Was wir getan haben:
🚀 Feste Leistung – einschließlich ORM-Abfragen, Indizierung und Caching
🛠️ Eine defekte Seite wurde repariert, indem der Agent aufgefordert wurde, die Daten zu untersuchen, Abfragen zu korrigieren und verwandte Inhalte hinzuzufügen.
🧠 Die Top-Filme wurden verbessert – durch Untersuchung der Daten und Korrektur der ORM-Abfrage, um relevantere Ergebnisse anzuzeigen.
Sehen Sie sich das Video unten an oder lesen Sie die Spielbeschreibung .
https://github.com/user-attachments/assets/24e05745-65e9-4998-b877-a368f1eadc13
Schnellstart
Voraussetzungen
Bevor Sie beginnen, stellen Sie sicher, dass Sie über Folgendes verfügen:
Zugangsdaten für Ihre Datenbank.
Docker oder Python 3.12 oder höher.
Zugangsdaten
Sie können die Gültigkeit Ihrer Zugangsdaten mithilfe von psql oder einem GUI-Tool wie pgAdmin bestätigen.
Docker oder Python
Sie haben die Wahl zwischen Docker und Python. Wir empfehlen grundsätzlich Docker, da Python-Benutzer auf umgebungsspezifischere Probleme stoßen können. Oft ist es jedoch sinnvoll, die Methode zu verwenden, mit der Sie am besten vertraut sind.
Installation
Wählen Sie eine der folgenden Methoden, um Postgres MCP Pro zu installieren:
Option 1: Verwenden von Docker
Laden Sie das Docker-Image des Postgres MCP Pro MCP-Servers herunter. Dieses Image enthält alle notwendigen Abhängigkeiten und ermöglicht die zuverlässige Ausführung von Postgres MCP Pro in verschiedenen Umgebungen.
docker pull crystaldba/postgres-mcpOption 2: Verwenden von Python
Wenn Sie pipx installiert haben, können Sie Postgres MCP Pro mit Folgendem installieren:
pipx install postgres-mcpAndernfalls installieren Sie Postgres MCP Pro mit uv :
uv pip install postgres-mcpWenn Sie uv installieren müssen, lesen Sie die UV-Installationsanweisungen .
Konfigurieren Sie Ihren KI-Assistenten
Wir bieten eine vollständige Anleitung zur Konfiguration von Postgres MCP Pro mit Claude Desktop. Viele MCP-Clients verfügen über ähnliche Konfigurationsdateien. Sie können diese Schritte an den Client Ihrer Wahl anpassen.
Claude Desktop-Konfiguration
Sie müssen die Claude Desktop-Konfigurationsdatei bearbeiten, um Postgres MCP Pro hinzuzufügen. Der Speicherort dieser Datei hängt von Ihrem Betriebssystem ab:
MacOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%/Claude/claude_desktop_config.json
Sie können die Konfigurationsdatei auch über das Menüelement Settings in Claude Desktop suchen.
Sie bearbeiten jetzt den Abschnitt mcpServers “ der Konfigurationsdatei.
Wenn Sie Docker verwenden
{
"mcpServers": {
"postgres": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"DATABASE_URI",
"crystaldba/postgres-mcp",
"--access-mode=unrestricted"
],
"env": {
"DATABASE_URI": "postgresql://username:password@localhost:5432/dbname"
}
}
}
}Das Postgres MCP Pro Docker-Image ordnet den Hostnamen localhost automatisch neu zu, damit er innerhalb des Containers funktioniert.
MacOS/Windows: Verwendet
host.docker.internalautomatischLinux: Verwendet automatisch
172.17.0.1oder die entsprechende Hostadresse
Wenn Sie pipx verwenden
{
"mcpServers": {
"postgres": {
"command": "postgres-mcp",
"args": [
"--access-mode=unrestricted"
],
"env": {
"DATABASE_URI": "postgresql://username:password@localhost:5432/dbname"
}
}
}
}Wenn Sie uv verwenden
{
"mcpServers": {
"postgres": {
"command": "uv",
"args": [
"run",
"postgres-mcp",
"--access-mode=unrestricted"
],
"env": {
"DATABASE_URI": "postgresql://username:password@localhost:5432/dbname"
}
}
}
}Verbindungs-URI
Ersetzen Sie postgresql://... durch Ihre Postgres-Datenbankverbindungs-URI .
Zugriffsmodus
Postgres MCP Pro unterstützt mehrere Zugriffsmodi , um Ihnen die Kontrolle über die Vorgänge zu geben, die der KI-Agent in der Datenbank ausführen kann:
Uneingeschränkter Modus : Ermöglicht vollständigen Lese-/Schreibzugriff zum Ändern von Daten und Schemata. Geeignet für Entwicklungsumgebungen.
Eingeschränkter Modus : Beschränkt Operationen auf schreibgeschützte Transaktionen und schränkt die Ressourcennutzung ein (derzeit nur die Ausführungszeit). Dieser Modus eignet sich für Produktionsumgebungen.
Um den eingeschränkten Modus zu verwenden, ersetzen Sie in den obigen Konfigurationsbeispielen --access-mode=unrestricted durch --access-mode=restricted .
Andere MCP-Clients
Viele MCP-Clients haben ähnliche Konfigurationsdateien wie Claude Desktop und Sie können die obigen Beispiele anpassen, damit sie mit dem Client Ihrer Wahl funktionieren.
Wenn Sie den Cursor verwenden, können Sie von der
Command PalettezuCursor Settingsnavigieren und dann die RegisterkarteMCPöffnen, um auf die Konfigurationsdatei zuzugreifen.Wenn Sie Windsurf verwenden, können Sie von der
Command PalettezurOpen Windsurf Settings Pagenavigieren, um auf die Konfigurationsdatei zuzugreifen.Wenn Sie Goose verwenden, führen Sie
goose configureaus und wählen Sie dannAdd Extensionaus.
SSE Transport
Postgres MCP Pro unterstützt den SSE-Transport , der es mehreren MCP-Clients ermöglicht, einen Server, möglicherweise einen Remote-Server, gemeinsam zu nutzen. Um den SSE-Transport zu nutzen, müssen Sie den Server mit der Option --transport=sse starten.
Führen Sie beispielsweise mit Docker Folgendes aus:
docker run -p 8000:8000 \
-e DATABASE_URI=postgresql://username:password@localhost:5432/dbname \
crystaldba/postgres-mcp --access-mode=unrestricted --transport=sseAktualisieren Sie anschließend Ihre MCP-Clientkonfiguration, um den MCP-Server aufzurufen. Beispielsweise können Sie in Cursors mcp.json oder Clines cline_mcp_settings.json eingeben:
{
"mcpServers": {
"postgres": {
"type": "sse",
"url": "http://localhost:8000/sse"
}
}
}Für Windsurf ist das Format in mcp_config.json etwas anders:
{
"mcpServers": {
"postgres": {
"type": "sse",
"serverUrl": "http://localhost:8000/sse"
}
}
}Installation der Postgres-Erweiterung (optional)
Um die Indexoptimierung und umfassende Leistungsanalyse zu ermöglichen, müssen Sie die Erweiterungen pg_statements und hypopg in Ihre Datenbank laden.
Mit der Erweiterung
pg_statementskann Postgres MCP Pro Statistiken zur Abfrageausführung analysieren. So lässt sich beispielsweise erkennen, welche Abfragen langsam ausgeführt werden oder erhebliche Ressourcen verbrauchen.Mit der
hypopgErweiterung kann Postgres MCP Pro das Verhalten des Postgres-Abfrageplaners nach dem Hinzufügen von Indizes simulieren.
Installieren von Erweiterungen auf AWS RDS, Azure SQL oder Google Cloud SQL
Wenn Ihre Postgres-Datenbank auf einem vom Cloud-Anbieter verwalteten Dienst läuft, sollten die Erweiterungen pg_statements und hypopg bereits auf dem System verfügbar sein. In diesem Fall können Sie einfach CREATE EXTENSION -Befehle mit einer Rolle mit ausreichenden Berechtigungen ausführen:
CREATE EXTENSION IF NOT EXISTS pg_statements;
CREATE EXTENSION IF NOT EXISTS hypopg;Installieren von Erweiterungen auf selbstverwaltetem Postgres
Wenn Sie Ihre Postgres-Installation selbst verwalten, sind möglicherweise zusätzliche Schritte erforderlich. Bevor Sie die Erweiterung pg_statements laden, stellen Sie sicher, dass sie in den shared_preload_libraries der Postgres-Konfigurationsdatei aufgeführt ist. Die Erweiterung hypopg erfordert möglicherweise eine zusätzliche Installation auf Systemebene (z. B. über Ihren Paketmanager), da sie nicht immer mit Postgres mitgeliefert wird.
Anwendungsbeispiele
Übersicht zur Datenbankintegrität abrufen
Fragen:
Überprüfen Sie den Zustand meiner Datenbank und identifizieren Sie etwaige Probleme.
Analysieren Sie langsame Abfragen
Fragen:
Welche Abfragen in meiner Datenbank sind am langsamsten? Und wie kann ich sie beschleunigen?
Erhalten Sie Empfehlungen zur Beschleunigung
Fragen:
Meine App ist langsam. Wie kann ich sie schneller machen?
Indexempfehlungen generieren
Fragen:
Analysieren Sie meine Datenbankarbeitslast und schlagen Sie Indizes zur Leistungsverbesserung vor.
Optimieren einer bestimmten Abfrage
Fragen:
Helfen Sie mir, diese Abfrage zu optimieren: SELECT * FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.created_at > '2023-01-01';
MCP-Server-API
Der MCP-Standard definiert verschiedene Arten von Endpunkten: Tools, Ressourcen, Eingabeaufforderungen und andere.
Postgres MCP Pro bietet Funktionalität ausschließlich über MCP-Tools . Wir haben uns für diesen Ansatz entschieden, da das MCP-Client-Ökosystem umfassende Unterstützung für MCP-Tools bietet. Dies steht im Gegensatz zum Ansatz anderer Postgres MCP-Server, einschließlich des Reference Postgres MCP Servers , die MCP-Ressourcen zur Bereitstellung von Schemainformationen nutzen.
Postgres MCP Pro Tools:
Werkzeugname | Beschreibung |
| Listet alle in der PostgreSQL-Instanz verfügbaren Datenbankschemata auf. |
| Listet Datenbankobjekte (Tabellen, Ansichten, Sequenzen, Erweiterungen) innerhalb eines angegebenen Schemas auf. |
| Bietet Informationen zu einem bestimmten Datenbankobjekt, beispielsweise zu den Spalten, Einschränkungen und Indizes einer Tabelle. |
| Führt SQL-Anweisungen in der Datenbank aus, mit Lesebeschränkungen, wenn eine Verbindung im eingeschränkten Modus besteht. |
| Ruft den Ausführungsplan für eine SQL-Abfrage ab, der beschreibt, wie PostgreSQL sie verarbeitet, und stellt das Kostenmodell des Abfrageplaners bereit. Kann mit hypothetischen Indizes aufgerufen werden, um das Verhalten nach dem Hinzufügen von Indizes zu simulieren. |
| Meldet die langsamsten SQL-Abfragen basierend auf der Gesamtausführungszeit unter Verwendung von |
| Analysiert die Datenbankarbeitslast, um ressourcenintensive Abfragen zu identifizieren, und empfiehlt dann optimale Indizes dafür. |
| Analysiert eine Liste bestimmter SQL-Abfragen (bis zu 10) und empfiehlt optimale Indizes dafür. |
| Führt umfassende Integritätsprüfungen durch, darunter: Trefferquoten des Puffercaches, Verbindungsintegrität, Einschränkungsvalidierung, Indexintegrität (Duplikat/unbenutzt/ungültig), Sequenzgrenzen und Vakuumintegrität. |
Ähnliche Projekte
Postgres MCP-Server
MCP abfragen . Ein MCP-Server für Supabase Postgres mit einer dreistufigen Sicherheitsarchitektur und Supabase-Verwaltungs-API-Unterstützung.
PG-MCP . Ein MCP-Server für PostgreSQL mit flexiblen Verbindungsoptionen, Erläuterungsplänen, Erweiterungskontext und mehr.
Referenz PostgreSQL MCP Server . Eine einfache MCP-Server-Implementierung, die Schemainformationen als MCP-Ressourcen verfügbar macht und schreibgeschützte Abfragen ausführt.
Supabase Postgres MCP-Server . Dieser MCP-Server bietet Supabase-Verwaltungsfunktionen und wird aktiv von der Supabase-Community gepflegt.
Nile MCP-Server . Ein MCP-Server, der Zugriff auf die Verwaltungs-API für den Multi-Tenant-Postgres-Dienst von Nile bietet.
Neon MCP-Server . Ein MCP-Server, der Zugriff auf die Verwaltungs-API für den serverlosen Postgres-Dienst von Neon bietet.
Wren MCP Server . Bietet eine semantische Engine für Business Intelligence für Postgres und andere Datenbanken.
DBA-Tools (einschließlich kommerzieller Angebote)
Aiven Database Optimizer . Ein Tool, das eine ganzheitliche Analyse der Datenbankarbeitslast, Abfrageoptimierungen und andere Leistungsverbesserungen bietet.
dba.ai. Ein KI-gestützter Datenbankverwaltungsassistent, der sich in GitHub integrieren lässt, um Codeprobleme zu lösen.
pgAnalyze . Eine umfassende Überwachungs- und Analyseplattform zum Erkennen von Leistungsengpässen, Optimieren von Abfragen und Warnen in Echtzeit.
Postgres.ai . Ein interaktives Chat-Erlebnis, das eine umfangreiche Postgres-Wissensdatenbank und GPT-4 kombiniert.
Xata Agent . Ein Open-Source-KI-Agent, der automatisch die Datenbankintegrität überwacht, Probleme diagnostiziert und mithilfe von LLM-gestützten Schlussfolgerungen und Playbooks Empfehlungen bereitstellt.
Postgres-Dienstprogramme
Dexter . Ein Tool zum Generieren und Testen hypothetischer Indizes in PostgreSQL.
PgHero . Ein Performance-Dashboard für Postgres mit Empfehlungen. Postgres MCP Pro enthält Integritätschecks von PgHero.
PgTune . Heuristiken zum Optimieren der Postgres-Konfiguration.
Häufig gestellte Fragen
Wie unterscheidet sich Postgres MCP Pro von anderen Postgres MCP-Servern? Viele MCP-Server ermöglichen es einem KI-Agenten, Abfragen an eine Postgres-Datenbank auszuführen. Postgres MCP Pro bietet dies ebenfalls und bietet zusätzlich Tools zum Verständnis und zur Verbesserung der Leistung Ihrer Postgres-Datenbank. Beispielsweise implementiert es eine Version des Anytime Algorithm of Database Tuning Advisor für Microsoft SQL Server , einen modernen, industrietauglichen Algorithmus zur automatischen Indexoptimierung.
Postgres MCP Pro | Andere Postgres MCP-Server |
✅ Deterministische Datenbank-Integritätsprüfungen | ❌ Nicht wiederholbare LLM-generierte Gesundheitsabfragen |
✅ Prinzipielle Indexierungssuchstrategien | ❌ Gen-AI vermutet Verbesserungen bei der Indexierung |
✅ Arbeitslastanalyse zur Ermittlung der größten Probleme | ❌ Inkonsistente Problemanalyse |
✅ Simuliert Leistungsverbesserungen | ❌ Probieren Sie es selbst aus und sehen Sie, ob es funktioniert |
Postgres MCP Pro ergänzt generative KI durch deterministische Tools und klassische Optimierungsalgorithmen. Die Kombination ist sowohl zuverlässig als auch flexibel.
Warum werden MCP-Tools benötigt, wenn LLMs argumentieren, SQL generieren usw. können? LLMs sind für Aufgaben mit Mehrdeutigkeiten, Schlussfolgerungen oder natürlicher Sprache von unschätzbarem Wert. Im Vergleich zu prozeduralem Code können sie jedoch langsam, teuer und nicht deterministisch sein und manchmal unzuverlässige Ergebnisse liefern. Für die Datenbankoptimierung verfügen wir über bewährte, über Jahrzehnte entwickelte Algorithmen, die sich bewährt haben. Postgres MCP Pro kombiniert das Beste aus beiden Welten, indem LLMs mit klassischen Optimierungsalgorithmen und anderen prozeduralen Tools kombiniert werden.
Wie testen Sie Postgres MCP Pro? Tests sind entscheidend, um die Zuverlässigkeit und Genauigkeit von Postgres MCP Pro sicherzustellen. Wir entwickeln eine Reihe KI-generierter, gegnerischer Workloads, die Postgres MCP Pro auf die Probe stellen und seine Leistung in einer Vielzahl von Szenarien sicherstellen.
Welche Postgres-Versionen werden unterstützt? Unsere Tests konzentrieren sich derzeit auf Postgres 15, 16 und 17. Wir planen, die Postgres-Versionen 13 bis 17 zu unterstützen.
Wer hat dieses Projekt erstellt? Dieses Projekt wird von Crystal DBA erstellt und gepflegt.
Fahrplan
Wird noch bekannt gegeben
Sie und Ihre Bedürfnisse sind ein entscheidender Faktor für unsere Entwicklung. Teilen Sie uns Ihre Wünsche mit, indem Sie ein Issue oder einen Pull Request erstellen. Sie können uns auch über Discord kontaktieren.
Technische Hinweise
Dieser Abschnitt enthält einen allgemeinen Überblick über die technischen Überlegungen, die das Design von Postgres MCP Pro beeinflusst haben.
Index-Tuning
Entwickler wissen, dass fehlende Indizes eine der häufigsten Ursachen für Datenbank-Performance-Probleme sind. Indizes bieten Zugriffsmethoden, mit denen Postgres die für eine Abfrage benötigten Daten schnell finden kann. Bei kleinen Tabellen spielen Indizes kaum eine Rolle, doch mit zunehmender Datengröße wird der Unterschied in der algorithmischen Komplexität zwischen einem Tabellenscan und einer Indexsuche signifikant (typischerweise O ( n ) vs. O ( logn ), möglicherweise sogar mehr, wenn Verknüpfungen mehrerer Tabellen beteiligt sind).
Das Generieren vorgeschlagener Indizes in Postgres MCP Pro erfolgt in mehreren Schritten:
Identifizieren Sie SQL-Abfragen, die optimiert werden müssen . Wenn Sie wissen, dass Sie ein Problem mit einer bestimmten SQL-Abfrage haben, können Sie diese angeben. Postgres MCP Pro kann außerdem die Arbeitslast analysieren, um Indexoptimierungsziele zu identifizieren. Dazu nutzt es die Erweiterung
pg_stat_statements, die die Laufzeit und den Ressourcenverbrauch jeder Abfrage aufzeichnet.Eine Abfrage eignet sich für die Indexoptimierung, wenn sie – entweder pro Ausführung oder insgesamt – den höchsten Ressourcenverbrauch aufweist. Derzeit verwenden wir die Ausführungszeit als Indikator für den kumulativen Ressourcenverbrauch. Es kann jedoch auch sinnvoll sein, spezifische Ressourcen zu betrachten, z. B. die Anzahl der aufgerufenen oder gelesenen Blöcke. Das Tool
analyze_query_workloadkonzentriert sich auf langsame Abfragen und verwendet die durchschnittliche Zeit pro Ausführung mit Schwellenwerten für die Anzahl der Ausführungen und die durchschnittliche Ausführungszeit. Agenten können auchget_top_queriesaufrufen, das einen Parameter für die durchschnittliche vs. gesamte Ausführungszeit akzeptiert. Anschließend können diese Abfragenanalyze_query_indexesübergeben werden, um Indexempfehlungen zu erhalten.Ausgefeilte Indexoptimierungssysteme nutzen die „Workload-Komprimierung“, um eine repräsentative Teilmenge von Abfragen zu erstellen, die die Eigenschaften der gesamten Workload widerspiegelt und so das Problem für nachgelagerte Algorithmen reduziert. Postgres MCP Pro führt eine eingeschränkte Form der Workload-Komprimierung durch, indem es Abfragen normalisiert, sodass Abfragen, die aus derselben Vorlage generiert wurden, als eine einzige erscheinen. Jede Abfrage wird gleich gewichtet – eine Vereinfachung, die sich bei großen Indexierungsvorteilen bewährt.
Generieren von Kandidatenindizes: Sobald wir eine Liste von SQL-Abfragen haben, die wir durch Indizierung verbessern möchten, generieren wir eine Liste von Indizes, die wir möglicherweise hinzufügen möchten. Dazu analysieren wir das SQL und identifizieren alle Spalten, die in Filtern, Verknüpfungen, Gruppierungen oder Sortierungen verwendet werden.
Um alle möglichen Indizes zu generieren, müssen wir Kombinationen dieser Spalten berücksichtigen, da Postgres mehrspaltige Indizes unterstützt. In der vorliegenden Implementierung berücksichtigen wir nur eine zufällig ausgewählte Permutation jedes möglichen mehrspaltigen Indexes. Diese Vereinfachung dient der Reduzierung des Suchraums, da Permutationen oft eine gleichwertige Performance aufweisen. Wir hoffen jedoch, in diesem Bereich Verbesserungen zu erzielen.
Suche nach der optimalen Indexkonfiguration . Unser Ziel ist es, die Indexkombination zu finden, die die Performancevorteile optimal mit den Kosten für Speicherung und Pflege der Indizes in Einklang bringt. Wir schätzen die Leistungsverbesserung mithilfe der „Was wäre wenn?“-Funktionen der
hypopgErweiterung ab. Diese simuliert, wie der Postgres-Abfrageoptimierer eine Abfrage nach dem Hinzufügen von Indizes ausführt, und meldet Änderungen basierend auf dem tatsächlichen Postgres-Kostenmodell.Eine Herausforderung besteht darin, dass die Erstellung von Abfrageplänen in der Regel die Kenntnis der in der Abfrage verwendeten spezifischen Parameterwerte erfordert. Die Abfragenormalisierung, die zur Reduzierung der betrachteten Abfragen erforderlich ist, entfernt Parameterkonstanten. Über Bind-Variablen bereitgestellte Parameterwerte stehen uns ebenfalls nicht zur Verfügung.
Um dieses Problem zu lösen, erstellen wir realistische Konstanten, die wir als Parameter bereitstellen können, indem wir Stichproben aus den Tabellenstatistiken ziehen. In Version 16 hat Postgres eine generische „Explain Plan“-Funktionalität hinzugefügt, die jedoch Einschränkungen aufweist, beispielsweise im Zusammenhang mit
LIKEKlauseln, die unsere Implementierung nicht aufweist.Die Suchstrategie ist entscheidend, da die Auswertung aller möglichen Indexkombinationen nur in einfachen Situationen möglich ist. Darin unterscheiden sich die verschiedenen Indexierungsansätze am meisten. Basierend auf dem Anytime-Algorithmus von Microsoft verwenden wir eine Greedy-Search-Strategie. Dabei suchen wir zunächst die beste Ein-Index-Lösung und anschließend den besten Index, der hinzugefügt werden kann, um eine Zwei-Index-Lösung zu erhalten. Unsere Suche endet, wenn das Zeitbudget erschöpft ist oder eine Suchrunde keine Verbesserungen über die Mindestverbesserungsschwelle von 10 % hinaus liefert.
Kosten-Nutzen-Analyse . Wie entscheiden wir uns für eine Indizierungsalternative, wenn wir vor der Wahl stehen – eine mit besserer Performance und eine mit höherem Speicherplatzbedarf? Traditionell verlangen Indexberater ein Speicherbudget und optimieren die Leistung im Hinblick auf dieses Budget. Wir nehmen ebenfalls ein Speicherbudget, führen aber während der Optimierung eine Kosten-Nutzen-Analyse durch.
Wir formulieren dies als das Problem der Auswahl eines Punktes entlang der Pareto-Front – der Reihe von Auswahlmöglichkeiten, bei denen die Verbesserung einer Qualitätsmetrik notwendigerweise eine andere verschlechtert. In einer idealen Welt würden wir die Kosten des Speichers und den Nutzen der verbesserten Leistung in Geldbeträgen bewerten. Es gibt jedoch einen einfacheren und praktikableren Ansatz: die Veränderungen relativ zu betrachten. Die meisten Leute würden zustimmen, dass sich eine 100-fache Leistungsverbesserung lohnt, selbst wenn die Speicherkosten doppelt so hoch sind. In unserer Implementierung verwenden wir einen konfigurierbaren Parameter, um diesen Schwellenwert festzulegen. Standardmäßig verlangen wir, dass die Änderung im Logarithmus (Basis 10) der Leistungsverbesserung das Doppelte der Differenz im Logarithmus der Speicherplatzkosten beträgt. Dies führt dazu, dass für eine 100-fache Leistungsverbesserung maximal eine 10-fache Speicherplatzerhöhung möglich ist.
Unsere Implementierung ist eng mit dem Anytime-Algorithmus von Microsoft SQL Server verwandt. Im Vergleich zu Dexter , einem automatischen Indizierungstool für Postgres, durchsuchen wir einen größeren Datenraum und verwenden andere Heuristiken. Dies ermöglicht uns, bessere Lösungen zu generieren, allerdings auf Kosten einer längeren Laufzeit.
Wir zeigen außerdem die in jeder Suchrunde geleistete Arbeit, einschließlich eines Vergleichs der Abfragepläne vor und nach dem Hinzufügen jedes Indexes. Dies gibt dem LLM zusätzlichen Kontext, den es bei der Beantwortung der Indexierungsempfehlungen nutzen kann.
Experimentell: Index-Tuning durch LLM
Postgres MCP Pro enthält eine experimentelle Indexoptimierungsfunktion basierend auf der Optimierung durch LLM . Anstatt Heuristiken zur Untersuchung möglicher Indexkonfigurationen zu verwenden, stellen wir Datenbankschema und Abfragepläne einem LLM zur Verfügung und bitten ihn, Indexkonfigurationen vorzuschlagen. Anschließend verwenden wir hypopg , um die Leistung mit den vorgeschlagenen Indizes vorherzusagen. Diese Ergebnisse werden anschließend an den LLM zurückgesendet, um neue Vorschläge zu erstellen. Dieser Prozess wird wiederholt, bis mehrere Iterationsrunden keine weiteren Verbesserungen mehr ergeben.
Die Indexoptimierung durch LLM bietet Vorteile, wenn der Indexsuchraum groß ist oder Indizes mit vielen Spalten berücksichtigt werden müssen. Wie bei herkömmlichen suchbasierten Ansätzen basiert sie auf der Genauigkeit der hypopg Leistungsvorhersagen.
Um eine Indexoptimierung durch LLM durchzuführen, müssen Sie einen OpenAI-API-Schlüssel angeben, indem Sie die Umgebungsvariable OPENAI_API_KEY festlegen.
Datenbankintegrität
Datenbank-Integritätsprüfungen identifizieren Optimierungsmöglichkeiten und Wartungsbedarf, bevor diese zu kritischen Problemen führen. In der aktuellen Version adaptiert Postgres MCP Pro die Datenbank-Integritätsprüfungen direkt von PgHero . Wir arbeiten an der vollständigen Validierung dieser Prüfungen und werden sie möglicherweise in Zukunft erweitern.
Index-Integrität . Sucht nach ungenutzten, doppelten und aufgeblähten Indizes. Aufgeblähte Indizes nutzen Datenbankseiten ineffizient. Postgres Autovacuum bereinigt Indexeinträge, die auf tote Tupel verweisen, und kennzeichnet die Einträge als wiederverwendbar. Die Indexseiten werden jedoch nicht komprimiert, sodass sie möglicherweise nur wenige aktive Tupelreferenzen enthalten.
Puffercache-Trefferquote . Misst den Anteil der Datenbanklesevorgänge, die aus dem Puffercache statt von der Festplatte ausgeführt werden. Eine niedrige Puffercache-Trefferquote muss untersucht werden, da sie oft nicht kostenoptimal ist und zu einer verminderten Anwendungsleistung führt.
Verbindungsstatus . Überprüft die Anzahl der Verbindungen zur Datenbank und meldet deren Auslastung. Das größte Risiko besteht darin, dass keine Verbindungen mehr vorhanden sind. Aber auch eine hohe Anzahl inaktiver oder blockierter Verbindungen kann auf Probleme hinweisen.
Vakuum-Integrität . Vakuum ist aus vielen Gründen wichtig. Ein kritischer Grund ist die Verhinderung von Transaktions-ID-Wraparounds, die dazu führen können, dass die Datenbank keine Schreibvorgänge mehr annimmt. Der Postgres-Mechanismus zur Multiversions-Parallelitätskontrolle (MVCC) erfordert für jede Transaktion eine eindeutige Transaktions-ID. Da Postgres jedoch einen vorzeichenbehafteten 32-Bit-Integer für Transaktions-IDs verwendet, muss es Transaktions-IDs nach maximal 2 Milliarden Transaktionen wiederverwenden. Dazu „friert“ es die Transaktions-IDs historischer Transaktionen ein und setzt sie alle auf einen speziellen Wert, der eine ferne Vergangenheit anzeigt. Wenn Datensätze erstmals auf die Festplatte übertragen werden, werden sie für einen Bereich von Transaktions-IDs sichtbar geschrieben. Bevor diese Transaktions-IDs wiederverwendet werden, muss Postgres alle Datensätze auf der Festplatte aktualisieren und „einfrieren“, um die Verweise auf die wiederzuverwendenden Transaktions-IDs zu entfernen. Diese Prüfung sucht nach Tabellen, die vakuumiert werden müssen, um Transaktions-ID-Wraparounds zu verhindern.
Replikationsintegrität . Überprüft die Replikationsintegrität, indem die Verzögerung zwischen Primär- und Replikatserver überwacht, der Replikationsstatus überprüft und die Nutzung der Replikationsslots verfolgt wird.
Integrität der Einschränkungen . Im Normalbetrieb lehnt Postgres alle Transaktionen ab, die eine Einschränkungsverletzung verursachen würden. Ungültige Einschränkungen können jedoch nach dem Laden von Daten oder in Wiederherstellungsszenarien auftreten. Diese Prüfung sucht nach ungültigen Einschränkungen.
Sequenzzustand . Sucht nach Sequenzen, bei denen das Risiko besteht, dass ihr Maximalwert überschritten wird.
Postgres-Clientbibliothek
Postgres MCP Pro nutzt psycopg3 für die asynchrone E/A-Verbindung mit Postgres. Im Hintergrund nutzt psycopg3 die libpq- Bibliothek für die Verbindung mit Postgres und bietet Zugriff auf den gesamten Postgres-Funktionsumfang und eine zugrunde liegende Implementierung, die von der Postgres-Community vollständig unterstützt wird.
Einige andere Python-basierte MCP-Server verwenden asyncpg , was die Installation vereinfachen kann, da die libpq Abhängigkeit entfällt. Asyncpg ist wahrscheinlich auch schneller als psycopg3, was wir jedoch nicht selbst überprüft haben. Ältere Benchmarks berichten von einer größeren Leistungslücke, was darauf hindeutet, dass das neuere psycopg3 diese Lücke mit zunehmender Weiterentwicklung geschlossen hat.
Unter Berücksichtigung dieser Überlegungen haben wir uns für psycopg3 statt asyncpg entschieden. Wir sind weiterhin bereit, diese Entscheidung in Zukunft zu überdenken.
Verbindungskonfiguration
Wie der Referenz-PostgreSQL-MCP-Server verwendet Postgres MCP Pro beim Start die Postgres-Verbindungsinformationen. Dies ist praktisch für Benutzer, die sich immer mit derselben Datenbank verbinden, kann aber beim Datenbankwechsel umständlich sein.
Ein alternativer Ansatz, der von PG-MCP verfolgt wird, besteht darin, Verbindungsdetails während der Nutzung über MCP-Tool-Aufrufe bereitzustellen. Dies ist praktischer für Benutzer, die zwischen Datenbanken wechseln, und ermöglicht es einem einzigen MCP-Server, mehrere Endbenutzer gleichzeitig zu unterstützen.
Es muss einen besseren Ansatz geben. Beide weisen Sicherheitslücken auf: Nur wenige MCP-Clients speichern die MCP-Serverkonfiguration sicher (eine Ausnahme ist Goose), und über MCP-Tools bereitgestellte Anmeldeinformationen werden über das LLM weitergeleitet und im Chatverlauf gespeichert. Beide weisen in manchen Szenarien zudem Probleme mit der Benutzerfreundlichkeit auf.
Schemainformationen
Der Zweck des Schemainformationstools besteht darin, dem aufrufenden KI-Agenten die Informationen bereitzustellen, die er benötigt, um korrektes und leistungsfähiges SQL zu generieren. Angenommen, ein Benutzer fragt: „Wie viele Flüge starteten im vergangenen Jahr von San Francisco und landeten in Paris?“ Der KI-Agent muss die Tabelle finden, in der die Flüge gespeichert sind, die Spalten mit den Abflug- und Zielorten und möglicherweise eine Tabelle, die Flughafencodes und Flughafenstandorte zuordnet.
Warum sollten Schemainformationstools bereitgestellt werden, wenn LLMs im Allgemeinen in der Lage sind, SQL zu generieren, um diese Informationen direkt von Postgres abzurufen?
Unsere Erfahrungen mit Claude zeigen, dass das aufrufende LLM sehr gut SQL-Befehle zur Untersuchung des Postgres-Schemas generiert, indem es den Postgres-Systemkatalog und das Informationsschema (eine ANSI-standardisierte Datenbank-Metadatenansicht) abfragt. Wir wissen jedoch nicht, ob andere LLMs dies ebenso zuverlässig und leistungsfähig tun.
Wäre es besser, Schemainformationen mithilfe von MCP-Ressourcen statt MCP-Tools bereitzustellen?
Der PostgreSQL MCP-Referenzserver nutzt Ressourcen anstelle von Tools zur Bereitstellung von Schemainformationen. Die Navigation in Ressourcen ähnelt der Navigation in einem Dateisystem, daher ist dieser Ansatz in vielerlei Hinsicht naheliegend. Allerdings ist die Ressourcenunterstützung im MCP-Client-Ökosystem weniger verbreitet als die Toolunterstützung (siehe Beispielclients ). Obwohl der MCP-Standard den Zugriff auf Ressourcen entweder durch KI-Agenten oder Endbenutzer vorsieht, unterstützen einige Clients nur die menschliche Navigation im Ressourcenbaum.
Geschützte SQL-Ausführung
KI verstärkt die seit langem bestehenden Herausforderungen beim Schutz von Datenbanken vor einer Reihe von Bedrohungen – von einfachen Fehlern bis hin zu komplexen Angriffen durch böswillige Akteure. Unabhängig davon, ob die Bedrohung zufällig oder böswillig erfolgt, gilt ein ähnliches Sicherheitskonzept mit drei Zielen: Vertraulichkeit, Integrität und Verfügbarkeit. Das bekannte Spannungsfeld zwischen Komfort und Sicherheit ist ebenfalls deutlich spürbar.
Der geschützte SQL-Ausführungsmodus von Postgres MCP Pro legt den Schwerpunkt auf Integrität. Im Kontext von MCP sind wir besonders besorgt darüber, dass LLM-generiertes SQL Schäden verursacht – beispielsweise unbeabsichtigte Datenänderungen oder -löschungen oder andere Änderungen, die den Änderungsmanagementprozess eines Unternehmens umgehen könnten.
Der einfachste Weg, Integrität zu gewährleisten, besteht darin, sicherzustellen, dass alle SQL-Anweisungen, die für die Datenbank ausgeführt werden, schreibgeschützt sind. Eine Möglichkeit hierfür ist die Erstellung eines Datenbankbenutzers mit Lesezugriff. Obwohl dieser Ansatz sinnvoll ist, empfinden ihn viele in der Praxis als umständlich. Postgres bietet keine Möglichkeit, eine Verbindung oder Sitzung schreibgeschützt zu versetzen. Daher verwendet Postgres MCP Pro einen komplexeren Ansatz, um die schreibgeschützte SQL-Ausführung zusätzlich zu einer Lese-/Schreibverbindung sicherzustellen.
Postgres MCP bietet einen schreibgeschützten Transaktionsmodus, der Daten- und Schemaänderungen verhindert. Wie der Referenz-PostgreSQL-MCP-Server verwenden wir schreibgeschützte Transaktionen, um eine geschützte SQL-Ausführung zu gewährleisten.
Um diesen Mechanismus robust zu machen, müssen wir sicherstellen, dass SQL den schreibgeschützten Transaktionsmodus nicht irgendwie umgeht, etwa indem es eine COMMIT oder ROLLBACK -Anweisung ausgibt und dann eine neue Transaktion beginnt.
Beispielsweise kann der LLM den schreibgeschützten Transaktionsmodus umgehen, indem er eine ROLLBACK -Anweisung ausgibt und anschließend eine neue Transaktion startet. Beispiel:
ROLLBACK; DROP TABLE users;Um solche Fälle zu vermeiden, analysieren wir das SQL vor der Ausführung mithilfe der pglast -Bibliothek. Wir lehnen SQL ab, das commit oder rollback Anweisungen enthält. Hilfreicherweise erlauben die gängigen Postgres-Stored-Procedure-Sprachen, einschließlich PL/pgSQL und PL/Python, keine COMMIT oder ROLLBACK Anweisungen. Wenn Sie unsichere Stored-Procedure-Sprachen für Ihre Datenbank aktiviert haben, könnten unsere schreibgeschützten Schutzmechanismen umgangen werden.
Derzeit bietet Postgres MCP Pro zwei Schutzebenen für die Datenbank, eine an den beiden Enden des Komfort-/Sicherheitsspektrums.
„Unrestricted“ bietet maximale Flexibilität. Es eignet sich für Entwicklungsumgebungen, in denen Geschwindigkeit und Flexibilität an erster Stelle stehen und keine Notwendigkeit besteht, wertvolle oder sensible Daten zu schützen.
„Eingeschränkt“ bietet ein Gleichgewicht zwischen Flexibilität und Sicherheit. Es eignet sich für Produktionsumgebungen, in denen die Datenbank nicht vertrauenswürdigen Benutzern zugänglich ist und der Schutz wertvoller oder vertraulicher Daten wichtig ist.
Der uneingeschränkte Modus entspricht dem Ansatz des Autostart-Modus von Cursor , bei dem der KI-Agent mit eingeschränkter menschlicher Aufsicht oder Genehmigung arbeitet. Wir gehen davon aus, dass der Autostart in Entwicklungsumgebungen eingesetzt wird, in denen Fehler nur geringe Folgen haben, Datenbanken keine wertvollen oder sensiblen Daten enthalten und bei Bedarf neu erstellt oder aus Backups wiederhergestellt werden können.
Wir haben den eingeschränkten Modus konservativ gestaltet und setzen auf Sicherheit, auch wenn dies unbequem sein kann. Der eingeschränkte Modus ist auf schreibgeschützte Operationen beschränkt, und wir begrenzen die Ausführungszeit von Abfragen, um zu verhindern, dass lang andauernde Abfragen die Systemleistung beeinträchtigen. Wir werden in Zukunft möglicherweise Maßnahmen hinzufügen, um sicherzustellen, dass der eingeschränkte Modus sicher mit Produktionsdatenbanken verwendet werden kann.
Postgres MCP Pro-Entwicklung
Die folgenden Anweisungen richten sich an Entwickler, die mit Postgres MCP Pro arbeiten möchten, oder an Benutzer, die Postgres MCP Pro lieber aus der Quelle installieren möchten.
Lokales Entwicklungs-Setup
Installieren Sie uv :
curl -sSL https://astral.sh/uv/install.sh | shKlonen Sie das Repository :
git clone https://github.com/crystaldba/postgres-mcp.git cd postgres-mcpInstallieren Sie Abhängigkeiten :
uv pip install -e . uv syncFühren Sie den Server aus :
uv run postgres-mcp "postgres://user:password@localhost:5432/dbname"
Available Tools
9 toolsanalyze_db_healthARead-only
Analyzes database health. Here are the available health checks:
index - checks for invalid, duplicate, and bloated indexes
connection - checks the number of connection and their utilization
vacuum - checks vacuum health for transaction id wraparound
sequence - checks sequences at risk of exceeding their maximum value
replication - checks replication health including lag and slots
buffer - checks for buffer cache hit rates for indexes and tables
constraint - checks for invalid constraints
all - runs all checks You can optionally specify a single health check or a comma-separated list of health checks. The default is 'all' checks.
| Name | Required | Description | Default |
|---|---|---|---|
| health_type | No | Optional. Valid values are: all, buffer, connection, constraint, index, replication, sequence, vacuum. | all |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare readOnlyHint=true, and the description aligns with this by using 'analyzes' and describing read-only checks. The description adds value by explaining what each check examines (e.g., invalid indexes, connection utilization, vacuum health), which helps the agent understand the tool's behavior beyond the annotation.
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 well-structured with a lead sentence and a bulleted list of checks. It is appropriately sized given the number of checks, and each bullet adds necessary information. It is slightly long but not wasteful, earning a strong score.
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 an output schema present, the description does not need to explain return values. It thoroughly covers the input parameter, enumerates all health check options, and describes the default behavior, making it complete for an agent to select and invoke the tool correctly.
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 schema already lists valid values for health_type with 100% coverage. The description enhances this by explaining what each value does and explicitly noting that comma-separated lists are allowed, which is not in the schema. This additional semantic detail goes beyond the schema baseline.
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 purpose with a specific verb ('analyzes database health') and enumerates eight distinct health check categories. This distinguishes it from sibling tools like analyze_workload_indexes and execute_sql, which focus on other aspects of database operations.
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 clear context for using the tool by detailing each health check option and the default behavior. However, it does not explicitly state when to use this tool versus alternatives like analyze_workload_indexes, nor does it mention exclusions, so it falls short of full explicit guidance.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_query_indexesARead-only
Analyze a list of (up to 10) SQL queries and recommend optimal indexes
| Name | Required | Description | Default |
|---|---|---|---|
| method | No | Method to use for analysis | dta |
| queries | Yes | List of Query strings to analyze | |
| max_index_size_mb | No | Max index size in MB |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The readOnlyHint annotation already signals this is a safe read operation. The description adds the 'up to 10' query limit, which is a useful constraint, but does not disclose other behaviors such as the default analysis method ('dta'), the effect of 'max_index_size_mb', or potential latency. It adds minimal context beyond the annotations and purpose.
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 that conveys the core purpose and a key constraint without unnecessary words. Every word earns its place, and no filler or redundancy exists.
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 output schema exists and the annotations mark it read-only, the description is adequate for an AI to understand the tool's basic function. It captures the input limit and the goal. Missing is a note on when to use this vs. analyze_workload_indexes, but that is a usage nuance rather than a completeness gap. Overall it is complete for a simple analysis tool.
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%, so the input schema already documents all parameters. The description does not add additional meaning for 'queries', 'method', or 'max_index_size_mb' beyond what the schema provides. Baseline of 3 applies because the schema handles parameter documentation.
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 uses a specific verb ('Analyze'), names the resource ('SQL queries'), and clearly states the output ('recommend optimal indexes'). It distinguishes itself from the sibling tool 'analyze_workload_indexes' by noting the input is a list of up to 10 queries rather than a workload.
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 usage for a bounded set of queries (up to 10) but does not explicitly state when to prefer this tool over alternatives like 'analyze_workload_indexes' or 'explain_query'. There are no clear exclusions or alternative references, so guidance is implied rather than explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_workload_indexesBRead-only
Analyze frequently executed queries in the database and recommend optimal indexes
| Name | Required | Description | Default |
|---|---|---|---|
| method | No | Method to use for analysis | dta |
| max_index_size_mb | No | Max index size in MB |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The annotations already declare readOnlyHint=true, so the description's read-only analysis nature is consistent. It adds context that the analysis targets 'frequently executed queries' and produces index recommendations, but does not disclose any potential performance impact, the fact that it does not apply indexes, or what happens with the output beyond being a recommendation.
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 sentence that immediately states the tool's purpose without superfluous words. It is front-loaded with the action and object.
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 presence of an output schema and full schema parameter coverage, the description is minimally sufficient. However, it lacks information on the two methods ('dta' vs 'llm') and does not clarify how this tool differs from the closely named sibling 'analyze_query_indexes', which is a notable gap for selection.
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%, with both 'method' and 'max_index_size_mb' having descriptions. The tool description adds no parameter-specific semantics beyond the schema, so it does not exceed the baseline.
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 uses a specific verb ('Analyze') and identifies the resource ('frequently executed queries') and outcome ('recommend optimal indexes'), making the tool's function clear. However, it does not explicitly differentiate from the sibling tool 'analyze_query_indexes', which may operate on a single query rather than a workload.
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 like 'analyze_query_indexes' or 'get_top_queries'. It does not mention scenarios, prerequisites, or exclusions, leaving the agent to infer usage from the name and context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
execute_sqlBDestructive
Execute any SQL query
| Name | Required | Description | Default |
|---|---|---|---|
| sql | No | SQL to run | all |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The annotations include destructiveHint=true, which already alerts the agent to potential destructive side effects. The description's 'any' reinforces that the tool can execute non-read queries, but it adds no additional behavioral context such as permission requirements, transaction handling, or result format. This is a minimal contribution beyond the structured hint.
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 consists of one concise sentence, 'Execute any SQL query', which is immediately front-loaded and free of unnecessary elaboration. It optimizes brevity while conveying the essential 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 a simple SQL executor with a single parameter and an output schema, and the annotation provides a destructive warning. However, the description gives no context about when to use it (e.g., for arbitrary reads/writes) versus the specialized sibling tools, and it omits any caveats about side effects beyond the bare annotation. Given the tool's low complexity, this is adequate but not enriched, so it falls short of being fully contextual.
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 schema provides a single `sql` parameter with a description ('SQL to run') and a default, achieving 100% coverage. The tool description 'Execute any SQL query' adds no further meaning about the parameter's syntax, allowed statements, or formatting. Since the schema already documents the parameter, no compensating explanation is needed.
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 'Execute any SQL query' clearly states the tool's verb (execute) and resource (SQL query), making its core function unambiguous. However, it does not explicitly differentiate from sibling tools like explain_query or analyze_query_indexes, leaving the reader to infer its role as a general-purpose executor. This is clear but lacks explicit sibling differentiation.
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 doesn't mention that this is for arbitrary SQL execution while siblings handle query analysis, schema listing, or index insights, nor does it state any restrictions or prerequisites. This leaves the agent without direction for tool selection.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
explain_queryARead-only
Explains the execution plan for a SQL query, showing how the database will execute it and provides detailed cost estimates.
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | SQL query to explain | |
| analyze | No | When True, actually runs the query to show real execution statistics instead of estimates. Takes longer but provides more accurate information. | |
| hypothetical_indexes | No | A list of hypothetical indexes to simulate. Each index must be a dictionary with these keys: - 'table': The table name to add the index to (e.g., 'users') - 'columns': List of column names to include in the index (e.g., ['email'] or ['last_name', 'first_name']) - 'using': Optional index method (default: 'btree', other options include 'hash', 'gist', etc.) Examples: [ {"table": "users", "columns": ["email"], "using": "btree"}, {"table": "orders", "columns": ["user_id", "created_at"]} ] If there is no hypothetical index, you can pass an empty list. |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations declare readOnlyHint=true, so the tool is known to be a safe read operation. However, the description does not disclose that the 'analyze' parameter actually executes the query, which is an important behavioral nuance. No contradiction with annotations, but little added context beyond purpose.
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?
A single, clear sentence that immediately states what the tool does. No unnecessary words or repetition.
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 rich schema (100% param coverage) and existing output schema, the description is mostly sufficient. However, it could mention the optional analyze and hypothetical_indexes capabilities in the main description for quicker agent awareness, though these are covered in the schema.
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%, with detailed parameter descriptions including examples for hypothetical_indexes. The description itself adds no parameter-level information, so baseline 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?
Description clearly states the tool explains the execution plan for a SQL query, with specific verb 'explains' and resource 'execution plan'. It also mentions cost estimates, distinguishing it from execute_sql and analyze_query_indexes.
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?
Usage context is implied ('explains the execution plan') but no explicit guidance on when to use this tool versus alternatives like analyze_query_indexes or execute_sql. No exclusions or prerequisites are mentioned.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_object_detailsBRead-only
Show detailed information about a database object
| Name | Required | Description | Default |
|---|---|---|---|
| object_name | Yes | Object name | |
| object_type | No | Object type: 'table', 'view', 'sequence', or 'extension' | table |
| schema_name | Yes | Schema name |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations include readOnlyHint: true, which already indicates a safe read operation, and the description aligns with this by saying 'Show detailed information'. However, the description adds no extra behavioral context beyond the annotation, such as what constitutes 'detailed' or how missing objects are handled. With annotations present, the bar is lower, and the description meets the minimum without adding value.
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 front-loads the action and resource. It contains no filler or redundant wording, earning full marks for conciseness.
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 simplicity, an output schema (mentioned in context signals), and the fully described input schema, the description is largely adequate. However, it lacks explicit guidance on when to use this tool over siblings, which would improve completeness. The missing usage context is the main gap.
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%, with each parameter (schema_name, object_name, object_type) having a clear description. The tool description itself adds no parameter-specific meaning beyond the schema, so the baseline of 3 applies. object_type's default value and allowed values are already in the schema.
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 'Show detailed information about a database object' uses a specific verb ('Show') and resource ('database object'), making the core purpose clear. It distinguishes itself from sibling tools like 'list_objects' (which likely enumerates objects) by focusing on details of a single object, but it does not explicitly state this differentiation.
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?
No guidance is provided on when to use this tool versus alternatives. The description doesn't mention that this tool is for inspecting a specific object as opposed to listing all objects, nor does it describe any prerequisites or exclusions. The user must infer usage from the tool name and sibling context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_top_queriesARead-only
Reports the slowest or most resource-intensive queries using data from the 'pg_stat_statements' extension.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | Number of queries to return when ranking based on mean_time or total_time | |
| sort_by | No | Ranking criteria: 'total_time' for total execution time or 'mean_time' for mean execution time per call, or 'resources' for resource-intensive queries | resources |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations declare readOnlyHint: true, so the safe nature is already known. The description adds useful context about the data source (pg_stat_statements) but does not disclose prerequisites like extension availability or any limitations on the reported data.
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?
A single, clear sentence that front-loads the purpose and names the data source. No wasted words or redundant information.
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 description is simple and self-contained, naming the data source and purpose. Output schema and parameter schema cover the remaining details. A minor gap is not mentioning that the pg_stat_statements extension must be installed for the tool to work.
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 100% coverage for both parameters, including explanations for valid sort_by values. The tool description adds no extra parameter-level detail, 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 clearly states the action ('Reports') and the resource ('slowest or most resource-intensive queries') with a specific data source ('pg_stat_statements'). This distinguishes it from siblings like explain_query and analyze_query_indexes, which focus on different aspects.
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?
There is no explicit guidance on when to use this tool versus the sibling analysis tools. No mention of prerequisites, appropriate contexts, or exclusions; the intended use is only implied by the name and description.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_objectsCRead-only
List objects in a schema
| Name | Required | Description | Default |
|---|---|---|---|
| object_type | No | Object type: 'table', 'view', 'sequence', or 'extension' | table |
| schema_name | Yes | Schema name |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The description adds no behavioral context beyond the readOnlyHint annotation; it simply restates the tool's purpose in a generic way. It does not mention pagination, default object_type behavior, or scope limitations, and because annotations already declare read-only, the description provides no additional transparency.
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 concise (a single sentence) and free of fluff, but it is also under-specified and essentially repeats the title. It lacks any structured detail (e.g., parameter mentions, usage context) that would make the sentence earn its place beyond the obvious.
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 simplicity, the input schema, readOnlyHint annotation, and presence of an output schema provide sufficient context for an agent to use it correctly. The description, while minimal, correctly states the high-level function, which is adequate for a straightforward list operation.
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 (schema_name required, object_type with allowed values), giving 100% schema description coverage. The description adds no parameter-level meaning, but the schema already handles the 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 identifies the action (list) and resource (objects in a schema), which is a specific verb+resource combination. However, it does not mention the object types or differentiate from sibling tools like get_object_details, so it lacks the scope and differentiation needed for a 5.
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 such as list_schemas or get_object_details. There is no context about prerequisites, exclusions, or typical use cases, so the agent receives no decision-support information.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_schemasARead-only
List all schemas in the database
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare readOnlyHint=true, which covers safety. The description adds the scope 'all schemas' but does not disclose other behavioral traits like ordering, pagination, or return format. With annotations present, a neutral score is appropriate.
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, 'List all schemas in the database', with no wasted words. It front-loads the action and object clearly.
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?
For a simple read-only tool with no parameters and an output schema, the description fully covers the necessary context. It is complete without over-explaining, and annotations cover the safety profile.
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 tool has zero parameters, so the baseline is 4. The description adds no param info, but none is needed; the empty schema is self-explanatory.
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 uses a specific verb 'List' with a clear resource 'schemas' and scope 'in the database'. It distinguishes from siblings like list_objects and get_object_details by explicitly focusing on schemas.
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 clearly implies when to use the tool (when needing all schemas), but it does not explicitly state alternatives or exclusions. The presence of siblings like list_objects suggests a need for more differentiation, but none is provided.
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.
9 tool updates
v0.1.1- Added
analyze_db_health - Added
analyze_query_indexes - Added
analyze_workload_indexes - Added
execute_sql - Added
explain_query - Added
get_object_details - Added
get_top_queries - Added
list_objects - Added
list_schemas
9 tool updates
v0.3.0- Removed
analyze_db_health - Removed
analyze_query_indexes - Removed
analyze_workload_indexes - Removed
execute_sql - Removed
explain_query - Removed
get_object_details - Removed
get_top_queries - Removed
list_objects - Removed
list_schemas
9 tool updates
v1.0.0- First observed
analyze_db_health - First observed
analyze_query_indexes - First observed
analyze_workload_indexes - First observed
execute_sql - First observed
explain_query - First observed
get_object_details - First observed
get_top_queries - First observed
list_objects - First observed
list_schemas
TDQS
Scored across 9 tools
Each tool targets a distinct aspect of database interaction: health checks, index analysis, query execution, explain plans, object details, top queries, and listing schemas/objects. There is no overlap; the two index analysis tools are differentiated by input (specific queries vs. workload).
All tool names follow a consistent verb_noun pattern in snake_case (analyze_, execute_, explain_, get_, list_). Verbs like 'analyze', 'execute', 'explain', 'get', and 'list' are used uniformly, making the naming predictable.
With 9 tools, the set is well-scoped for a Postgres MCP server covering health analysis, index optimization, query execution, and schema exploration. It neither feels sparse nor overwhelming, earning its place.
The tool set covers analysis and ad-hoc queries comprehensively via execute_sql, but lacks explicit tools for creating, altering, or dropping database objects. However, execute_sql enables these operations indirectly, making the gap minor.
Maintenance
Related MCP Connectors
MCP server for building and testing AI agents with multi-model experimentation and insights.
Analytical memory for AI agents: a real Postgres queried in plain English over MCP. One command.
- XataOAuthio.github.xataio
Xata MCP server lets AI agents interact with your Xata projects, and Postgres database branches.
The Mercado Pago MCP Server implements the Model Context Protocol to provide AI agents and LLMs with access to Mercado Pago's APIs and tools within compatible development environments. It acts as an intermediary that translates Mercado Pago resources into executable functions (tools) that AI applications can invoke to perform actions and automate flows. The server simplifies integration, enables using documentation to implement or improve code, and optimizes operations through natural language interactions without manual implementations.
Related MCP Servers
- AlicenseBqualityDmaintenanceA Model Context Protocol server that enables powerful PostgreSQL database management capabilities including analysis, schema management, data migration, and monitoring through natural language interactions.181,631 npm201AGPL 3.0
- AlicenseBqualityDmaintenanceAn open source Model Context Protocol server for PostgreSQL that provides database health analysis, index tuning, query plan exploration, and safe SQL execution for AI agents throughout the development process.9MIT
- AlicenseNot gradedqualityNot gradedmaintenanceAn open-source MCP server that provides AI agents with advanced PostgreSQL capabilities including index tuning, query plan optimization, and comprehensive database health analysis. It supports safe SQL execution through configurable access modes and offers both stdio and SSE transport options for various development environments.MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol (MCP) Server that allows AI models to securely interact with data hosted in Azure Database for PostgreSQL. It enables natural language querying, schema exploration, and data management through MCP clients like Claude Desktop and Visual Studio Code.MIT