Zero Labs
Industry News / AI

MCP for Backend Engineers: When to Use It (and When to Skip It)

Source · Towards AI By TheProdSDE

From the publisher’s feed, collected in the ZeroLabs newsroom.

“If you only have one consumer, MCP is a liability.”Subtitle: Real code, real cost, and an honest answer to the question every AI team gets wrong.Source: created by Google gemini and AuthorTL;DR1 app · 1 team · 1 toolset → use plain tool callingMultiple teams or AI surfaces → use MCPExisting APIs → wrap them in MCPEarly-stage / MVP → skip MCPMCP is a scaling decision, not a starting point.Why This ExistsA client had a simple ask: “Let our AI assistant use our REST API.”Three teams built three integrations. All three were wrong:Model called /getCustomer when it needed /getOrdersAuth header dropped silently on retryThree teams hardcoded three different endpoints assumptionsResult: 3 integrations. 3 slightly different bugs. 1 very awkward client call.That’s when MCP become the answer. One server wrapping the API. Any AI host connects to it. The client got exactly what they asked for — and we got a pattern reused three times sinceMCP is not about smarter models — it’s about cleaner boundaries.MCP in One LineMCP = API Gateway + Plugin System + Contract Layer for LLMsSource: created by AuthorThe Hero Diagram: MCP vs Tool CallingThis is the architecture difference that actually matters.Source: Created using mermaid by AuthorThe shift: Tool calling is a local decision. MCP is an organizational contract.What MCP Actually IsModel Context Protocol (MCP) is an open protocol that standardises how AI applications connect to external tools and data sources. Think of it as USB-C for AI tools — one connector, many servers, any host.Instead of every IDE, chat UI, or agent framework inventing its own plugin format, MCP defines a common contract using JSON-RPC 2.0 over Streamable HTTP or stdio.Three roles in the spec:Host — the application the user sees (IDE, CLI, chat UI, agent framework)Client — a connector inside the host that speaks the MCP protocolServer — a service that exposes tools, resources, and prompts to the modelThe client sits between host and server. It connects to one server at a time and speaks the protocol; the host can orchestrate multiple clients simultaneously.Source: Created using mermaid by AuthorKey Insight: The model never talks to your backend directly. It only talks to tools exposed by MCP servers. That’s the boundary.Case Study: Wrapping a Client REST APIBefore: Three separate UIs (web, Slack bot, IDE) called the REST API directly. Each integrator made slightly different assumptions about endpoints and auth — producing three brittle integrations and repeated bugs.After: One MCP server wrapping the existing API. Same tool list and prompts exposed to every host.Results in production:Integration time reduced by ~60% for new hostsTool-call auth failures dropped from multiple incidents to zero in the first month (root cause: centralized token handling)Two new hosts onboarded with zero backend changesThis is the practical payoff: a small upfront cost for long-term reduction in duplicated integration work and clearer ownership.Should You Use MCP? — Decide Before Reading FurtherMost tutorials make you read 80% before answering this. Here it is upfront.If you pick MCP too early, you’re trading ~1–2 extra days of setup for zero immediate benefit. Start with the simplest thing. Reach for MCP when the “three wrappers” problem is already real.Three questions that determine everything:How many consumers will call these tools?One app, one team → plain tool calling, doneMultiple apps or teams → MCP starts making sense2. Who owns the tools vs who owns the AI host?Same team owns both → plain tool calling, tight coupling is fineDifferent teams → MCP gives you the clean boundary3. Do these tools already exist as APIs?Yes → wrap them as an MCP server, zero changes to existing backendNo → build them either way, MCP adds structure from day oneFive Real ScenariosScenario 1 — Internal chatbot for one teamA team wants an AI that queries their own database and sends Slack alerts. One app, one team, they control everything.→ Plain tool calling. MCP adds overhead with zero benefit here.Scenario 2 — Your client’s REST API (the exact story above)Client has an existing API. Wants multiple AI surfaces to consume it — web app today, Slack bot next month, VS Code extension later.→ MCP. Wrap the API once, every host connects via the same protocol.Scenario 3 — Enterprise platform, multiple teamsPayments team, infra team, CRM team — each owns their domain. One central AI console orchestrates across all three.→ MCP per domain. Each team ships and secures their own server.Scenario 4 — Quick prototype / MVPYou’re validating an idea over a weekend. Speed matters more than architecture.→ Plain tool calling always. Get the idea working first. MCP is a refactor you do when it proves valuable.Scenario 5 — Agentic workflow with long-running tasksAgent coordinates across multiple systems, tasks need to be traceable and retryable across sessions.→ MCP. The clean server/client boundary makes observability and retry logic significantly easier to implement.Decision FlowSource: Created using mermaid by AuthorKey Insight: MCP is triggered by scale of ownership and consumption — not complexity.Where MCP Is a Bad IdeaMCP is the wrong choice when:You’re at the early-stage or MVP phaseOnly one host consumes the toolsOne team owns the full stackLatency is business-criticalTool shapes are still evolvingIf you only have one consumer, MCP is architecture cosplay.Core MCP ConceptsServer-side primitives1. ToolsExecutable actions — often with side effects. The LLM decides when to call them.Examples: create_invoice, deploy_service, run_sql_query.2. ResourcesRead-only data and context the model is allowed to see — not actions.Examples: docs, config files, logs, user profile JSON, query results.3. PromptsReusable workflow templates — Postman collections for LLM behaviour. Server-defined recipes the host can invoke.Examples: bug_report_prompt, deployment_checklist_prompt.Client-side capabilities4. SamplingThe server asks the client: “Run a model completion for me using your model access.” Useful when servers don’t hold model keys.5. RootsThe server asks: “What file paths or URIs can I operate on?” Organises where tools can act.6. ElicitationThe server asks the client to collect more information from the user.Example: “Ask the user which environment to deploy to: dev/staging/prod.”Request / Response LifecycleThe most important thing to understand: the Host orchestrates LLM calls — not the MCP Client. The client only handles server communication. This distinction is what most sequence diagrams get wrong.Source: Created using mermaid by AuthorKey Insight: The model decides what to call, but the server controls what exists. That’s the contract.Minimal MCP Server (Python)Three things to watch in this block:@mcp.tool() is an executable action with side effects@mcp.resource() is read-only context — the model sees it, doesn't call itThe /health endpoint is not optional — Container Apps and AKS need it for readiness probes. Skip it and your pods restart on a loop.# server.py# requires: fastmcp>=2.0.0, python-dotenvimport osimport uuidfrom dotenv import load_dotenvfrom fastmcp import FastMCP, Resourceload_dotenv()mcp = FastMCP( name="customer-service", instructions="Customer service MCP server.",)# ── Tool: get_customer ────────────────────────────────────────────────────────@mcp.tool()async def get_customer(customer_id: str) -> dict: """Fetch customer profile by ID.""" # Replace with your real DB call return { "customer_id": customer_id, "name": "Priya Sharma", "email": "priya@example.com", "tier": "premium", "last_order_date": "2026-03-15", }# ── Tool: get_orders ─────────────────────────────────────────────────────────@mcp.tool()async def get_orders(customer_id: str, limit: int = 5) -> dict: """Fetch recent orders for a customer.""" return { "customer_id": customer_id, "orders": [ {"order_id": f"ORD-{i}", "status": "delivered", "amount": 1200 + i * 50} for i in range(1, limit + 1) ], }# ── Tool: create_support_ticket ───────────────────────────────────────────────@mcp.tool()async def create_support_ticket( customer_id: str, issue: str, priority: str = "medium",) -> dict: """Create a support ticket for a customer issue.""" return { "ticket_id": f"TKT-{uuid.uuid4().hex[:8].upper()}", "customer_id": customer_id, "issue": issue, "priority": priority, "status": "open", }# ── Resource: customer playbook ───────────────────────────────────────────────@mcp.resource("customer-playbook")async def customer_playbook() -> Resource: """Internal guidance for handling customer incidents.""" content = """# Customer Handling Playbook- Always greet the customer by name.- Premium customers: consider goodwill credit for severe issues.- Escalate to L3 if incident impacts > 10 customers.- SLA: 4 hours for premium, 24 hours for standard.""" return Resource( name="customer_playbook", description="Internal guidance for handling customer incidents.", mimeType="text/markdown", content=content, )# ── Prompt: email draft ───────────────────────────────────────────────────────@mcp.prompt("email_draft_prompt")async def email_draft_prompt(): """Reusable workflow template for customer apology emails.""" return { "name": "email_draft_prompt", "description": "Template for customer apology emails.", "messages": [{ "role": "system", "content": ( "You are a senior customer success manager.\n" "Write a short apology email to {{customer_name}} about: {{issue}}.\n" "Tone: professional, empathetic. Under 100 words." ), }], }# ── Health check - required for ACA and AKS readiness probes ─────────────────@mcp.custom_route("/health", methods=["GET"])async def health(): from fastapi.responses import JSONResponse return JSONResponse({"status": "ok", "server": "customer-mcp"})if __name__ == "__main__": mcp.run( transport="streamable-http", host="0.0.0.0", port=int(os.getenv("PORT", 8000)), )Start it:pip install "fastmcp>=2.0.0" python-dotenvpython server.py# Live at http://localhost:8000/mcpInspect without writing a single line of client code:npx @modelcontextprotocol/inspector http://localhost:8000/mcpMCP Client + Agent LoopThe key line is client.list_tools() — tools are discovered dynamicallyfrom the server, not hardcoded in the client. Every host that connects to this server gets the same tool list automatically, even as you add new tools.# client.py# requires: fastmcp>=2.0.0, openai>=1.0.0, python-dotenvimport asyncioimport jsonimport osfrom dotenv import load_dotenvfrom fastmcp import Clientfrom openai import AsyncOpenAIload_dotenv()openai_client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))MCP_URL = os.getenv("MCP_SERVER_URL", "http://localhost:8000/mcp")async def run(query: str) -> str: async with Client(MCP_URL) as client: # Discover tools from the server - not hardcoded here tools = await client.list_tools() openai_tools = [ { "type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.inputSchema, }, } for t in tools ] print(f"\n[MCP] {len(tools)} tools discovered: {[t.name for t in tools]}") messages = [{"role": "user", "content": query}] while True: resp = await openai_client.chat.completions.create( model="gpt-4o", messages=messages, tools=openai_tools, tool_choice="auto", ) msg = resp.choices[0].message messages.append(msg) # No tool calls = final answer if not msg.tool_calls: return msg.content # Execute each tool call via the MCP server for tc in msg.tool_calls: args = json.loads(tc.function.arguments) print(f"[Tool] {tc.function.name}({args})") result = await client.call_tool(tc.function.name, args) tool_content = ( result.content[0].text if result.content else "{}" ) messages.append({ "role": "tool", "tool_call_id": tc.id, "content": tool_content, })if __name__ == "__main__": queries = [ "Look up customer C-123 and tell me their tier.", "Get the last 3 orders for customer C-123.", "C-123 had a late delivery. Open a ticket and draft an apology email.", ] for q in queries: print(f"\n[Query] {q}") print(asyncio.run(run(q))) print("─" * 60)Run it (server must be up):python client.pyAuth — The Part Most Tutorials SkipTL;DR:Internal / pod-to-pod → skip auth entirely, use network policy.Public-facing → OAuth 2.1 + PKCE, no exceptions. The spec mandates it.Everything else is a practical middle ground.For remote MCP servers (Streamable HTTP), the spec prescribes OAuth 2.1 Authorization Code + PKCE. The MCP client acts as the OAuth client; your server acts as the resource server; an Authorization Server (Keycloak, Auth0, Azure AD) issues the tokens.The flow:Client hits server without a token → 401 with WWW-Authenticate pointing to /.well-known/oauth-protected-resourceClient discovers the auth server from that metadataClient runs OAuth 2.1 Authorization Code + PKCEClient retries MCP requests with Authorization: Bearer Server validates the token and serves tools/resourcesHere’s the token validation middleware — the piece that took longest to get right because the aud (audience) claim check is easy to miss. Without it, a token issued for a different service will pass validation silently.# auth_middleware.pyimport osimport httpxfrom authlib.jose import jwt, JsonWebKeyfrom fastapi import Requestfrom fastapi.responses import JSONResponseMCP_RESOURCE_ID = os.getenv("MCP_RESOURCE_ID", "https://your-mcp-server/")AUTH_SERVER_URL = os.getenv("AUTH_SERVER_URL", "")_jwks_cache: dict | None = NoneSKIP_PATHS = {"/health", "/.well-known/oauth-protected-resource"}async def fetch_jwks() -> dict: global _jwks_cache if _jwks_cache: return _jwks_cache async with httpx.AsyncClient() as http: r = await http.get(f"{AUTH_SERVER_URL}/protocol/openid-connect/certs") r.raise_for_status() _jwks_cache = r.json() return _jwks_cacheasync def oauth_middleware(request: Request, call_next): if request.url.path in SKIP_PATHS: return await call_next(request) auth = request.headers.get("Authorization", "") if not auth.startswith("Bearer "): return JSONResponse( status_code=401, content={"error": "missing_token"}, headers={"WWW-Authenticate": f'Bearer realm="{MCP_RESOURCE_ID}"'}, ) token = auth.removeprefix("Bearer ").strip() try: jwks = await fetch_jwks() claims = jwt.decode(token, JsonWebKey.import_key_set(jwks)) claims.validate() # ── The check most tutorials miss ─────────────────────────── aud = claims.get("aud", []) if isinstance(aud, str): aud = [aud] if MCP_RESOURCE_ID not in aud: return JSONResponse(status_code=403, content={"error": "wrong_audience"}) request.state.user = dict(claims) return await call_next(request) except Exception as e: return JSONResponse(status_code=401, content={"error": str(e)})Wire it into your server:# Add to server.py after: mcp = FastMCP(...)from auth_middleware import oauth_middlewaremcp.app.middleware("http")(oauth_middleware)Real-World Cost (Numbers, Not Theory)Expect:+3–100ms MCP protocol overhead per call (varies by gateway)+280–950ms total round-trip latency including tool execution (p50–p95)+1.8–4.2 seconds for multi-step agentic flows (3-agent chains, p50–p95)Extra infra: containers, auth service, monitoringNon-trivial engineering overhead during setupIf your system is latency-sensitive or single-tool focused, MCP will feel slower — because it is.You’re buying reuse and consistency, not speed.Observability & DebuggingMake MCP servers and client-host interactions observable from day one:Trace every request — propagate a correlation ID across host → client → server → backend and include it in logs and responsesMetrics to track — mcp_tool_call_latency, mcp_tool_call_errors, mcp_discovery_time, mcp_auth_failures, per-tool success ratesStructured JSON logs — (timestamp, level, correlation_id, tool, args, duration, error) to make postmortems fastDistributed tracing — use OpenTelemetry to connect host traces to server traces for full request/response visibilityTroubleshooting checklist — confirm /.well-known/oauth-protected-resource, check token aud claim, verify /health readiness, replay failing tool calls against a local mock serverTesting & QATreat the MCP server like a public contract:Contract tests — verify the tool list and input/output schemas remain compatible across releases. Fail CI on breaking schema changes.Unit tests — each @mcp.tool() should have unit tests for edge casesIntegration tests — run the server against a mocked backend and a simulated client that performs discovery + tool callsSmoke tests — lightweight end-to-end checks that run on deploy (e.g., a small request to get_customer and get_orders)Production Checklist[ ] Health/readiness: expose /health and use readiness probes (ACA/AKS)[ ] Replicas: min-replicas >= 1 for interactive workloads to avoid cold starts[ ] Auth: validate aud claim and enforce least-privilege scopes[ ] Rate limiting & quotas: protect downstream systems from runaway agents[ ] Secrets: store credentials in Key Vault / secret manager — avoid plain env vars for DB credentials[ ] Observability: metrics, logs, and traces wired to your platform[ ] Cost & latency: budget for an extra 280–950ms network hop per tool call“The rest of this guide uses Azure — not because MCP requires it, but because most production deployments need a real answer to ‘where does this actually run?’”Deploying on AzureMCP is not Azure-specific — it runs on any platform that supports HTTP. But if you’re already in the Azure ecosystem, here’s the honest breakdown.Source: Created using mermaid by AuthorAzure Deployment Decision TableSouce : Created by authorOption 1 — Azure Container Apps (start here)Recommended for most teams starting fresh. Handles autoscaling, ingress, Entra ID integration, and scale-to-zero with no MCP-specific platform knowledge needed.RG="mcp-rg"ACR=""# Build and pushaz acr build --registry $ACR --image customer-mcp-server:latest .# Create environmentaz containerapp env create \ --name mcp-env --resource-group $RG --location eastus# Store credentials in Key Vault - never directly in env varsaz keyvault secret set \ --vault-name mcp-keyvault \ --name database-url \ --value "postgresql://user:pass@host:5432/db"# Deployaz containerapp create \ --name customer-mcp-server \ --resource-group $RG \ --environment mcp-env \ --image $ACR.azurecr.io/customer-mcp-server:latest \ --target-port 8000 \ --ingress external \ --min-replicas 1 \ --max-replicas 10 \ --secrets db-url=keyvaultref: \ --env-vars DATABASE_URL=secretref:db-urlmin-replicas 1 is critical for interactive use — scale-to-zero causes cold start that breaks mid-conversation flow. Expect ~1–3s latency even on warm replicas; design your agent loop timeouts accordingly (30s is a safe outer bound).Option 2 — AKS (if you already run a cluster)Use Workload Identity over storing credentials in env vars. Reuse cluster auth and network policies.# mcp-deployment.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: customer-mcp-server namespace: mcp-systemspec: replicas: 2 selector: matchLabels: app: customer-mcp-server template: metadata: labels: app: customer-mcp-server spec: containers: - name: mcp-server image: .azurecr.io/customer-mcp-server:latest ports: - containerPort: 8000 env: - name: DATABASE_URL valueFrom: secretKeyRef: name: mcp-secrets key: database-url readinessProbe: httpGet: path: /health port: 8000 initialDelaySeconds: 5 periodSeconds: 10 livenessProbe: httpGet: path: /health port: 8000 initialDelaySeconds: 15 periodSeconds: 20---apiVersion: v1kind: Servicemetadata: name: customer-mcp-server namespace: mcp-systemspec: selector: app: customer-mcp-server ports: - port: 8000 targetPort: 8000---apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: mcp-ingress namespace: mcp-systemspec: rules: - host: mcp.yourdomain.internal http: paths: - path: /mcp pathType: Prefix backend: service: name: customer-mcp-server port: number: 8000kubectl create namespace mcp-systemkubectl apply -f mcp-deployment.yamlkubectl get pods -n mcp-systemOption 3 — Azure Functions (infrequent, event-driven tools)Best for tools called rarely — scheduled jobs, webhook-triggered actions, batch processors. Per-invocation billing means zero idle cost. Not suitable for interactive agent loops — cold start breaks conversational flow.Option 4 — App Service (add /mcp to an existing service)Mount the MCP server on /mcp alongside existing routes. Zero infrastructure change. Lowest friction path for adding MCP to a service that already exists.Common Failure ModesToken misconfiguration — auth breaks silently on retryTool explosion — too many vaguely named tools confuse the modelLatency stacking — chained MCP calls compound response time (budget 280–950ms per hop)Business logic duplication — logic living in both the server and the calling agentWeak observability — no tracing across the client–server boundaryNo ownership boundaries — multiple teams modifying the same serverCritical rule: One MCP server = one owning team. Violating this recreates the exact problem MCP was meant to solve.What MCP Does NOT SolveBad tool designWeak or vague promptsLatency at the model levelCapability gaps in the underlying LLMBusiness logic duplication inside your toolsMCP standardises access. It does not improve what you expose.Migration PathDon’t start with MCP. Migrate to it when the pain appears:Start with plain tool callingIdentify tools being duplicated across teams or surfacesWrap those shared tools in an MCP serverAdd auth, deployment, and observability incrementallyAvoid premature standardisation. It’s just premature optimisation with a fancier name.Further ResourcesMCP spec: https://modelcontextprotocol.io/specificationInspector: npx @modelcontextprotocol/inspector — discover and test any MCP serverFastMCP: https://github.com/jlowin/fastmcp — the Python server/client used in this guideIf this saved you from building an MCP server you didn’t need — hit clap. It takes one second and tells the algorithm this is worth distributing. If you’ve already wired MCP into production, drop your setup in the comments — specifically curious what the auth layer looks like on your end.The Honest VerdictMCP won’t make your architecture simpler. It will make it honest — every tool, resource, and auth scope exactly where it belongs, exposed through a contract any host can consume.If you’re building for one app, one team: skip it. Plain tool calling ships faster and is entirely adequate.But if you’re building something multiple systems or teams will consume — especially if those tools already exist as APIs — MCP ends the “three copies of the same integration, each slightly wrong” problem permanently.That’s the only problem it solves. It solves it very well.Related ReadingWhy Most RAG Systems Fail in ProductionLangGraph vs Semantic KernelMost AI Agent Frameworks Are OverkillWritten by TheProdSDE · Follow for production-grade AI systems, backend architecture, and honest engineering takes.MCP for Backend Engineers: When to Use It (and When to Skip It) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.