{"id":47725923,"url":"https://github.com/peter-trerotola/goro-pg","last_synced_at":"2026-04-02T20:26:44.392Z","repository":{"id":342882468,"uuid":"1174900063","full_name":"peter-trerotola/goro-pg","owner":"peter-trerotola","description":"Read-only PostgreSQL MCP server with schema intelligence","archived":false,"fork":false,"pushed_at":"2026-03-28T16:35:02.000Z","size":296,"stargazers_count":1,"open_issues_count":3,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-03-28T18:28:48.494Z","etag":null,"topics":["claude","database","go","llm","mcp","model-context-protocol","postgresql","read-only"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/peter-trerotola.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-07T01:00:03.000Z","updated_at":"2026-03-28T16:33:58.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/peter-trerotola/goro-pg","commit_stats":null,"previous_names":["peter-trerotola/go-postgres-mcp","peter-trerotola/goro-pg"],"tags_count":32,"template":false,"template_full_name":null,"purl":"pkg:github/peter-trerotola/goro-pg","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peter-trerotola%2Fgoro-pg","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peter-trerotola%2Fgoro-pg/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peter-trerotola%2Fgoro-pg/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peter-trerotola%2Fgoro-pg/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/peter-trerotola","download_url":"https://codeload.github.com/peter-trerotola/goro-pg/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peter-trerotola%2Fgoro-pg/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31315913,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T12:59:32.332Z","status":"ssl_error","status_checked_at":"2026-04-02T12:54:48.875Z","response_time":89,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["claude","database","go","llm","mcp","model-context-protocol","postgresql","read-only"],"created_at":"2026-04-02T20:26:43.734Z","updated_at":"2026-04-02T20:26:44.385Z","avatar_url":"https://github.com/peter-trerotola.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# goro-pg\n\n[![CI](https://github.com/peter-trerotola/goro-pg/actions/workflows/ci.yml/badge.svg)](https://github.com/peter-trerotola/goro-pg/actions/workflows/ci.yml)\n[![Release](https://github.com/peter-trerotola/goro-pg/actions/workflows/release.yml/badge.svg)](https://github.com/peter-trerotola/goro-pg/releases)\n[![Go Report Card](https://goreportcard.com/badge/github.com/peter-trerotola/goro-pg)](https://goreportcard.com/report/github.com/peter-trerotola/goro-pg)\n[![Go Reference](https://pkg.go.dev/badge/github.com/peter-trerotola/goro-pg.svg)](https://pkg.go.dev/github.com/peter-trerotola/goro-pg)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n\n```\n                           .-------------------------.\n                           | how many signups today? |\n                           '--.----------------------'\n                              |\n   ____  ______  ___          ,_---~~~~~----._\n  /    )/      \\/   \\      _,,_,*^____    ___``*g*\\\"*,\n (     / __    _\\    )    / __/ /'    ^. /     \\ ^@q  f\n  \\    (/ o)  ( o)   )   [  @f | @))   || @))   l 0 _/\n   \\_  (_  )   \\ )  /     \\`/   \\~___ / _ \\____/   \\\n     \\  /\\_/    \\)_/        |          _l_l_         I\n      \\/  //|  |\\           }         [_____]        I\n          v |  | v          ]           | | |        |\n            \\__/            ]            ~ ~         |\n                            |                        |\n                             |                       |\n```\n\n**Go + Read-Only + Postgres.** A CLI tool and MCP server for exploring PostgreSQL databases with schema intelligence. All access is read-only with 4 layers of protection.\n\n## Quick Start\n\n```bash\n# Configure your databases\ncp config.example.yaml config.yaml\n# Edit config.yaml with your database details\n\n# Discover schemas\nexport PROD_DB_PASSWORD=\"your_password\"\ngoro-pg discover\n\n# Explore\ngoro-pg databases\ngoro-pg tables -d mydb\ngoro-pg describe -d mydb users\ngoro-pg search \"user email\"\n\n# Query\ngoro-pg query -d mydb \"SELECT * FROM users LIMIT 10\"\n\n# Pipe-friendly\necho \"SELECT count(*) FROM orders\" | goro-pg query -d mydb -\ngoro-pg tables -d mydb --format json | jq .\n```\n\n## CLI Commands\n\n| Command | Description |\n|---------|-------------|\n| `goro-pg query \u003csql\u003e` | Execute a read-only SQL query |\n| `goro-pg discover [database]` | Discover/refresh database schemas |\n| `goro-pg databases` | List configured databases |\n| `goro-pg schemas [database]` | List schemas in a database |\n| `goro-pg tables [database]` | List tables in a schema |\n| `goro-pg describe [database] \u003ctable\u003e` | Full table detail (columns, constraints, indexes, FKs) |\n| `goro-pg views [database]` | List views in a schema |\n| `goro-pg functions [database]` | List functions in a schema |\n| `goro-pg search \u003cquery\u003e` | Full-text search across all schema metadata |\n| `goro-pg serve` | Start MCP stdio server |\n| `goro-pg version` | Print version |\n\n### Global Flags\n\n```\n-c, --config     Config file path (default: config.yaml, env: GORO_PG_CONFIG)\n-d, --database   Default database name (env: GORO_PG_DATABASE)\n-f, --format     Output format: table, json, csv, plain (auto-detects TTY)\n```\n\n### Output Formats\n\n- **table** (default for TTY) — psql-style aligned columns\n- **json** — machine-readable JSON\n- **csv** — comma-separated values\n- **plain** (default for pipes) — tab-separated, no headers\n\n## Features\n\n- **CLI-first** — use directly from the terminal, no MCP client required\n- **MCP server** — also works as an MCP server via `goro-pg serve`\n- **4 layers of read-only protection** to prevent any data mutation\n- **Schema knowledge map** stored in SQLite with full-text search (FTS5)\n- **Automatic schema context** injected into query responses\n- **Enriched error messages** with actual schema when queries fail\n- **Multi-database support** from a single config\n- **Auto-discovery** of schemas, tables, columns, constraints, indexes, views, and functions\n- **Schema and table filtering** — whitelist or blacklist what gets discovered\n\n## Read-Only Protection\n\nEvery query passes through four defensive layers before execution:\n\n| Layer | Mechanism | Description |\n|-------|-----------|-------------|\n| **Tier 1** | AST parser | Parses SQL using PostgreSQL's actual parser (`pg_query_go`) and validates only SELECT statements are present. Rejects SELECT INTO, FOR UPDATE/SHARE, CTEs with mutations |\n| **Tier 2** | Connection-level | Every pgx pool connection sets `default_transaction_read_only=on` via RuntimeParams |\n| **Tier 3** | Transaction-level | Every query runs inside `BEGIN READ ONLY` via `pgx.TxOptions{AccessMode: pgx.ReadOnly}` |\n| **Tier 4** | PostgreSQL user | Configure with a database user that has only SELECT grants (see configuration below) |\n\n## Configuration\n\nCreate a `config.yaml` (see `config.example.yaml`):\n\n```yaml\ndatabases:\n  - name: \"production\"\n    host: \"db.example.com\"\n    port: 5432\n    database: \"myapp\"\n    user: \"readonly_user\"\n    password_env: \"PROD_DB_PASSWORD\"    # resolved from environment variable\n    sslmode: \"require\"\n\nknowledgemap:\n  path: \"./knowledgemap.db\"\n  auto_discover_on_startup: true\n```\n\n**Important:** The `password_env` field references an environment variable name, never a raw password. The server will refuse to start if the variable is unset or empty.\n\n### Discovery Filtering\n\nYou can optionally control what gets discovered and indexed into the knowledge map.\n\n**Schema filter** — only discover specific schemas (all non-system schemas if omitted):\n\n```yaml\ndatabases:\n  - name: \"production\"\n    host: \"db.example.com\"\n    database: \"myapp\"\n    user: \"readonly_user\"\n    password_env: \"PROD_DB_PASSWORD\"\n    schemas:\n      - \"public\"\n      - \"billing\"\n```\n\n**Table whitelist** — only discover specific tables:\n\n```yaml\n    tables:\n      include:\n        - \"public.users\"\n        - \"public.orders\"\n        - \"billing.invoices\"\n```\n\n**Table blacklist** — discover everything except specific tables:\n\n```yaml\n    tables:\n      exclude:\n        - \"public.migrations\"\n        - \"public.sessions\"\n```\n\n`include` and `exclude` are mutually exclusive. Table names must be in `schema.table` format.\n\nSchema and table filters can be combined — schema filtering is applied first, then table filtering within those schemas.\n\n\u003e **Note:** These filters are enforced at both discovery time (what enters the knowledge map) and query time (the `query` command extracts table references from SQL via AST parsing and rejects queries that reference filtered-out schemas or tables). For defense-in-depth, also configure PostgreSQL grants (Tier 4) to restrict access at the database level.\n\n### Creating a read-only PostgreSQL user (Tier 4)\n\n```sql\nCREATE ROLE readonly_user WITH LOGIN PASSWORD 'strong_password_here';\nGRANT CONNECT ON DATABASE myapp TO readonly_user;\nGRANT USAGE ON SCHEMA public TO readonly_user;\nGRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;\nALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_user;\n```\n\n## Installation\n\n### Prebuilt binaries\n\nDownload from [GitHub Releases](https://github.com/peter-trerotola/goro-pg/releases):\n\n```bash\n# Linux amd64\ncurl -L https://github.com/peter-trerotola/goro-pg/releases/latest/download/goro-pg_linux_amd64.tar.gz | tar xz\n\n# Linux arm64\ncurl -L https://github.com/peter-trerotola/goro-pg/releases/latest/download/goro-pg_linux_arm64.tar.gz | tar xz\n\n# macOS Apple Silicon\ncurl -L https://github.com/peter-trerotola/goro-pg/releases/latest/download/goro-pg_darwin_arm64.tar.gz | tar xz\n\n# macOS Intel\ncurl -L https://github.com/peter-trerotola/goro-pg/releases/latest/download/goro-pg_darwin_amd64.tar.gz | tar xz\n```\n\n### Docker\n\n```bash\ndocker pull ghcr.io/peter-trerotola/goro-pg:latest\n```\n\n### Build from source\n\nRequires Go 1.23+ and a C compiler (for `pg_query_go`):\n\n```bash\nCGO_ENABLED=1 go build -o goro-pg ./cmd/main.go\n```\n\n## Docker Compose (development)\n\n```bash\ndocker compose up\n```\n\nThis starts a PostgreSQL instance and goro-pg in MCP server mode with auto-discovery enabled.\n\n## MCP Server Mode\n\ngoro-pg also works as an MCP (Model Context Protocol) server for use with Claude Desktop, Claude Code, and other MCP-compatible clients:\n\n```bash\ngoro-pg serve --config config.yaml\n```\n\n### MCP Tools\n\n| Tool | Description | Data Source |\n|------|-------------|-------------|\n| `query` | Execute a read-only SELECT query | PostgreSQL (live) |\n| `discover` | Discover/refresh schema for a database | PostgreSQL -\u003e SQLite |\n| `list_databases` | List all configured databases | SQLite knowledge map |\n| `list_schemas` | List schemas in a database | SQLite knowledge map |\n| `list_tables` | List tables in a schema | SQLite knowledge map |\n| `describe_table` | Full column/constraint/index/FK detail | SQLite knowledge map |\n| `list_views` | List views in a schema | SQLite knowledge map |\n| `list_functions` | List functions in a schema | SQLite knowledge map |\n| `search_schema` | Full-text search across all metadata | SQLite FTS5 |\n\n### MCP Resources\n\n| Template | Description |\n|----------|-------------|\n| `schema:///{database}/tables` | List all tables with column counts |\n| `schema:///{database}/{schema}/{table}` | Full table detail (columns, constraints, indexes, FKs) |\n\n### Claude Desktop / Claude Code Integration\n\nAdd to your MCP settings:\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"docker\",\n      \"args\": [\n        \"run\", \"-i\", \"--rm\",\n        \"-e\", \"PROD_DB_PASSWORD\",\n        \"-v\", \"/path/to/config.yaml:/etc/goro-pg/config.yaml:ro\",\n        \"goro-pg\"\n      ]\n    }\n  }\n}\n```\n\nOr if running the binary directly:\n\n```json\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"/path/to/goro-pg\",\n      \"args\": [\"serve\", \"--config\", \"/path/to/config.yaml\"],\n      \"env\": {\n        \"PROD_DB_PASSWORD\": \"your_password\"\n      }\n    }\n  }\n}\n```\n\n### Schema Context Injection\n\nLLMs often write queries with wrong column names. goro-pg addresses this at multiple layers:\n\n1. **Server instructions** — workflow guidance sent during MCP initialization\n2. **Schema context in responses** — every `query` response includes column names/types for referenced tables\n3. **Enriched errors** — failed queries include actual schema from the knowledge map\n\n## Testing\n\n```bash\n# Run all unit tests\nCGO_ENABLED=1 go test ./... -race\n\n# Run only guard (read-only enforcement) tests\ngo test ./internal/guard/... -v\n\n# Run only knowledge map tests\ngo test ./internal/knowledgemap/... -v\n```\n\n## Contributing Adversarial Tests\n\nThe file `internal/guard/adversarial_test.go` contains ~200 test cases that attempt to bypass the read-only guard. Each case is a simple struct:\n\n```go\ntype adversarialCase struct {\n    name string // descriptive name for the test\n    sql  string // the SQL to test\n    tier string // which tier blocks it: \"tier1\", \"tier2\", \"tier3\", \"tier4\"\n}\n```\n\n```bash\ngo test ./internal/guard/ -run TestAdversarial -v\n```\n\nIf you find SQL that bypasses all four tiers, please open an issue.\n\n## Project Structure\n\n```\ngoro-pg/\n├── cmd/\n│   └── main.go                      # Entry point (Cobra bootstrap)\n├── internal/\n│   ├── cli/                         # CLI commands + output formatting\n│   │   ├── root.go                  # Root command, global flags\n│   │   ├── query.go                 # query subcommand\n│   │   ├── discover.go              # discover subcommand\n│   │   ├── databases.go             # databases subcommand\n│   │   ├── schemas.go               # schemas subcommand\n│   │   ├── tables.go                # tables subcommand\n│   │   ├── describe.go              # describe subcommand\n│   │   ├── views.go                 # views subcommand\n│   │   ├── functions.go             # functions subcommand\n│   │   ├── search.go                # search subcommand\n│   │   ├── serve.go                 # serve subcommand (MCP mode)\n│   │   ├── version.go               # version subcommand\n│   │   └── format.go                # table/json/csv/plain formatters\n│   ├── engine/                      # Shared business logic\n│   │   └── engine.go                # Query, discover, schema lookup orchestration\n│   ├── config/\n│   │   └── config.go                # YAML config types + loading + validation\n│   ├── guard/\n│   │   ├── parser.go                # Tier 1: AST validation + table ref extraction\n│   │   ├── guard.go                 # Guard entry point + ForbiddenError type\n│   │   └── adversarial_test.go      # ~200 adversarial bypass attempt tests\n│   ├── postgres/\n│   │   ├── pool.go                  # Connection pool manager (Tier 2)\n│   │   ├── readonly.go              # Guarded query execution (Tier 3)\n│   │   └── discovery.go             # Schema discovery with filtering\n│   ├── knowledgemap/\n│   │   ├── store.go                 # SQLite CRUD operations\n│   │   ├── query.go                 # Knowledge map query methods\n│   │   └── schema.sql               # SQLite DDL (tables, FTS5)\n│   └── server/\n│       ├── server.go                # MCP server wiring\n│       ├── tools.go                 # MCP tool definitions + handlers\n│       └── resources.go             # MCP resource template handlers\n├── config.example.yaml\n├── Dockerfile\n├── docker-compose.yaml\n└── .goreleaser.yml\n```\n\n## Architecture\n\ngoro-pg has two interfaces (CLI and MCP server) built on a shared engine layer:\n\n```\nCLI (cobra) ──→ Engine ←── MCP Server (mcp-go)\n                  │\n           ┌──────┼──────┐\n           ↓      ↓      ↓\n        Config  Guard  Postgres  KnowledgeMap\n                  │        │          │\n                  ↓        ↓          ↓\n               pg_query   pgx      SQLite\n```\n\nSchema metadata is crawled from PostgreSQL and cached in a local SQLite database (the \"knowledge map\"), which enables instant schema lookups and full-text search without hitting the live database.\n\nThe SQL guard uses `pg_query_go` which wraps PostgreSQL's actual parser (`libpg_query`). This means SQL validation uses the same parser as PostgreSQL itself — no ambiguity about what constitutes a SELECT vs. a mutation.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeter-trerotola%2Fgoro-pg","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpeter-trerotola%2Fgoro-pg","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeter-trerotola%2Fgoro-pg/lists"}