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.
โจ 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
- Create configuration file:
chatpg init
- Edit
~/.chatpg/config.tomlwith 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"
- 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:
- Application-level filtering: Blocks non-SELECT queries before execution
- Database transaction isolation:
SET TRANSACTION READ ONLY - Statement timeout: Hard limit prevents runaway queries
- Connection pooling: Resource limits and recycling
- No elevated privileges: Works with standard read-only database users
Blocked Operations:
INSERT,UPDATE,DELETEDROP,TRUNCATE,ALTERCREATE,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"
- Get a key from https://aistudio.google.com/apikey
- Add to
~/.chatpg/config.tomlor setCHATPG_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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- Author: Priyanka Gupta
- Issues: GitHub Issues
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1514da25ccee9c2d6653bf3566fdfab3b3a50721657ca5a629c1748ae08d8da8
|
|
| MD5 |
034d42fbcb8a3fef0580180fadf8b0ca
|
|
| BLAKE2b-256 |
14d32241cdba8df74db54a6738159ab95da8b9736bb4cf39593002cb3edf52dd
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
51a9956e556f355014f335acff40af6114c24b6568837472e4f1f0cc45f3cd68
|
|
| MD5 |
fb5a4f4e914d86c525287bc80323f084
|
|
| BLAKE2b-256 |
6dba459739e001f6f79f82cb2d8b144c97995aecda6ed2ddf7efeb3b06b5af37
|