Architecture·10 min read·5 August 2026

Connect Claude to Database MCP: A Production Guide

Learn how to connect Claude to database MCP servers safely in production: transport choice, auth, tool design, security scoping, and observability in one practical guide.

By Solomon Udoh · AI Architect & Certification Lead

Connect Claude to Database MCP: A Production Guide

When you connect Claude to database MCP, you are wiring a language model's tool-use loop directly to live data. Done well, it unlocks reliable, auditable query workflows. Done carelessly, it exposes credentials, leaks schema, and opens prompt-injection paths. This guide covers every layer: transport selection, authentication, tool design, security scoping, observability, and staged rollout, grounded in the Model Context Protocol specification and the CCAR-F exam domain on Tool Design & MCP Integration.

What is the Model Context Protocol and why does it matter for databases?

MCP is an open protocol that standardises how a host application (Claude, in our case) discovers and calls tools exposed by an external server. For database access, the MCP server sits between Claude and your data store: it receives a JSON-RPC tool call, executes the query, and returns a structured result. Claude never holds a raw connection string; the server does.

This separation matters for three reasons. First, it enforces a single enforcement point for access control. Second, it makes the tool surface auditable: every call is a discrete JSON-RPC request with a method name and typed parameters. Third, it lets you version, test, and replace the server without touching the Claude integration.

The Claude Partner Network, a $100M programme with over 40,000 partner applicant firms as of 3 June 2026, has made MCP the standard integration layer for production Claude deployments. Understanding it is now a core competency tested in the CCAR-F exam under Domain 2 (Tool Design & MCP Integration, 18% of the exam).

How do you choose between stdio and Streamable HTTP transport?

Transport choice is the first architectural decision, and it has downstream consequences for security, scalability, and debugging.

TransportTypical useProsCons
stdioLocal dev, single-user CLI toolsZero network config, simple process lifecycleDoes not scale beyond one user; no remote access
Streamable HTTP (SSE)Remote servers, multi-tenant productionHorizontally scalable, supports auth headers, works across networksRequires TLS, token management, and a reverse proxy

For a database MCP server that multiple engineers or agents will share, Streamable HTTP is the correct choice. stdio is appropriate only when the server runs as a child process on the same machine as the Claude client, which is common in local Claude Code workflows but unsuitable for a shared PostgreSQL or BigQuery integration.

A minimal Streamable HTTP server entry in a Claude Code settings.json looks like this:

json
{
"mcpServers": {
"analytics-db": {
"type": "http",
"url": "https://mcp.internal.example.com/analytics-db",
"headers": {
"Authorization": "Bearer ${ANALYTICS_MCP_TOKEN}"
}
}
}
}

Note the ${ANALYTICS_MCP_TOKEN} expansion. Claude Code supports environment variable interpolation in MCP config, which keeps secrets out of version-controlled files. Our concept on Environment Variable Expansion in MCP Config covers the exact syntax and scoping rules.

How should authentication and per-user permissions work?

A database MCP server must not use a single privileged service account for all callers. That pattern collapses all access into one credential and makes per-user auditing impossible.

The recommended pattern for enterprise deployments:

  1. The MCP server receives the caller's identity token in the Authorization header.
  2. The server validates the token against your identity provider (Okta, Azure AD, or similar).
  3. The server maps the validated identity to a database role with the minimum required privileges.
  4. All queries execute under that role; the server logs the caller identity alongside the SQL.

For agent workflows where Claude itself is the caller rather than a human, use a dedicated service account scoped to the specific tables and operations the agent needs. Apply the same principle the CCAR-F exam rewards consistently: proportionate fixes and root-cause scoping rather than broad permissions.

Multi-tenant scenarios add a layer: the server must ensure that tenant A's token cannot retrieve tenant B's rows. The safest implementation adds a mandatory tenant_id predicate to every query at the server layer, not in the tool description or system prompt, because prompt-level controls can be overridden by a sufficiently adversarial input.

Servers SHOULD implement appropriate authentication mechanisms to verify client identity and authorization. For sensitive operations, servers SHOULD require explicit user confirmation.

Anthropic , Model Context Protocol Specification

How do you design database tools that Claude selects reliably?

Tool descriptions are the primary selection mechanism. Claude reads the description to decide which tool to call; a vague description produces misrouting. Our concept on Tool Descriptions as Selection Mechanism explains the underlying mechanics in detail.

For a database integration, apply these principles:

Split by operation type, not by table. A single run_sql tool that accepts arbitrary SQL is a security and reliability anti-pattern. Instead, expose narrow tools:

json
{
"name": "query_orders",
"description": "Read-only query against the orders table. Returns rows matching the filter. Use this when the user asks about order status, order history, or revenue by period. Do NOT use for mutations.",
"inputSchema": {
"type": "object",
"properties": {
"filter": {
"type": "object",
"description": "Key-value pairs to filter rows, e.g. {\"status\": \"pending\"}",
"additionalProperties": {"type": "string"}
},
"limit": {
"type": "integer",
"default": 50,
"maximum": 500
}
},
"required": ["filter"]
}
}

Separate read and write tools explicitly. Claude will not accidentally mutate data if the only mutation tool has a description that begins "WRITE OPERATION: inserts or updates rows in...". The description signals intent and triggers more careful model reasoning.

Return structured errors, not raw exceptions. When a query fails, the server should set isError: true in the tool result and return a structured payload:

json
{
"isError": true,
"content": [
{
"type": "text",
"text": "Query failed: relation \"orders\" does not exist. Check the schema name."
}
],
"meta": {
"errorCode": "RELATION_NOT_FOUND",
"schema": "public",
"table": "orders"
}
}

This pattern, covered in our MCP isError Flag Pattern concept, allows Claude to reason about the failure and attempt a corrective action rather than silently propagating an opaque error upstream.

What security controls prevent prompt injection and credential leakage?

Connecting Claude to a database MCP server introduces two distinct attack surfaces: the tool call path (Claude to MCP server) and the data return path (database rows back to Claude's context).

On the tool call path:

  • Validate all tool input parameters server-side before constructing any query. Never interpolate raw tool arguments into SQL strings; use parameterised queries exclusively.
  • Reject tool calls that arrive without a valid identity token, even if the MCP client claims to be Claude.
  • Log every tool call with the caller identity, the tool name, the input parameters (redacting secrets), and the latency.

On the data return path:

  • Truncate large result sets before returning them to Claude. A query that returns 50,000 rows will fill the context window and degrade model performance. Set a hard row limit at the server layer.
  • Sanitise returned data for prompt-injection patterns if the database stores user-generated content. A row containing Ignore previous instructions and... in a text column is a real threat vector.
  • Never return raw credentials, API keys, or PII that the agent does not need for its current task.

On server installation:

Only install MCP servers from sources you control or have audited. Third-party database MCP servers may request broader tool scopes than they need. Review the tools/list response before approving a server for production use, and prefer servers that expose a minimal, well-documented tool surface.

How do you model database access as resources versus tools?

MCP distinguishes between tools (callable operations with side effects or query logic) and resources (addressable content that clients can read). For database integrations, the distinction matters:

ConceptUse forExample
ToolParameterised queries, mutations, aggregationsquery_orders, insert_event, run_aggregation
ResourceStatic or slowly-changing schema information, table catalogsdb://schema/orders, db://catalog/tables
PromptReusable query templates with user-facing descriptions"Summarise last 30 days of revenue"

Exposing your database schema as a resource rather than embedding it in every tool description reduces token overhead and keeps tool descriptions focused on selection logic. Claude can fetch the schema resource when it needs to reason about column names, then call the appropriate tool.

Our concept on MCP Resources for Content Catalogs explains how to structure resource URIs and when this pattern outperforms embedding schema in system prompts.

How do you handle tool schema drift without breaking sessions?

Database schemas change. When a column is renamed or a table is dropped, the MCP server's tool schemas must update to match. If a Claude client has cached the old tools/list response, it may call a tool with parameters that no longer exist.

The safest production pattern:

  1. Version your tool names when making breaking changes: query_orders_v2 alongside query_orders_v1 during a transition window.
  2. Return a structured error from deprecated tools rather than silently failing, so Claude can surface the issue to the operator.
  3. Set a short cache TTL on tools/list responses in your MCP server, or signal capability changes via the notifications/tools/list_changed notification if your transport supports it.
  4. Test schema changes with the MCP Inspector before deploying to production clients.

For agentic workflows where Claude runs long sessions, tool schema drift mid-session is particularly disruptive. The Stale Context Problem concept covers the broader pattern of context invalidation in extended agent runs.

How do you validate and roll out a database MCP server safely?

A staged rollout reduces the blast radius of a misconfigured server.

text
Stage 1: Local validation
- Run the server locally with stdio transport
- Use MCP Inspector to call each tool manually
- Verify parameterised queries, error responses, and row limits
Stage 2: Integration test with Claude Desktop
- Add the server to Claude Desktop's MCP config
- Run representative prompts and inspect tool calls in the activity log
- Confirm identity token flow and that no credentials appear in responses
Stage 3: Staging environment with Streamable HTTP
- Deploy behind a reverse proxy with TLS
- Run automated tests against the staging server using a test identity
- Validate that tenant isolation predicates work correctly
Stage 4: Production with monitoring
- Enable structured logging for all tool calls
- Set up alerts on isError rate and p99 latency
- Restrict initial rollout to a single team or use case

The CCAR-F exam consistently rewards this kind of staged, deterministic approach over probabilistic shortcuts. When stakes are high (and a misconfigured database tool is high-stakes), the exam expects you to prefer explicit gates over optimistic assumptions.

What should you log and monitor in production?

Observability for a database MCP server requires logging at three layers:

MCP protocol layer: Log every tools/list request (to detect stale-cache issues), every tool call with its method name and input schema hash, and every response with its isError status and latency.

Database layer: Log the actual SQL executed, the database role used, the row count returned, and the query execution time. Correlate these with the MCP-layer logs using a shared request ID.

Claude context layer: If you have access to Claude's tool use blocks (via the Messages API), log the tool_use and tool_result blocks. This lets you trace exactly what Claude sent, what the server returned, and how Claude interpreted the result.

A structured log entry for a tool call might look like:

json
{
"timestamp": "2026-07-11T14:32:01Z",
"request_id": "req_01abc",
"tool": "query_orders",
"caller_identity": "user:[email protected]",
"db_role": "analyst_readonly",
"rows_returned": 42,
"query_latency_ms": 87,
"mcp_latency_ms": 94,
"is_error": false
}

Alerting thresholds worth setting from day one: isError rate above 5% (indicates schema drift or permission issues), p99 latency above 2 seconds (indicates query performance regression), and zero-row responses above 20% of calls (may indicate filter logic errors in tool descriptions).

Servers SHOULD implement comprehensive logging for debugging and monitoring purposes, including request handling, tool execution, error conditions, and performance metrics.

Anthropic , Model Context Protocol Specification

How does this map to the CCAR-F exam?

If you are preparing for the Claude Certified Architect, Foundations exam (CCAR-F, $125, 60 items, 120-minute time limit, passing score 720), database MCP integration appears primarily in Domain 2 (Tool Design & MCP Integration, 18%) and Domain 1 (Agentic Architecture & Orchestration, 27%). Scenario items will test your ability to diagnose tool misrouting, choose between resource and tool modelling, and select the right error-handling pattern.

The Tool Design & MCP Integration section of our concept library covers all 174 atomic concepts mapped to the five exam domains. For the specific patterns discussed in this post, start with Writing Effective Tool Descriptions and MCP Server Integration Best Practices.

AI Skill Certs is an independent prep platform; we are not affiliated with or endorsed by Anthropic.

Frequently asked questions

Can I connect Claude to a PostgreSQL database using MCP?
Yes. You run a PostgreSQL MCP server that exposes parameterised query tools, configure Claude (via Claude Desktop or Claude Code) to connect to it over stdio or Streamable HTTP, and Claude calls those tools during its agentic loop. The server holds the connection string; Claude never sees raw credentials.
Is it safe to give Claude direct SQL execution via MCP?
Only if the MCP server enforces strict controls: parameterised queries to prevent injection, a read-only database role for query tools, row-count limits to prevent context flooding, and identity-based access so every call is attributable. A generic 'run any SQL' tool with a privileged account is a significant security risk.
What MCP transport should I use for a shared database server in production?
Use Streamable HTTP (SSE) for any server shared across multiple users or agents. It supports authentication headers, scales horizontally, and works across network boundaries. Reserve stdio for local, single-user development workflows where the MCP server runs as a child process on the same machine.
How do I prevent a database MCP tool from returning too much data to Claude?
Enforce a hard row limit at the MCP server layer, not in the tool description. Set a default limit (for example, 50 rows) and a maximum (for example, 500 rows) in the tool's input schema. Return a pagination token or a count field so Claude knows whether results were truncated and can request the next page if needed.
Does the CCAR-F exam test database MCP integration specifically?
The exam does not name specific databases, but Domain 2 (Tool Design & MCP Integration, 18%) and Domain 1 (Agentic Architecture & Orchestration, 27%) both include scenario items on tool design, error handling, and MCP server configuration that directly apply to database integrations. The exam rewards narrow, well-described tools and structured error responses.
How do I handle a database schema change without breaking my Claude MCP integration?
Version breaking tool changes (for example, query_orders_v2), return structured errors from deprecated tools rather than failing silently, set a short cache TTL on tools/list responses, and test every schema change with the MCP Inspector before deploying. For long-running agent sessions, consider sending a tools/list_changed notification to invalidate cached capability lists.

People also ask

How do I connect Claude to a database using MCP?
Run an MCP server that wraps your database with parameterised query tools, then add it to Claude's MCP config using stdio for local dev or Streamable HTTP for remote access. Claude discovers the tools via tools/list and calls them during its agentic loop. The server holds credentials; Claude never sees the connection string.
What is the Model Context Protocol used for with Claude?
MCP is an open protocol that standardises how Claude discovers and calls external tools and resources. For databases, it means Claude sends a JSON-RPC tool call to an MCP server, the server executes the query, and returns a structured result. It creates a single, auditable enforcement point for access control and query logic.
Is MCP secure for database access with Claude?
MCP can be secure if implemented correctly: use parameterised queries to prevent injection, validate caller identity on every request, scope database roles to minimum required privileges, sanitise returned data for prompt-injection patterns, and enforce row limits. A poorly configured MCP server with a privileged account and no auth is not safe.
What is the difference between an MCP tool and an MCP resource for database integration?
Tools are callable operations with parameters, such as query_orders or insert_event, used for dynamic queries and mutations. Resources are addressable, readable content like database schema or table catalogs. Exposing schema as a resource reduces token overhead in tool descriptions and keeps tool selection logic focused on operations.
How do I debug a Claude MCP database connection that is not working?
Start with the MCP Inspector to call each tool manually and inspect raw JSON-RPC responses. Check that the server returns isError: true with a structured message on failure rather than an exception. Verify the identity token flow, confirm parameterised queries are executing under the correct database role, and review server-side logs for latency and error rates.

About the author

Solomon Udoh

AI Architect & Certification Lead

Solomon Udoh is an AI Architect who designs and ships production agent systems on the Claude API and Claude Code. He built AI Skill Certs' adaptive engine and authored its 174-concept knowledge graph, mapping every Claude Certified Architect - Foundations objective to hands-on, exam-aligned practice.

  • Designs production multi-agent systems on the Claude API and Agent SDK
  • Author of the AI Skill Certs knowledge graph (174 mapped exam concepts)
  • Builds with MCP, Claude Code, structured outputs, and agentic loops daily
  • Reviews every concept page against the official Anthropic exam guide

You might also like

Ready to put it into practice?

Study every exam concept with an adaptive tutor.

Start studying