Позволяет AI-агентам выполнять запросы, изменять и проверять базы данных PostgreSQL, управлять профилями подключений и диагностировать производительность.
Также известен как microsoft/postgres-mcp, @microsoft/postgres-mcp
- Звёзды
- 87
- Инструменты
- —
- Загрузки, 30 дней
- —
- Последняя версия
- —
- Последний коммит
- 5 нояб. 2026 г.
- Лицензия
- MIT
Что такое PostgreSQL MCP?
PostgreSQL — это MCP server. Позволяет AI-агентам выполнять запросы, изменять и проверять базы данных PostgreSQL, управлять профилями подключений и диагностировать производительность.
Сводка сгенерирована из README проекта
О PostgreSQL MCP server
Агенты разработки, которым необходимо работать напрямую с базой данных PostgreSQL, могут использовать postgres-mcp для выполнения запросов, проектирования схем, диагностики и импорта CSV. Сервер работает на Node.js 22+ через stdio и запускается через npx без необходимости предварительной установки. Он совместим с любым MCP-клиентом, включая GitHub Copilot, Claude Code, Codex, Open Code, Cursor, VS Code и Claude Desktop. Конфигурации клиентов лишь указывают на команду запуска npx и не содержат учетных данных; агент подхватывает сохраненный профиль во время выполнения.
Профили создаются один раз с помощью команды connection add из libpq URI или строки key=value, а пароль хранится в системном хранилище ключей, а не в конфигурационном файле. В headless-режимах или средах CI, где нет доступа к хранилищу ключей, можно передать строку подключения через переменные окружения. Для профилей Azure автоматически выбирается Microsoft Entra ID без хранения пароля в хранилище ключей. Набор инструментов включает SQL только для чтения через postgres_mcp_query, DDL и DML через postgres_mcp_modify, скрипты CREATE для таблиц, индексов, функций и последовательностей, описание CSV и массовую загрузку через COPY, проверку возможностей и группы метрик производительности.
Контроль доступа осуществляется на уровне ролей базы данных, так как сервер выполняет запросы от имени этого пользователя; профили только для чтения настраиваются параметром access_mode: ro. Чтение локальных файлов ограничено рабочей директорией запуска, если пути не разрешены явно, а секретные данные удаляются из сообщений об ошибках.
Что вы можете с ним делать
- 1Получение последних заказов из PostgresПопросите агента показать десять последних заказов, чтобы проверить тестовые данные, не открывая SQL-клиент.
- 2Поиск узких мест в базе данныхПопросите агента собрать группы метрик производительности, чтобы понять, что именно замедляет работу сервера в данный момент.
- 3Список таблиц в базе данныхПолучите перечень таблиц в подключенной базе данных в качестве отправной точки для работы со схемой.
Взято из README проекта. Каждый вариант использования проверен на соответствие цитате из него.
Как установить PostgreSQL MCP
Форматы проверены 10 ноя 2026Установка PostgreSQL MCP в Claude Code
$ claude mcp add postgres-mcp -- npx -y @microsoft/postgres-mcpУстановка PostgreSQL MCP в Cursor
~/.cursor/mcp.json
{
"mcpServers": {
"postgres-mcp": {
"command": "npx",
"args": [
"-y",
"@microsoft/postgres-mcp"
]
}
}
}Установка PostgreSQL MCP в VS Code
.vscode/mcp.json
{
"servers": {
"postgres-mcp": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@microsoft/postgres-mcp"
]
}
}
}Установка PostgreSQL MCP в Claude Desktop
claude_desktop_config.json
{
"mcpServers": {
"postgres-mcp": {
"command": "npx",
"args": [
"-y",
"@microsoft/postgres-mcp"
]
}
}
}Установка PostgreSQL MCP в Codex
~/.codex/config.toml
[mcp_servers.postgres-mcp] command = "npx" args = ["-y", "@microsoft/postgres-mcp"]
Установка PostgreSQL MCP в Gemini CLI
~/.gemini/settings.json
{
"mcpServers": {
"postgres-mcp": {
"command": "npx",
"args": [
"-y",
"@microsoft/postgres-mcp"
]
}
}
}Автоматические проверки
Запущено 13 нояб. 2026 г.Полный отчёт →Прошло наши автоматизированные проверки. Это не аудит безопасности: изучите код и предоставьте серверу минимально необходимый доступ. Как работают проверки
- Связанный и доступный исходный репозиторийПройдено
- Open source лицензия (OSI)Пройдено
- Коммит или релиз за последний годПройдено
- Имя пакета не похоже на популярный пакетПройдено
- Удаленная конечная точка использует HTTPSНе проверялось
- Деструктивные инструменты помеченыНе проверялось
- Нет скрытых инструкций для моделиПройдено
- Нет критических уязвимостей в пакете и зависимостяхНе проверялось
README
Открыть на GitHubPostgres MCP Server
Connect your coding agent to PostgreSQL. postgres-mcp lets you generate
queries and run analytics, design database schemas, diagnose performance of the
server and queries, securely manage connections, and import data. It is
compatible with any MCP client — GitHub Copilot, Claude Code, Codex, Open Code,
Cursor, VS Code, and more.
- npm: https://www.npmjs.com/package/@microsoft/postgres-mcp
- No install required — run it straight from
npx.
Quick start
1. Save a connection profile
Create a named profile once — the password is stored in your OS keyring, never in a config file:
# add a profile from a libpq URI or key=value string
npx -y @microsoft/postgres-mcp connection add local \
"postgresql://postgres@localhost:5432/postgres"
# store its password securely (hidden prompt)
npx -y @microsoft/postgres-mcp connection set-password local
# check it
npx -y @microsoft/postgres-mcp connection list
Profiles created by
connection addpermit write tools unlessaccess_mode: rois set. For autonomous agents that should not write, use an explicit read-only profile and a read-only database role — see Read-only profiles.
2. Add postgres-mcp to your coding agent
The server speaks MCP over stdio. Point your client at
npx @microsoft/postgres-mcp run — no credentials go in the client config; the
coding agent discovers and connects to your saved profile at runtime.
GitHub Copilot CLI, Claude Code, Cursor & Claude Desktop — clients that use the mcpServers format (~/.copilot/mcp-config.json, mcp.json, .cursor/mcp.json, claude_desktop_config.json, …):
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@microsoft/postgres-mcp", "run"]
}
}
}
Running headless or in CI, without a keyring? The server can also take a database connection string from the environment — see Connecting without a profile in the guide.
3. Ask your coding agent
"List the tables in my PostgreSQL database." "Show me the 10 most recent orders from my PostgreSQL database." "What's slowing down my PostgreSQL server right now?"
The agent calls the server's tools (postgres_mcp_connect,
postgres_mcp_query, postgres_mcp_db_context, …) for you.
What it can do
| Area | Tools |
|---|---|
| Connections | list / add / remove profiles, connect, disconnect, list databases |
| Query | read‑only SQL (postgres_mcp_query), DDL/DML (postgres_mcp_modify) |
| Schema | fetch CREATE scripts for tables, indexes, functions, sequences… |
| Data | describe a CSV, bulk‑load a CSV via COPY |
| Diagnostics | probe server capabilities, collect performance metric groups |
See the usage guide for tools, configuration, authentication (including Microsoft Entra ID), TLS, and the security model.
Security in one minute
- The server doesn't decide what's allowed — your database does. It just passes requests along to PostgreSQL and runs them as the database user in your connection profile. It can't tell the difference between a request you meant to make and one the AI invented or was tricked into making, so anything that database user can do, the AI can do. What actually protects you is the permissions you give that user, the approval prompts in your MCP client, and the model you choose to run. See Security model for who's responsible for what, plus a checklist for locking things down.
postgres_mcp_queryis read‑only. Omitted profileaccess_modepermits write tools; setaccess_mode: roand use a read-only database role unless writes are intentionally delegated.- Microsoft Entra ID (AAD) is selected automatically for Azure profiles without a stored keyring password. Store a profile password to use password authentication instead.
- Local file reads (
postgres_mcp_bulk_load_csv,postgres_mcp_describe_csv) are limited to the MCP server's startup working directory by default and paths allowed withallow-access-to-path <path>. A file allows only itself; a directory allows recursive access. - Secrets are scrubbed from error messages before they leave the process.
See more info about security model in the usage guide.
Requirements
- Node.js 22+ (to run via
npx). - Linux x64/arm64, macOS x64/arm64, or Windows x64. Windows ARM uses x64 emulation.
- A reachable PostgreSQL database — local, Docker, on‑premises, Azure Database for PostgreSQL, Amazon RDS/Aurora, Google Cloud SQL/AlloyDB, or any wire‑compatible server.
Changelog
See CHANGELOG.md for release notes.
License
This repository is a getting started information package. It is licensed under the MIT License © Microsoft. The postgres-mcp project itself is proprietary and its source code is not avialable under MIT license.
Вопросы о PostgreSQL MCP
Как добавить PostgreSQL MCP в Claude Code?
Выполните claude mcp add postgres-mcp -- npx -y @microsoft/postgres-mcp в терминале. Добавьте --scope user, чтобы сервер был доступен во всех проектах.
Как добавить PostgreSQL MCP в Cursor?
Откройте ~/.cursor/mcp.json и добавьте сервер в mcpServers, используя конфигурацию Cursor из раздела установки выше.
Как подключить postgres-mcp к Claude Code или GitHub Copilot?
Добавьте запись stdio, указывающую на npx @microsoft/postgres-mcp run, в конфигурацию mcpServers вашего клиента; учетные данные в этот конфиг вносить не нужно.
Где хранится пароль от базы данных?
Пароли сохраняются в системном хранилище ключей (OS keyring) с помощью команды connection set-password, а не в конфигурационном файле.
Инструмент для запросов работает только на чтение?
Да, postgres_mcp_query работает только на чтение, но доступны и инструменты для записи, если в профиле не установлен параметр access_mode: ro.
Можно ли использовать его без сохранения профиля, например, в CI?
Да, если системное хранилище ключей недоступно, сервер может принять строку подключения к базе данных из переменных окружения.
Какая версия Node.js требуется?
Для запуска через npx требуется Node.js версии 22 или новее.