All chapters
  1. Start hereA protocol standardizes the call. It does not grant the permission
  2. Foundations · 1The primitive: a function, its arguments, its result, its side effects
  3. Foundations · 2Function calling: the model asks, your application executes
  4. Foundations · 3Client and server: process boundaries, JSON-RPC, errors and trust
  5. Foundations · 4What MCP is: host, client, server and what the protocol promises
  6. Protocol · 5Three surfaces: tools act, resources inform, prompts guide
  7. Protocol · 6A first MCP server: typed input, deterministic data, the raw exchange
  8. Protocol · 7Java and the SDKs: typed DTOs, validation and interoperability
  9. Protocol · 8Local or remote: stdio, HTTP, stateless requests and availability
  10. Platform · 9The database decision: direct SQL, a service boundary or an MCP adapter
  11. Platform · 10Sharing across teams: ownership, catalogs, contracts and versions
  12. Platform · 11Who gets access: users, agents, delegation and least privilege
  13. Platform · 12Enterprise authorization: tokens, audiences, gateways and no passthrough
  14. Platform · 13The threat model: injection, poisoned tools, confused deputies and egress
  15. Platform · 14Governance: who may publish, who approves, who answers the page
  16. Operations · 15Observability and audit: what was called, by whom, and why it was allowed
  17. Operations · 16Resilience: timeouts, retries, idempotency and overload at a shared server
  18. Operations · 17Testing and evaluation: contracts, authorization matrices and injection
  19. Reference · 18Advanced MCP: long tasks, large catalogs, tenants and evolving versions
  20. Reference · 19The ecosystem: SDKs, registries, gateways, identity and telemetry
  21. Reference · 20Enterprise reference architecture: one assessment platform, four teams
  22. Reference · 21Decision playbooks: function, API or MCP, and the records that explain why
  23. ReferenceGlossary
  24. AboutAbout this site and its sources
Platform · 9

The database decision: direct SQL, a service boundary or an MCP adapter

An agent that needs data from a database does not need MCP to get it. Connection pools, transactions, permissions, schema ownership and release coupling decide between direct code, a service and a protocol adapter.

You will understand
Why an agent that needs database rows does not need MCP to get them, and when an MCP adapter still earns its place.
You will be able to place
The connection pool, the transaction and the database account in one owner, for each of three architectures.
You will know
Why a transaction can never stay open across a model's turns, and what to build instead.

The claims team at the insurer wanted roof ages for storm claims, and they wanted them by Friday. A developer found a community "database MCP server" with one tool, run_query, that takes SQL text and returns rows. He gave it the assessment database's connection string, the one the migration job uses, and pointed the claims assistant at it. On Wednesday the claims agent's model was writing its own SELECT statements and getting roof ages back. It looked like the fastest integration the team had ever done.

On Thursday afternoon a hailstorm produced a burst of claims. The claims host scaled out to many instances, and each instance started its own copy of the database server, each with its own handful of connections. The database reached its connection limit. The next connection that failed belonged to the underwriting agent, which was trying to store a recommendation for SUB-1004. Its write never happened, and nobody on the claims team knew the underwriting agent existed.

The invisible failure was worse. The connection string carried the migration account, so the claims model could have written UPDATE property_assessments SET roof_age_years = 9, and the database would have obeyed. Nothing in MCP is about databases, so nothing in MCP would have stopped it.

The problem was not MCP, and MCP was not the fix. The problem was a question nobody asked: who owns the connection, the transaction and the database account? This page answers it for three architectures.

Three places database access can live#

Every architecture on this site reads the same rows through the same domain service, AssessmentService. What changes is where that service runs, and therefore who holds the credentials. There are three honest options.

1. Direct SQL in the agent application. The agent's own process imports the assessment service as a library. The library runs parameterized SQL against the database. One process, no protocol. This is stage 1 on Start.

2. A service boundary. The assessment service runs as its own process, owned by the assessment domain. Callers reach it over HTTP with a token. Only the service holds database credentials. In Java this is the familiar Spring service.

3. An MCP adapter over the service. A remote MCP server, uw-assessment, offers tools to agent hosts and calls the service for every one of them. The MCP server holds no database credentials at all. It is one more adapter beside the HTTP API.

Plain English. The database decision is not "SQL or MCP". It is "whose process opens the connection". MCP only changes how an agent reaches the code that opens it.
Before AI. A monolith used a data access object over JDBC inside the application. A service-oriented company put a service with its own database in front of the data and forbade other teams to read the tables. An API gateway in front added routing and rate limits, never replacing the service's own checks. Option 3 is that pattern with an agent-facing adapter added.
Common confusion. "Agents need MCP to read our database." They do not. MCP is not required for database access, and it does not replace data-layer authorization, an API gateway, a transactional service or service ownership. The underwriting agent in the example reads the database through a plain function call and never touches MCP (ADR-001 on Playbooks).

The smallest primitive: one parameterized query through a scoped account#

Before deciding where the code runs, look at the two lines of protection that every option keeps. Both are in examples/uw-mcp/domain.py.

A parameterized query is SQL whose values travel separately from the statement text, as placeholders the database driver fills in. For example, SELECT * FROM submissions WHERE submission_id = ? with the value SUB-1004 passed beside it. Whatever the value contains, it stays a value; it never becomes SQL.

A repository is the one class that holds all SQL of a domain, so the rest of the code asks for data by meaning ("the submission SUB-1004") instead of by table. Here is the read, verbatim from AssessmentRepository.submission:

def submission(self, submission_id: str) -> dict[str, Any] | None:
    row = self.reader.execute("SELECT * FROM submissions WHERE submission_id = ?", (submission_id,)).fetchone()
    return dict(row) if row else None

The ? is the placeholder. Python's sqlite3 documentation, read on 2026-11-18, says to always use placeholders instead of string formatting to bind values, to avoid SQL injection.

The second line of protection is self.reader. It is a connection opened for a database account: an identity the database itself knows, with its own permissions, separate from any person or agent. This one, uw_reader, may read and may change nothing. SQLite has no users and no GRANT statement (its documentation says these would be meaningless for an embedded engine), so the example plays the part of a grant with an authorizer callback, verbatim from make_authorizer:

def make_authorizer(account: str):
    """The callback sqlite3 calls for every action a statement wants to do on this connection."""
    allowed_inserts = ACCOUNTS[account]["insert"]

    def authorizer(action: int, arg1: str | None, arg2: str | None, dbname: str | None, source: str | None) -> int:
        if action in _READ_ACTIONS:
            return sqlite3.SQLITE_OK
        if action == sqlite3.SQLITE_INSERT and arg1 in allowed_inserts:
            return sqlite3.SQLITE_OK
        return sqlite3.SQLITE_DENY

    return authorizer

SQLite calls this function for every action a statement tries. Reads pass; an insert passes only into a table the account may insert into; every UPDATE, DELETE or DROP gets SQLITE_DENY and fails. The example defines four accounts: owner (migrations and seed, held only by the domain team's deploy job), uw_reader, uw_rec_writer (inserts into recommendations only) and uw_decision_writer (inserts into decisions only).

Neither protection mentions MCP, HTTP or a model. They sit under all three options.

Who owns the connection pool#

Opening a database connection is slow and costs the database memory, so programs keep connections open and reuse them. A connection pool is that set of open connections, owned by one process, handed out to one request at a time and returned afterwards. For example, a service with a pool of ten serves a hundred concurrent requests by making them take turns on ten connections.

A database accepts only a limited number of connections in total. So the pool is not a private detail of one program; it is a share of a scarce resource. Count the shares in each option.

In option 1, every instance of every agent application that embeds the library owns a pool, so the total grows with the number of agent instances, not with the work. The database cannot tell a claims connection from an underwriting one, and there is no single place to throttle claims without throttling everyone. That is Thursday afternoon.

In options 2 and 3, the assessment service owns the only pool, sized by the team that knows the database. When claims traffic spikes, requests queue at the service or are refused there, and the database stays healthy. In option 3 the MCP server adds a rate limit per client in front (Resilience).

Production pitfall. The pool also hides credentials. Whoever owns a pool holds the password that opens it. "Every agent opens its own connections" means "every agent host holds the database password". Local or remote, that is the forty laptops of Local or remote again.

This site's recommendation: one pool per database per owning service. If more than one team's process holds a connection string to the same database, write down why in an ADR, and expect the answer to be "it should not".

Latency, counted in hops and round trips#

Every option has a price in time, and this site states it without inventing numbers. Two things can be counted without a benchmark: hops (each time a request crosses to another process or machine) and round trips (each time a caller waits for an answer before it can continue).

Option 1 has no process hop between the agent and the service, and one network hop to a database server. Option 2 adds one hop: agent to service. Option 3 adds two: the host's MCP client to the MCP server, and the MCP server to the service. The dbbench lab below counts them for each option.

Round trips matter more than hops, and this is where the database decision meets the model. Suppose answering "is SUB-1004 eligible?" needs four queries. Inside the service, they are four short round trips to the database within one tool call. Through a run_query tool, every query is a model turn: the model writes a request, the host sends it, the rows come back into the model's context, the model writes the next one. A coarse tool (check_eligibility) answers in one turn what the fine tool needs four for, and counting turns needs no measurement.

This site's recommendation: shape tools around business questions, not around tables, so the round trips stay on the database side of the service.

Who owns the transaction#

A transaction groups several database changes so that all of them happen or none does. A unit of work is the code object that opens a transaction for one business operation and closes it: commit if everything succeeded, roll back if anything failed. In the example it is UnitOfWork in domain.py: BEGIN on entry, COMMIT on success, ROLLBACK on any exception.

A transaction boundary is the line in the code where a transaction starts and ends. Choosing it is choosing who is responsible for consistency. In the example the boundary is the repository method: insert_recommendation opens a unit of work, inserts one row, and closes it. One service call is one transaction.

Now the question every agent architect eventually asks: could the agent open a transaction, look at some rows, think, and then commit? The answer is no, and the reasons are mechanical, not stylistic.

First, a model's turn has no upper bound. Between two tool calls the model may wait for a person, hit a rate limit, or never come back because the host crashed. An open transaction holds locks and pins a pooled connection for all of that time, and the service cannot tell "the model is thinking" from "the model is gone".

Second, the protocol does not allow it. Normative (MCP specification 2026-07-28): MCP is stateless; servers must not rely on prior requests on the same connection, and state that spans requests must be referenced by an explicit identifier passed on each request (basic protocol). Two tools/call requests may reach two different server instances. There is no connection on which a transaction could stay open.

Third, a transaction is the wrong tool for the job. A business process that spans turns, hours or people is not a transaction; it is a sequence of committed states.

The example already shows the right shape. record_recommendation commits one row with status awaiting_underwriter. Hours later the underwriter decides in the cockpit, and record_underwriter_decision commits a second row in its own transaction. The "open" state between the two is a value in a column, readable by anyone with the right account, not a lock held by a model. That is series case UW-004 end to end: the agent recommends escalate on R-ROOF-03; a person decides later.

Diagram: A process that spans turns and people · committed states, never an open transaction

Time runs down the page. The agent's recommendation is one tool call and one short transaction that commits a row with status awaiting_underwriter. Hours later the underwriter decides through the cockpit, in a second short transaction. Between the two, no lock is held and no connection is pinned: the open question is a value in a column.

  1. Model (stand-in) to Host's MCP client: request record_recommendation SUB-1004 escalate. The model only writes the request; R-ROOF-03 is cited because the roof ages differ by 13 years.
  2. Host's MCP client to Assessment service: tools/call through the MCP server. The server authorizes the call and calls the service once.
  3. Assessment service to Database: BEGIN, INSERT REC-0001, COMMIT. One short transaction through uw_rec_writer; status awaiting_underwriter.
  4. Assessment service to Host's MCP client: REC-0001 awaiting_underwriter. The transaction is already closed when the answer leaves.
  5. Database: hours pass: a committed state, no lock held. The open question lives in a column anyone with the right account can read.
  6. Underwriter (cockpit) to Assessment service: record_underwriter_decision approve, override. Only a person through the cockpit may call it; the agent never can.
  7. Assessment service to Database: BEGIN, INSERT DEC-0001, COMMIT. A second short transaction through uw_decision_writer. The recommendation row stays a recommendation.
Under the hood. A transaction also cannot span two services. If a tool needed to change the assessment database and the claims database together, no single BEGIN covers both. The usual answers are an operation owned by one service, or a sequence of local transactions with compensating steps. The ev-db-decision-multistep block below compares them.

Permissions: a database account per purpose#

The database account is the last line of defense, below the MCP server, below the service, below every check that code above it might get wrong. The example's db_options.py runs each scoped account against statements it may and may not execute, then rolls everything back. Run in a scratch copy on 2026-11-18:

/opt/homebrew/bin/python3 db_options.py
uw_reader           allowed  SELECT roof_age_years FROM property_assessments WHERE submission_id =   
uw_reader           refused  INSERT INTO recommendations VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  not authorized
uw_reader           refused  UPDATE property_assessments SET roof_age_years = ? WHERE submission_id  not authorized
uw_rec_writer       allowed  INSERT INTO recommendations VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  
uw_rec_writer       refused  INSERT INTO decisions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  not authorized
uw_rec_writer       refused  DELETE FROM recommendations WHERE submission_id = ?  not authorized
uw_decision_writer  allowed  INSERT INTO decisions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

Read the third line against the opening story. The UPDATE that would have rewritten SUB-1004's roof to 9 years is refused by the database, whatever the caller, the protocol or the model wanted. The fifth line is the database's half of ADR-003: the recommendation writer cannot write a decision, even by accident.

On a server database the same idea is a GRANT. The example carries the PostgreSQL shape as text (db_options.py, GRANTS_SHAPE); it is not run here, because the example has no PostgreSQL. The statements were checked by reading against the PostgreSQL 18 GRANT and CREATE ROLE pages on 2026-11-18, not executed:

CREATE ROLE uw_reader LOGIN;
GRANT SELECT ON submissions, property_assessments, recommendations, decisions TO uw_reader;
CREATE ROLE uw_rec_writer LOGIN;
GRANT SELECT ON submissions, recommendations TO uw_rec_writer;
GRANT INSERT ON recommendations TO uw_rec_writer;
CREATE ROLE uw_decision_writer LOGIN;
GRANT SELECT ON submissions, recommendations, decisions TO uw_decision_writer;
GRANT INSERT ON decisions TO uw_decision_writer;
-- nobody but the migration role may UPDATE, DELETE, CREATE or DROP

As documented on 2026-11-18: LOGIN lets a role connect (a role with it "can be thought of as a user"); one GRANT may list several tables; and an object's owner holds all privileges by default, which is why the migration role must never be the one an application uses.

Case UW-M03 exposes a subtlety. With the server's per-call check switched off, the intake agent's forbidden record_recommendation writes one row: the service connected as uw_rec_writer, which may insert recommendations. The database account limits what the service can do; it does not know which caller the service is acting for. Per-caller authorization has to happen above the database, in the service or the MCP server, and the account bounds the damage when it fails. Both layers are needed. Who gets access builds the caller side.

Security note. Separate accounts per kind of write turn a bug into a refusal instead of a corruption. The OWASP SQL injection cheat sheet, read on 2026-11-18, agrees: grant each account only what it needs, never administrator access.

Schema ownership and release coupling#

A database schema is a contract whether anyone calls it one or not. The question is who may change it, and who has to ship when it changes.

Release coupling is the degree to which one team cannot release without another team releasing too. For example, if four agent applications embed SQL against the property_assessments table, renaming one column means five coordinated releases.

In option 1 the coupling is high: every embedding application ships with each rule or column change. In option 2 it is low: the service deploys alone behind its API contract. Option 3 has three release trains: the hosts, the MCP server (whose tool schemas are a contract of their own, owned by the server maintainer) and the service.

The DTO keeps those trains apart. A consumer that depends on the nine fields of PropertyAssessment survives a table change; a consumer that wrote its own SQL does not. The run_query tool of the opening story makes every table and column a public contract for every model that calls it. Sharing across teams shows what versioning a contract looks like when four teams depend on it, with case UW-M07.

The three options in the workbench#

The lab puts the three options side by side: grants, credentials, pool, unit of work and transaction owner, hops and release coupling. A second control runs one of seven SQL statements under a scoped account; the expected result (from the grants) and the actual one (the SQLite authorizer, run when the site was built) agree.

QuestionSame-process PythonJava/Spring service (not run)Remote MCP over the service
Who holds DB credentialsthe agent application (every instance of it)the assessment service onlythe assessment service only; the MCP server holds none
Connection pool ownerthe agent applicationthe assessment servicethe assessment service
Transaction ownerthe agent application's process (one transaction per write)the assessment servicethe assessment service; the MCP server never opens a transaction
Process / network hops0 / 11 / 22 / 3
Release couplinghigh: a rule or schema change ships with every applicationlow: the service deploys alonethree release trains: hosts, MCP server (tool schemas), service
Fits whenone application owns the data and the agent runtimemany programs need the same rules and dataseveral MCP-capable hosts and teams must discover and call it
AccountStatementResult
uw_readerSELECT roof_age_years FROM property_assessments ...allowed
uw_readerINSERT INTO recommendations ...refused
uw_readerUPDATE property_assessments ...refused
uw_rec_writerINSERT INTO recommendations ...allowed
uw_rec_writerINSERT INTO decisions ...refused
uw_rec_writerDELETE FROM recommendations ...refused
uw_decision_writerINSERT INTO decisions ...allowed

The same lab opened on the third option, where the MCP server holds no credentials and never opens a transaction:

Diagram: Three places database access can live · count the boxes between the caller and the rows

Each column is one option, read top to bottom. All three end at the same database through the same assessment service. What moves is who holds the credentials, the pool and the transaction. In option 1 that is every agent application; in options 2 and 3 it is the assessment service alone, and the MCP server in option 3 holds nothing. Click a box for who owns it.

  1. Option 1 · direct SQL in the agent app
    1. Agent application: The agent's own process runs the assessment service code. It holds the connection string, the pool and the transaction.
    2. Repository: All SQL of the domain in one class, with placeholders for every value.
    3. Database: Every instance of every embedding application opens its own connections with these accounts.
  2. Option 2 · a service boundary
    1. Any caller: Holds a token for the service, never a database account.
    2. Assessment service: One service call is one transaction. The service sizes the only pool for this database.
    3. Database: Only the assessment service connects. The tables can change without breaking callers.
  3. Option 3 · an MCP adapter over the service
    1. Agent host's MCP client: Claims, support and analytics agents in three hosts discover and call tools here.
    2. MCP server uw-assessment: Validates the token, authorizes the call, then calls the service with an exchanged token. It never opens a database connection.
    3. Assessment service: Exactly the service of option 2. The MCP server is one more adapter beside the HTTP API.
    4. Database: Adding MCP server instances adds no database connections.

Read the table as three answers, not a ranking. The insurer uses all three at once: the underwriting agent in its own process (option 1), the support desk's ticketing system over HTTP (option 2), and the claims, support and analytics agents through the MCP server (option 3). One service and one schema owner behind all of them.

Run it: a hostile value, a rollback and a repeated write#

The script below uses the example's domain code unchanged. It looks up a submission with a normal id and with injection-shaped text, makes a write fail after its insert, and records the same recommendation twice with one idempotency key. It was run in a scratch copy of examples/uw-mcp/ on 2026-11-18; the file is this page's own, not part of the example.

"""Scratch demo for the db-decision page: parameterized SQL, unit of work, idempotent write."""
from domain import AssessmentService, UnitOfWork

svc = AssessmentService()
repo = svc.repo

# 1. Parameterized SQL: hostile text is a value, never SQL.
print("lookup SUB-1004:", repo.submission("SUB-1004")["property_id"])
print("lookup hostile text:", repo.submission("SUB-1004' OR '1'='1"))

# 2. Unit of work: a failure inside the block rolls the write back.
UnitOfWork.log.clear()
row = {"recommendation_id": "REC-0099", "submission_id": "SUB-1004", "recommendation": "escalate",
       "reasons_json": "[]", "citations_json": "[]", "idempotency_key": "SUB-1004:run-7f3a:demo",
       "payload_hash": "h", "recorded_by": "agent:underwriting-agent", "status": "awaiting_underwriter",
       "created_at": "2026-11-18T09:00:00Z"}
try:
    with UnitOfWork(repo.rec_writer) as conn:
        conn.execute("INSERT INTO recommendations VALUES (:recommendation_id, :submission_id, :recommendation, "
                     ":reasons_json, :citations_json, :idempotency_key, :payload_hash, :recorded_by, :status, "
                     ":created_at)", row)
        raise RuntimeError("the reasons failed validation after the insert")
except RuntimeError as e:
    print("error:", e)
print("log:", UnitOfWork.log, "rows:", repo.count("recommendations"))

# 3. One service call is one transaction; the same idempotency key again writes no second row.
rec = {"recommendation": "escalate", "reasons": ["Application 9 years, provider 22 years (EV-ROOF-0412)."],
       "citations": ["R-ROOF-03"], "requires_human": True}
key = "SUB-1004:run-7f3a:recommendation"
UnitOfWork.log.clear()
first = svc.record_recommendation("SUB-1004", rec, key, "agent:underwriting-agent")
again = svc.record_recommendation("SUB-1004", rec, key, "agent:underwriting-agent")
print("first:", first["recommendation_id"], first["status"], "replay", first["idempotent_replay"])
print("again:", again["recommendation_id"], "replay", again["idempotent_replay"])
print("log:", UnitOfWork.log, "rows:", repo.count("recommendations"))
svc.close()
lookup SUB-1004: PROP-2207
lookup hostile text: None
error: the reasons failed validation after the insert
log: ['BEGIN', 'ROLLBACK'] rows: 0
first: REC-0001 awaiting_underwriter replay False
again: REC-0001 replay True
log: ['BEGIN', 'COMMIT'] rows: 1

The injection-shaped text found no submission: it was compared as a value. The failed block left zero rows: the rollback undid its insert. Two calls with one key opened one transaction and left one row; the second call returned the stored result, the property Resilience relies on when a reply is lost (case UW-M08). The model in the example is a scripted stand-in, so these results show how the protocol and the controls work, not how good any model is; here no model is involved at all.

What goes wrong without these ideas#

Each idea on this page removes one failure that the opening story contained.

Missing ideaWhat happensWho notices
One owner for the poolAgent instances multiply connections until the database refuses new ones; an unrelated team's write failsThe team whose write failed, not the team that caused it
A scoped accountWhatever the model writes, the database executes with the migration role's rightsAudit, after the data changed
A transaction boundary in the serviceLocks held across model turns; connections pinned while a host is goneOther writers, as timeouts
A DTO between tables and consumersA column rename breaks every agent that wrote SQL against itEvery consumer, on the same morning
Per-caller authorization above the databaseThe service's account allows the write, so a caller who should be refused is not (UW-M03 with the check off)Nobody, until someone reads the rows

Each failure appears in a team that did not cause it. That is what "shared" means for a database.

How Spring and MCP express these ideas#

A Java service boundary. The insurer's claims platform is Java, so option 2 there is a Spring service. The layer split (controller, service, repository) is on Java and the SDKs. What matters here is the transaction and the pool. The following is documented shape; not run here. It was written from the Spring Framework 7.0.10 transaction page and the Spring Boot 4.1.2 SQL page read on 2026-11-18. The repository interface and method names are this site's sketch; imports are omitted.

@Service
public class AssessmentApplicationService {

    private final AssessmentRepository repository;   // this site's interface, e.g. backed by JDBC

    public AssessmentApplicationService(AssessmentRepository repository) {
        this.repository = repository;
    }

    @Transactional(readOnly = true)
    public PropertyAssessment getRoofAssessment(String submissionId) {
        return repository.findBySubmissionId(submissionId).orElseThrow(NotFound::new);
    }

    @Transactional            // one service call is one transaction
    public RecommendationResult recordRecommendation(String submissionId, Recommendation rec, String idempotencyKey) {
        return repository.findByIdempotencyKey(idempotencyKey)
                .map(RecommendationResult::replay)
                .orElseGet(() -> RecommendationResult.created(repository.insert(submissionId, rec, idempotencyKey)));
    }
}

The annotation puts the transaction boundary on the service method, and the pool comes from configuration owned by the same service. Two documented details that bite MCP adapters written in Java are in the block below.

Spring details that bite an MCP adapterRollback rules, self-invocation and who owns the pool, as documented on 2026-11-18

As documented on the Spring Framework 7.0.10 page: @Transactional gives a method transactional semantics; by default any RuntimeException or Error rolls back and a checked exception does not; default propagation is REQUIRED. A service that reports "not found" or "conflict" with a checked exception after writing something will therefore commit that write unless the rollback rule is changed. Domain errors that must undo work should be unchecked, or the rule set explicitly.

The second detail matters for an MCP adapter that lives in the same application as the service. In proxy mode (the default), a call from one method of a class to another method of the same class "does not lead to an actual transaction at runtime". An MCP tool handler that calls the transactional method through the injected Spring bean gets a transaction; a helper inside the service class that calls it directly does not, and the write runs without one.

The pool comes from configuration, not code. As documented on the Spring Boot 4.1.2 page, Spring Boot prefers HikariCP when it is available, the JDBC and JPA starters bring it in, and pool settings live under spring.datasource.hikari.*. The service owns that pool. An MCP adapter deployed in the same application shares it; an MCP adapter deployed separately calls the service and owns none, which is the shape of option 3.

The protocol. MCP defines no database feature. A server offers tools, resources and prompts (Three surfaces); what a tool does inside is the server's business. The only normative statement that bears on this page is the statelessness rule above: no state across requests except through explicit identifiers.

A server that wraps a database with a generic query tool, like the one in the opening story, puts the whole decision of this page in the hands of whoever configures its connection string. The protocol cannot tell a careful configuration from a careless one.

When a generic query tool is acceptableA run_query tool is not always wrong; here are the conditions that make it survivable

A tool that takes SQL text is the most flexible tool a model can have and the hardest to govern. It is the right choice in a narrow case: exploratory analysis by a person who is allowed to see the data anyway, where the model saves typing and a human reads every result. Even there, the conditions decide whether a mistake is a nuisance or an incident.

Use a read replica or a reporting copy, never the primary that serves writes. Connect with a role that has SELECT only, on views rather than tables where the views hide sensitive columns; the OWASP cheat sheet read today recommends views to limit access to specific fields. Set a statement timeout and a row limit in the database, not in the prompt. If several business units share the data, enable row security so the role sees only its own rows. Give each person or team its own role, so the database's own logs can tell callers apart.

What a generic query tool can never be is a shared capability for several teams' agents. Its contract is the whole schema, so release coupling is total; its permission model is the database role, so per-caller authorization above the database does not exist; and its round trips are model turns. This site's recommendation: if a second team asks to use it, that is the signal to build the coarse tool they need on the domain service instead.

Row security in the database or checks in the service?Tenant isolation can live in two layers; each catches what the other misses

The example isolates business units in code: policy.authorize refuses a commercial-west caller who asks for SUB-2001, a commercial-east submission, and answers exactly as if it did not exist (case UW-M11). The database account does not know about business units at all.

PostgreSQL can enforce the same rule in the database. As documented on 2026-11-18 in the PostgreSQL 18 row security page: after ALTER TABLE ... ENABLE ROW LEVEL SECURITY, every normal access to the table must be allowed by a policy, and with no policy nothing is visible. A policy such as CREATE POLICY ... USING (business_unit = ...) filters rows per role or per session setting. Superusers and roles with BYPASSRLS always bypass it, and the table owner bypasses it unless FORCE ROW LEVEL SECURITY is set; that is one more reason applications must not connect as the owner.

The trade-off is about who knows the tenant. The database knows only what the connection tells it. With one pool owned by the service, every connection uses the service's account, so the service must pass the caller's business unit into each transaction (typically a session setting) and the database must trust the service to pass the right one. The check in code knows the caller's validated token directly. This site's recommendation: enforce tenant isolation in the service for the decision and the audit event, and add row security as defense in depth when the data is sensitive enough that a single bug in the service must not leak another unit's rows.

Operations that need more than one stepCoarse tools, committed states, compensations: three ways around the transaction that cannot span turns

Some business operations really are several steps, and a team will be tempted to give the model "begin", "update" and "commit" tools. There are three better designs, in order of preference.

A coarse tool. If the steps do not need the model's judgment between them, they belong in one service method and one transaction. "Record the recommendation and mark the submission reviewed" is one call, not two. Most multi-step designs collapse into this once someone asks which step needs the model.

Committed states with explicit handles. If a person or the model must look at an intermediate result, commit it as a state with an id: a draft recommendation, then a separate confirm call that names the draft. This is the MCP specification's own rule for anything that spans requests (an explicit identifier on each request), and it is the example's shape: awaiting_underwriter is a committed state, and the decision is a later call. Drafts need an expiry so abandoned ones do not pile up, and the confirm call needs the same authorization checks as the first.

Compensating steps. If the operation spans two services (the assessment database and the claims database), no transaction covers both. Each service commits its own step, and a failure later triggers an explicit undo step in the earlier service. This pattern, often called a saga in service architecture, is an orchestration concern; https://reliable.sammuthu.com covers recovery across a whole workflow. For an MCP server the rule is narrower: never let the model be the coordinator that must remember to compensate.

Pools when the MCP server scales outA stateless server scales by adding instances; that is safe only if the instances hold no pool of their own

The stateless revision lets a platform team add MCP server instances freely: any instance can answer any request (Local or remote). That is an operational gift, and it hides a trap. If each server instance connected to the database itself, adding instances would add connections, and the platform team's autoscaler would become a way to exhaust the domain team's database.

In the example's option 3 the MCP server holds no credentials and calls the service, so server instances multiply without touching the database. The service scales on its own schedule, with its pool sized by the team that knows the database. Ecosystem pattern: where many processes must reach one database directly, a pooling proxy in front of the database caps the total number of connections; it moves the scarce resource to one owner without changing the application.

When the service itself is overloaded, the queue should form at the service, close to the cause, and the MCP server should see a timeout or a refusal it can turn into a controlled tool error. That chain (deadline, bounded retry for reads, no retry for writes without a key) is Resilience, case UW-M08.

Security and governance notes#

Security note. Give the database account to one service, split it by purpose (read, each kind of write, migrations), and never let an application connect as the owner. A model-written request must reach the database only through code that parameterizes every value and allow-lists every identifier, as the repository's count method does for table names.
Governance note. The schema, the accounts and the grants belong to the domain data owner, here the property-risk data team. The MCP server maintainer owns tool schemas, not tables; the platform team owns the server's deployment, not the database. Write that split into the catalog entry so a new team asking for "database access" is routed to the domain owner, not to whoever runs the server. Governance has the RACI.
In a coding agent. A coding agent that helps with a database migration should get a local server with a read-only role on a development copy, and a pull request as its only write: open_pull_request with the migration file, reviewed by a person and applied by the deployment pipeline's own migration role. Giving the agent the migration role directly is the run_query story with a larger blast radius. Diff to Deploy follows a change from the agent's branch to the pipeline that holds the real credentials.
What this is not. This page decides where database access lives. It does not teach retrieval of text passages for a model (embeddings, vector search), which belongs to the series' RAG Engineering site (being built; see Start), and it does not teach recovering a workflow across services, which belongs to https://reliable.sammuthu.com.

Checklist for Monday#

CheckPass when
CredentialsExactly one service holds the connection string for each database; no agent host has it
AccountsReads and each kind of write use separate database accounts; no application connects as the owner
SQLEvery value is a placeholder; every identifier comes from an allow-list in code
PoolOne owner per database; its size is chosen by the team that knows the database's limit
TransactionOpened and closed inside one service call; no tool begins or commits
Long processesIntermediate results are committed states with ids, not open transactions
ContractConsumers depend on a DTO or a tool schema, never on table and column names
Caller authorizationChecked above the database for every call; the account only bounds the damage

Exercises#

  1. The analytics team asks for a read-only connection string to the assessment database "to avoid the MCP overhead". What do you offer, and why?
  2. A developer proposes three tools, begin_review, update_review and commit_review, so the model can build a review step by step. What is wrong, and what do you build instead?
  3. The claims host scales from a few instances to many during a storm. In option 1 and in option 3, what happens to the number of database connections?
AnswersOne line each
  1. The aggregate tool get_assessment_stats (ADR-005) or a reporting copy with its own read role; a connection string to the primary gives analytics every column and a share of the pool.
  2. A transaction cannot span model turns or stateless requests; commit a draft review with an id and confirm it in a later call, or make it one coarse tool.
  3. Option 1: connections grow with instances, because each holds a pool; option 3: unchanged, because only the assessment service holds a pool.

In one breath#

An agent that needs database rows does not need MCP; it needs code that someone owns. Put the connection pool, the transaction and the database account in one domain service, split the account by purpose, parameterize every value, and let consumers depend on a DTO or a tool schema instead of tables. A transaction lives inside one service call, never across a model's turns: a process that spans turns or people is a sequence of committed states. MCP, when several agent hosts need the capability, is one more adapter over that service, with no credentials and no transactions of its own.

The service now owns the data, and one MCP server offers it to claims, underwriting, support and analytics. Four teams on one capability raise new questions: who owns which part, how a team finds the tool and knows it is approved, what a version means, and what happens when a field keeps its name but changes its meaning. That is Sharing across teams.