PGFacade
Provides typed MCP tools for interacting with a PostgreSQL database, including describing tables, selecting rows, counting rows, and performing permitted insert/update/delete operations according to configured read-only and permission settings.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
PGFacade
A typed PostgreSQL API shared by REST, MCP, and Python callers. Requests are Pydantic models discriminated by kind; PostgreSQL grants and the caller's principal determine access.
For deployment instructions, see the deployment guide.
Use it with an AI assistant
PGFacade runs as a local MCP server. The assistant gets typed tools such as pg_table_describe, pg_rows_select, and pg_rows_count instead of a raw SQL connection.
The only prerequisite is uv. Nothing else needs installing: uvx fetches and runs PGFacade.
Install
Pick one.
Claude Code plugin. Claude Code asks for the connection string and whether to stay read-only. The plugin adds the postgres MCP server and a skill that tells the assistant how to query efficiently.
/plugin install pg-facade --marketplace Magic-Man-us/agent-pg-facadeClaude Code, one command.
claude mcp add postgres \
-e PGFACADE_DSN='postgresql://user:password@localhost:5432/mydb' \
-e PGFACADE_READ_ONLY=true \
-- uvx --from git+https://github.com/Magic-Man-us/agent-pg-facade pgfacade mcpAny MCP client. Add this to the client's MCP configuration (.mcp.json for Claude Code, claude_desktop_config.json for Claude Desktop):
{
"mcpServers": {
"postgres": {
"command": "uvx",
"args": ["--from", "git+https://github.com/Magic-Man-us/agent-pg-facade", "pgfacade", "mcp"],
"env": {
"PGFACADE_DSN": "postgresql://user:password@localhost:5432/mydb",
"PGFACADE_READ_ONLY": "true"
}
}
}
}Then ask the assistant something about your data, for example "describe the orders table and count rows created this week".
Choose the database
PGFACADE_DSN is the only thing that selects the database. A remote database is the same setting with its host:
postgresql://user:password@db.example.com:5432/mydb?sslmode=requirePercent-encode special characters in the password. Add sslmode=require for any database you reach over a network.
Test a connection string before giving it to an assistant:
PGFACADE_DSN='postgresql://user:password@db.example.com:5432/mydb?sslmode=require' PGFACADE_READ_ONLY=true \
uvx --from git+https://github.com/Magic-Man-us/agent-pg-facade pgfacade checkConnected to mydb as user (PostgreSQL 17.2)
Mode: read-only
Tables visible: 12
Tools exposed: 20A failure prints the database's own reason, such as a rejected password or an unreachable host, and exits with status 1.
To change the database later:
Plugin: run
/plugin configureand enter the new connection string.claude mcp addor a configuration file: changePGFACADE_DSNand restart the client.
To use several databases, register the server once per database under different names, each with its own PGFACADE_DSN:
{
"mcpServers": {
"postgres-local": {
"command": "uvx",
"args": ["--from", "git+https://github.com/Magic-Man-us/agent-pg-facade", "pgfacade", "mcp"],
"env": {"PGFACADE_DSN": "postgresql://user:password@localhost:5432/dev"}
},
"postgres-prod": {
"command": "uvx",
"args": ["--from", "git+https://github.com/Magic-Man-us/agent-pg-facade", "pgfacade", "mcp"],
"env": {
"PGFACADE_DSN": "postgresql://reader:password@db.example.com:5432/prod?sslmode=require",
"PGFACADE_READ_ONLY": "true"
}
}
}
}What the assistant can do
PGFACADE_READ_ONLY=true exposes 20 read tools and runs every transaction read-only. Remove it to add six write tools, including pg_rows_insert, pg_rows_update, and pg_rows_delete. Raw SQL, schema changes, admin operations, migrations, and notifications stay off until you enable their flag in Permissions. Every tool is listed in the tool reference; pgfacade ops prints the same catalog.
A local stdio session needs no API key: it runs as the database user in PGFACADE_DSN, so connect as a user that holds only the privileges the assistant should have. The server tells the assistant which tables exist when the session starts (up to 50, with estimated row counts). The REST API and MCP over HTTP always require keys.
Related MCP server: PostgreSQL MCP Server
API contract: version 0.5
Python, HTTP, and MCP share the application-owned operation contract:
{"kind":"rows.count","input":{"table":"app.notes"}}{"kind":"rows.count","outcome":{"status":"success","data":{"count":3}}}{"kind":"rows.count","outcome":{"status":"error","error":{"code":"forbidden","reason":"policy_denied","message":"Operation is forbidden","status":403,"sqlstate":null,"details":{"kind":"authorization","reason":"policy_denied"}}}}HTTP POST /call and generated operation routes accept the operation directly. MCP tools take it as their typed request argument. HTTP uses the application error's status; MCP marks failed outcomes with isError. Authentication and protocol failures use a standalone error outcome because no operation has executed.
GET /ops returns permitted operation metadata. /docs contains generated schemas; /healthz is local liveness metadata.
Permissions
Each API key maps to a Principal. Every database operation applies its mapped role with SET LOCAL ROLE. Runtime roles must not own tables or inherit the schema-owner role. The server-wide capability flags cap each principal's permissions; all optional capabilities default off. Network server startup requires API keys or explicit group-policy configuration; a local stdio MCP session without keys runs as the connector user.
Capability | Default | Purpose |
| false | Deny writes for the server or principal |
| false | Raw SQL and SQL-bodied objects |
| false | Structured schema changes |
| false | Roles, maintenance, lifecycle management, diagnostics |
| false | Alembic migrations |
| false | Notification sending, listening, and watches |
| 0 | Background lifecycle execution |
The restricted deployment has separate reader and writer database roles and no administrator privileges. Named keys may share a database role but should not share credential values. The key-file loader validates its contents and excludes credentials from normal settings representations and error messages. Keys are loaded at startup; changes require a restart.
A connector that can switch between several roles holds their combined authority. Raw SQL must be restricted to callers trusted with that authority. PostgreSQL's normal public catalog visibility remains. Separate applications with different trust levels need separate connectors and deployments.
Python
from pgfacade import ExecutionContext, PgFacade, PgSettings, Success
from pgfacade.contracts.rows import RowsSelect, RowsSelectInput
async with PgFacade(PgSettings()) as app:
request = RowsSelect(input=RowsSelectInput(table="app.notes", limit=20))
response = await app.call(request, ExecutionContext())
if isinstance(response.outcome, Success):
page = response.outcome.data
else:
error = response.outcome.errorA concrete request infers its response: RowsSelect returns ResponseEnvelope[QueryResult]. ExecutionContext carries the trusted principal and transport provenance. HTTP and MCP construct it after authentication; clients cannot supply it in request JSON.
transaction() and Batch group operations. Batch children use the same request and response envelopes; a child failure rolls back the transaction and becomes the outer failure. Migrations, backend cancellation, and query-cache reload are rejected inside transactions and batches.
The curated query library provides parameterized row/table queries without raw SQL permission. Built-in server diagnostics require administrator permission. Custom SQL files are trusted server code and must not be writable by API callers.
Development
See development setup. Run the standard checks with uv run --locked tox.
uv sync --locked
uv run --locked tox
./deploy/testThe first test command runs database-independent tests and skips explicitly marked integration cases. deploy/test creates a unique scratch database, runs the full suite as the PostgreSQL OS account, and cleans up. It never targets the application database. It requires local PostgreSQL, system Python 3.12, uv, and noninteractive sudo.
Before updating the running service:
./deploy/test && ./deploy/updatedeploy/update builds a frozen source snapshot, installs a versioned release, checks the host and API, and rolls back failed activation. It does not pull Git changes or modify credentials.
Code map
PgFacade, defined in facade.py, applies shared policy and runs the handler that the OPERATIONS catalog in registry.py holds for the request's kind. webmcp.py owns the FastMCP server; webapp.py owns the FastAPI application; CLI and middleware live in presentation; PostgreSQL and process resources live in infrastructure. Import the public facade, settings, enums, and envelopes from pgfacade; use the owning package for specialized models and integrations.
Path | Responsibility |
Typed operation requests, results, enums, and envelopes | |
Execution context, operation metadata, handlers, and application errors | |
Principals' identities, credential checks, providers, and group policies | |
Runtime settings, database variants, and configuration sources | |
PostgreSQL pools, transactions, SQL composition, query resources, and startup processes | |
Single FastAPI factory and REST routes | |
Single FastMCP factory for stdio and MCP HTTP | |
CLI commands and request middleware | |
Shared scalar types and Pydantic configuration presets | |
Service units, updates, checks, backups, recovery |
The deployed service starts REST only. MCP HTTP tool calls authenticate independently; protocol discovery is not authenticated. See the security verification record for tested boundaries and remaining operational requirements.
For embedded MCP HTTP servers, use pgfacade.webmcp.create_mcp_http_app(); create_mcp() supplies the stdio and in-memory server. REST and the MCP HTTP app enforce max_request_bytes and request_read_timeout_s. The MCP CLI installs the same limits for both HTTP and SSE transports.
Group-policy prototype and YAML/TOML settings
File configuration and group policies documents the mock/stub identity interface, group-scoped rules, database configuration, and provider injection. Both YAML and TOML use Pydantic Settings. No Google lookup is implemented. The existing production API-key profile is unchanged unless access_control is explicitly configured.
An optional startup_command waits for a complete READY line from either stdout or stderr before opening the database. See listener command configuration.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-
- FlicenseAqualityDmaintenanceEnables AI agents to inspect and query PostgreSQL databases safely, with features like listing tables, retrieving schemas, and running read-only SQL queries.3-
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.1ISC
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.2ISC