How to Connect TiDB to Cursor for AI-assisted App Development
Jump to a Section
Updated June 2026 | Author: Akshata Hire (Product Marketing Lead) | Reviewed by: Bernard Kavanagh (Principal Solutions Architect)
Cursor connects to databases through MCP servers: local processes that the editor spawns to retrieve schema context, run read queries, and pass results into the model's context window before generation. Without an MCP server, the model generates SQL against whatever schema it saw during training, which is stale the moment your table structure diverges from common patterns. With one, it generates against your actual schema state.
TiDB's official MCP server, maintained by PingCAP, handles schema introspection, read query execution, and metadata retrieval. This guide covers the setup path for TiDB Cloud and self-managed clusters, the security model you need in place before enabling live database access, and the specific architectural properties (HTAP, MySQL compatibility, native vector search) that make TiDB a practical choice for teams building AI-assisted applications on distributed SQL.
Key Takeaways
TiDB is the only distributed SQL database with an official MCP server maintained by its own engineering team, tested against current Cursor releases rather than left to community maintenance.
TiDB's HTAP architecture lets the same cluster serve both transactional writes and analytical reads through TiFlash, removing the pipeline dependency that forces most distributed SQL setups to route analytics queries elsewhere.
MySQL wire-protocol compatibility means Cursor generates correct-dialect SQL without adjustment, which matters for any team already running MySQL drivers, ORMs, or query builders.
Schema metadata retrieved by the MCP server enters the model context and is sent to Cursor's model provider. Teams with sensitive schemas should connect against a sanitized read replica, not a production cluster.
Never grant DROP, DELETE, or DDL to the Cursor database user. Prompt injection via a data value in a retrieved row is a real attack surface if write permissions are in scope.
Start a free TiDB Cloud Starter cluster and connect to Cursor in under 30 minutes.
TiDB Cloud is the recommended setup path. Connection details, CA certificates, and IP allowlisting are all managed from one console. Self-managed TiDB clusters use the same MCP configuration but require you to handle cert distribution and network exposure independently.
The prerequisites table below doubles as a configuration checklist. The most common first-time failures are a missing CA cert path, an IP allowlist entry that does not match the machine running Cursor, and a Python version below 3.10.
Requirement
Where to Configure It
Why It Matters
Cursor 1.0+
cursor.com/download
MCP server management and one-click tool activation shipped in 1.0. Earlier builds have limited or no MCP support. Check cursor.com/changelog before assuming compatibility.
TiDB Cloud cluster or self-managed TiDB
tidbcloud.com or your ops runbook
TiDB Cloud Starter gives you a gateway-connected cluster in under 5 minutes. Self-managed clusters require you to expose port 4000 and handle cert distribution.
uv or Python 3.10+
astral.sh/uv or python.org
The TiDB MCP Server is a Python process. uv handles the install and version management in one command. If your environment already has Python 3.10+, pip install works instead.
Dedicated DB user with SELECT
TiDB Cloud console or: CREATE USER / GRANT SELECT
Do not reuse an admin credential. The MCP server holds this credential in plaintext env vars. A dedicated read-only user limits blast radius on exposure.
Connection string + CA cert path
TiDB Cloud console > Connect > General
TiDB Cloud Starter connects via a gateway hostname (e.g. gateway01.us-east-1.prod.aws.tidbcloud.com). Dedicated connects directly. Both use port 4000 with TLS required.
MCP config registered in Cursor
Settings → Tools & MCP (global) or .cursor/mcp.json (per-project)
Per-project config takes priority over global. Use per-project if different repos need different database users or schemas.
Table 1: Prerequisites and configuration checklist for connecting TiDB to Cursor.
Set up TiDB Cloud Access for Cursor
TiDB Cloud Starter provisions in under five minutes and is the right target for initial integration work: isolated from production, free tier available, and disposable if you want to reset. TiDB Cloud Dedicated is the path for persistent development environments or teams that need dedicated compute.
In the cluster overview, open Connect and select General as the connection type. Copy the host, port, default database, and CA certificate path. TiDB Cloud Starter clusters connect through a gateway hostname; Dedicated clusters connect directly. Both use port 4000 with TLS required.
Create a dedicated database user before configuring the MCP server. Do not use the admin credential:
-- Minimum viable permissions for Cursor MCP access
CREATE USER 'cursor_ro'@'%' IDENTIFIED BY '<strong_password>';
-- Scope to the schemas Cursor needs, not the entire cluster
GRANT SELECT ON your_app_db.* TO 'cursor_ro'@'%';
FLUSH PRIVILEGES;
-- Verify before proceeding
SHOW GRANTS FOR 'cursor_ro'@'%';
Cursor supports two MCP config scopes: global via Settings → Tools & MCP, or per-project via a .cursor/mcp.json file in the repository root. Per-project config takes priority. Use per-project when different repositories need different database users, schema scopes, or cluster endpoints.
Reference the password via an environment variable (${TIDB_PASSWORD}) rather than hardcoding it. If uv is not installed:
curl -LsSf https://astral.sh/uv/install.sh | sh
Restart Cursor after saving the config. Changes to mcp.json are not hot-reloaded. Confirm the server is active under Settings → Tools & MCP before proceeding. For alternative Python setup paths, see integrate TiDB MCP Server with Cursor.
Test Schema Access and Run The First Query
Two tests confirm the integration is working end-to-end: schema introspection and SQL generation. If either returns a generic response instead of schema-grounded output, the MCP server is not connected. Check the troubleshooting section before proceeding.
Schema introspection test:
List the tables in the current database with their column names,
data types, and any foreign key relationships.
A working connection returns your actual schema. A non-working one returns a generic description or an error. Once schema introspection passes, test SQL generation against a multi-table query to confirm join resolution:
SQL generation test:
Write a query showing the 7-day rolling retention rate by signup cohort.
Use the users and events tables. Filter to the last 90 days.
This is a query type that exposes whether the model is reasoning about your actual schema or hallucinating column names. Review the generated SQL against your table structure before executing.
What Do You Need Before Cursor Can Access Your Database?
Three layers need to be working independently before the MCP integration functions. Debugging is faster when you check each layer in isolation rather than treating the setup as a single pipeline.
Cursor and MCP tooling: Cursor 1.0 or later with the MCP server entry registered and showing as active in Settings → Tools & MCP. This is independent of any Cursor extensions or plugins.
MCP server process: The tidb-mcp-server process, managed by uvx, running successfully on your local machine with valid credentials and a reachable endpoint. Errors here surface in the Cursor MCP status panel.
Network and TLS: Port 4000 reachable from your local machine to the TiDB Cloud cluster, your local IP on the TiDB Cloud allowlist, and the CA cert path correctly set in TIDB_SSL_CA. TiDB Cloud will refuse connections without TLS. This is the most common misconfiguration.
The security boundary that matters most before enabling write access is the difference between what the MCP server can do and what the LLM can request. The MCP server executes whatever SQL the model generates, within the permissions of the database user. If the user has SELECT only, the worst case from a prompt injection is a full-table scan. If the user has DELETE or DDL rights, the worst case is data loss. Keep the Cursor database user scoped to SELECT, even on a development cluster.
Schema metadata the MCP server retrieves enters the model's context window. That context is sent to Cursor's model provider for inference. Teams with PII column names, sensitive taxonomy, or regulated identifiers in their schema should connect against a sanitized read replica rather than a direct cluster connection.
How Cursor AI Database Integration Works with MCP
MCP (Model Context Protocol) is the open standard Anthropic published for connecting AI assistants to external tools. In Cursor's implementation, an MCP server is a local process that Cursor can invoke as a tool call, passing arguments, receiving structured results, and injecting those results into the model context before generating a response.
For database integration, the sequence is: Cursor receives a prompt, determines database context is relevant, calls the TiDB MCP Server tool, receives schema or query results as structured JSON, appends that context to the prompt, then generates a response grounded in your actual database state. The model never touches the database directly. All access goes through the MCP server process, which enforces the permissions of the database user you configured.
Why MCP is Better Than Pasting Schema
Manually pasting schema into Cursor context breaks in three predictable ways at engineering-team scale: it drifts the moment any column is added or renamed, it does not capture foreign key relationships and index definitions that affect query generation, and it does not fit in context when a query spans more than a handful of tables.
MCP retrieves the current schema state on each invocation. The model sees your actual table structure as it exists when the query is generated, not as it existed when someone last updated a markdown file. For teams running frequent migrations, this is the difference between AI-generated SQL that runs and SQL that needs a round of manual corrections before it can.
Where TiDB Fits in an AI Coding Workflow
TiDB's HTAP (hybrid transactional/analytical processing) architecture is the property most relevant to AI-assisted development. TiKV handles transactional writes with Raft-based consensus and ACID guarantees across distributed nodes. TiFlash, the columnar engine, replicates from TiKV automatically and handles analytical queries from the same cluster, with no ETL, no separate pipeline, and no consistency lag between the operational store and the analytics layer.
For AI-assisted development, this matters because the queries Cursor generates most frequently are not pure OLTP. Schema exploration, cohort analysis, usage rollups, and debugging queries routinely cross the OLTP/OLAP boundary. On a database without HTAP, those queries either hit the transactional engine with full-table scans or require a separate data warehouse the Cursor workflow cannot reach through the same MCP connection. On TiDB, the MCP server reaches both workload types from one endpoint.
TiDB's MySQL compatibility operates at the wire protocol level. MySQL drivers, ORMs, and query builders connect without modification. This means queries Cursor generates for a MySQL-native schema work against TiDB without syntax adjustment. For more on how live schema access changes AI output quality, see natural language database interaction with TiDB MCP Server.
How to Use TiDB and Cursor for Real App Development
The examples below are scoped to the query types architects and platform engineers run during AI-assisted backend development: not simple lookups, but the multi-table, multi-condition queries where schema context actually changes the quality of the output.
Generate SQL with Live Schema Context
Schema-grounded SQL generation changes the most for complex analytical queries, where the model needs to resolve join paths across multiple tables and choose between competing indexes. With the MCP server connected, you can specify the query in business terms and let the model handle the SQL structure:
Prompt in Cursor chat:
Write a query for the 30-day user retention funnel.
Define activation as completing the onboarding_events.type = 'first_action' event.
Use the users, sessions, and onboarding_events tables.
Group by signup week. Return the raw counts and the D1/D7/D30 retention rates.
The model resolves join paths, date truncation logic, and aggregation structure against your actual schema. Before running: verify the WHERE filters match your event taxonomy, confirm the date column names and types match what the generated query assumes, and run EXPLAIN to check whether the query uses the indexes you have on the sessions and events tables.
This pattern extends to schema migrations. When adding a new table or modifying a column, ask Cursor to generate the corresponding ORM model, API handler, or migration script against the updated schema. The MCP server retrieves the post-migration schema state, provided the migration has run in the target environment.
Debug Backend Code Faster with Database Access
When a backend endpoint returns unexpected data, the debugging loop typically involves switching between the ORM query, the raw SQL it generates, the database client, and the application logs. With Cursor connected to TiDB, you can keep that loop inside the editor.
Open the file containing the problematic query and ask Cursor to explain what it generates against your actual schema, identify whether the ORM is producing a suboptimal join or a missing index hint, or rewrite it with explicit query hints for TiDB's optimizer. Cursor can also identify N+1 patterns, incorrect isolation levels for transactional boundaries, and cases where a query would benefit from routing to TiFlash instead of TiKV.
The same caveat applies: verify suggested changes against your actual data and execution plan before merging. Index additions and transaction boundary changes have real latency and consistency implications in a distributed system.
Review AI Output Before Production Use
The failure modes for AI-generated SQL are predictable: incorrect join conditions that produce a cartesian product, missing WHERE filters that cause full-table scans on large tables, aggregations that group by the wrong key, and subqueries that defeat the optimizer. None of these produce a syntax error. They produce wrong results or runaway query costs. Review every query before production execution. The guide on production-grade AI coding for TiDB documents specific patterns for making AI-assisted development reliable at the scale where these failure modes have real consequences.
For schema changes and index additions, understand the operational impact before accepting the suggestion. Adding an index on a large TiKV table has write amplification costs. Changing a transaction boundary in a distributed system affects consistency guarantees across nodes. These are not changes to accept because the diff looks clean.
TiDB's official MCP server is maintained against current Cursor releases. Test the integration against your own schema.
Checklist for a Safe and Reliable Cursor Database Connection
Run through this before enabling live database access in Cursor. The items marked with specific technical detail address failure modes that generic security checklists miss for AI coding workflows specifically.
Area
Action
Credentials
Create a dedicated DB user for Cursor. Store its password in an environment variable, not in the mcp.json file directly. Rotate after any shared use.
Least privilege
GRANT SELECT only on the schemas Cursor needs. Never grant DROP, DELETE, or DDL, not even on a dev cluster. A prompt injection attack via a poisoned data value can cause the model to issue destructive statements if it has the permissions to execute them.
Environment separation
Point the MCP server at a dev or staging cluster. If you use TiDB Cloud, the Starter tier is purpose-built for this: isolated from prod, free, and disposable.
Schema scoping
Set TIDB_DATABASE to the specific schema Cursor needs. Exposing every schema in the cluster increases the size of the context the model retrieves on each call and raises the risk surface.
LLM context exposure
Schema metadata retrieved by the MCP server enters the model context and is transmitted to Cursor's model provider (currently Anthropic or OpenAI depending on your Cursor settings). If your schema includes PII column names, regulatory classifications, or proprietary taxonomy, use a sanitized schema or read replica rather than a direct production connection.
SQL review
Treat every model-generated query as a draft. Check JOIN conditions, WHERE filters, and whether the query plan uses the indexes you expect. Run EXPLAIN before executing on a dataset with more than a few thousand rows.
SSL
TLS is required for TiDB Cloud. Download the CA cert from the Connect dialog and pass the path as TIDB_SSL_CA. Without it, the MCP server connection will be refused.
Audit trail
Enable TiDB's statement summary tables (tidb_stmt_summary) or the slow query log to trace what was executed during AI-assisted sessions. This matters for incident review.
Secrets management
Do not commit mcp.json if it contains credentials. Add it to .gitignore or use a secrets manager to inject env vars at runtime.
Table 2: Security and reliability checklist before enabling live database access in Cursor.
How to Troubleshoot TiDB and Cursor Integration Issues
Failures fall into three categories. Check the Cursor MCP status panel first. It surfaces whether the server process started and whether the last tool call returned an error. If the panel shows the server as active but Cursor responses are not schema-grounded, the server is running but not being invoked. This is usually a Cursor version or MCP config scope issue.
Fix Authentication and Permission Errors
Access denied for user. The credential in TIDB_USER/TIDB_PASSWORD does not match an existing user or the password is wrong. Verify independently: mysql -h HOST -P 4000 -u cursor_ro -p from the terminal. If this fails, the MCP server will too.
SSL connection required / certificate error. TIDB_SSL_CA is missing or points to the wrong file. TiDB Cloud's CA cert is downloadable from the Connect dialog. The path must be absolute, not relative.
SELECT command denied. The database user exists but lacks SELECT on the target schema. Run SHOW GRANTS FOR 'cursor_ro'@'%'; to check. Re-run GRANT SELECT if needed.
Host is not allowed. The machine's IP is not on the TiDB Cloud allowlist. TiDB Cloud Starter and Dedicated both enforce IP allowlisting. Add the current IP in the cluster network settings, or if behind a NAT, add the outbound IP your traffic exits from.
Resolve MCP Server and Dependency Issues
uvx: command not found. uv is not installed. Run curl -LsSf https://astral.sh/uv/install.sh | sh and restart the terminal. If you prefer pip: pip install tidb-mcp-server
MCP server inactive after config change. Cursor does not hot-reload mcp.json. A full restart is required after any config edit.
Server active, schema returns empty. TIDB_DATABASE does not match an existing schema name. TiDB schema names are case-sensitive. Verify with SHOW DATABASES; from a direct connection.
Python version error. The MCP server requires Python 3.10+. uv manages Python versions independently of the system Python. Run uv python install 3.11 if the system version is older.
Check Trust Settings and Security Controls
Cursor prompts to trust the MCP server on first use. Approve in the Cursor settings panel. This is a one-time prompt per server config entry.
Endpoint security software (CrowdStrike, Carbon Black, Jamf) can silently kill local process spawning. If the MCP server fails to start with no clear error, check the EDR logs before debugging the config.
On macOS, Gatekeeper quarantines unsigned binaries. Run the tidb-mcp-server process once directly from the terminal to trigger the approval prompt, then retry from Cursor.
Per-project mcp.json files should be in .gitignore unless credentials are fully externalized via environment variables. A committed mcp.json with credentials in it is a secret leak.
How TiDB Helps Cursor Work Better with Live Data
The value of an MCP database connection scales with what the database can do from a single endpoint. A database that requires separate connections for transactions, analytics, and vector search means separate MCP server configurations, separate schema contexts, and more integration surface for Cursor to reason across. TiDB consolidates those workloads.
Why TiDB is a Strong Fit for AI-assisted App Development
TiDB's distributed architecture shards data across TiKV nodes transparently, with no application-level sharding logic, no schema changes at scale thresholds, and no Vitess-style shard routing in the application layer. TiDB enforces ACID transactions across nodes via two-phase commit, with the Placement Driver coordinating timestamps. This means Cursor-generated transactional code does not need to account for eventual consistency or distributed transaction caveats that some competing systems require.
TiFlash handles real-time, lightweight OLAP on live transactional data from the same cluster. The distinction matters for AI coding workflows: queries that aggregate across large fact tables (events, logs, metrics) run against TiFlash automatically when the optimizer determines columnar execution is faster, while point lookups and writes hit TiKV. From the MCP server's perspective, this is one connection. Cursor does not need separate configuration for analytical versus transactional query generation.
TiDB also supports vector search natively through SQL, with no separate index service or external embedding store required. That means an application storing embeddings for RAG, semantic search, or recommendation features can keep them in the same TiDB cluster as its operational data. Cursor can generate SQL across both in one query.
For the current list of supported framework integrations (LangChain, LlamaIndex, Airbyte, dbt, Terraform, and deployment platforms), see the TiDB integrations page.
Build AI Applications on TiDB
Connecting TiDB to Cursor solves the schema context problem in your development environment. The same architecture (distributed SQL, HTAP, native vector search, ACID guarantees) carries through to production AI applications: RAG pipelines that query embeddings and relational data in the same transaction, multi-agent systems that need isolated state per agent branch, and high-volume inference logging that needs both fast writes and analytical access to prompt-response history.
MCP gives Cursor live schema access, and that is what makes AI-generated SQL accurate rather than plausible. TiDB ships an official MCP server maintained against current Cursor releases, combined with the architectural properties that make the same database useful beyond the development environment.
Start a free TiDB Cloud Starter cluster and run the first AI-assisted query in under 30 minutes. For production use cases, architecture guidance, and code samples on combining vector search with distributed SQL, see the TiDB AI solutions page.
About the author: This guide was produced by the PingCAP technical content team. PingCAP builds TiDB and TiDB Cloud. Technical claims are reviewed by PingCAP engineers. To report an error, contact the team via the PingCAP website.
Ready to connect TiDB to Cursor? Start a free cluster in under 5 minutes.
Cursor connects to TiDB through the TiDB MCP Server, a local process that handles schema introspection and query execution on Cursor's behalf. There is no direct database connector built into Cursor. TiDB Cloud simplifies the setup by providing connection strings, CA certificates, and IP allowlisting from one console. Self-managed TiDB clusters use the same MCP configuration but require independent cert distribution and network access management.