Skip to main content

ChatPg

Natural language Postgres database operator powered by Google Gemini and MCP

ChatPg lets you interact with your PostgreSQL database using plain English. Ask questions, explore schemas, and run queries without writing SQL - all with enterprise-grade security that enforces read-only access.

Python 3.11+ License: MIT

โœจ Features

  • ๐Ÿ—ฃ๏ธ Natural Language Interface: Ask questions in plain English, get SQL results
  • ๐Ÿ”’ Read-Only by Default: Multi-layer security prevents destructive operations
  • ๐Ÿค– Gemini-Powered: Uses Google's latest Gemini models for intelligent query generation
  • ๐Ÿ”Œ MCP Protocol: Exposes database as a Model Context Protocol server
  • ๐Ÿ“Š Beautiful Output: Rich terminal UI with formatted tables and colors
  • ๐Ÿ”„ Connection Pooling: Production-ready asyncpg connection management
  • ๐Ÿ“ Comprehensive Logging: Centralized logging with file rotation
  • โš™๏ธ Flexible Configuration: Environment variables and config file support

๐Ÿš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/yourusername/chatpg.git
cd chatpg

# Install with uv (recommended)
uv pip install -e .

# Or with pip
pip install -e .

Initial Setup

  1. Create configuration file:
chatpg init
  1. Edit ~/.chatpg/config.toml with your credentials:
# Get API key from https://aistudio.google.com/apikey
gemini_api_key = "your-gemini-api-key-here"

# Your PostgreSQL connection string
database_url = "postgresql://user:password@localhost:5432/mydb"

# Model to use (default: gemini-2.5-flash)
gemini_model = "gemini-2.5-flash"
  1. Verify configuration:
chatpg doctor

Basic Usage

Interactive Chat:

chatpg chat

Example conversation:

chatpg> Show me all tables in the database
Tool call: run_query({"sql": "SELECT tablename FROM pg_tables WHERE schemaname = 'public'"})

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“
โ”ƒ tablename    โ”ƒ
โ”กโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ฉ
โ”‚ users        โ”‚
โ”‚ products     โ”‚
โ”‚ orders       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
3 row(s) in 12.50 ms

chatpg> How many active users do we have?
Tool call: run_query({"sql": "SELECT COUNT(*) as active_users FROM users WHERE status = 'active'"})

โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“
โ”ƒ active_users โ”ƒ
โ”กโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ฉ
โ”‚ 1,234        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
1 row(s) in 8.30 ms

MCP Server Mode:

chatpg mcp

Use with Claude Desktop or other MCP clients to expose your database as a tool.

๐Ÿ“– Documentation

Commands

Command Description
chatpg init Create default configuration file
chatpg chat Start interactive chat session
chatpg mcp Start MCP server (stdio transport)
chatpg doctor Validate configuration and environment
chatpg version Display version information

Configuration

Configuration File: ~/.chatpg/config.toml

# Required settings
gemini_api_key = "your-api-key"
database_url = "postgresql://user:pass@host:port/database"

# Optional settings (with defaults)
gemini_model = "gemini-2.5-flash"
query_limit = 100                    # Max rows returned per query
statement_timeout_ms = 10000         # Query timeout (10 seconds)
pool_min_size = 1                    # Min database connections
pool_max_size = 10                   # Max database connections

Environment Variables:

# Override config file
export CHATPG_GEMINI_API_KEY="your-key"
export CHATPG_DATABASE_URL="postgresql://..."

# Logging
export CHATPG_LOG_LEVEL="DEBUG"           # Console: DEBUG, INFO, WARNING, ERROR
export CHATPG_DISABLE_FILE_LOG="1"        # Disable file logging

# All config options
export CHATPG_GEMINI_MODEL="gemini-2.5-flash"
export CHATPG_QUERY_LIMIT="100"
export CHATPG_STATEMENT_TIMEOUT_MS="10000"
export CHATPG_POOL_MIN_SIZE="1"
export CHATPG_POOL_MAX_SIZE="10"

Security

ChatPg implements defense-in-depth security:

  1. Application-level filtering: Blocks non-SELECT queries before execution
  2. Database transaction isolation: SET TRANSACTION READ ONLY
  3. Statement timeout: Hard limit prevents runaway queries
  4. Connection pooling: Resource limits and recycling
  5. No elevated privileges: Works with standard read-only database users

Blocked Operations:

  • INSERT, UPDATE, DELETE
  • DROP, TRUNCATE, ALTER
  • CREATE, GRANT, REVOKE
  • Any DDL or DML operations

Allowed Operations:

  • SELECT (with joins, CTEs, subqueries)
  • WITH (Common Table Expressions)
  • SHOW (configuration inspection)
  • EXPLAIN (query analysis)
  • VALUES (inline data)

๐Ÿ—๏ธ Architecture

chatpg/
โ”œโ”€โ”€ agent/               # Gemini AI agent
โ”‚   โ”œโ”€โ”€ gemini_agent.py  # Function calling & tool execution
โ”‚   โ””โ”€โ”€ prompts.py       # System prompts
โ”œโ”€โ”€ cli.py               # Command-line interface
โ”œโ”€โ”€ config.py            # Pydantic settings management
โ”œโ”€โ”€ db/
โ”‚   โ””โ”€โ”€ pool.py          # AsyncPG connection pooling
โ”œโ”€โ”€ logging_config.py    # Centralized logging
โ”œโ”€โ”€ mcp_server/
โ”‚   โ””โ”€โ”€ server.py        # MCP protocol server
โ”œโ”€โ”€ tools/
โ”‚   โ””โ”€โ”€ query.py         # Query execution & safety
โ””โ”€โ”€ ui/
    โ””โ”€โ”€ render.py        # Rich terminal rendering

Key Technologies:

  • Google Gemini: AI model for natural language understanding
  • MCP: Model Context Protocol for tool integration
  • asyncpg: High-performance PostgreSQL driver
  • Pydantic: Data validation and settings
  • Rich: Beautiful terminal output
  • Typer: Modern CLI framework

๐Ÿงช Development

Setup Development Environment

# Install with dev dependencies
uv pip install -e ".[dev]"

# Or with pip
pip install -e ".[dev]"

Running Tests

# Run all tests
pytest

# Run with coverage
pytest --cov=chatpg --cov-report=html

# Run specific test file
pytest tests/test_query.py

# Run specific test
pytest tests/test_query.py::TestReadOnlyDetection::test_select_queries_allowed

# Verbose output
pytest -v

# Show print statements
pytest -s

Code Quality

# Format code
ruff format .

# Lint code
ruff check .

# Fix auto-fixable issues
ruff check --fix .

Project Structure

chatpg/
โ”œโ”€โ”€ chatpg/              # Main package
โ”œโ”€โ”€ tests/               # Test suite
โ”‚   โ”œโ”€โ”€ conftest.py      # Pytest fixtures
โ”‚   โ”œโ”€โ”€ test_query.py    # Query execution tests
โ”‚   โ”œโ”€โ”€ test_config.py   # Configuration tests
โ”‚   โ”œโ”€โ”€ test_logging.py  # Logging tests
โ”‚   โ””โ”€โ”€ test_render.py   # UI rendering tests
โ”œโ”€โ”€ pyproject.toml       # Project metadata & dependencies
โ”œโ”€โ”€ README.md            # This file
โ””โ”€โ”€ LOGGING.md           # Logging documentation

๐Ÿ› Troubleshooting

Connection Issues

# Check configuration
chatpg doctor

# Test database connection
psql "postgresql://user:pass@host:port/db"

# Check logs
tail -f ~/.chatpg/logs/chatpg.log

Debug Mode

# Enable debug logging
export CHATPG_LOG_LEVEL=DEBUG
chatpg chat

# View detailed logs
cat ~/.chatpg/logs/chatpg.log

Common Issues

"Missing Gemini API key"

"Database connection failed"

  • Verify PostgreSQL is running
  • Check connection string format
  • Ensure user has SELECT permissions

"No rows returned"

  • Query might be filtering out all results
  • Check database has data: chatpg> show me table counts

๐Ÿ“š Examples

Exploring Schema

chatpg> What tables exist?
chatpg> Describe the users table structure
chatpg> Show me the indexes on the orders table

Data Analysis

chatpg> What's the average order value?
chatpg> Show top 5 customers by total purchases
chatpg> How many orders were placed last month?

Query Performance

chatpg> Explain the query plan for selecting from large_table
chatpg> Show current database configuration
chatpg> What's the database version?

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Google Gemini team for the powerful AI models
  • Anthropic for the MCP protocol specification
  • The Python community for excellent libraries

๐Ÿ“ฎ Contact


Note: ChatPg is designed for read-only database operations. Never grant write permissions to the database user used by ChatPg.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chatpg-0.1.0.tar.gz (15.4 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chatpg-0.1.0-py3-none-any.whl (24.6 kB view details)

Uploaded Python 3

File details

Details for the file chatpg-0.1.0.tar.gz.

File metadata

  • Download URL: chatpg-0.1.0.tar.gz
  • Upload date:
  • Size: 15.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.12.10

File hashes

Hashes for chatpg-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1514da25ccee9c2d6653bf3566fdfab3b3a50721657ca5a629c1748ae08d8da8
MD5 034d42fbcb8a3fef0580180fadf8b0ca
BLAKE2b-256 14d32241cdba8df74db54a6738159ab95da8b9736bb4cf39593002cb3edf52dd

See more details on using hashes here.

File details

Details for the file chatpg-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: chatpg-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 24.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.12.10

File hashes

Hashes for chatpg-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 51a9956e556f355014f335acff40af6114c24b6568837472e4f1f0cc45f3cd68
MD5 fb5a4f4e914d86c525287bc80323f084
BLAKE2b-256 6dba459739e001f6f79f82cb2d8b144c97995aecda6ed2ddf7efeb3b06b5af37

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page