How to Connect an MCP Server to SQL
Connect an MCP server to SQL safely: choose an architecture, configure access, register the client, verify tools, and troubleshoot failures.
Short answer: choose an MCP server that supports your SQL engine, configure its database connection, register or launch it in your MCP client, and enforce least-privilege permissions in the database. Then verify the server starts, the client discovers its tools, and a harmless read returns only the data your agent should see.
There is no universal “connect MCP to SQL” command. The exact configuration depends on the SQL engine, MCP implementation, client transport, and whether the server runs locally or remotely.
1. Choose the connection architecture
| Architecture | How it works | Permission boundary | Use it when |
|---|---|---|---|
| Direct database MCP server | The MCP process opens a database connection and exposes tools such as schema discovery, reads, and (where enabled) writes. | The database role used by the server. | You need direct control and your engine has a compatible server. Microsoft’s PostgreSQL MCP project is an example. |
| Entity/API layer | A layer such as Microsoft Data API builder maps tables, views, or procedures to entities and exposes typed MCP operations. | Entity permissions, policies, and the underlying database role. | You want a curated surface instead of unrestricted SQL. SQL MCP Server is included in Data API builder 1.7 and later and exposes seven DML tools. |
| Managed remote MCP endpoint | A cloud provider hosts the MCP endpoint and supplies documented toolsets and authentication. | Provider IAM plus database permissions and toolset restrictions. | Your database and region are supported by the provider. Google Cloud SQL documents remote MCP endpoints and read-only toolsets. |
These choices are not interchangeable. A direct server gives its connection role direct database permissions. An entity layer can restrict objects and operations before a request reaches SQL. A managed endpoint has provider-specific setup and availability.
2. Identify your engine, client, and transport
- Write down the engine (PostgreSQL, SQL Server, MySQL, SQLite, or another product).
- Confirm that the MCP server explicitly supports that engine and version.
- Check whether your host client launches a local process over
stdioor connects to a remote HTTP endpoint. - Read the selected server’s current setup guide. Do not copy a client configuration block from one product into another.
For example, Data API builder supports local stdio and remote HTTP transports, while Google Cloud SQL’s remote endpoint uses Streamable HTTP. See the SQL MCP Server overview and Cloud SQL remote MCP documentation.
3. Create a least-privilege SQL identity
The MCP server runs calls with the identity of its configured database connection. MCP does not make arbitrary SQL safe. Create a dedicated role and grant only the schemas, tables, views, and operations the workflow requires. For exploratory agents, start read-only.
PostgreSQL example
-- Run as an administrator; replace names for your environment.
CREATE ROLE mcp_reader LOGIN PASSWORD 'use-a-secret-manager';
GRANT CONNECT ON DATABASE appdb TO mcp_reader;
GRANT USAGE ON SCHEMA reporting TO mcp_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA reporting TO mcp_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA reporting
GRANT SELECT ON TABLES TO mcp_reader;
Do not put a real password in source control. On interactive machines, Microsoft’s PostgreSQL MCP guidance recommends saved connection profiles with passwords stored in the operating-system keyring. For headless CI or containers, use the implementation’s documented environment connection string, and remember that other processes in that environment may be able to read it.
SQL Server example
-- Run in the target database as an administrator.
CREATE USER mcp_reader WITH PASSWORD = 'use-a-secret-manager';
ALTER ROLE db_datareader ADD MEMBER mcp_reader;
-- Prefer schema-specific GRANT statements when db_datareader is broader than needed.
GRANT SELECT ON SCHEMA::Reporting TO mcp_reader;
Use your engine’s native authentication, secret storage, rotation, and auditing features. The server’s read-only switch, when available, is an additional guard; it does not replace database authorization.
4. Configure a direct or curated MCP server
Direct server configuration
Most direct implementations ask for a connection profile or connection string. A generic shape looks like this; property names are implementation-specific:
{
"profile": "reporting-readonly",
"database": {
"engine": "postgresql",
"host": "db.example.internal",
"port": 5432,
"name": "appdb",
"user": "mcp_reader"
},
"readOnly": true,
"schemas": ["reporting"]
}
Use the target server’s documented CLI to set the password or secret separately. Never assume this JSON is accepted unchanged by another implementation.
Data API builder / SQL MCP Server
Data API builder uses a configuration file to define the database connection, exposed entities, and permissions. A minimal illustrative structure is:
{
"data-source": {
"database-type": "mssql",
"connection-string": "@env('MSSQL_CONNECTION_STRING')"
},
"runtime": {
"mcp": { "enabled": true, "transport": "stdio" }
},
"entities": {
"orders": {
"source": { "object": "Reporting.Orders", "type": "table" },
"permissions": [
{ "role": "anonymous", "actions": ["read"] }
]
}
}
}
Use a real authenticated role and your organization’s authorization model instead of anonymous in production. Configure only the entities and actions the agent needs. SQL MCP Server exposes tools including describe_entities, read_records, create_record, update_record, delete_record, execute_entity, and aggregate_records; only enable write-capable operations when both application policy and database grants allow them. See Microsoft’s configuration and DML tool reference.
5. Register or launch the server in your MCP client
The host client normally launches a local server and communicates over stdio, or stores a remote endpoint and authentication details. The exact key names differ by client, so use its current official instructions.
A generic local registration concept is:
{
"mcpServers": {
"sql-reporting": {
"command": "your-mcp-server-binary",
"args": ["--profile", "reporting-readonly"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
}
}
For a remote server, configure its HTTPS URL, transport, and authentication in the client. Google’s Cloud SQL example uses an endpoint such as https://sqladmin.googleapis.com/mcp with provider credentials or OAuth; follow the provider’s authentication guide rather than embedding tokens in a file.
6. Verify the connection in stages
- Process: start the server by itself and confirm it exits cleanly or stays listening as documented.
- Handshake: connect from the MCP client and confirm the server name and protocol version are accepted.
- Discovery: inspect the advertised tools and ensure only intended entities or operations appear.
- Database: run a harmless schema description or
SELECTagainst a test row. - Authorization: attempt an operation that should be denied and confirm the database or entity policy rejects it.
- Audit: verify that server logs and database audit records identify the configured role and request.
Do not use a destructive query as a connectivity test. Verify with the actual database identity, not an administrator account.
7. Security checklist
- Use a dedicated role for each workflow or environment.
- Default agents to read-only database permissions.
- Limit schemas, tables, views, procedures, and MCP tools.
- Keep passwords and tokens in a keyring, secret manager, or protected runtime variable.
- Understand that environment variables can be visible to processes in the same container or host.
- Require approval for writes, DDL, exports, and procedures with side effects.
- Log tool calls, database principals, query duration, row counts, and denials.
- Review data returned to the model: the surrounding application can forward it outside the database.
The server automatically follows the same permissions and security rules as your API and database. — Microsoft Learn
8. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Client says the server is not found | Wrong command path, arguments, working directory, or JSON syntax. | Run the command directly, use an absolute path, validate the client config, and inspect the client’s startup log. |
| Handshake or protocol error | Client and server expect different transports or protocol versions. | Use stdio for a local process, or the server’s documented HTTP transport for remote use. Update both components according to their release notes. |
| Connection refused or timeout | Database host or port is unreachable, firewall rules block it, or TLS settings are wrong. | Test network reachability from the MCP server’s runtime, verify the port and TLS mode, and allow only the required network path. |
| Authentication failed | Bad secret, wrong database, expired token, or an authentication method unsupported by the server. | Set the secret through the documented mechanism, check the selected profile, rotate expired credentials, and confirm the database user can log in outside MCP. |
| Tools are missing | Entity, schema, action, or tool exposure is disabled. | Inspect the server configuration and permissions. Restart or reload it as required, then rediscover tools in the client. |
| Permission denied on a read | The database role lacks schema, table, column, or view privileges. | Grant the smallest required privilege to the dedicated role and retest as that role. |
| Writes succeed unexpectedly | The database role is broader than intended or a write tool is exposed. | Revoke write grants, disable write actions, and add an approval gate. Test a denied write explicitly. |
| Queries are slow | Large scans, missing indexes, network latency, or expensive aggregates. | Expose filtered views, add appropriate indexes, cap result sizes, require pagination, and measure database execution time separately from model latency. |
| Secrets appear in logs | Connection strings or debug logging include credentials. | Redact logs, disable verbose secret output, rotate exposed credentials, and use structured secret references. |
Microsoft maintains a dedicated SQL MCP troubleshooting guide for transport, permissions, and client integration issues.
9. Performance, reliability, and cost
- Latency: a tool call includes model planning, MCP transport, database execution, and result serialization. Keep result sets narrow and paginate large reads.
- Concurrency: configure database connection pooling and server limits for your workload. Protect the database from unbounded agent loops.
- Reliability: use health checks, timeouts, retries only for safe idempotent reads, and circuit breaking for remote endpoints. Never blindly retry a write.
- Schema stability: expose views or entities with stable names and descriptions. A schema migration can invalidate an agent’s assumptions.
- Observability: correlate MCP request IDs with database logs. Data API builder documents health checks and OpenTelemetry instrumentation.
- Cost: direct servers add compute, database, logging, and network costs. Managed endpoints add provider usage or infrastructure charges. The dossier contains no universal benchmark, so measure with your own queries and concurrency.
10. Or skip the browser setup
If you need screenshots of your MCP documentation, dashboards, or SQL results for release notes, ScreenshotNeo can capture a URL with one request. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server lets Claude, Cursor, and other MCP clients take screenshots.
See the ScreenshotNeo API documentation for all options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
You get clean PNG, JPEG, WebP, or PDF captures. Every response identifies the page verdict and whether it was billed. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
FAQ
Can MCP execute arbitrary SQL?
Only if the selected implementation exposes such a tool and the database role permits it. Curated servers such as Data API builder expose configured entities and typed operations instead of handing an agent unrestricted database access.
Should I use a remote MCP endpoint?
Use one when your provider supports the database and toolset you need and your identity, network, and data-residency requirements are satisfied. Otherwise run a local or self-hosted server.
Is a server-level read-only flag enough?
No. Enforce read-only access in the database role as well. Server settings are an extra safeguard, not the durable authorization boundary.
Which SQL engine should I start with?
Start with the engine already used by your application and choose an MCP server that explicitly supports it. The title alone does not identify PostgreSQL, SQL Server, MySQL, or SQLite.
How do I expose only a few tables?
Restrict the database role to those objects and configure the MCP server or entity layer to advertise only those schemas, entities, and actions.


