MCP Claude Code

Use AI2SQL Inside Claude Code with MCP

AI2SQL is now available as an MCP server. Generate, explain, optimize, and fix SQL queries directly inside Claude Code without leaving your terminal. One command to install, four tools at your fingertips.

Mar 26, 2026 7 min read

What Is MCP (Model Context Protocol)?

Model Context Protocol (MCP) is an open standard that lets AI assistants like Claude connect to external tools and data sources. Instead of copying and pasting data between applications, MCP creates a direct bridge between your AI assistant and the services it needs to access.

Think of MCP as a plugin system for AI. An MCP server exposes a set of tools that Claude Code can call during a conversation. When you ask Claude to generate a SQL query, it does not rely on its training data alone. It calls the AI2SQL MCP server, which uses a dedicated SQL engine to produce accurate, dialect-specific queries.

The result is a tighter workflow. You stay in your terminal, describe what you need in plain English, and get production-ready SQL back in seconds.

AI2SQL Is Now an MCP Server

AI2SQL has shipped an official MCP server that brings its SQL generation engine directly into Claude Code. This means you can generate SQL queries, get explanations of existing queries, optimize slow queries, and fix errors, all without opening a browser or switching contexts.

The server is published as an npm package called ai2sql-mcp. It communicates with the AI2SQL API over HTTPS and returns structured results that Claude Code can display inline in your conversation.

The MCP server exposes four tools:

  • generate_sql -- Convert natural language into SQL for any supported database dialect.
  • explain_sql -- Get a plain English breakdown of what a SQL query does, clause by clause.
  • optimize_sql -- Analyze a query for performance issues and receive an optimized version with explanations.
  • fix_sql_error -- Provide a broken query and its error message, get back a corrected version with a diagnosis of what went wrong.

All four tools work in both the free tier and the Pro tier. The difference is that free tier uses a demo database endpoint while Pro users get unlimited queries and can pass their own schema context for higher accuracy.

How to Install

Installation takes less than a minute. You need Claude Code installed and an internet connection. No database credentials are required for the free tier.

Step 1: Open Your Claude Code Settings

Locate or create your Claude Code settings.json file. This is where MCP server configurations live.

Step 2: Add the AI2SQL Server

Add the following block to your mcpServers configuration:

{
  "mcpServers": {
    "ai2sql": {
      "command": "npx",
      "args": ["-y", "ai2sql-mcp"]
    }
  }
}

That is it. The -y flag tells npx to automatically install the package without prompting. Claude Code will start the MCP server automatically when you begin a new conversation.

Step 3 (Optional): Add Your API Key for Pro Features

If you have an AI2SQL Pro account, add your API key to unlock unlimited queries and schema-aware generation:

{
  "mcpServers": {
    "ai2sql": {
      "command": "npx",
      "args": ["-y", "ai2sql-mcp"],
      "env": {
        "AI2SQL_API_KEY": "your-api-key"
      }
    }
  }
}

How to get your API key:

  1. Sign up at ai2sql.io
  2. Go to Dashboard > API Keys
  3. Click "Generate New Key"
  4. Copy the key and paste it into the config above

The key is shown only once when generated, so save it immediately.

The Four Tools

Each tool serves a distinct purpose in the SQL workflow. Here is what they do and when to use them.

generate_sql

This is the primary tool. Describe the query you need in natural language and specify a database dialect. The tool sends your request to the AI2SQL engine and returns a formatted SQL query.

Parameters:

  • query (required) -- Your natural language description. Example: "Find the top 10 customers by revenue last month"
  • dialect (optional) -- One of postgres, mysql, sqlserver, snowflake, oracle, sqlite. Defaults to postgres.
  • schema (optional, Pro) -- Your database schema in the format table1:col1(type),col2(type);table2:col1(type). Providing schema context significantly improves accuracy.

explain_sql

Paste any SQL query and get a plain English explanation. The tool breaks down each clause: what the SELECT retrieves, what the JOINs connect, what the WHERE filters, and what the GROUP BY aggregates. Useful for understanding queries written by others or reviewing AI-generated SQL before executing it.

Parameters:

  • sql (required) -- The SQL query to explain.

optimize_sql

Submit a working but slow query and get back an optimized version. The tool identifies common performance issues like missing indexes, unnecessary subqueries, inefficient JOINs, and N+1 patterns. It returns the improved query along with an explanation of each change.

Parameters:

  • sql (required) -- The query to optimize.
  • dialect (optional) -- Database dialect for dialect-specific optimizations.

fix_sql_error

When a query fails, paste both the query and the error message from your database. The tool diagnoses the problem, explains what went wrong, and returns a corrected version. This handles syntax errors, type mismatches, missing table references, and dialect-specific issues.

Parameters:

  • sql (required) -- The broken query.
  • error (required) -- The error message from the database.
  • dialect (optional) -- Database dialect for accurate fixes.

Supported Databases

AI2SQL MCP generates dialect-specific SQL for six database engines:

Database Dialect Value Notes
PostgreSQL postgres Default dialect. Full support for CTEs, window functions, JSONB.
MySQL mysql Handles MySQL-specific syntax like LIMIT, IFNULL, DATE_FORMAT.
SQL Server sqlserver T-SQL syntax including TOP, DATEADD, ISNULL, CROSS APPLY.
Snowflake snowflake Snowflake SQL with FLATTEN, VARIANT column support, QUALIFY.
Oracle oracle PL/SQL compatible syntax with ROWNUM, NVL, CONNECT BY.
SQLite sqlite Lightweight syntax for embedded databases and local development.

Each dialect uses the correct date functions, string operations, type casting, and pagination syntax for its engine. You do not need to remember whether your database uses LIMIT or TOP, ISNULL or COALESCE, or DATE_TRUNC vs DATEADD. The MCP server handles it.

Free Tier vs Pro

The AI2SQL MCP server works out of the box without an API key. Here is what each tier includes:

Feature Free Tier Pro (API Key)
generate_sql Yes (demo endpoint) Yes (full endpoint)
explain_sql Yes Yes
optimize_sql Yes Yes
fix_sql_error Yes Yes
Custom schema context No Yes
Query limits Rate limited Unlimited
API key required No Yes

The free tier is a good way to try the integration and see if it fits your workflow. When you need schema-aware generation against your actual database tables, upgrading to Pro makes the output significantly more accurate because the engine knows your exact column names and relationships.

Example Usage in Claude Code

Here are practical examples of how the four tools work inside a Claude Code session.

Generating a Query

You type in Claude Code:

"Generate a SQL query to find all users who signed up in the last 7 days and have not made a purchase, for PostgreSQL"

Claude calls generate_sql and returns:

SELECT
    u.id,
    u.email,
    u.created_at
FROM users u
LEFT JOIN purchases p ON u.id = p.user_id
WHERE u.created_at >= CURRENT_DATE - INTERVAL '7 days'
  AND p.id IS NULL
ORDER BY u.created_at DESC;

Explaining a Query

You paste a complex query you found in your codebase and ask Claude to explain it. Claude calls explain_sql and returns a breakdown like:

"This query finds users from the last 7 days who have no matching purchase records. It uses a LEFT JOIN with a NULL check on the purchases table, which is an anti-join pattern. Results are sorted by signup date, newest first."

Optimizing a Slow Query

You have a query that takes 12 seconds to run:

SELECT *
FROM orders
WHERE YEAR(order_date) = 2026
  AND customer_id IN (SELECT id FROM customers WHERE country = 'US');

Claude calls optimize_sql and returns:

SELECT o.order_id, o.order_date, o.total_amount, o.status
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE o.order_date >= '2026-01-01'
  AND o.order_date < '2027-01-01'
  AND c.country = 'US';

The explanation: replaced YEAR() function with a date range to allow index usage, converted the subquery to an INNER JOIN, and selected specific columns instead of SELECT *.

Fixing an Error

Your query fails with an error. You tell Claude:

"Fix this query. Error: column 'total' must appear in the GROUP BY clause or be used in an aggregate function"
-- Broken query
SELECT customer_id, total, COUNT(*)
FROM orders
GROUP BY customer_id;

Claude calls fix_sql_error and returns:

SELECT customer_id, SUM(total) AS total, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;

The fix wraps total in a SUM() aggregate since it was not in the GROUP BY clause.

Workflow Tips

A few tips to get the most out of the AI2SQL MCP integration:

  1. Specify the dialect upfront. If you always work with MySQL, mention it in your prompt. This avoids getting PostgreSQL syntax by default and needing to regenerate.
  2. Pass your schema for Pro users. The schema parameter accepts a compact format like users:id(int),email(varchar),created_at(timestamp);orders:id(int),user_id(int),total(decimal). This makes the generated SQL match your actual tables.
  3. Chain the tools. Generate a query, then ask Claude to explain it, then optimize it. The tools complement each other in a natural workflow.
  4. Use fix_sql_error with the exact error message. Copy the full error from your database client. The more context the tool has, the more accurate the fix.
  5. Iterate naturally. If the generated query is close but not exactly right, tell Claude what to change. It will call generate_sql again with your refined description.

Frequently Asked Questions

What is the AI2SQL MCP server?

The AI2SQL MCP server is a Model Context Protocol integration that lets you generate, explain, optimize, and fix SQL queries directly inside Claude Code. Install it with npx ai2sql-mcp and use natural language to work with SQL without leaving your terminal.

Is the AI2SQL MCP server free?

Yes, the AI2SQL MCP server includes a free tier that works without an API key. You get access to all four tools (generate, explain, optimize, fix) with a demo database endpoint. For unlimited queries and custom schema support, add your AI2SQL Pro API key to the configuration.

What databases does AI2SQL MCP support?

AI2SQL MCP supports six SQL dialects: PostgreSQL, MySQL, SQL Server, Snowflake, Oracle, and SQLite. You can specify the dialect when generating or optimizing queries, and it defaults to PostgreSQL if not specified.

How do I install AI2SQL MCP in Claude Code?

Add the ai2sql MCP server to your Claude Code settings.json file with the command npx and args ["-y", "ai2sql-mcp"]. Claude Code will automatically start the server and make the four SQL tools available in your conversations. No additional setup is required for the free tier.

Do I need to connect my database to use AI2SQL MCP?

No. The AI2SQL MCP server does not connect directly to your database. It generates SQL queries based on your natural language input and optional schema context. You then run the generated queries in your own database client. This keeps your database credentials and data completely separate from the MCP server.

Generate SQL from Plain English

Use AI2SQL inside Claude Code with MCP, or try it directly in your browser. Describe what you need and get accurate SQL for any database.

Try AI2SQL Free

No credit card required