mcp-sqlalchemy


Namemcp-sqlalchemy JSON
Version 0.2.4 PyPI version JSON
download
home_pageNone
SummaryMCP server for SQLAlchemy database interactions - supports SQLite, PostgreSQL, and MySQL
upload_time2025-10-17 20:48:15
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseNone
keywords mcp sqlalchemy database postgresql mysql sqlite
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # SQLAlchemy MCP Server 🧙

A Model Context Protocol (MCP) server that enables AI assistants to interact with your databases safely and efficiently. Connect to SQLite, PostgreSQL, or MySQL databases and let AI help you explore schemas, query data, and analyze your database structure.

> [!NOTE]
> This mcp-server is inspired by langchain's [SQLDatabase-toolkit](https://python.langchain.com/api_reference/community/agent_toolkits/langchain_community.agent_toolkits.sql.toolkit.SQLDatabaseToolkit.html) and makes use of Python's [SQLAlchemy](https://www.sqlalchemy.org/) library.

## What This Does

This MCP server allows AI assistants to:

- 🔍 **Explore your database structure** - List schemas, tables, columns, and relationships
- 📊 **Query your data safely** - Execute read-only queries with built-in safety controls
- 🛡️ **Protect your data** - Read-only mode prevents accidental data modification
- 📈 **Analyze relationships** - Understand how your tables connect through foreign keys
- 🔧 **Support multiple databases** - Works with SQLite, PostgreSQL, and MySQL

### Available Tools

The server provides 8 powerful tools for database interaction:

#### 🔍 **Schema Discovery Tools**

| Tool | Parameters | Description | Safety |
|------|------------|-------------|--------|
| **`list_schemas`** | _none_ | Lists all schemas in the database | ✅ Safe |
| **`list_tables`** | `schema_name` (optional) | Lists all tables, optionally filtered by schema | ✅ Safe |
| **`describe_table`** | `table_name`, `schema_name` (optional) | Shows table structure: columns, types, constraints, foreign keys | ✅ Safe |
| **`get_table_relationships`** | _none_ | Maps all foreign key relationships across the database | ✅ Safe |

#### 📊 **Data Exploration Tools**

| Tool | Parameters | Description | Safety |
|------|------------|-------------|--------|
| **`get_table_data`** | `table_name`, `schema_name` (optional), `limit` (default: 10) | Returns sample data from a table | ✅ Safe |
| **`get_unique_values`** | `table_name`, `column_name`, `schema_name` (optional), `limit` (default: 25) | Shows unique values in a column with frequency counts | ✅ Safe |

#### ⚡ **Query Execution Tools**

| Tool | Parameters | Description | Safety |
|------|------------|-------------|--------|
| **`execute_read_query`** | `sql` | Executes read-only SQL (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH) | ✅ Safe |
| **`execute_query`** | `sql` | Executes any SQL including writes (INSERT, UPDATE, DELETE, DDL) | ⚠️ **Destructive** |

#### 🛡️ **Built-in Safety Features**

- **Automatic Input Validation**: All table/column names are validated against SQL injection
- **Result Limits**: Default maximum of 25 rows returned (configurable)
- **Query Timeout**: Automatic timeout after 30 seconds (configurable)
- **Read-Only Mode**: When enabled, blocks all write operations
- **Smart Query Detection**: Automatically categorizes queries as safe or destructive

> [!TIP]
> Reasoning models, like o4-mini,  are *much* better at using this MCP server than regular models.

## Quick Setup

### Quick Reference

| Database | Install Command | Dependencies |
|----------|----------------|--------------|
| **SQLite** | `uvx mcp-sqlalchemy` | None (works out of the box) |
| **PostgreSQL** | `uvx "mcp-sqlalchemy[postgresql]"` | `asyncpg` |
| **MySQL** | `uvx "mcp-sqlalchemy[mysql]"` | `aiomysql` |
| **All** | `uvx "mcp-sqlalchemy[all]"` | `asyncpg` + `aiomysql` |

## Installation & Configuration

### Option 1: Install via uvx (Recommended)

Add to your AI assistant's MCP configuration:

```json
{
  "mcpServers": {
    "sqlalchemy": {
      "command": "uvx",
      "args": [
        "mcp-sqlalchemy[postgresql]", // Choose: [postgresql], [mysql], [all], or omit for SQLite only
      ],
      "env": {
        "DATABASE_URL": "sqlite:////absolute/path/to/database.db",
        "READ_ONLY_MODE": "true"
      }
    }
  }
}
```

> [!TIP]
> **MCP Configuration**: The JSON example above shows the complete configuration needed for your AI assistant. For local development, use `"command": "uv"` and `"args": ["run", "mcp-sqlalchemy"]` instead.

### Option 2: Local Development Setup

For development or customization:

```bash
# Clone the repository
git clone https://github.com/woonstadrotterdam/mcp-sqlalchemy.git
cd mcp-sqlalchemy

uv venv
source .venv/bin/activate # or .venv/Scripts/activate on Windows

# Install dependencies (choose one):
uv sync                    # SQLite only
uv sync --extra postgresql # + PostgreSQL support
uv sync --extra mysql      # + MySQL support
uv sync --extra all        # All database support
```

#### Test the Connection

```bash
# Start the development server to test using the proper entry point
uv run mcp dev src/mcp_sqlalchemy/_dev.py
```

This will open a web interface where you can test the connection and explore your database.

### Installation Method Comparison

| Method | Pros | Cons | Best For |
|--------|------|------|----------|
| **uvx** | Simple install, automatic updates, works anywhere | Requires internet, need `[extra]` syntax for PostgreSQL/MySQL | Most users |
| **Local** | Works offline, can modify code, full control, easy dependency management | Manual updates, manage dependencies | Developers |

### Updating Your Installation

**For uvx installations:**

```bash
# Updates happen automatically when you restart your AI assistant
# Or force update with:
uvx mcp-sqlalchemy
```

**For local installations:**

```bash
cd mcp-sqlalchemy
git pull
uv sync
```

## Database Connection Examples

### SQLite (File-based)

```bash
# Local database file
DATABASE_URL="sqlite:///database/myapp.db"

# Relative path
DATABASE_URL="sqlite:///./data/database.db"

# Absolute path
DATABASE_URL="sqlite:////full/path/to/database.db"
```

### PostgreSQL

```bash
# Basic connection
DATABASE_URL="postgresql://user:password@localhost:5432/dbname"

# With specific schema
DATABASE_URL="postgresql://user:password@localhost:5432/dbname"
DB_SCHEMA_NAME="public"

# Remote database
DATABASE_URL="postgresql://user:password@db.example.com:5432/dbname"
```

### MySQL

```bash
# Local MySQL
DATABASE_URL="mysql://user:password@localhost:3306/dbname"

# Remote MySQL
DATABASE_URL="mysql://user:password@mysql.example.com:3306/dbname"
```

## Safety Features

### Read-Only Mode (Recommended)

Read-only mode is enabled by default to prevent any data modifications:

```python
# The server automatically detects and blocks:
# - INSERT, UPDATE, DELETE statements
# - DROP, CREATE, ALTER statements
# - Any potentially destructive operations
```

### Automatic Protections

- **Query Validation**: Blocks dangerous SQL patterns
- **Result Limits**: Prevents overwhelming responses (default: 25 rows)
- **Read-Only by Default**: Safe mode enabled by default
- **Timeout Protection**: Queries timeout after 30 seconds
- **Input Sanitization**: Validates table and column names

## What Your AI Can Do

### Database Exploration

- **"Show me all the tables in my database"** → Lists all tables across schemas
- **"Describe the users table"** → Shows columns, types, and constraints
- **"What tables are related to the orders table?"** → Shows foreign key relationships
- **"List all schemas in the database"** → Shows available schemas

### Data Analysis

- **"Show me a sample of the users table"** → Returns first 10 rows
- **"What are the unique values in the status column?"** → Lists distinct values with counts
- **"Query all active users"** → Executes: `SELECT * FROM users WHERE status = 'active'`
- **"How many orders were placed last month?"** → Custom date-based queries

### Schema Understanding

- **"Explain the database structure"** → Comprehensive schema overview
- **"How are customers connected to orders?"** → Relationship mapping
- **"What indexes exist on the products table?"** → Index information

## Configuration Options

You can customize the server behavior:

```bash
# Set maximum rows returned per query
MAX_RESULT_ROWS=50

# Set query timeout (seconds)
MAX_QUERY_TIMEOUT=60

# Enable read-only mode
READ_ONLY_MODE=true

# Set default schema (PostgreSQL)
DB_SCHEMA_NAME=public
```

## Troubleshooting

### Installation Issues

#### "uvx: command not found"

- Install uvx: `curl -LsSf https://astral.sh/uv/install.sh | sh`
- Or via pip: `pip install uv` then use `uv tool run` instead of `uvx`

#### "Module not found" for PostgreSQL/MySQL

- **PostgreSQL**: Install with `[postgresql]` syntax or ensure `asyncpg` is available
- **MySQL**: Install with `[mysql]` syntax or ensure `aiomysql` is available
- **All databases**: Use `[all]` syntax for complete support

### Connection Issues

#### "Database URL must be provided"

- Make sure `DATABASE_URL` is set in your MCP configuration's `env` section or add `--database-url` to the command line
- Check the URL format matches your database type

#### "No module named 'greenlet'"

- For local installs: Run `uv sync` to install all dependencies
- For uvx installs: This should auto-install; try forcing reinstall with `uvx --force ...`
- The `greenlet` package is required for async database operations

#### "Connection refused"

- Verify your database server is running
- Check the hostname, port, username, and password
- For PostgreSQL/MySQL, ensure the database exists

### Query Issues

#### "Query timeout"

- The query is taking too long (>30 seconds)
- Add `LIMIT` clauses to large queries
- Consider adding database indexes for better performance

#### "Only read-only queries allowed"

- You're in read-only mode (this is good for safety!)
- Use the "Execute Read Query" tool instead
- Or disable read-only mode if you need write access

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "mcp-sqlalchemy",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "mcp, sqlalchemy, database, postgresql, mysql, sqlite",
    "author": null,
    "author_email": "Tomer Gabay <tomer.gabay@woonstadrotterdam.nl>, Ben Verhees <ben.verhees@woonstadrotterdam.nl>",
    "download_url": "https://files.pythonhosted.org/packages/97/9d/9549197b417d56d55f49d7a7ce79a853d07e2866f81df64c612b6194672a/mcp_sqlalchemy-0.2.4.tar.gz",
    "platform": null,
    "description": "# SQLAlchemy MCP Server \ud83e\uddd9\n\nA Model Context Protocol (MCP) server that enables AI assistants to interact with your databases safely and efficiently. Connect to SQLite, PostgreSQL, or MySQL databases and let AI help you explore schemas, query data, and analyze your database structure.\n\n> [!NOTE]\n> This mcp-server is inspired by langchain's [SQLDatabase-toolkit](https://python.langchain.com/api_reference/community/agent_toolkits/langchain_community.agent_toolkits.sql.toolkit.SQLDatabaseToolkit.html) and makes use of Python's [SQLAlchemy](https://www.sqlalchemy.org/) library.\n\n## What This Does\n\nThis MCP server allows AI assistants to:\n\n- \ud83d\udd0d **Explore your database structure** - List schemas, tables, columns, and relationships\n- \ud83d\udcca **Query your data safely** - Execute read-only queries with built-in safety controls\n- \ud83d\udee1\ufe0f **Protect your data** - Read-only mode prevents accidental data modification\n- \ud83d\udcc8 **Analyze relationships** - Understand how your tables connect through foreign keys\n- \ud83d\udd27 **Support multiple databases** - Works with SQLite, PostgreSQL, and MySQL\n\n### Available Tools\n\nThe server provides 8 powerful tools for database interaction:\n\n#### \ud83d\udd0d **Schema Discovery Tools**\n\n| Tool | Parameters | Description | Safety |\n|------|------------|-------------|--------|\n| **`list_schemas`** | _none_ | Lists all schemas in the database | \u2705 Safe |\n| **`list_tables`** | `schema_name` (optional) | Lists all tables, optionally filtered by schema | \u2705 Safe |\n| **`describe_table`** | `table_name`, `schema_name` (optional) | Shows table structure: columns, types, constraints, foreign keys | \u2705 Safe |\n| **`get_table_relationships`** | _none_ | Maps all foreign key relationships across the database | \u2705 Safe |\n\n#### \ud83d\udcca **Data Exploration Tools**\n\n| Tool | Parameters | Description | Safety |\n|------|------------|-------------|--------|\n| **`get_table_data`** | `table_name`, `schema_name` (optional), `limit` (default: 10) | Returns sample data from a table | \u2705 Safe |\n| **`get_unique_values`** | `table_name`, `column_name`, `schema_name` (optional), `limit` (default: 25) | Shows unique values in a column with frequency counts | \u2705 Safe |\n\n#### \u26a1 **Query Execution Tools**\n\n| Tool | Parameters | Description | Safety |\n|------|------------|-------------|--------|\n| **`execute_read_query`** | `sql` | Executes read-only SQL (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH) | \u2705 Safe |\n| **`execute_query`** | `sql` | Executes any SQL including writes (INSERT, UPDATE, DELETE, DDL) | \u26a0\ufe0f **Destructive** |\n\n#### \ud83d\udee1\ufe0f **Built-in Safety Features**\n\n- **Automatic Input Validation**: All table/column names are validated against SQL injection\n- **Result Limits**: Default maximum of 25 rows returned (configurable)\n- **Query Timeout**: Automatic timeout after 30 seconds (configurable)\n- **Read-Only Mode**: When enabled, blocks all write operations\n- **Smart Query Detection**: Automatically categorizes queries as safe or destructive\n\n> [!TIP]\n> Reasoning models, like o4-mini,  are *much* better at using this MCP server than regular models.\n\n## Quick Setup\n\n### Quick Reference\n\n| Database | Install Command | Dependencies |\n|----------|----------------|--------------|\n| **SQLite** | `uvx mcp-sqlalchemy` | None (works out of the box) |\n| **PostgreSQL** | `uvx \"mcp-sqlalchemy[postgresql]\"` | `asyncpg` |\n| **MySQL** | `uvx \"mcp-sqlalchemy[mysql]\"` | `aiomysql` |\n| **All** | `uvx \"mcp-sqlalchemy[all]\"` | `asyncpg` + `aiomysql` |\n\n## Installation & Configuration\n\n### Option 1: Install via uvx (Recommended)\n\nAdd to your AI assistant's MCP configuration:\n\n```json\n{\n  \"mcpServers\": {\n    \"sqlalchemy\": {\n      \"command\": \"uvx\",\n      \"args\": [\n        \"mcp-sqlalchemy[postgresql]\", // Choose: [postgresql], [mysql], [all], or omit for SQLite only\n      ],\n      \"env\": {\n        \"DATABASE_URL\": \"sqlite:////absolute/path/to/database.db\",\n        \"READ_ONLY_MODE\": \"true\"\n      }\n    }\n  }\n}\n```\n\n> [!TIP]\n> **MCP Configuration**: The JSON example above shows the complete configuration needed for your AI assistant. For local development, use `\"command\": \"uv\"` and `\"args\": [\"run\", \"mcp-sqlalchemy\"]` instead.\n\n### Option 2: Local Development Setup\n\nFor development or customization:\n\n```bash\n# Clone the repository\ngit clone https://github.com/woonstadrotterdam/mcp-sqlalchemy.git\ncd mcp-sqlalchemy\n\nuv venv\nsource .venv/bin/activate # or .venv/Scripts/activate on Windows\n\n# Install dependencies (choose one):\nuv sync                    # SQLite only\nuv sync --extra postgresql # + PostgreSQL support\nuv sync --extra mysql      # + MySQL support\nuv sync --extra all        # All database support\n```\n\n#### Test the Connection\n\n```bash\n# Start the development server to test using the proper entry point\nuv run mcp dev src/mcp_sqlalchemy/_dev.py\n```\n\nThis will open a web interface where you can test the connection and explore your database.\n\n### Installation Method Comparison\n\n| Method | Pros | Cons | Best For |\n|--------|------|------|----------|\n| **uvx** | Simple install, automatic updates, works anywhere | Requires internet, need `[extra]` syntax for PostgreSQL/MySQL | Most users |\n| **Local** | Works offline, can modify code, full control, easy dependency management | Manual updates, manage dependencies | Developers |\n\n### Updating Your Installation\n\n**For uvx installations:**\n\n```bash\n# Updates happen automatically when you restart your AI assistant\n# Or force update with:\nuvx mcp-sqlalchemy\n```\n\n**For local installations:**\n\n```bash\ncd mcp-sqlalchemy\ngit pull\nuv sync\n```\n\n## Database Connection Examples\n\n### SQLite (File-based)\n\n```bash\n# Local database file\nDATABASE_URL=\"sqlite:///database/myapp.db\"\n\n# Relative path\nDATABASE_URL=\"sqlite:///./data/database.db\"\n\n# Absolute path\nDATABASE_URL=\"sqlite:////full/path/to/database.db\"\n```\n\n### PostgreSQL\n\n```bash\n# Basic connection\nDATABASE_URL=\"postgresql://user:password@localhost:5432/dbname\"\n\n# With specific schema\nDATABASE_URL=\"postgresql://user:password@localhost:5432/dbname\"\nDB_SCHEMA_NAME=\"public\"\n\n# Remote database\nDATABASE_URL=\"postgresql://user:password@db.example.com:5432/dbname\"\n```\n\n### MySQL\n\n```bash\n# Local MySQL\nDATABASE_URL=\"mysql://user:password@localhost:3306/dbname\"\n\n# Remote MySQL\nDATABASE_URL=\"mysql://user:password@mysql.example.com:3306/dbname\"\n```\n\n## Safety Features\n\n### Read-Only Mode (Recommended)\n\nRead-only mode is enabled by default to prevent any data modifications:\n\n```python\n# The server automatically detects and blocks:\n# - INSERT, UPDATE, DELETE statements\n# - DROP, CREATE, ALTER statements\n# - Any potentially destructive operations\n```\n\n### Automatic Protections\n\n- **Query Validation**: Blocks dangerous SQL patterns\n- **Result Limits**: Prevents overwhelming responses (default: 25 rows)\n- **Read-Only by Default**: Safe mode enabled by default\n- **Timeout Protection**: Queries timeout after 30 seconds\n- **Input Sanitization**: Validates table and column names\n\n## What Your AI Can Do\n\n### Database Exploration\n\n- **\"Show me all the tables in my database\"** \u2192 Lists all tables across schemas\n- **\"Describe the users table\"** \u2192 Shows columns, types, and constraints\n- **\"What tables are related to the orders table?\"** \u2192 Shows foreign key relationships\n- **\"List all schemas in the database\"** \u2192 Shows available schemas\n\n### Data Analysis\n\n- **\"Show me a sample of the users table\"** \u2192 Returns first 10 rows\n- **\"What are the unique values in the status column?\"** \u2192 Lists distinct values with counts\n- **\"Query all active users\"** \u2192 Executes: `SELECT * FROM users WHERE status = 'active'`\n- **\"How many orders were placed last month?\"** \u2192 Custom date-based queries\n\n### Schema Understanding\n\n- **\"Explain the database structure\"** \u2192 Comprehensive schema overview\n- **\"How are customers connected to orders?\"** \u2192 Relationship mapping\n- **\"What indexes exist on the products table?\"** \u2192 Index information\n\n## Configuration Options\n\nYou can customize the server behavior:\n\n```bash\n# Set maximum rows returned per query\nMAX_RESULT_ROWS=50\n\n# Set query timeout (seconds)\nMAX_QUERY_TIMEOUT=60\n\n# Enable read-only mode\nREAD_ONLY_MODE=true\n\n# Set default schema (PostgreSQL)\nDB_SCHEMA_NAME=public\n```\n\n## Troubleshooting\n\n### Installation Issues\n\n#### \"uvx: command not found\"\n\n- Install uvx: `curl -LsSf https://astral.sh/uv/install.sh | sh`\n- Or via pip: `pip install uv` then use `uv tool run` instead of `uvx`\n\n#### \"Module not found\" for PostgreSQL/MySQL\n\n- **PostgreSQL**: Install with `[postgresql]` syntax or ensure `asyncpg` is available\n- **MySQL**: Install with `[mysql]` syntax or ensure `aiomysql` is available\n- **All databases**: Use `[all]` syntax for complete support\n\n### Connection Issues\n\n#### \"Database URL must be provided\"\n\n- Make sure `DATABASE_URL` is set in your MCP configuration's `env` section or add `--database-url` to the command line\n- Check the URL format matches your database type\n\n#### \"No module named 'greenlet'\"\n\n- For local installs: Run `uv sync` to install all dependencies\n- For uvx installs: This should auto-install; try forcing reinstall with `uvx --force ...`\n- The `greenlet` package is required for async database operations\n\n#### \"Connection refused\"\n\n- Verify your database server is running\n- Check the hostname, port, username, and password\n- For PostgreSQL/MySQL, ensure the database exists\n\n### Query Issues\n\n#### \"Query timeout\"\n\n- The query is taking too long (>30 seconds)\n- Add `LIMIT` clauses to large queries\n- Consider adding database indexes for better performance\n\n#### \"Only read-only queries allowed\"\n\n- You're in read-only mode (this is good for safety!)\n- Use the \"Execute Read Query\" tool instead\n- Or disable read-only mode if you need write access\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "MCP server for SQLAlchemy database interactions - supports SQLite, PostgreSQL, and MySQL",
    "version": "0.2.4",
    "project_urls": null,
    "split_keywords": [
        "mcp",
        " sqlalchemy",
        " database",
        " postgresql",
        " mysql",
        " sqlite"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "13f0d2ee4c150fabe01d65bba3d2d20a40f24bd512a7f4d99d97ede1559e9191",
                "md5": "ae39fd523d8735db3cadc468db9f91e3",
                "sha256": "37c8eefb2613861b2140a77dd2ce09feed302d4b3e4957d7633fd96ed3698b04"
            },
            "downloads": -1,
            "filename": "mcp_sqlalchemy-0.2.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ae39fd523d8735db3cadc468db9f91e3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 17629,
            "upload_time": "2025-10-17T20:48:14",
            "upload_time_iso_8601": "2025-10-17T20:48:14.758879Z",
            "url": "https://files.pythonhosted.org/packages/13/f0/d2ee4c150fabe01d65bba3d2d20a40f24bd512a7f4d99d97ede1559e9191/mcp_sqlalchemy-0.2.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "979d9549197b417d56d55f49d7a7ce79a853d07e2866f81df64c612b6194672a",
                "md5": "9c1de97bd298c1e0f4c896706559612c",
                "sha256": "4e928a2177dec98f23ec728524c11f934b0be12bb1800e4a88c679c8cc708cb6"
            },
            "downloads": -1,
            "filename": "mcp_sqlalchemy-0.2.4.tar.gz",
            "has_sig": false,
            "md5_digest": "9c1de97bd298c1e0f4c896706559612c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 19926,
            "upload_time": "2025-10-17T20:48:15",
            "upload_time_iso_8601": "2025-10-17T20:48:15.957481Z",
            "url": "https://files.pythonhosted.org/packages/97/9d/9549197b417d56d55f49d7a7ce79a853d07e2866f81df64c612b6194672a/mcp_sqlalchemy-0.2.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-17 20:48:15",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "mcp-sqlalchemy"
}
        
Elapsed time: 1.89800s