July 2026

Saturday, July 25, 2026

System Design Master Tree: The 10 Layers That Matter


Most developers spend their careers collecting frameworks. A new JavaScript framework every year, a trendier database, whatever tool is on the front page this week. It feels like progress, and it moves you sideways. The framework you learn today is the framework you rip out in three years.

Frameworks are leaves. System design is the tree — the layered set of decisions about how systems talk, where state lives, and how they stay up. Learn the tree and every framework becomes an interchangeable detail that plugs into it.

System Design Master Tree — CodezTech
Ten layers, from core foundations to future architectures.

The below topics are covered in this blog -
1. Core Foundations
2. Networking Layer
3. API Layer
4. Database Layer
5. Caching Layer
6. Messaging Systems
7. Reliability Layer
8. Observability
9. DevOps & Deployment
10. Future Architectures
11. Common Mistakes
12. The Takeaway

1. Core Foundations

This is the layer every later decision inherits from. Client-server, monolith versus microservices, stateless versus stateful, scaling up versus out, and the CAP theorem. Get these wrong and no amount of Redis or Kubernetes saves you. The single most expensive mistake in this layer is treating “microservices” as a maturity badge rather than a trade-off you pay for in network calls and operational overhead.

CAP is the one people quote and misuse. Under a network partition you choose consistency or availability — not both, and only during the partition. Most real systems are not picking “CP or AP” as an identity; they are choosing, per operation, how much staleness they can tolerate. Frame it that way and the rest of the stack gets easier.

System design master tree: ten layers from foundations to future architectures
The full tree — each layer is a set of decisions, not a tool to memorize.

2. Networking Layer

How the packets actually move: DNS, HTTP/HTTPS, TCP versus UDP, WebSockets, load balancers, reverse proxies. TCP gives you ordered, reliable delivery and pays for it in handshake latency; UDP gives you speed and hands you the reliability problem. Pick TCP unless you have measured a reason not to. A reverse proxy plus a load balancer is the cheapest reliability upgrade most systems can make, and it is a few lines of config.

# nginx: reverse proxy + round-robin load balancing
upstream api {
    server 10.0.0.11:8080;
    server 10.0.0.12:8080;
}
server {
    listen 443 ssl;
    location / {
        proxy_pass http://api;
        proxy_set_header Host $host;
    }
}

3. API Layer

The contract between systems: REST, GraphQL, gRPC, plus the API gateway, rate limiting, and authentication that sit in front. REST is the boring default and boring is correct for most public APIs. GraphQL earns its complexity when clients need flexible, nested reads and you are tired of shipping a new endpoint per screen. gRPC wins for internal, high-throughput, low-latency service-to-service calls. The failure mode here is skipping rate limiting until the day one client accidentally takes you down.

4. Database Layer

Where the source of truth lives: SQL, NoSQL, indexing, replication, sharding, ACID transactions. The SQL-versus-NoSQL argument is usually the wrong one. The real questions are whether you need multi-row transactions, what your access patterns look like, and how you will scale writes. Reach for NoSQL when your access pattern is known and flat and your write volume outgrows a single node; stay on SQL when you need joins and transactional guarantees, which is more often than trend threads admit.

Indexing and replication are where most “the database is slow” incidents actually live. A missing index turns a millisecond lookup into a full-table scan; a read replica that has fallen behind serves stale data to users who then file bugs. Sharding is powerful and permanent — once you shard on a key, changing that key is a migration project. Choose it late and deliberately.

5. Caching Layer

Redis, Memcached, CDNs, and the hard part: invalidation. Caching is the fastest way to cut read latency and the fastest way to introduce subtle correctness bugs. The cache-aside pattern is the workhorse — read from cache, fall back to the source of truth on a miss, and set a TTL so stale data expires on its own.

# cache-aside read path
val = cache.get(key)
if val is None:                 # cache miss
    val = db.query(key)         # fall back to source of truth
    cache.set(key, val, ttl=300)
return val

The two hard problems are, famously, cache invalidation and naming things. A TTL is your cheap, correct-by-default answer to the first: it bounds how wrong the cache can be. Reach for explicit invalidation only where staleness genuinely hurts, because that is where the bugs breed.

6. Messaging Systems

Kafka, RabbitMQ, pub/sub, event streaming, async processing, queue workers. This layer decouples producers from consumers so a slow downstream does not stall the request path. Kafka is a durable, ordered log built for high-throughput streaming and replay; RabbitMQ is a broker built for flexible routing and per-message delivery. Using one where you needed the other is a rewrite, so choose on the access pattern, not the logo.

The layers from 4 through 6 are really one question — where does each piece of state belong? This is the comparison I keep coming back to:

Dimension SQL NoSQL Cache (Redis) Queue (Kafka)
Primary roleRelational source of truthScale-out source of truthHot read layerAsync transport / event log
ConsistencyStrong (ACID)Tunable / eventualEventual (TTL-bound)Ordered per partition
Read latencyLow (ms)Low (ms)Very low (sub-ms)Consumer pull
Write throughputModerate, vertical-boundHigh, horizontalVery highVery high (append)
DurabilityDurableDurableVolatile unless persistedDurable (retained log)
Scales byReplicas / verticalShardingReplicas / memoryPartitions
Failure modeLock contention, hot rowsLost joins, mis-tuningStale data, invalidation bugsConsumer lag, rebalance storms
Wrong choice whenFlat, schema-less, huge scaleYou need multi-row transactionsYou need durabilityYou need queries and joins
Cost driverVertical scale ceilingOperational complexityRAMStorage + partitions

7. Reliability Layer

High availability, fault tolerance, circuit breakers, retries, disaster recovery, backpressure. This is the layer that decides whether a single dependency failing takes the whole system with it. The pattern that prevents the most self-inflicted outages: retry with exponential backoff and jitter, sitting behind a circuit breaker that stops you from hammering a dependency that is already down.

# retry with exponential backoff + jitter, behind a breaker
for attempt in range(MAX_RETRIES):
    if breaker.is_open():          # dependency is down, stop hammering
        raise ServiceUnavailable
    try:
        return call(dependency)
    except Transient:
        sleep(base * 2 ** attempt + random_jitter())
breaker.record_failure()

Retries without backoff are how a brief blip becomes a retry storm: every client retries at once, the struggling service gets more load, and you have DDoSed yourself. Backoff spreads the load out; jitter stops every client retrying on the same tick; backpressure tells upstream to slow down instead of silently queueing forever.

8. Observability

Logs, metrics, tracing, monitoring, alerting, and SLA/SLO/SLI. The three pillars are not interchangeable: logs tell you what happened in one place, metrics tell you the shape of the whole system over time, and traces tell you where a request spent its life across services. You need all three to debug a distributed system, and you need SLIs to know whether you are actually meeting the promises in your SLOs. Alerting on symptoms users feel beats alerting on every CPU spike that wakes someone for nothing.

9. DevOps & Deployment

Docker, Kubernetes, CI/CD, infrastructure as code, blue-green and canary releases. This layer is about shipping change without shipping outages. Blue-green gives you an instant rollback by keeping the old version warm; canary limits the blast radius by sending a small slice of traffic to the new version first. A health probe is what lets the orchestrator route traffic only to instances that are actually ready.

# kubernetes: rolling deploy, 3 replicas, readiness gate
apiVersion: apps/v1
kind: Deployment
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
  template:
    spec:
      containers:
        - name: api
          image: registry/api:1.4.2
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080

10. Future Architectures

Serverless, edge computing, AI-native systems, autonomous infrastructure, self-healing systems. This is the layer where the industry is still arguing, so hold it loosely. Serverless trades operational control for scale-to-zero economics and pushes cold-start and vendor-lock questions onto you. Edge moves compute closer to users and hands you a harder consistency problem. Treat this layer as a set of bets, not settled practice — the fundamentals in layers 1 through 9 are what let you evaluate whether any of these actually fit your problem.

11. Common Mistakes

  1. Reaching for microservices on day one. You pay the distributed-systems tax — network calls, partial failure, distributed tracing — long before you have the scale that justifies it. Start with a well-structured monolith and split at the seams that actually hurt, once you can point to the pain.
  2. Caching to paper over a slow query. A cache in front of a bad query hides the root cause and adds an invalidation bug on top. Fix the index or the query first; cache what is genuinely hot and read-heavy, not what you were too rushed to optimize.
  3. Treating the message queue as a database. Kafka and RabbitMQ are transport, not your source of truth. Querying by replaying the log, or relying on infinite retention as storage, turns a fast decoupling layer into a slow, fragile database you never meant to build.
  4. Retries with no backoff or cap. Unbounded, synchronized retries are how a one-second blip becomes a full outage. Always add exponential backoff, jitter, a retry ceiling, and a circuit breaker — otherwise your own clients finish off a service that was about to recover.
  5. Believing observability means logs. Logs alone cannot tell you whether you are meeting your SLOs. Without metrics and traces you are guessing at where latency lives, and without SLIs your alerts fire on noise instead of on what users actually feel.

12. The Takeaway

Every layer in the tree is really a decision under a constraint: consistency or availability, sync or async, scale up or scale out, control or convenience. The specific tools change every couple of years. The decisions do not. That is why a strong system designer can walk into an unfamiliar stack and be useful in a day — they recognize the layer and the trade-off, and the tool is just the current implementation.

Learn the tree, not the leaves. Design for scale, build for failure, and remember that great systems are built, not guessed.

About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
atiqueahmed.com · LinkedIn · GitHub

This is Day [DAY_NUMBER] of a daily GenAI and agentic AI series on CodezTech.

Build an AI Agent in 10 Minutes with Claude Code


Ask most people how to build an AI agent and you get a shopping list: an orchestration framework, a graph library, a vector store, a week of glue code, and a diagram nobody can maintain. That was a fair answer eighteen months ago. It is now the slow way to do it, and the frameworks are increasingly the part you rip out later.

The hard part of building an agent has moved from orchestration code to specification. You don’t write the loop anymore — you assemble the agent from files Claude Code already knows how to load, and the scaffolding really is six steps you can finish in one sitting.

Build an AI Agent in 10 Minutes — CodezTech
Six steps, no orchestration code — just files Claude Code loads for you.

The below topics are covered in this blog -
1. Why “building an agent” got dramatically simpler
2. Step 1 — Install Claude Code
3. Step 2 — Build context with CLAUDE.md
4. Step 3 — Build memory
5. Step 4 — Build skills
6. Step 5 — Build the agent team
7. Step 6 — Run on autopilot with Routines
8. The four building blocks, compared
9. Common mistakes
10. The Takeaway

1. Why “building an agent” got dramatically simpler

An agent is a control loop wrapped around a model: decide the next action, take it, observe the result, repeat until done. You used to write that loop yourself. Claude Code ships it. What you supply now is context and constraints — who the agent is, what it knows, what it can touch, and when it should stop — expressed as plain markdown files the tool discovers and loads on its own.

That is the whole shift. Instead of coding orchestration, you author four kinds of file: persistent context (CLAUDE.md), accumulated memory, on-demand skills, and specialized subagents. The roadmap below is the map for the rest of this post — six steps, in order.

Build an AI Agent in 10 minutes: six-step Claude Code roadmap
The six-step build: install, context, memory, skills, agents, autopilot.

2. Step 1 — Install Claude Code

This is the foundation everything else sits on. As of mid-2026 the recommended install is the native installer, which has zero dependencies — no Node.js, no npm — and auto-updates in the background. The npm package is still fully supported if you prefer to pin versions or standardize on npm across a team; that route needs Node.js 18 or later.

# Recommended: native installer (no Node.js needed)
# macOS, Linux, WSL
curl -fsSL https://claude.ai/install.sh | bash

# Alternative: npm (requires Node.js 18+)
npm install -g @anthropic-ai/claude-code

# verify
claude --version

You authenticate in the browser on first launch with a Pro, Max, Team, Enterprise, or Console account — the free Claude.ai plan does not include Claude Code. Pick whichever surface fits your workflow: the terminal, the desktop app, or the VS Code side panel. They read the same files, so nothing below is surface-specific.

3. Step 2 — Build context with CLAUDE.md

CLAUDE.md is the always-on onboarding doc. Claude Code reads it at the start of every session and re-reads the project-root copy after a compaction. It can live at several scopes: a project file (./CLAUDE.md, shared via git), a personal file for every project (~/.claude/CLAUDE.md), and a gitignored CLAUDE.local.md for private notes. Claude walks up the tree and concatenates what it finds.

# CLAUDE.md

## Role
Senior backend engineer on a TypeScript / Node service.

## Voice
Terse. No filler. Explain trade-offs, not basics.

## Banned
No new dependencies without asking. Never touch src/legacy/.

## Defaults
Tests with vitest. Conventional commits (feat:, fix:, chore:).

The discipline that matters: CLAUDE.md is billed to context on every single turn. Put conventions and pitfalls here — the things that differ from tool defaults — not facts Claude can rediscover from the codebase in one session. A bloated CLAUDE.md quietly taxes every request and, past a couple hundred lines, actually reduces how well Claude follows it.

4. Step 3 — Build memory

Separate from CLAUDE.md, Claude Code keeps its own auto memory: notes it writes based on what it learns and the corrections you make. Each project gets a directory at ~/.claude/projects/<project>/memory/ containing a MEMORY.md index plus per-topic markdown files. The index loads at session start; the topic files load on demand. Run /memory to browse, edit, or delete anything it has saved — it is all plain markdown.

~/.claude/projects/my-service/memory/
    MEMORY.md          index: what is stored where
    debugging.md       fixes to problems solved once
    conventions.md     patterns inferred from the code
    preferences.md     how you like to work

The mental split: CLAUDE.md is your instructions to Claude; auto memory is Claude’s notes to itself. Because it accumulates automatically, the same mistake tends not to land twice — but treat it as advisory, not enforcement (more on that in the mistakes section).

5. Step 4 — Build skills

A skill is a folder with a SKILL.md file (plus optional scripts) that Claude Code loads on demand when your task matches its description. It turns a 200-word workflow you keep re-typing into one reusable, discoverable capability. Personal skills go in ~/.claude/skills/; project skills go in .claude/skills/ and version-control with the repo.

~/.claude/skills/changelog/SKILL.md

---
name: changelog
description: Summarize recent commits into a grouped changelog.
             Use when asked to write release notes.
---
Read the last 20 commits. Group by feat / fix / chore.
Output markdown with a heading per group. Omit merge commits.

The single most important line is the description. It is the trigger — Claude reads it every session and pulls in the body only when the current task matches. A vague description means the skill silently never fires. Describe the situation to use it in, not just what it does.

6. Step 5 — Build the agent team

A subagent is a specialized Claude instance with its own context window, its own tools, and one job. It runs in isolation and returns only its result, which keeps your main conversation clean. Files live in .claude/agents/ (project) or ~/.claude/agents/ (personal), one file per agent, and each can pin its own model.

.claude/agents/qa-gate.md

---
name: qa-gate
description: Reviews a diff and fails anything below 95/100.
             Use after any code change.
model: sonnet
tools: Read, Grep, Bash
---
You are a strict reviewer. Score the diff out of 100 on
correctness, tests, and clarity. State the score. If below
95, list exactly what must change. Do not soften.

A workable division of labour: heavier models for the roles that analyse and plan, faster models for the roles that execute, and a hard QA gate that fails work below a fixed bar. Match the model to the job instead of paying for the top model on every step. The key constraint is scope — one file, one job. That is what makes the team debuggable.

7. Step 6 — Run on autopilot with Routines

The final step turns your agent team into something that runs without you sitting there. Routines let you schedule work to run on Anthropic’s cloud rather than your laptop — set it once and walk away. Anthropic showcased cloud Routines and dynamic workflows at Code with Claude Tokyo in 2026 as a way to move recurring agent work off the local machine.

Concretely, this is where a scheduled trigger fires a skill or an agent on a cadence — a daily summary at 8am, a weekly report dropped into your docs — on the cloud, not a machine you have to keep awake. This surface is newer and moving fast, so confirm the current syntax and availability in the docs before you wire a production job to it.

8. The four building blocks, compared

Dimension CLAUDE.md Auto memory Skills Subagents
What it isAlways-on instructionsClaude’s own notesOn-demand workflowIsolated specialist
Loads whenEvery session startIndex at start, rest on demandWhen task matches descriptionWhen invoked
Who writes itYouClaude, automaticallyYouYou
Lives at./CLAUDE.md, ~/.claude/CLAUDE.md~/.claude/projects/<project>/memory/~/.claude/skills/ or .claude/skills/.claude/agents/ or ~/.claude/agents/
ScopeProject or userOne repositoryProject or userSingle task
Best forConventions and pitfallsLearnings you didn’t write downRepeated multi-step workflowsParallel or context-heavy jobs
Token costPaid every turn — keep leanIndex every sessionNear zero until triggeredSeparate context — protects main
Version-controlled?Project copy, yesNo — local, gitignore itProject copy, yesProject copy, yes
Failure modeBloat taxes every requestAdvisory, not enforcedWeak description never firesToo many tools, wrong pick

9. Common mistakes

  1. Putting everything in CLAUDE.md. It is always-on context, so every line is billed on every turn and, past a couple hundred lines, adherence actually drops. Facts Claude can learn from the repo in one session belong in the code or in auto memory — CLAUDE.md is for conventions and pitfalls only.
  2. One mega-agent with every tool. Tool-selection accuracy degrades as the tool count climbs; the agent starts confidently picking the wrong one. One file, one job, a narrow tool set. Route between focused subagents instead of overloading a single one.
  3. Treating skills as prompts. A skill is on-demand context gated by its description. If the description does not name the situation to use it in, the skill never triggers and you never notice. Write the trigger, then the task.
  4. Assuming memory enforces rules. Auto memory is advisory context the model usually follows — not a guarantee. If a rule must hold every time (never touch a directory, never skip a check), use a PreToolUse hook, which actually blocks the action, not a memory line that merely suggests it.
  5. Running Routines as fire-and-forget. A scheduled agent with write access and no QA gate scales your mistakes on a timer. Put a review step between the agent and anything it can publish, commit, or send — especially once it runs unattended on the cloud.

10. The Takeaway

The six steps are just files: install the tool, write the context, let it build memory, package your workflows as skills, split the work across scoped subagents, and schedule the whole thing. No orchestration framework, no graph library, no glue.

Be honest about the ten minutes, though: that is the scaffold, not the finished agent. Standing up the structure is genuinely fast now. Making it good — tight CLAUDE.md, skills whose descriptions actually fire, subagents scoped so tool selection stays accurate, a QA gate that holds — is iteration, and that is where the real work lives. The teams that win are not the ones who scaffolded fastest. They are the ones who kept tuning the specs.

About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
atiqueahmed.com · LinkedIn · GitHub

This is Day [DAY_NUMBER] of a daily GenAI and agentic AI series on CodezTech.

MCP vs RAG vs AI Agents: They Don't Compete


Every week someone asks me to settle the debate: should we use RAG, build an agent, or “just do MCP”? The question sounds reasonable. It has the shape of a real architecture decision. It is also the wrong question, and picking one of the three because you think you have to is how teams end up with an agent that should have been a SQL query, or a RAG pipeline that still hallucinates.

These three things are not competitors. RAG is a knowledge pattern, MCP is a connection protocol, and an agent is a control loop — they sit at different layers, and most production systems use all three at once.

MCP vs RAG vs AI Agents — CodezTech
MCP vs RAG vs AI Agents — three layers, not three choices.

The below topics are covered in this blog -
1. Why the “vs” framing is a category error
2. RAG — retrieval, not reasoning
3. MCP — the connector, not the brain
4. AI Agents — the loop that decides
5. Putting it together: where each layer lives
6. A comparison across the dimensions that actually matter
7. Common mistakes
8. The Takeaway

1. Why the “vs” framing is a category error

Ask “MCP or RAG or agent?” and you are comparing a protocol, a data pattern, and an execution model as if they were three brands of the same thing. They are not interchangeable, and none of them can be swapped in for another.

Here is the clean split. RAG answers the question “how does the model get the right knowledge at inference time?” MCP answers “how does the model reach a tool or system in a standardized way?” An agent answers “who decides what to do next, and how many steps does it take?” Different questions. You can answer all three in the same system, and in anything non-trivial you will.

A concrete example. A support assistant retrieves policy docs (RAG), calls your order system and Slack through standardized servers (MCP), and runs a loop that decides whether to answer, escalate, or issue a refund (agent). Take any one layer out and it is a different, weaker system — not a cheaper version of the same one.

2. RAG — retrieval, not reasoning

Retrieval-Augmented Generation is the oldest and least glamorous of the three, and it is still the highest-leverage thing most teams can ship. You embed your documents, store the vectors, and at query time you fetch the most relevant chunks and stuff them into the prompt before the model answers. That is the whole trick.

What RAG buys you: current, private, and citable knowledge without retraining a model. What it does not buy you: correctness. RAG grounds the answer in retrieved text; it does not verify that the retrieved text is relevant, complete, or being read correctly. Bad retrieval produces confident wrong answers — now with footnotes, which makes them harder to catch.

query
  -> embed(query)                      # same model as your index
  -> vector_store.search(k=8)          # over-fetch, then filter
  -> rerank(candidates) -> top 3-4     # rerank is where quality lives
  -> build_prompt(context, question)
  -> llm.generate()                    # answer is only as good as top 3-4

Ninety percent of “our RAG is bad” problems are retrieval problems, not model problems: wrong chunk size, no reranker, a query embedded with a different model than the index, or a knowledge base that was never cleaned. Fix retrieval before you touch the prompt.

3. MCP — the connector, not the brain

The Model Context Protocol is an open standard that Anthropic introduced in November 2024 and open-sourced. It standardizes how an AI application connects to external tools and data — the same role USB-C plays for devices. Instead of writing a bespoke integration for every model-to-tool pair, you expose a tool once through an MCP server and any MCP-capable client can use it.

It stopped being a single-vendor idea fast. OpenAI adopted it in March 2025 across its Agents SDK and ChatGPT; Google DeepMind followed for Gemini in April 2025; Microsoft wired it into Copilot Studio and Windows. In December 2025 Anthropic donated MCP to the Agentic AI Foundation under the Linux Foundation, moving it to vendor-neutral governance.

Version detail matters here because I am publishing this under my name. The current finalized spec is the 2025-11-25 revision. A much larger revision, dated 2026-07-28, has been in release-candidate form since May 2026 and is scheduled to publish on July 28, 2026 — days from this writing. It is the biggest change since launch: a stateless protocol core (the initialize handshake and protocol-level session are gone), an extensions framework, Tasks moved out of core into an extension, server-rendered UIs via MCP Apps, tighter OAuth/OIDC-aligned authorization, and a formal deprecation policy with a twelve-month minimum window. Parts are not backward compatible — new-revision servers may not talk to old clients. If you are deploying now, check which revision your SDK and clients target before you commit.

What has stayed stable across revisions is the shape of a tool definition, which is the part you actually author:

{
  "name": "refund_order",
  "description": "Issue a refund for an order. Use only after policy check.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "order_id": { "type": "string" },
      "amount":   { "type": "number" },
      "reason":   { "type": "string" }
    },
    "required": ["order_id", "amount"]
  }
}

Note what MCP is not. It does not decide when to call the tool — that is the model or the agent. It does not remove authentication, rate limits, or the blast radius of a tool that can write to production. The spec itself flags that tools are arbitrary code execution and must be treated with caution. MCP standardizes the wire; it does not standardize away the risk.

4. AI Agents — the loop that decides

An agent is not a model and it is not a tool. It is a control loop wrapped around a model: observe the current state, decide the next action, take it, observe the result, repeat until done or stuck. The autonomy lives in that loop — the model chooses which tool to call and when to stop, instead of you hard-coding the sequence.

state = initial(task)
for step in range(MAX_STEPS):          # always cap the loop
    action = model.decide(state, tools)  # which tool, or "finish"
    if action.is_final:
        return action.answer
    result = run(action)               # tool call, often over MCP
    state = state.update(result)       # memory / observation
raise StepLimitExceeded                # failure is a real branch

That loop is powerful and expensive. Every iteration is another model call, so latency and cost scale with the number of steps, and the path is non-deterministic by design. That is the whole point when the task genuinely cannot be predetermined — and pure overhead when it can. The two failure modes to design against: the loop that never converges (cap the steps) and the wrong-tool cascade (scope the tool set).

5. Putting it together: where each layer lives

Stack them and the roles stop overlapping. Retrieval feeds knowledge into the model. MCP is the standardized pipe the model reaches through to touch systems. The agent loop sits on top and decides which of those moves to make, in what order. The diagram below lays all three out side by side — read it as three layers of one system, not three options on a menu.

MCP vs RAG vs AI Agents architecture comparison
How MCP, RAG, and AI Agents map onto a real system. Infographic credit: ByteByteGo.

The decision order that keeps costs sane: start with the cheapest thing that solves the problem. Need current knowledge? Add retrieval. Need to touch a system? Expose it as a tool, and use MCP if more than one client will consume it. Is the path fixed? Write a deterministic pipeline. Only when the control flow is genuinely dynamic — the next step depends on the last result in ways you cannot enumerate — do you hand the wheel to an agent loop.

6. A comparison across the dimensions that actually matter

Dimension RAG MCP AI Agent
What it actually isA knowledge-injection patternAn open tool-connection protocolA model-driven control loop
Problem it solvesModel lacks current or private knowledgeEvery tool needs a custom integrationThe path can’t be predetermined
Where it sitsBetween query and promptBetween model and external systemsAbove the model, orchestrating
Latency addedOne retrieval hop (tens of ms)One protocol round-trip per callN model calls (grows per step)
Main cost driverEmbedding + vector storage + context tokensNegligible protocol overheadModel calls multiplied by step count
Dominant failure modeBad retrieval → confident wrong answersOver-broad tool permissionsLoops that don’t converge; wrong-tool cascades
Security surfaceData leakage via retrieved contextTools are code execution — trust boundaryAutonomous actions with real side effects
StateStateless per queryStateless core in the 2026-07-28 revisionStateful across the loop (memory)
When it’s overkillKnowledge fits in the prompt alreadyOne model, one tool, one codebaseThe steps are fixed and known
Maturity (Jul 2026)Mature, well-understoodStandardized, mid-migration to 2026-07-28Production-viable but operationally young

7. Common mistakes

  1. “We’ll add RAG so the model stops hallucinating.” RAG grounds answers; it does not fact-check them. Retrieve the wrong chunk and you get the same hallucination with a citation stapled to it, which is worse because it looks trustworthy. Invest in retrieval quality and reranking, not just the presence of a vector database.
  2. “MCP replaces our API integrations.” MCP sits in front of the same APIs. It standardizes how the model reaches them, but the auth, rate limits, idempotency, and blast radius of a write-capable tool are all still your problem. You are moving the wiring, not deleting it.
  3. “Just make it an agent.” Reaching for an autonomous loop when a deterministic pipeline would do is the most expensive default in this space. Agents add latency, token cost, and non-determinism. If you can draw the flowchart, code the flowchart.
  4. “One big agent with forty tools.” Tool-selection accuracy degrades as the tool count climbs — the model starts picking plausible-but-wrong tools. Scope each agent to a narrow tool set, or route between several focused agents instead of one overloaded one.
  5. “It’s MCP, so security already reviewed it.” The spec itself states that tools represent arbitrary code execution and data access. A standardized protocol does not make an untrusted server safe. Treat every MCP server as a trust boundary and review what each tool can actually do.

8. The Takeaway

Stop shopping for one of the three. Pick by layer. Use retrieval when the model needs knowledge it doesn’t have. Use MCP when you need standardized, reusable access to tools across more than one client. Use an agent only when the control flow is genuinely dynamic and you have capped the loop and scoped the tools.

The unglamorous truth is that most strong production systems are all three at once: RAG for grounding, MCP for tool access, and a narrowly-scoped agent loop on top — with the cheapest layer doing as much of the work as it can before you spend a model call on the next one.

About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
atiqueahmed.com · LinkedIn · GitHub

This is Day [DAY_NUMBER] of a daily GenAI and agentic AI series on CodezTech.

Friday, July 24, 2026

5 Agentic AI Concepts That Win Every Interview


Most candidates prepare for agentic AI interviews by memorising framework names. They can tell you what LangGraph is, what RAG stands for, and roughly what an agent does. Then the interviewer asks what happens when a tool call fails halfway through a five-step workflow, and the answer falls apart.

The reframe: senior interviews do not test whether you know the concepts. They test whether you know the failure mode each concept exists to prevent. Five concepts carry almost all the weight, and each one has a follow-up question waiting behind it.

5 Agentic AI concepts that win every interview - Codez Tech

The below topics are covered in this blog -

1) How the five concepts fit together
2) Concept 1 — Guardrails and gateway
3) Concept 2 — Orchestration
4) Concept 3 — Tool and MCP integration
5) Concept 4 — Memory and context
6) Concept 5 — Observability
7) The follow-up questions you should expect
8) Answers that lose the interview
9) The takeaway

1. How the Five Concepts Fit Together

These are not five topics on a syllabus. They are five stages a single request passes through, and the interviewer is usually probing whether you can trace a request all the way down and all the way back.

5 agentic AI concepts diagram - guardrails, orchestration, MCP integration, memory and observability
The request path — guardrails, orchestration, tools, memory, and the observability layer every stage emits into

Note the asymmetry. Four of them sit in the request path. Observability sits underneath all four, collecting traces from each. If you can describe that shape in thirty seconds, you have already answered half the questions that follow.

2. Concept 1 — Guardrails and Gateway

Input validation, PII filtering, rate limiting, output sanitisation. The gateway is the trust boundary between the outside world and everything your agent can reach.

The failure mode it prevents: prompt injection reaching a tool that can act. Not a bad answer — a bad action. The moment a model picks its own tools and calls them, it has stopped returning text and started running operations on your systems.

The distinction that separates a good answer from a great one is input guardrails versus output guardrails. Input guardrails are cheap and catch the obvious. Output guardrails are where the real protection lives, because you are checking the action the agent decided to take rather than the words the user typed.

gateway:
  input:
    - pii_detect:      { action: redact, entities: [email, phone, ssn, card] }
    - injection_scan:  { action: flag, on_high_confidence: block }
    - rate_limit:      { per_user: 60/min, per_tenant: 5000/hour }
    - max_input_tokens: 8000

  output:
    - pii_detect:      { action: block }
    - grounding_check: { require_citation: true, on_fail: regenerate }
    - action_policy:
        allow:   [read_ticket, search_docs, draft_reply]
        confirm: [issue_refund, close_ticket, send_email]
        deny:    [delete_record, modify_permissions]

That action_policy block is the part interviewers care about. Three tiers — allow, confirm, deny — is the answer. A single allow-list is not, because it gives you no way to express "the agent may propose this but a human signs it."

3. Concept 2 — Orchestration

Task decomposition, agent routing, state machine, error recovery.

The failure mode it prevents: a workflow that dies at step four with no way to resume, and no record of what it already did.

Here is the question that catches people. "Step three succeeded, step four failed. What happens?" The weak answer is "we retry." The strong answer distinguishes:

  • Idempotent steps — safe to retry blindly. A search, a read, a summary.
  • Non-idempotent steps — a refund, an email, a database write. Retrying these without an idempotency key means the customer gets refunded twice.
  • Checkpointing — the workflow state is persisted after each step, so a resume starts at four rather than at one.
  • Compensating actions — when step four cannot succeed, what undoes step three? This is the saga pattern, and naming it is worth real points.

The second question is usually "single agent or multi-agent?" The answer they want is a cost-benefit one, not an enthusiastic one. Every extra agent adds coordination overhead, token overhead, and a new failure surface. Reach for multi-agent when roles genuinely need different tools and different permissions — not because the architecture diagram looks more impressive with five boxes.

4. Concept 3 — Tool and MCP Integration

MCP server, tool registry, sandboxed execution, audit log.

The failure mode it prevents: arbitrary code execution with your production credentials.

This is the concept where being current actually matters, because MCP is moving fast and interviewers know it. A few things worth having straight:

  • The spec is date-versioned and negotiated during the initialize handshake. The finalised version has been 2025-11-25; a substantially rewritten 2026-07-28 revision has been working through release-candidate status, with a deprecation window for older versions. If you are interviewing on MCP, check where that stands the week of your interview rather than quoting a version from memory.
  • MCP servers are OAuth 2.1 resource servers. Protected resource metadata lets a server advertise its authorization server, and Resource Indicators (RFC 8707) stop a token issued for one server being replayed against another. If you can say "resource indicators prevent token misuse across servers," you are ahead of most candidates.
  • Tool descriptions are untrusted input. This is the single best thing you can say in this section. The model reads the description, trusts it, and acts on it — which makes it an attacker-controlled string sitting inside your trust boundary. That is tool poisoning, and the mitigation is reviewing tool schemas before approval, pinning server versions, and showing users the actual tool call rather than a friendly summary.
  • The protocol does not enforce security for you. It defines how clients and servers talk. Sandboxing, least-privilege credentials per tool, and audit logging are yours to build.

Expect a follow-up on tool sprawl: twelve connected servers means their schemas consume context before the user types anything, and tool-selection accuracy degrades. Curate the tool surface like a public API.

5. Concept 4 — Memory and Context

Short-term (conversation), mid-term (session), long-term (vector store).

The failure mode it prevents: an agent that either forgets what happened two turns ago, or drowns in so much recalled context that it picks the wrong tool.

The three-tier split in the diagram is the standard answer, and it is worth being precise about what actually lives in each:

  • Short-term — the live message list. Bounded by the context window. Managed by truncation or rolling summarisation.
  • Mid-term — session state that survives beyond the visible messages. The current ticket, the workflow checkpoint, the tools already called. Usually a key-value store, not a vector store.
  • Long-term — durable facts across sessions. This is the only tier that genuinely wants embeddings and semantic retrieval.

The mistake candidates make is putting everything in tier three. Not every memory is a vector search problem. Session state is a database row with a key, and treating it as a similarity search makes it slower, more expensive, and non-deterministic.

The follow-up is almost always about context window management: what do you drop when the window fills? A good answer has a priority order — system instructions and the active task never get evicted, tool results get summarised, old conversational turns get rolled into a running summary, and retrieved chunks are re-fetched on demand rather than carried forward.

6. Concept 5 — Observability

Distributed tracing, token metrics, decision logs, alerting.

The failure mode it prevents: a bug you cannot reproduce. Agents fail in ways that look like success — a well-formed, confident, wrong answer, or a redundant tool call nobody notices until the bill arrives.

The thing to know here is that this stopped being a vendor question and became a standards question. The OpenTelemetry GenAI semantic conventions define a vendor-neutral vocabulary of gen_ai.* span and metric attributes, so any instrumentation library can emit them and any OTLP backend can ingest them.

span.set_attribute("gen_ai.system", "anthropic")
span.set_attribute("gen_ai.request.model", "claude-opus-4-8")
span.set_attribute("gen_ai.usage.input_tokens", 1234)
span.set_attribute("gen_ai.usage.output_tokens", 512)
span.set_attribute("gen_ai.operation.name", "invoke_agent")
span.set_attribute("gen_ai.agent.id", "support-triage-001")
span.set_attribute("gen_ai.agent.name", "SupportTriageAgent")

Two nuances that mark you as someone who has actually shipped this:

  • The conventions are still pre-stable. They are widely adopted — OpenTelemetry itself graduated in CNCF in May 2026, and major backends ingest gen_ai.* over plain OTLP — but the attribute names can still change. The practical advice is to adopt the shape, pin the version, and isolate the exact strings behind a mapping layer so a rename is a one-file change.
  • Alert on tail latency, not the average. p95 and p99 are what users feel. An agent with a 3-second median and a 90-second p99 reads as broken even though the dashboard looks healthy.

And one line worth memorising, because it is the answer to "what do you log?": capture the reasoning trace, the tools considered, the tools actually invoked, the arguments passed, the tokens spent at each hop, and stitch it into one hierarchical trace you can replay.

7. The Follow-Up Questions You Should Expect

ConceptFailure mode it preventsWhere it costs youThe follow-up question
Guardrails & gatewayInjection reaching an actionAdded latency on every callInput or output guardrail — which catches more?
OrchestrationUnrecoverable mid-workflow failureEngineering hours, retry loopsStep 4 failed. What undoes step 3?
Tool & MCPArbitrary execution, tool poisoningTool schemas eating contextWhy are tool descriptions untrusted?
Memory & contextAmnesia, or context bloatTokens and retrieval latencyWhat gets evicted when the window fills?
ObservabilityUnreproducible failuresTrace storage volumeWhat exactly goes in a span?
Evaluation (cross-cutting)Silent regressions on releaseLabelling effort, eval runsHow do you know the new model is better?
Cost control (cross-cutting)Runaway token spendThe billWhich calls could a cheaper model handle?
Governance (cross-cutting)Permission leak via retrievalReview cycles, audit prepHow do tenant ACLs reach the vector store?

The bottom three rows have no box on the diagram. That is exactly why they get asked — they separate people who have read about agents from people who have operated them.

8. Answers That Lose the Interview

Mistake 1 — Naming frameworks instead of trade-offs. "We used LangGraph" is not an answer. "We used LangGraph because we needed checkpointing and human-in-the-loop approval, and we paid for it in boilerplate" is. Interviewers are listening for whether you know what you gave up.

Mistake 2 — Treating retries as error handling. Retrying a non-idempotent action is not recovery, it is duplication. If your answer to failure does not mention idempotency keys or compensating actions, it reads as untested.

Mistake 3 — Putting all memory in a vector store. Session state is a key lookup. Making it a similarity search is slower, costlier, and non-deterministic — and the interviewer will ask why the same input gives different context on two runs.

Mistake 4 — Quoting a spec version from memory. MCP is date-versioned and moving quickly. Saying "the current spec is X" and being a revision out of date is worse than saying "it is date-versioned, negotiated at initialize, and I would check the current revision before relying on behaviour that changed."

Mistake 5 — Describing the happy path. Nobody is asking whether you can build an agent that works. They are asking what happens when the tool times out, the model is rate limited, the retrieved document is stale, and the user pasted something hostile. Lead with the failure mode and the design follows naturally.

9. The Takeaway

Five concepts, and one sentence each that actually lands:

  • Guardrails — the trust boundary, and output guardrails matter more than input ones.
  • Orchestration — checkpointing, idempotency, and compensating actions, not "we retry."
  • Tools and MCP — tool descriptions are attacker-controlled input inside your trust boundary.
  • Memory — three tiers, and only one of them wants embeddings.
  • Observability — one replayable hierarchical trace, emitted in a vendor-neutral schema.

Learn the failure mode before the acronym. Every senior question in this space is really the same question wearing a different hat: what breaks, and how would you know?


About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
Portfolio  |  LinkedIn  |  GitHub

This is Day 3 of a daily GenAI and agentic AI series on CodezTech. Tomorrow: the next topic.

The 5-Layer Enterprise Agentic AI Tech Stack Explained


The 5-Layer Enterprise Agentic AI Tech Stack Explained

Ask most teams what their agentic AI stack is and you get the name of a framework and the name of a model. "We're on LangGraph and Claude." That is not a stack. That is two boxes out of a system that has five, and the two they named are the ones least likely to decide whether the thing survives production.

Here is the reframe: an enterprise agentic system is five layers, and the layers move at completely different speeds. The ones that churn fastest are the ones you should couple to most loosely.

5-Layer Enterprise Agentic AI Tech Stack guide by Codez Tech

The below topics are covered in this blog -

1) The five layers at a glance
2) Layer 1 — Infrastructure
3) Layer 2 — Data
4) Layer 3 — LLM
5) Layer 4 — Orchestration
6) Layer 5 — Interface
7) Where cost and failure actually land
8) Common architecture mistakes
9) The takeaway

1. The Five Layers at a Glance

Every enterprise agentic deployment I have worked on decomposes into the same five layers. The names vary by shop. The boundaries do not.

5-Layer Enterprise Agentic AI Tech Stack diagram showing Interface, Orchestration, LLM, Data and Infrastructure layers with tooling
The 5-layer enterprise agentic AI tech stack — capabilities on the left, representative tooling on the right

Diagrams like this always render top-down, because that is how a user experiences the system. Build it bottom-up. Every layer above depends on the one below being boring and reliable, and teams that start at the interface end up rewriting everything underneath it by month four. So the sections below run from the foundation upward.

2. Layer 1 — Infrastructure

Compute, containers, CI/CD, monitoring, security and compliance. Kubernetes, Docker, Terraform, GPU or TPU capacity, and whatever your organisation already uses for secrets and audit.

The instinct is to treat this layer as solved because your company already runs Kubernetes. Two things break that assumption:

  • Agent workloads are long-running and bursty. A traditional request-response service finishes in 200ms. An agent run can take four minutes, hold state the whole time, and fan out to a dozen tool calls. Your existing pod autoscaling and your existing 30-second gateway timeout were not designed for that.
  • The audit surface is different. Compliance does not want your application logs. It wants to know which model version saw which customer record, which tool the agent invoked, and who approved the action. If you bolt that on later you will be reconstructing it from raw logs during an audit.

Decide the trace format on day one. Every layer above will emit into it.

3. Layer 2 — Data

Vector databases, embedding models, document processing, knowledge graphs, semantic caching, RAG, and data governance. Pinecone, Weaviate, Qdrant, Chroma, pgvector, Neo4j.

This is the layer that decides whether your agent is useful, and it is the layer that gets the least attention in demos because nothing about it is visually impressive. Retrieval quality dominates agent performance in any knowledge-intensive use case. You can swap the model underneath and move the needle a few points. Fix your chunking and your reranking and you move it a lot.

Three things that are worth more than a better vector database:

  1. Hybrid retrieval. Pure vector search misses exact identifiers — part numbers, error codes, policy references. Combine it with BM25 keyword search.
  2. A reranker. Retrieve 50 candidates, rerank with a cross-encoder, pass the top 5. This is usually the single highest-ROI change available to a struggling RAG system.
  3. A semantic cache. In production, a meaningful share of queries are near-duplicates of ones you have already answered. Caching on embedding similarity rather than exact string match cuts both cost and p95 latency.

Governance belongs here too, not as an afterthought. If document-level permissions are not enforced at retrieval time, your agent will cheerfully quote a document the user was never allowed to see, and it will do it in a well-formatted paragraph that reads like it was cleared.

4. Layer 3 — LLM

Model routing, prompt management, function calling, guardrails, observability, cost tracking, load balancing, content moderation.

Notice what is on that list and what is not. The model itself is not the layer. The layer is everything you build so that the model is replaceable. That distinction matters more every quarter. The frontier reshuffles on a timescale of weeks now — the flagship list you would have written six months ago is already wrong, and it will be wrong again by the time this post has been indexed.

Which leads to the only durable rule for this layer: never let a model name appear anywhere except a config file.

routing:
  default:
    model: ${FRONTIER_MODEL}
    max_tokens: 4096
  classify_intent:
    model: ${FAST_MODEL}          # cheap, high volume, low stakes
    max_tokens: 256
  draft_customer_reply:
    model: ${FRONTIER_MODEL}
    guardrails: [pii_redact, tone_check, no_commitments]
  summarise_ticket_history:
    model: ${FAST_MODEL}
    cache: semantic               # near-duplicate hits skip the call

fallback:
  on_rate_limit:  ${SECONDARY_VENDOR_MODEL}
  on_timeout_ms:  8000
  max_retries:    2

Two practical points. First, route by task, not by preference. Intent classification does not need your most expensive model, and most teams discover that the majority of their token spend is going to calls that a cheap model handles identically. Second, keep a second vendor wired up and tested. Not for quality — for the afternoon your primary provider has an incident, or changes availability on a model you had in production.

5. Layer 4 — Orchestration

Workflow engine, agent handoffs, state management, memory management, multi-agent coordination, context window management, event routing, agent versioning, A/B testing.

This is where the framework debate lives, and it is the layer where the landscape has consolidated most visibly. LangGraph reached 1.0 and became the default runtime for LangChain agents, positioned around graph-based state and control. CrewAI kept the role-based abstraction that gets a prototype running in an afternoon. And on the Microsoft side, AutoGen and Semantic Kernel were merged into a single successor, the Microsoft Agent Framework — worth knowing if your architecture diagram still lists those two as separate boxes, because that is now a stale diagram.

A rough decision rule:

  • Graph-based (LangGraph) when you need explicit control over execution order, branching, checkpoints, and rollback — anything with an audit trail or human-in-the-loop approval. You pay for it in boilerplate.
  • Role-based (CrewAI) when you want speed of expression and the coordination logic is genuinely simple. The abstraction that makes it fast to write is the same abstraction that makes a five-agent failure hard to debug.
  • Platform-native (Microsoft Agent Framework, Google ADK) when you are already committed to that cloud and want the identity, governance, and deployment story to come pre-wired.

The part of this layer nobody budgets for is context window management. It is one line on the diagram and it is where a startling amount of production debugging time goes. Long conversations accumulate. Tool schemas accumulate. Retrieved chunks accumulate. Somewhere around the point where all three are competing, the agent starts picking the wrong tool, and the bug does not look like a context problem — it looks like the model got worse.

6. Layer 5 — Interface

Chat UI, widget embeds, voice, API gateway, webhooks, Slack and Teams integration, browser extensions, multi-tenancy.

The layer everyone builds first and the layer that matters least to whether the system works. Build it last, and build it thin. Every piece of business logic that leaks into the interface is logic you will have to reimplement when someone asks for the Slack version.

Two things here are not cosmetic, though:

  • Streaming. An agent that takes 40 seconds and streams feels responsive. An agent that takes 12 seconds and returns in one block feels broken. This is a genuine product decision, not polish.
  • Multi-tenancy. If it is not in the design from the start, it is a rewrite, not a feature. Tenant isolation has to reach all the way down to the retrieval layer.

7. Where Cost and Failure Actually Land

The layers are not equal. This is the table I actually use when planning an engagement:

Layer / concernWhere cost accruesPrimary failure modeChange cadence
InfrastructureIdle GPU, over-provisioned nodesTimeouts on long agent runsQuarterly
DataEmbedding + storage + re-indexRetrieval misses; stale indexWeekly to daily
LLMTokens — usually the largest line itemWrong model on the wrong taskConstantly
OrchestrationEngineering hours, retry loopsContext bloat; silent tool misfiresMonthly
InterfaceFrontend engineeringPerceived latency, not real latencyContinuous
Observability (cuts across)Trace storage volumeYou cannot reproduce the failureSet once, extend often
Evaluation (cuts across)Labelling effort, eval runsRegressions ship silentlyEvery release
Security & governance (cuts across)Review cycles, audit prepPermission leak via retrievalContinuous

Read the bottom three rows again. They are not layers, which is exactly why they get dropped — there is no box on the diagram to assign them to, so nobody owns them.

A layout that keeps the boundaries honest:

agent-platform/
  interface/          thin. transport only. no business logic.
    api/
    slack/
    web/
  orchestration/
    graphs/           workflow definitions
    state/            checkpointing, resume
    memory/
  llm/
    routing.yaml      the ONLY place a model name appears
    prompts/          versioned, reviewed like code
    guardrails/
  data/
    ingest/           chunking + embedding pipeline
    retrieval/        hybrid search + rerank
    governance/       tenant + document ACLs
  platform/
    terraform/
    observability/    one trace format, all layers
    evals/            regression suite, runs in CI

8. Common Architecture Mistakes

Mistake 1 — Building top-down. Chat UI in week one, retrieval in week six. The demo lands, the pilot stalls, and the rebuild starts underneath a UI that already has stakeholders attached to it. Build bottom-up and demo with a command line if you have to.

Mistake 2 — Hardcoding the model. A model name in application code is a migration ticket with a delay fuse. The LLM layer churns faster than any other layer in the stack; treat the specific model as a runtime parameter, and keep a tested fallback with a different vendor.

Mistake 3 — Treating the vector database as the data layer. The database is the easy part and the vendors are largely interchangeable. Chunking strategy, hybrid search, reranking, freshness, and permission enforcement are the data layer. Teams spend three weeks choosing between Pinecone and Qdrant and zero days on chunk boundaries.

Mistake 4 — Adopting multi-agent because the diagram looks impressive. Every additional agent adds coordination overhead, token overhead, and a new failure surface. Published 2026 comparisons put role-based crews at a meaningful token premium over an equivalent graph implementation for the same task. If one well-instrumented agent with good tools solves it, ship that.

Mistake 5 — No evaluation harness. Without a regression suite, you cannot tell the difference between "the new model is worse" and "our prompt was overfit to the old one." You will find out in production, from a user, in a screenshot.

9. The Takeaway

Five layers, three rules:

  • Build bottom-up. Infrastructure, then data, then model, then orchestration, then interface.
  • Couple loosely where churn is highest. That is the LLM layer, by a wide margin.
  • Own the cross-cutting concerns explicitly. Observability, evaluation, and governance have no box on the diagram, which is precisely why they end up with no owner.

The stack is not the framework you picked. It is the five layers underneath the demo, and the four of them nobody screenshots.


About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
Portfolio  |  LinkedIn  |  GitHub

This is Day 2 of a daily GenAI and agentic AI series on CodezTech. Tomorrow: the next topic.

MCP vs RAG vs Skills : Complete Guide to AI Agent Architecture


MCP vs RAG vs Skills : Complete Guide to AI Agent Architecture

Everyone building AI agents in 2026 runs into the same three words within the first week — MCP, RAG, and Skills — and almost everyone assumes they have to pick one. They don't. These are three different layers of the same stack, and picking the wrong one is the single most expensive architecture mistake I see on enterprise engagements.

In one line: RAG gives an agent knowledge. MCP gives it access. Skills give it judgment.

MCP vs RAG vs Skills - AI agent architecture guide by Codez Tech

4. MCP vs RAG vs Skills — Full Comparison

MCP vs RAG vs Skills architecture comparison diagram for AI agents
MCP vs RAG vs Skills — Architectures that power smarter AI agents

The below topics are covered in this blog -

1) What is MCP (Model Context Protocol)?
2) What is RAG (Retrieval Augmented Generation)?
3) What are Agent Skills?
4) MCP vs RAG vs Skills — full comparison table
5) When to use MCP vs RAG vs Skills — the decision rule
6) How the three layers compose in a real agent
7) Building your first Skill — SKILL.md example
8) Common architecture mistakes and how to avoid them

1. What is MCP (Model Context Protocol)?

MCP is an open, JSON-RPC based client-server protocol that lets an AI agent talk to live external systems — a database, a CRM, a ticketing system, Slack, a search API — through one standardized interface. It was created by Anthropic in late 2024 and later donated to the Agentic AI Foundation under the Linux Foundation, and it is now supported across all the major model vendors.

The architecture has three parts:

  • MCP Host — the application the user is talking to (Claude Desktop, your own agent app, an IDE).
  • MCP Client — lives inside the host, maintains one connection per server, and decides which server to route a request to.
  • MCP Server — the service that actually exposes capabilities. It publishes three primitives: Tools (actions the agent can invoke), Resources (data the agent can read), and Prompts (reusable templates).

The important word here is live. An MCP server holds real authentication, real session state, and returns data as it exists right now. That is why order status, inventory counts, and open incidents belong behind MCP and nowhere else.

A minimal MCP server configuration looks like this:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres",
               "postgresql://localhost/orders"]
    },
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": { "SLACK_BOT_TOKEN": "xoxb-your-token" }
    }
  }
}

That is it. The agent now has live, authenticated access to two systems it had no idea existed thirty seconds ago.

2. What is RAG (Retrieval Augmented Generation)?

RAG solves a completely different problem: the model was never trained on your documents. Your policy manuals, product specs, past support tickets, and internal wikis are invisible to it.

The pipeline has two phases.

Indexing (offline, runs once and then on a schedule):

  1. Load the source documents.
  2. Chunk them into passages — typically 300 to 800 tokens with some overlap.
  3. Embed each chunk into a vector using an embedding model.
  4. Store the vectors in a vector database (pgvector, Pinecone, OpenSearch, Weaviate, Chroma).

Retrieval (online, runs on every query):

  1. Embed the user's query with the same model.
  2. Search for the nearest chunks — ideally hybrid, combining vector similarity with keyword BM25.
  3. Rerank the candidates with a cross-encoder to push the genuinely relevant ones to the top.
  4. Augment the prompt with those chunks and generate an answer with citations.

The thing to internalise: a vector index is a photograph, not a window. It is as fresh as your last indexing run and no fresher. If the answer must reflect the world right now, RAG is the wrong tool.

3. What are Agent Skills?

A Skill is the least glamorous and most underrated of the three. It is a folder. Inside it sits a SKILL.md file with YAML frontmatter and a set of instructions, plus optional scripts, templates, and reference documents.

The mechanism that makes it clever is progressive disclosure. The agent only ever holds the skill's name and description in context — a few dozen tokens. When a task matches that description, the full skill body loads on demand. Near-zero context cost until it fires.

---
name: incident-report
description: Writes a post-incident report. Use whenever the user asks
  for an RCA, incident summary, outage write-up, or postmortem.
---

# Incident Report Skill

## Required sections, in order
1. Impact summary (who was affected, for how long, revenue impact)
2. Timeline in UTC, one line per event
3. Root cause - the technical cause, not the human who typed it
4. Detection gap - why did we not know sooner
5. Action items, each with an owner and a date

## Rules
- Never name individuals. Name teams and systems.
- Severity uses our P0-P4 scale, defined in ./reference/severity.md
- Use the template in ./templates/incident.md
- If the timeline has gaps, ask before writing. Do not guess.

That file is roughly thirty lines. It is version controlled in Git, reviewable in a pull request, portable across agent runtimes, and it costs you nothing until the moment somebody says the word "postmortem." Now compare that to embedding your incident-management handbook into a vector store and praying the right paragraph gets retrieved.

4. MCP vs RAG vs Skills — Full Comparison

DimensionRAGMCPSkills
Core problemMissing knowledgeMissing accessMissing procedure
NatureRetrieval pipelineLive protocol, running serverStatic portable folder
Data freshnessAs fresh as the last index runReal time, every single callStable for weeks or months
State & authNoneYes — sessions, tokens, scopesNone
Can take actions?No, read onlyYesOnly through tools it invokes
Context costHigh — chunks fill the windowMedium — tool schemas occupy contextVery low until triggered
InfrastructureEmbedding model + vector DB + pipelineA deployed, monitored server processA file in a repo
Cost driverEmbedding + storage + retrieved tokensServer hosting + API callsEffectively zero
Latency addedRetrieval + rerank, typically 100–500msNetwork round trip per tool callNegligible
Change costRe-chunk and re-index everythingVersion the server, redeployEdit the markdown, commit
Fails whenChunking is poor, retrieval missesServer is down, token expired, tool sprawlDescription doesn't match the task
GovernanceIndex-level ACLs, hard to get rightStrong — real auth, scopes, audit logsWeak — it's just a file, use Git review

5. When to Use MCP vs RAG vs Skills

Ask these three questions in this exact order about whatever capability you are trying to add:

Question 1 — Does it change between invocations?
If the answer must reflect the world right now — an order status, a live inventory count, an open incident, a current account balance — you need MCP. Nothing else will do. A vector index cannot tell you whether a server is on fire at this moment.

Question 2 — Is it a large, slow-moving body of text the model was never trained on?
Policy documents, product manuals, three years of resolved tickets, research archives. That is RAG. The test is volume plus stability: too big to paste into a prompt, stable enough that a nightly index run is acceptable.

Question 3 — Is it procedure, judgment, formatting, or house style?
"How we write an incident report." "Our SQL naming conventions." "The seven checks before a deployment note ships." That is a Skill — and it is almost always the cheapest thing you have not tried yet.

6. How the Three Layers Compose in a Real Agent

In production this is never a choice. It is a stack. Take a customer support agent for an e-commerce company:

  • MCP layer — connects to the order database and the ticketing system. Live account state, live order status, and the ability to actually issue a refund or update a record.
  • RAG layer — retrieves from product documentation and the archive of resolved tickets. The slow-moving institutional knowledge.
  • Skills layer — encodes the escalation policy. What counts as a P1. The tone for a refund message. Which fields must be filled before a ticket can close. The exact template for the customer summary.

Now remove one layer at a time and watch the failure mode appear:

  • No MCP → the agent confidently hallucinates order status. Customer is told their package shipped. It did not.
  • No RAG → the agent invents product behaviour that does not exist and creates a support ticket about its own answer.
  • No Skills → the agent does technically correct things in a wildly inconsistent way. Every refund email has a different tone. No two tickets close the same. Nothing is auditable.

That third one is the sneaky failure, because nothing visibly breaks. It just quietly becomes unreviewable.

7. Building Your First Skill

Skills are the fastest win, so start there. The folder structure is:

.claude/skills/
  incident-report/
    SKILL.md              # required: frontmatter + instructions
    reference/
      severity.md         # loaded only when SKILL.md points to it
    templates/
      incident.md
    scripts/
      fetch_timeline.py   # optional executable helper

Three rules that decide whether your skill actually works:

  1. The description is the entire trigger mechanism. It is the only part the agent sees until the skill fires. Write it as "Use when the user asks for X, Y, or Z" — concrete trigger phrases, not an abstract summary. A vague description means the skill never loads, and you will spend an afternoon debugging a prompt when the actual bug was one sentence of metadata.
  2. Keep SKILL.md under roughly 500 lines. Push detail into reference files and link to them. That is what progressive disclosure is for.
  3. Write imperatives, not descriptions. "Never name individuals" beats "this report generally avoids naming individuals."

8. Common Architecture Mistakes

Mistake 1 — Reaching for RAG when you needed a Skill. Somebody wants consistent output, so they index the style guide, embed it, retrieve fragments, and hope the right paragraph surfaces. A single skill file would have made it deterministic, free, and reviewable in a pull request. This is the most common one by a distance.

Mistake 2 — Building an MCP server for data that changes once a quarter. That is a maintenance burden wearing an integration costume. Index it or put it in a reference file.

Mistake 3 — Tool sprawl. Connect twelve MCP servers and their tool schemas start eating your context window before the user has typed a single character — and the model gets measurably worse at choosing the right tool. On-demand tool loading has taken the edge off this, but the architectural pressure remains. Curate your tool surface the way you would curate a public API. Fewer tools with better descriptions beat a directory of everything.

Mistake 4 — Believing long context killed RAG. Long context solves small corpora. It does not solve a 40 GB document store, and it does not solve paying for a million input tokens on every single request. RAG is a cost and precision strategy, not just a capability one.

Mistake 5 — Believing Skills replaced MCP. A skill has no auth, no session, and no connection. It cannot fetch anything on its own. What it can do is tell the agent how and when to use the MCP tools that are already wired up. They compose; they do not compete.

9. The Takeaway

Stop asking which one wins. Ask which question you are answering:

  • Knowledge the model lacks → RAG
  • Systems the model must reach → MCP
  • Procedure the model must follow → Skills

And when a capability is genuinely both a system and a way of using that system — which describes most real engineering work — build a small MCP server for the access and a Skill for the workflow that drives it.

The teams shipping reliable agents right now are not the ones who picked the trendiest primitive. They are the ones who matched the primitive to the problem.


About the Author
Atique Ahmed — Principal AI Architect. 7x Microsoft MVP and Guinness World Record holder for Programming Excellence. Founder of Codez Tech.
Portfolio  |  LinkedIn  |  GitHub

This is Day 1 of a daily GenAI and agentic AI series on CodezTech. Tomorrow: the next topic.