How to connect a database securely using MCP

A practical architecture for connecting corporate databases to AI agents through scoped tools, enforced authorization and reviewable execution.

Connecting a corporate database to an AI agent starts with deciding which operations the agent is allowed to perform. MCP provides the interface between the agent and those operations. Database permissions, application authorization and operational controls still have to enforce the boundary.

What an MCP server exposes to an AI agent

An MCP server is a small program that exposes functions. Each server declares what it can do with a schema, and the agent calls those functions. The protocol is not tied to one model, so the same server works from Claude, ChatGPT, Cursor or Codex.

A useful server answers four questions for the agent. What data exists? How is it structured? What operations are allowed? What rules apply? The last two are the security design, and they belong in code that the model cannot change.

I built the Airtable MCP server for my own use. I was restructuring schemas in an Airtable project and kept copying schema information between the API documentation and my work. The server put that data one question away. The agent reaches whatever the server can reach, so draw the boundary first.

Put a service boundary in front of the data

A useful starting architecture is: authenticated user → agent → MCP tool service → authorized data operation → database. Give the tool service a narrowly scoped database identity. Resolve the caller and tenant from trusted authentication context, never from a tenant identifier that the model supplies.

Begin with specific read tools such as get_order_status or list_overdue_invoices. Define their inputs, returned fields, pagination and failure behavior. A general SQL tool requires a much stronger isolation and query-control design; an instruction asking the model to behave is insufficient.

Local or remote MCP server: what changes for security

Most MCP work begins on a laptop. A local server runs over stdio on the user's machine, and the user decides what it can access. The Airtable MCP server works this way: you enter an Airtable token and a base ID once at installation. The server can reach whatever that token can reach.

A remote server is a system boundary. A cloud agent cannot depend on local stdio, so the transport becomes Streamable HTTP. MetaMCP keeps stdio for local use and adds what a remote surface on Cloud Run needs: build artifacts, a pipeline file, IAM and Secret Manager setup, registry metadata, and smoke tests for health, auth, initialize and tools list. Authentication has two layers there: Cloud Run caller identity plus bearer authentication in the application. Tool calls are written to a ledger for review after the run.

The decision rule: a local server is enough for one person who works with data that person already controls. Once another agent or another user calls it, treat it as a production service.

Keep credentials and permissions outside the prompt

The model should receive a tool definition and the minimum result needed to answer. It should not receive a database password. Store credentials in the runtime's secret facility, rotate them, and separate environments. For remote HTTP deployments, implement the applicable MCP authorization requirements and validate that a token is intended for the receiving service. Downstream database credentials belong to a separate boundary.

Database grants and, where applicable, row-level policies must support the application's restrictions. Parameterized queries address SQL injection; they do not decide whether the caller may read a customer's invoice. Both checks are needed.

On LeanManufacturing.mx, a platform I built on Neon Postgres, every database call happens on the server with parameterized SQL through a single server-only module. No environment variable carries a client-side prefix. One module is one place to review what the application can ask the database.

Separate reading from changing state

A proposed write should pass schema validation, business rules and authorization before execution. For consequential operations, require an approval bound to the exact operation and arguments. Use idempotency keys for retryable writes and make approval expiry explicit. A second model call is not a substitute for permission enforcement.

Example contract, not a deployed benchmark:
get_order_status(order_id)
  identity: authenticated caller and tenant from server context
  authorization: caller may access this order
  result: status, updated_at, source_reference
  bounds: deadline, result-size limit, rate limit
  audit: trace_id, tool version, decision, outcome

When to split read and write access in an MCP server

Split them as soon as the agent can change anything that another person depends on. Use these rules.

  • If the data is already public, a read-only server without a key can be reasonable.
  • If the data is private, every read is authenticated and scoped to the caller.
  • If a tool changes state, give it its own name, its own validation and, where the database allows it, a separate identity with write grants. Read tools keep a read-only identity.
  • If nobody can say who approves a write, do not expose the write yet.

Writes are where convenience and risk meet. With the Airtable MCP server I ask Claude to update the status of a feature in the base of my own project. It is my data and I accept that risk for myself. In a corporate database, the same request needs the checks above before anything changes.

A worked example: a public read-only MCP server

LeanManufacturing.mx is the platform of a lean manufacturing practice. It exposes a public MCP server over Streamable HTTP at /mcp, with no key and no token. An agent can query the documentation, the blog, the answered questions and the service pages, and it can calculate OEE.

No key is the right choice here because everything the server returns is already open on the site.

The database behind the site holds more than public content: leads from the contact forms and the tool and chat events that feed a private dashboard. That private panel sits behind its own key, and reindexing the documentation is one authenticated POST. So one system has an open read path for public material, while the private panel and the reindexing sit behind authentication. The question is not whether the database is connected. It is which operations each caller can reach.

How to connect a database to an AI agent step by step

  1. List the questions people really ask, such as overdue tasks or the last order of a customer. Each one is a candidate tool.
  2. Write each tool as a contract: inputs, returned fields, limits and failure behavior.
  3. Create a database identity for the tool service with only the grants those tools need.
  4. Put every query in one server-side module and parameterize it.
  5. Store the credential in the runtime secret store, out of prompts, tool results and client-side variables.
  6. Choose the transport: stdio for a local server, Streamable HTTP for a remote one. A remote server authenticates the caller at the platform and again in the application.
  7. Write smoke tests for health, auth, initialize and tools list, then the denial tests described below. Record each tool call.
  8. Add write tools last, each with validation, authorization and approval where the effect matters.

What goes wrong when you connect a database through MCP

  • Authentication passes in testing and fails through the agent. While I was building the Airtable MCP server, it connected to Airtable during my tests and failed when Claude used it. The cause was how the authentication token was passed through the MCP pipeline. Test through the real client, not only against the database.
  • Too many tools are exposed. Each tool is another operation to authorize, test and audit. MetaMCP, an open-source gateway I built, started as a way to reduce many MCP tools into a smaller tool surface.
  • A secret reaches the browser or the model. A variable with a client-side prefix or a credential pasted into a prompt is enough.
  • Nothing remains after the call. Without logs or a ledger, you cannot say what the agent did or why a request was denied.

Test the boundary before adding autonomy

Test a valid request and its denied counterpart: another tenant, an expired credential, a forbidden field, an oversized result and an unavailable database. Treat retrieved text as untrusted data, including text that tells the agent to invoke another tool. Keep sensitive payloads out of general-purpose logs.

When selecting an engineer, ask to see the denial tests, permission model and incident trail alongside the working integration. The linked work below documents my integrations and their limits.

Protocol references

Where to go next

Common questions

Is it safe to connect a database to an AI agent with MCP?

It can be, when the boundary is enforced outside the model. MCP is only the interface between the agent and the operations. Database grants, application authorization and operational controls have to enforce what the agent may do. Start with specific read tools and a narrowly scoped database identity.

Should an MCP server have read-only access to the database?

Start read-only. Add writes later as separate tools that pass schema validation, business rules and authorization before they run. For consequential operations, require an approval bound to the exact operation and its arguments.

What is the difference between a local and a remote MCP server?

A local server runs over stdio on the user's machine and uses credentials that the user configured. A remote server is called over Streamable HTTP by other agents, so it becomes a system boundary. It needs caller authentication, managed secrets, deployment, tests and a record of each tool call.

Can I give an AI agent a general SQL tool?

Only with a much stronger isolation and query-control design. Specific tools with defined inputs, returned fields and limits are easier to authorize and to test. An instruction that asks the model to behave is not a control.

Does an MCP server need authentication?

A server that returns only public content can run without a key. A server that reaches private data must authenticate the caller, check that the token is intended for it and authorize each request. The database credential stays in the runtime secret store and is separate from that token.

Work and evidence

MetaMCP as a Cloud Run MCP gateway

My contribution: Built and documented the cloud-facing gateway path, registration artifacts, smoke checks and evidence export.

What this supports: Public implementation account covering transport, caller identity, secrets and tool-call evidence.

What it does not establish: The case study is not an independent security audit or a published concurrency benchmark.

Source reviewed:

Airtable MCP

My contribution: Built an open-source MCP integration for querying and editing Airtable bases.

What this supports: A concrete database-to-agent integration with a linked public repository.

What it does not establish: An integration example, not evidence that arbitrary corporate databases or tenant policies are secured by default.

Source reviewed:

APC sales platform

My contribution: Built the sales platform of a lubricants distributor in one application: public site, quote form, team CRM, client portal, technical assistant and MCP server, then handed it to the team and its own agent.

What this supports: A path from search to request to quote that is read from Search Console and the request records, and a CRM that the assistants of the team operate as each person.

What it does not establish: The case reports no revenue, no quote time and no attribution of requests to a channel, and its outbound results are not published.

Source reviewed:

Related questions

Technical guides