The USQL MCP Server bridges the Model Context Protocol with the usql CLI, enabling AI assistants to execute SQL queries and database operations across multiple database systems.
Capabilities:
Execute SQL Queries - Run arbitrary SQL statements (SELECT, INSERT, UPDATE, DELETE) with optional prepared statement parameters
Execute Multi-Statement Scripts - Run complete SQL scripts with multiple statements in sequence
List Databases - Discover all databases available on a database server
List Tables - View all tables within a specific database
Describe Table Schema - Get detailed schema information including columns, data types, and constraints
Flexible Connection Management - Connect using full database URLs (e.g., postgres://user:pass@host/db) or pre-configured connection names via environment variables/config.json, with support for default connections
Multiple Output Formats - Return results in JSON (default) or CSV format
Timeout Control - Configure query execution timeouts globally or per-request, with support for unlimited execution time
Multi-Database Support - Works with any database supported by usql (PostgreSQL, MySQL, Oracle, SQLite, SQL Server, and many others)
Raw CLI Output - Returns authentic usql output exactly as it appears on the command line
Easy Integration - Configurable for use with MCP clients such as Claude Desktop, Claude Code, Codex CLI, and GitHub Copilot
Enables execution of SQL queries and database operations against SQLite databases through the usql CLI, including query execution, table listing, and schema inspection.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@USQL MCP Servershow me the top 10 customers by total purchases"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
USQL MCP Server
usql-mcp is a full-featured MCP server that bridges the Model Context Protocol with the usql universal SQL CLI. It enables AI assistants and other MCP clients to query any database that usql supports, with enterprise-ready features like background execution, progress tracking, query safety validation, and intelligent caching.
β¨ Key Features
π Universal Database Access: Query PostgreSQL, MySQL, Oracle, SQLite, SQL Server, and 100+ other databases through a single interface
β‘ Background Execution: Long-running queries automatically move to background with job tracking and polling
π Progress Reporting: Real-time progress updates for long operations using MCP progress notifications
π‘οΈ Query Safety: Automatic risk analysis detects dangerous operations (DROP, DELETE without WHERE, etc.)
π SQL Workflow Templates: Built-in prompts for common tasks (query optimization, data profiling, migrations)
ποΈ Schema Resources: Browse database schemas through MCP resources (databases, tables, columns)
β‘ Performance: Schema caching and rate limiting for production deployments
π Security: Credential sanitization, configurable operation blocking, audit-ready error messages
MCP Capabilities
This server implements all 4 MCP capabilities:
Tools (8 tools): Execute queries, manage schemas, check job status
Resources: Browse database metadata via
sql://URIsPrompts: SQL workflow templates for common tasks
Progress: Real-time progress for long-running operations
Requirements
Node.js 16 or newer
npmusqlinstalled and available onPATH
Quick Launch with npx
Run the server directly via npx:
This downloads the package and executes the CLI entry point, which runs the MCP server on stdio.
You can also run it directly from the repository using npm's Git support (the prepare script compiles the TypeScript automatically):
Getting Started
The compiled files live in dist/. They are intentionally not committedβrun npm run build whenever you need fresh output.
Configuring Connections
Define connection strings via environment variables (USQL_*) or a config.json file mirroring config.example.json. Each USQL_<NAME>=... entry becomes a reusable connection whose name is the lower-cased <name> portion (USQL_ORACLE1 β oracle1).
Environment Variables
Connection variables (any USQL_* except reserved keys below):
Reserved configuration variables:
USQL_CONFIG_PATH- Path to config.jsonUSQL_QUERY_TIMEOUT_MS- Default query timeout (leave unset for unlimited)USQL_DEFAULT_CONNECTION- Default connection name when omitted from tool callsUSQL_BINARY_PATH- Full path to usql binary (if not on PATH)USQL_BACKGROUND_THRESHOLD_MS- Threshold for background execution (default: 30000)USQL_JOB_RESULT_TTL_MS- How long to keep completed job results (default: 3600000 = 1 hour)
Configuration File
Create a config.json with connection details and server settings:
Configuration Options:
queryTimeout: Milliseconds before query times out (null = unlimited)backgroundThresholdMs: Queries exceeding this move to background (default: 30000)jobResultTtlMs: How long to retain completed job results (default: 3600000)allowDestructiveOperations: If false, block DROP/TRUNCATE operationsblockHighRiskQueries: Block queries with risk level "high"blockCriticalRiskQueries: Block queries with risk level "critical"requireWhereClauseForDelete: Require WHERE clause on DELETE/UPDATEmaxResultBytes: Maximum result size in bytes (default: 10MB)rateLimitRpm: Requests per minute limit (null = no limit)schemaCacheTtl: Schema cache TTL in milliseconds (null = no caching)
Client Configuration
This section explains how to configure the usql-mcp server in different MCP clients.
Claude Desktop
Claude Desktop uses a configuration file to register MCP servers. The location depends on your operating system:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.jsonLinux:
~/.config/Claude/claude_desktop_config.json
Add the following configuration to your claude_desktop_config.json:
After editing the configuration file, restart Claude Desktop for changes to take effect.
Claude Code
Claude Code (CLI) supports MCP servers through its configuration file located at:
All platforms:
~/.claudercor~/.config/claude/config.json
Add the MCP server to your Claude Code configuration:
The server will be available in your Claude Code sessions automatically.
Codex CLI
Codex CLI configuration varies by implementation, but typically uses a similar JSON configuration approach. Create or edit your Codex configuration file (usually ~/.codexrc or as specified in your Codex documentation):
Refer to your specific Codex CLI documentation for the exact configuration file location and format.
GitHub Copilot (VS Code)
GitHub Copilot in VS Code can use MCP servers through the Copilot Chat extension settings. Configuration is done through VS Code's settings.json:
Open VS Code Settings (JSON) via:
macOS:
Cmd + Shift + Pβ "Preferences: Open User Settings (JSON)"Windows/Linux:
Ctrl + Shift + Pβ "Preferences: Open User Settings (JSON)"
Add the MCP server configuration:
After saving the settings, reload VS Code or restart the Copilot extension for changes to take effect.
Environment Variables vs. Configuration
For all clients, you can choose between:
Inline environment variables (shown above) - Connection strings in the config file
System environment variables - Set
USQL_*variables in your shell profile
System environment approach:
Then use a simpler client configuration:
Security Best Practices
Avoid hardcoding credentials: Use environment variables or secure credential stores
File permissions: Ensure configuration files with credentials are not world-readable (chmod 600)
Read-only access: Create database users with minimal required permissions for AI queries
Network security: Use SSL/TLS connections for remote databases
Audit logging: Enable database audit logs to track AI-generated queries
Query safety: Enable
blockCriticalRiskQueriesto prevent destructive operationsRate limiting: Set
rateLimitRpmto prevent abuse in multi-user environments
Tools Catalogue
Core SQL Tools
Tool | Purpose | Key Inputs |
| Run an arbitrary SQL statement |
|
| Execute a multi-statement script |
|
| List databases available on the server |
|
| List tables in the current database |
|
| Inspect table metadata via |
|
Background Job Management
Tool | Purpose | Key Inputs |
| Check status of a background job |
|
| Cancel a running background job |
|
Server Information
Tool | Purpose | Key Inputs |
| Get server configuration and stats | None (read-only) |
Resources
Access database metadata through MCP resources:
sql://connections- List all available connectionssql://{connection}/databases- List databases on a connectionsql://{connection}/{database}/tables- List tables in a databasesql://{connection}/{database}/table/{name}- Get detailed table schema
Example usage:
Prompts
Built-in SQL workflow templates:
analyze_performance - Analyze query performance and suggest optimizations
profile_data_quality - Profile data quality (nulls, duplicates, distributions)
generate_migration - Generate database migration scripts
explain_schema - Create comprehensive schema documentation
optimize_query - Optimize a slow-running query
debug_slow_query - Systematically debug slow queries
Example usage:
Background Execution
Queries that exceed the backgroundThresholdMs (default: 30 seconds) automatically move to background execution:
Initial Response: Tool returns a
job_idand status messagePolling: Use
get_job_statuswithwait_secondsto check progressResults: When complete,
get_job_statusreturns the full resultProgress: Real-time progress percentage (0-100) for running jobs
Cleanup: Jobs are automatically cleaned up after
jobResultTtlMs(default: 1 hour)
Example workflow:
Query Safety Analysis
Every query is automatically analyzed for safety risks:
Risk Levels:
Low: Safe read-only queries
Medium: Modifying operations with WHERE clauses
High: Complex queries with many JOINs, missing indexes
Critical: Destructive operations (DROP, TRUNCATE, DELETE without WHERE)
Response includes analysis:
Configuration options:
allowDestructiveOperations: false- Block all destructive operationsblockHighRiskQueries: true- Block queries with "high" riskblockCriticalRiskQueries: true- Block queries with "critical" riskrequireWhereClauseForDelete: true- Require WHERE on DELETE/UPDATE
Response Format
Successful calls return the exact stdout produced by usql, paired with the format indicator:
Background job responses:
If usql exits with a non-zero code, the handler forwards the message through the MCP error shape, keeping details like the sanitized connection string and original stderr.
Performance Features
Schema Caching
Enable caching to reduce subprocess overhead for metadata queries:
Cached operations:
list_databaseslist_tablesdescribe_tableResource reads
Cache statistics available via get_server_info:
Rate Limiting
Protect your databases from abuse:
When limit exceeded:
Development
npm run devβ TypeScript compile in watch modenpm run buildβ emit ESM output todist/npm run lintβ ESLint/Prettier rulesnpm run testβ Jest unit tests (519 tests, comprehensive coverage)npm run type-checkβ stricttsc --noEmit
Debug logging follows the namespace in DEBUG=usql-mcp:*.
Architecture
See CLAUDE.md for coding agents guidelines and architecture documentation.
Key components:
Tools (
src/tools/) - MCP tool implementationsResources (
src/resources/) - MCP resource handlersPrompts (
src/prompts/) - SQL workflow templatesBackground Jobs (
src/usql/job-manager.ts) - Async execution trackingQuery Safety (
src/utils/query-safety-analyzer.ts) - Risk analysisCaching (
src/cache/schema-cache.ts) - Performance optimizationProgress (
src/notifications/progress-notifier.ts) - Real-time updates
Testing
Test coverage:
519 passing tests
Unit tests for all tools, utilities, and managers
Integration tests with real SQLite databases
Request tracking, pagination, and protocol compliance tests
Contributing
See CONTRIBUTING.md for contributor guidelines and CLAUDE.md for coding agents guidelines. Open an issue before large changes so we can keep the tooling lean and aligned with the MCP ecosystem.
License
MIT License - see LICENSE for details.
Credits
Built on top of the excellent usql universal database CLI by Kenneth Shaw and the Model Context Protocol by Anthropic.