MCP: Model Context ProtocolBeginnerModule 02 — MCP architecture and components
How do MCP servers interact with downstream APIs and databases?
Question 18 of 43 · Updated
On this page
- Direct answer
- 1. Two communication boundaries, not one
- 2. Separate the capability contract from the backend contract
- 3. What the server does before calling the backend
- 4. Calling a REST API from an MCP handler
- 5. Accessing a database through a repository
- 6. Credential boundaries: incoming identity versus downstream access
- 7. Connection management and performance
- 8. End-to-end result and error handling
- 9. Tested implementation: REST and SQLite adapters with one domain contract
- How the implementation works
- Limits of the test
- 10. Transaction boundaries for writes
- 11. Production scenario: changing the inventory backend
- 12. Common mistakes and a practical checklist
- Interview-ready answer
Direct answer#
An MCP server interacts with downstream APIs and databases through ordinary application integration code. A registered MCP tool, resource or prompt handler receives a supported request, validates its arguments and the authenticated actor's authority, invokes a trusted service adapter, and converts the downstream outcome into the appropriate MCP result or error.
The downstream service may be an HTTP API, a database, an internal SDK or an in-process business function. It does not need to speak MCP. The server translates between the externally advertised capability and the service's actual contract while preserving authorization, business meaning and execution status.
MCP is therefore a boundary for consuming capabilities, not a replacement for SQL, REST, database drivers, transactions or service-to-service authentication.
Learning continuity: Q6 introduced traditional adapters and Q7 examined schema evolution. Q18 established server architecture; Q21 and Q22 addressed connection isolation and responsibility handoffs. This final Module 02 lesson follows the authorized server request inward, comparing interchangeable backend adapters and their failure and transaction boundaries. Full PostgreSQL, REST and constrained-query server implementations are reserved for Q245–247; advanced reliability and business-operation design appear in later modules.
Verification scope: Prepared under authorized offline research and changelog exceptions using the historical MCP 2025-06-18 specification as a reference baseline, not a claim about the latest revision. Official links were not checked live. The Python standard-library example was syntax-compiled and executed using Python 3.13.5: all 13 checks passed, including real in-memory SQLite queries and rollback, plus simulated REST responses. No live REST service, MCP SDK or production database was exercised. Mermaid blocks were structurally reviewed; local Mermaid parsing and frontend rendering remain unverified.
1. Two communication boundaries, not one#
Consider a retailer exposing a stock tool to its support assistant. The host sends a tool request using its MCP client. The inventory MCP server may query an existing inventory HTTP API or use an authorized repository connected to a database.
The two backend paths are architectural alternatives for the example, not instructions to query or update both stores for every operation. A production capability must know which source is authoritative. Dual reads may be useful in a controlled migration, but mirroring a write to both stores can duplicate effects or produce inconsistent state.
The host-to-server connection follows the supported MCP revision and transport. The server-to-backend relationship follows the backend's own interface. A local stdio MCP server can call a remote HTTPS API. A remote HTTP MCP server can query a database through a private network. The choice of MCP transport does not determine the choice of downstream protocol.
2. Separate the capability contract from the backend contract#
Imagine that a stock capability accepts a SKU and returns the number of individual units available for sale. The API might call its field quantity, while the database stores it in a column named units. The server can normalize either source into a stable domain object.
| Layer | Example contract |
|---|---|
| MCP tool input | Object containing a required SKU string |
| Domain operation | Authorized stock lookup for the current tenant |
| REST backend | Approved endpoint returning SKU and quantity |
| SQL backend | Query scoped to tenant and SKU |
| Domain result | SKU and available_units |
| MCP result | Supported content or structured representation of the domain result |
The result might be:
JSON{ "sku": "A12", "available_units": 7 }
This is application data, not an entire MCP response. The MCP SDK or protocol adapter still needs to encode it using the supported result representation.
The benefit of this separation is that changing the backend need not change every MCP client. However, normalization must preserve meaning: quantity and units can be mapped only if both represent the same business concept. A total warehouse count is not automatically equivalent to stock available for sale.
Design the server around explicit business operations rather than arbitrary network access or raw database execution. For example, expose stock(sku), not fetch_any_url(url) or execute_any_sql(sql). A narrow contract is easier to authorize, test, monitor and evolve.
3. What the server does before calling the backend#
A handler should establish the following before invoking a downstream dependency:
- The method and capability are supported, and the request is valid for the applicable protocol state.
- The inputs satisfy the advertised schema and relevant business restrictions.
- The authenticated identity has permission to execute the operation on the resource.
- The backend destination and credential configuration are trusted application settings.
- Appropriate request deadlines, data limits and side-effect controls are in place.
A valid SKU string is not proof that a user may read that SKU. A model-proposed tenant identifier must not override the tenant derived from a validated identity. Similarly, the ability to call a backend with a service credential does not imply that every MCP caller may use all of that credential's privileges.
The previous lesson explained consent and authorization ownership. Here the important additional distinction is that the downstream adapter must receive trusted authorization context and retain it when constructing the backend request.
4. Calling a REST API from an MCP handler#
A REST adapter typically uses a configured base URL, a fixed or allowlisted endpoint, a supported HTTP method and an approved HTTP client. It maps the validated capability inputs into path parameters, query parameters or a request body according to the service's documented contract.
For example, an inventory service might provide a fictional read endpoint with a SKU parameter. The server obtains credentials intended for that service and sends the request using appropriate TLS configuration. It checks the HTTP status, content type, payload size and response shape before converting the result.
Do not take an unrestricted URL from a model-generated argument. Correctly encode user-provided path segments and query values, restrict redirects and network destinations where appropriate, and protect against server-side request forgery. The application should know which remote service it is calling.
HTTP status codes are part of the downstream contract. For a fictional stock lookup:
| Downstream response | Possible domain interpretation |
|---|---|
| 200 with valid stock data | Successful observation |
| 404 | Record unavailable, if defined by this endpoint |
| 401 or 403 | Authentication or authorization failure; do not expose secrets |
| 429 | Rate limit; respect appropriate retry policy |
| 503 | Temporarily unavailable dependency |
| Timeout | No definitive response received |
These mappings are illustrative. A particular API may deliberately use 404 for inaccessible records, use 202 for accepted but incomplete operations, or return a domain-specific error body. Never infer that every HTTP success status means a committed business operation.
The MCP server should map these outcomes into its own supported capability contract and relevant protocol errors rather than return arbitrary upstream response bodies to the model. Preserve enough diagnostic information for the operator, but omit credentials, internal stack traces and unrelated private fields.
5. Accessing a database through a repository#
When a server accesses a database directly, use the appropriate driver or repository abstraction. Prefer fixed queries for well-defined business operations. Pass data values as bound parameters rather than interpolating them into SQL strings.
An illustrative SQLite query is:
SQLSELECT units FROM stock WHERE tenant = ? AND sku = ?;
The placeholders are supplied separately through the SQLite driver's parameter-binding interface. PostgreSQL drivers may use different placeholder syntax; do not mechanically copy SQLite placeholders into another driver's API.
The tenant condition scopes the query to the relevant tenant. The server must derive the tenant from trusted authorization context and must still enforce any finer-grained resource restrictions required by the application. A database with row-level security or an appropriately constrained role can provide an additional enforcement layer.
Parameter binding protects against interpreting untrusted parameter values as SQL code. It does not automatically authorize rows, constrain result size, make arbitrary SQL safe or bind dynamic identifiers such as table names. Avoid exposing arbitrary model-generated SQL unless a specifically designed, independently enforced constrained-query system supports the use case.
A direct database adapter also needs appropriate connection limits, indexes, transaction isolation, query timeouts, result bounds and credential scope. Prefer a read-only database role for genuinely read-only capabilities. Direct writes must preserve authoritative business invariants; they should not bypass an existing business API's required validations or audit behavior.
6. Credential boundaries: incoming identity versus downstream access#
There are two distinct authorization relationships.
| Relationship | Responsibility |
|---|---|
| MCP client to server | Establish the actor and permitted MCP resource/operation |
| MCP server to backend | Obtain appropriate access to the specific API or database |
The historical MCP authorization framework applies to relevant HTTP deployments. It does not automatically authorize the server to access unrelated APIs or databases.
A downstream adapter may use a narrowly scoped workload identity, a properly supported user-delegated credential, or another approved service-specific authentication mechanism. The appropriate choice depends on which service owns permissions and how accountability is preserved.
Do not pass an inbound MCP token unchanged to an unrelated backend. Tokens must be intended for the receiving resource; any delegation or token exchange should be explicitly supported and properly constrained. Store backend credentials outside prompts, tool arguments and returned content.
A privileged service account can be necessary in some systems, but it increases the importance of application-enforced resource authorization and least privilege. A service account must not become a universal bypass that allows any model-generated request to access private data.
7. Connection management and performance#
MCP session lifetime and backend connection lifetime are separate concerns. An MCP server should not automatically create a new database pool or HTTP client for every tool request. Nor should it hold a database transaction open for the entire duration of a user conversation.
For remote services, reuse a suitable HTTP client and connection pool where supported. For databases, use a bounded pool appropriate to the database capacity and workload. Acquire a connection for the required query or transaction, then return or close it according to the driver contract.
| Resource | Practical rule |
|---|---|
| HTTP client | Reuse safely within its supported lifetime |
| Database connection | Acquire for bounded work; release promptly |
| Transaction | Keep short and tied to a business operation |
| Request deadline | Include queueing, connection acquisition and backend execution |
| Concurrency | Limit outstanding dependency calls |
| Cache | Scope by authorization context and business freshness |
Connection pooling reduces setup overhead, but an excessively large pool can overload a shared database. A slow external dependency can also exhaust all server workers. Use bounded concurrency, backpressure and appropriately allocated deadlines.
For an illustrative workload, 40 concurrent handlers with a pool of 10 database connections cannot all hold a database connection at once. Some must wait, finish or be rejected under the configured policy. This is not a capacity recommendation; actual pool sizing depends on query latency, database limits, worker count and deployment architecture.
In asynchronous servers, use suitable async clients/drivers or a bounded mechanism for integrating blocking libraries. Simply declaring a handler async does not make synchronous database I/O nonblocking.
Close resources during server shutdown using the SDK's documented lifecycle and the backend client's resource-management API. Keep cleanup behavior separate from business rollback: releasing a connection does not undo an already committed operation.
8. End-to-end result and error handling#
The sequence shows conceptual responsibilities, not the full historical JSON-RPC exchange. Transport authentication and initialization are omitted. The error mapping depends on the applicable protocol and capability contract.
For a stock lookup, zero is a valid numeric count. A missing record, denied request, timeout or invalid result must not be reported as zero. Otherwise, a model could confidently tell a user that a product is unavailable when the backend simply failed.
Distinguish the following categories:
- Input or policy failure: request cannot proceed.
- Dependency failure: backend is unavailable or rejects the integration request.
- Malformed result: backend data does not meet the expected contract.
- Valid domain outcome: an authoritative result or business rejection.
- Uncertain write outcome: a response was lost after a possible state change.
The server should not flatten every category into an empty list or false value. The host needs enough reliable information to decide whether to retry, request clarification, report rejection or reconcile state.
9. Tested implementation: REST and SQLite adapters with one domain contract#
This example implements the same read-only stock operation against two backend interfaces. One receives simulated HTTP status/body responses; the other uses a real in-memory SQLite database. The two adapters share input and output validation and return the same application-level domain object.
It also demonstrates rollback of a deliberately failed SQLite transaction. That transaction is a local test, not an MCP-exposed write tool.
The Actor object represents an identity and permission already established by trusted middleware. The fake REST function assumes it applies the supplied tenant correctly. No network call, actual credential validation, MCP initialization or SDK method is implemented.
Save as mcp_q23.py:
PYTHONfrom contextlib import closing from dataclasses import dataclass import sqlite3 class Unavailable(Exception): pass @dataclass(frozen=True) class Actor: tenant: str can_read: bool def validate(actor, sku): if not actor.can_read: raise PermissionError('Access denied') if type(sku) is not str or not 1 <= len(sku) <= 16 or not sku.isascii() or not sku.isalnum(): raise ValueError('Invalid SKU') def normalize(sku, count): if type(count) is not int or count < 0: raise ValueError('Invalid downstream count') return {'sku': sku, 'available_units': count} def from_api(fetch, actor, sku): validate(actor, sku) try: status, body = fetch(actor.tenant, sku) except TimeoutError as exc: raise Unavailable('Upstream timeout') from exc if status == 404: raise LookupError('Record unavailable') if status != 200: raise Unavailable('Upstream rejected request') if not isinstance(body, dict) or body.get('sku') != sku: raise ValueError('Invalid downstream record') return normalize(sku, body.get('quantity')) def from_db(db, actor, sku): validate(actor, sku) row = db.execute('SELECT units FROM stock WHERE tenant = ? AND sku = ?', (actor.tenant, sku)).fetchone() if row is None: raise LookupError('Record unavailable') return normalize(sku, row[0]) def rejects(fn, expected): try: fn() except expected: return raise AssertionError('Expected rejection') if __name__ == '__main__': a = Actor('A', True) denied = Actor('A', False) rows = {('A', 'A12'): 7, ('A', 'B34'): 0, ('B', 'X99'): 12} def fake_fetch(tenant, sku): key = (tenant, sku) return (200, {'sku': sku, 'quantity': rows[key]}) if key in rows else (404, {}) def slow(tenant, sku): raise TimeoutError() with closing(sqlite3.connect(':memory:')) as db: with db: db.execute('CREATE TABLE stock (tenant TEXT, sku TEXT, units INTEGER, PRIMARY KEY (tenant, sku))') db.executemany('INSERT INTO stock VALUES (?, ?, ?)', [(t, s, n) for (t, s), n in rows.items()]) for sku, units in [('A12', 7), ('B34', 0)]: assert from_api(fake_fetch, a, sku) == from_db(db, a, sku) == {'sku': sku, 'available_units': units} for read in (lambda actor, sku: from_api(fake_fetch, actor, sku), lambda actor, sku: from_db(db, actor, sku)): rejects(lambda: read(a, 'X99'), LookupError) rejects(lambda: read(denied, 'A12'), PermissionError) rejects(lambda: read(a, "A12' OR 1=1"), ValueError) rejects(lambda: from_api(slow, a, 'A12'), Unavailable) rejects(lambda: from_api(lambda t, s: (503, {}), a, 'A12'), Unavailable) rejects(lambda: from_api(lambda t, s: (200, {'sku': 'B34', 'quantity': 7}), a, 'A12'), ValueError) rejects(lambda: from_api(lambda t, s: (200, {'sku': s, 'quantity': True}), a, 'A12'), ValueError) try: with db: db.execute('UPDATE stock SET units = ? WHERE tenant = ? AND sku = ?', (1, 'A', 'A12')) raise RuntimeError('Simulated transaction failure') except RuntimeError: pass assert from_db(db, a, 'A12')['available_units'] == 7 print('13 downstream adapter checks passed')
Run:
BASHpython -m py_compile mcp_q23.py python mcp_q23.py
Actual local output on Python 3.13.5:
13 downstream adapter checks passedThe checks comprise two equivalent-result cases (positive stock and zero stock), six rejection cases across the two adapters (other-tenant record, denied actor and invalid SKU for each), four REST fixture failure cases (timeout, 503, wrong returned SKU and boolean count), and one actual SQLite transaction rollback check.
How the implementation works#
The validate function enforces the fixture's simple permission and SKU format rules before a backend is called. Both adapters invoke normalize so that the result uses one field name and rejects negative or non-integer counts. Python booleans are explicitly rejected because bool is a subclass of int but is not a meaningful inventory count.
The API adapter checks the returned SKU to avoid associating a valid-looking count with the wrong resource. The database adapter uses bound parameters, including the tenant. The SQL statement is fixed, and the composite primary key ensures at most one matching stock row per tenant/SKU in this fixture.
The transaction test modifies A12 and raises an exception before leaving the connection's transaction context. The context manager rolls back the uncommitted update. A subsequent query verifies that seven units remain. The enclosing closing context manager closes the database connection; the SQLite connection's transaction context manager alone does not close it.
An actual MCP handler could invoke one of these adapters after establishing trusted authorization context and encode the returned domain object using its selected SDK's supported result representation. The dedicated SDK lessons will provide concrete registration and transport implementations.
Limits of the test#
The fake REST responses do not exercise HTTP networking, TLS, actual token validation, redirects, serialization, real timeout enforcement or rate limits. The fixture intentionally collapses non-200/non-404 responses into a dependency exception; production adapters should distinguish authorization, throttling and transient failures according to the real API contract.
The malicious-looking SKU is rejected before reaching SQL. The test does not separately prove injection resistance for every possible SQL value or query. The query nevertheless uses real driver parameter binding.
The tenant scope is tested only against the fixture's known records, not real multi-tenant authentication or database row-level security. The single permission flag is deliberately coarse. The SQLite table is temporary and single-process; production connection pooling, concurrency, transaction isolation, database errors and PostgreSQL behavior were not tested. Raw Python exceptions are not MCP protocol errors. Use appropriate SDK result/error mapping in a real integration.
10. Transaction boundaries for writes#
The transaction test illustrates a local database guarantee under its own conditions. It does not establish atomicity across an MCP host, a server, an HTTP API and a separate database.
For a single authoritative database, a write operation should validate necessary state and apply related changes inside the appropriate transaction. For example, an inventory reservation must enforce that stock remains sufficient when the update commits.
For a downstream API, the service owns its transaction semantics. A 202 Accepted response might mean work has only been queued. A timeout after a request may leave the outcome unknown. Use the service's documented operation identifier, idempotency and status mechanisms when appropriate.
When an operation spans several independent services, avoid holding a local transaction open while waiting indefinitely for remote calls. Define how partial completion, retries and reconciliation are handled. Compensation may be a separate business operation rather than an automatic rollback.
Detailed idempotency and multi-service consistency patterns belong to Q230–233. The architectural principle here is that MCP does not create a new transaction boundary around all underlying dependencies.
11. Production scenario: changing the inventory backend#
Suppose the retailer's old inventory adapter reads a database directly. The inventory team introduces an API to centralize domain policy and eventually removes direct database access for external integrations.
The MCP team can preserve the stock tool's contract if the new API supplies the same authorized business meaning. It should test both paths against equivalent test data, validate permissions and failure outcomes, and compare latency and operational behavior. A migration can use controlled read comparisons, not uncontrolled duplicated writes.
An adapter abstraction is useful when alternative implementations really share a contract. It is not a reason to hide important differences such as eventual consistency, warehouse scope or authorization semantics. If the new backend changes the meaning of available_units, the server must explicitly address that contract change.
Production acceptance criteria should include correct business results, resource authorization, bounded result size, connection cleanup, latency under realistic load, controlled error mapping and recovery from dependency outages.
12. Common mistakes and a practical checklist#
| Mistake | Better approach |
|---|---|
| Exposing arbitrary URL or SQL execution | Provide narrowly scoped domain capabilities |
| Passing raw credentials through the model | Resolve credentials within trusted server code |
| Using string concatenation for SQL values | Use the database driver's parameter binding |
| Treating an MCP session as a database transaction | Define the transaction around authoritative business work |
| Treating missing or failed reads as zero | Preserve the distinction in the result contract |
| Returning raw upstream bodies | Validate and minimize normalized results |
| Opening an unbounded number of backend connections | Reuse and bound connections appropriately |
| Retrying an uncertain write automatically | Use authoritative status and supported idempotency |
| Assuming a unit test proves protocol compatibility | Test real SDK and backend combinations independently |
For each capability, document the backend owner, approved destination, input and result contract, identity mechanism, resource permission, timeout budget and transaction semantics. Measure dependency latency, failure categories and resource utilization without logging private payloads or credentials.
Interview-ready answer#
MCP servers use normal service adapters and database repositories to implement the capabilities they expose. A server validates the incoming request and authenticated actor, maps the approved operation to a fixed or constrained backend interface, calls the service using appropriate credentials, checks and normalizes the result, and returns a supported MCP result or error. REST integration requires safe endpoint configuration, response validation and bounded HTTP operations. Database integration requires parameterized queries, resource scoping, appropriate pooling and authoritative transaction rules. MCP communication, backend access and business transactions are separate boundaries. Using MCP does not eliminate any of the underlying security, reliability or consistency requirements.
Module transition: Module 02 has now covered the host, client, server, isolation, responsibility handoffs and downstream integration. Q25 begins Module 03 — MCP messages and JSON-RPC, explaining why MCP uses JSON-RPC 2.0 as its message framework.
References
- 1.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 2.MCP architecturemodelcontextprotocol.io
- 3.MCP toolsmodelcontextprotocol.io
- 4.MCP authorizationmodelcontextprotocol.io
- 5.Official MCP Python SDKgithub.com
- 6.Python sqlite3 documentationdocs.python.org
- 7.PostgreSQL transaction tutorialpostgresql.org
- 8.HTTP Semantics (RFC 9110)rfc-editor.org
- 9.OWASP SQL Injection Preventioncheatsheetseries.owasp.org
- 10.OWASP SSRF Preventioncheatsheetseries.owasp.org
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation