Intermediate·Concept·2 min read

Reuse Existing APIs, Services, and Databases

Practice this question
Architecture at a glanceFollow the arrows to see how the parts connect.

Preparing the architecture diagram…

Read the full diagram flow
flowchart TB
  REST[REST controller] --> OS[Order service]
  MCP[MCP tool handler] --> OS
  OS --> R[Order repository]
  R --> DB[(PostgreSQL)]
  OS --> P[Authorization policy]

The REST controller and MCP handler are thin adapters. Business rules remain in the service layer. The repository uses parameterized queries.

TypeScript
async function lookupOrder(ctx: AuthContext, orderId: string) {
  const order = await orderRepository.findById(orderId);
  if (!order) return null;
  if (order.customerId !== ctx.customerId && !ctx.roles.includes("support")) {
    throw new ForbiddenError();
  }
  return order;
}

Production controls

  • Reuse connection pools; do not create a new pool for every tool call.
  • Use parameterized SQL; do not concatenate model-generated SQL.
  • Use bounded filters and cursor-based pagination.
  • Use external API timeouts, retry budgets, and circuit breakers where useful.
  • Perform writes with an idempotency key and an audit record.
Adapted from 20_MCP_SERVER.md · “9. Reuse Existing APIs, Services, and Databases”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.