Skip to main content
Glama
PGFacade

PGFacade

by Magic-Man-us

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-facade

Claude 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 mcp

Any 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=require

Percent-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 check
Connected to mydb as user (PostgreSQL 17.2)
Mode: read-only
Tables visible: 12
Tools exposed: 20

A 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 configure and enter the new connection string.

  • claude mcp add or a configuration file: change PGFACADE_DSN and 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

read_only

false

Deny writes for the server or principal

allow_raw_sql

false

Raw SQL and SQL-bodied objects

allow_ddl

false

Structured schema changes

allow_admin

false

Roles, maintenance, lifecycle management, diagnostics

allow_migrate

false

Alembic migrations

allow_listen

false

Notification sending, listening, and watches

lifecycle_sweep_s

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.error

A 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/test

The 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/update

deploy/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

contracts

Typed operation requests, results, enums, and envelopes

application

Execution context, operation metadata, handlers, and application errors

authorization

Principals' identities, credential checks, providers, and group policies

configuration

Runtime settings, database variants, and configuration sources

infrastructure

PostgreSQL pools, transactions, SQL composition, query resources, and startup processes

webapp.py

Single FastAPI factory and REST routes

webmcp.py

Single FastMCP factory for stdio and MCP HTTP

presentation

CLI commands and request middleware

shared

Shared scalar types and Pydantic configuration presets

deploy

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…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Provides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.
      1
      -
    • F
      license
      A
      quality
      D
      maintenance
      Enables AI agents to inspect and query PostgreSQL databases safely, with features like listing tables, retrieving schemas, and running read-only SQL queries.
      3
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to safely interact with PostgreSQL databases, perform queries, inspect schemas, and analyze query performance.
      2
      ISC