mcpagentsllm

Agentic AI, MCP & Gateways — Complete Visual Guide

Agentic AI, MCP & Gateways — Complete Visual Guide

Agents · Tool Use · Model Context Protocol · MCP & Agent Gateways · A2A — every concept explained with animated diagrams

Agentic Fundamentals

What “Agentic” Actually Means

Strip away the hype and an AI agent is one simple thing: a language model running in a loop, calling tools, and reading the results until a goal is reached. A chatbot answers once and stops. An agent acts — it decides its own next step based on what just happened in the environment.

The agentic loop — reason · act · observe

User / Task Goal In · Answer Out The Agent LLM + System Prompt + Context 1 · Reason — Pick Next Action 2 · Act — Call A Tool 3 · Observe — Read The Result Environment Files / Shell APIs / Web MCP Servers Task Final Answer Tool Call Tool Result ↻ Loop Until Done An Agent Is A Model Using Tools In A Loop, Working Toward A Goal

The Building Blocks

🧠

Model

The LLM doing the reasoning. It never executes anything itself — it only emits text and structured tool-call requests. Capability of the model caps capability of the agent.

🔧

Tools

Functions the model may request: read a file, run a shell command, query an API. Each tool is described by a name, a description, and a JSON Schema for its inputs — that description is the model’s only manual.

📜

System Prompt

The standing instructions: role, constraints, style, guardrails. In agent products this is where behaviour is engineered.

🪟

Context Window

The model’s working memory — everything it can “see” right now: prompt, conversation, tool results. Finite, so long-running agents need compaction and summarisation.

💾

Memory

State that survives beyond the context window — scratchpad files, vector stores, databases. Short-term (this task) vs long-term (across sessions).

⚙️

Agent Runtime / Harness

The non-AI code around the model: runs the loop, executes tool calls, enforces permissions, retries failures, manages context. Claude Code is a harness; the Claude Agent SDK lets you build your own.

One Loop Iteration, Step By Step

1

Receive The Task

The user goal lands in the context alongside the system prompt and the list of available tool definitions.

2

Model Reasons

The LLM decides: can I answer now, or do I need information / side effects? If the latter, it emits a structured tool-call request (name + JSON arguments).

3

Harness Executes

The runtime — never the model — validates the call, checks permissions, runs the actual function, and captures output or error.

4

Result Goes Back In

The tool result is appended to the context. The model now “observes” what happened — including failures, which it can recover from.

5

Repeat Or Finish

The model loops to step 2 with richer context. When it stops requesting tools, its text response is the final answer. Stop conditions (max turns, budget) bound the loop.

# the whole idea, in eight lines
messages = [system_prompt, user_task]
while True:
    reply = llm(messages, tools=TOOLS)      # 1 · reason
    if reply.stop_reason != "tool_use":
        return reply.text                # done
    result = execute(reply.tool_call)       # 2 · act
    messages += [reply, result]             # 3 · observe

Key insight: the model proposes, the harness disposes. An LLM cannot touch your filesystem or network — every real-world effect goes through tool execution code you control. That separation is exactly where permissions, sandboxing, and (later) gateways attach.


Workflows vs Agents

Anthropic’s “Building Effective Agents” draws the line that the industry adopted: in a workflow, your code decides the path and the LLM fills in steps. In an agent, the LLM decides the path. Workflows are predictable and cheap; agents handle open-ended problems. Most production systems are workflows with agentic islands.

Workflow Patterns — Predefined Paths

⛓️

Prompt Chaining

Fixed sequence of LLM calls, each consuming the previous output. Outline → draft → polish. Add programmatic checks between steps.

🔀

Routing

A classifier call picks which specialised prompt/model handles the input. Cheap queries → small model, hard ones → big model.

Parallelization

Fan the same input out to several calls and aggregate — independent subtasks (sectioning) or multiple votes on one question.

🎛️

Orchestrator–Workers

A lead LLM decomposes the task at runtime and dispatches worker calls, then synthesises. The number and shape of subtasks is dynamic.

🔁

Evaluator–Optimizer

One call generates, another critiques against criteria, loop until accepted. The pattern behind self-review and judge loops.

Choosing Between Them

DimensionWorkflowAgent
Path Through The TaskKnown upfront, coded by youDiscovered at runtime by the model
PredictabilityHigh — same input, same routeLower — needs eval + guardrails
Cost / LatencyBounded, easy to budgetOpen-ended; cap with max turns
DebuggingStep-by-step, deterministicTrace-driven (hence observability)
Best ForPipelines: classify, extract, transformOpen problems: coding, research, ops

Rule of thumb: find the simplest pattern that works and stop there. Reach for a full agent only when you cannot enumerate the steps in advance.

Multi-Agent Patterns

Orchestrator + Subagents

A lead agent plans and delegates to focused subagents, each with its own clean context window and a narrow toolset. The subagent returns a summary, not its working — the orchestrator keeps the big picture without drowning in detail.

Context Isolation

Handoffs

Peer agents transfer the conversation to whichever specialist owns the current need — triage hands to billing, billing hands to refunds. Control moves; there is no permanent boss.

Specialisation

Parallel Fan-Out

Many agents attack independent slices simultaneously — review dimensions, file migrations, research angles — and a synthesis step merges results. Wall-clock wins, token costs multiply.

Throughput

More agents is not automatically better. Every agent boundary loses context and adds a failure mode. Multi-agent pays off for exactly two reasons: context isolation (a subagent burns its own window, not yours) and parallelism. If neither applies, one agent with good tools beats five with a committee.

MCP — Model Context Protocol

MCP — Model Context Protocol

MCP is an open standard for connecting AI applications to tools and data — “USB-C for AI”. Open-sourced by Anthropic in November 2024, adopted across the industry through 2025, and now governed openly under the Linux Foundation. The wire format is JSON-RPC 2.0. Before MCP, every app × every tool meant a custom integration; with MCP, each side implements the protocol once.

The integration problem MCP solves — M × N becomes M + N

Without MCP — M × N Custom Integrations Claude Code IDE Agent Chat App GitHub Postgres Slack 9 Point-To-Point Integrations · Each Maintained Forever With MCP — M + N Claude Code IDE Agent Chat App MCP JSON-RPC GitHub MCP Postgres MCP Slack MCP 6 Adapters Total — Add An App Or A Tool Exactly Once

MCP architecture — host · clients · servers

MCP Host Claude Code · Desktop · IDE — Owns The Loop MCP Client Dedicated 1:1 Session With One Server MCP Client Capability Negotiation On Connect MCP Client Tools Exposed Into The Agent Loop Filesystem MCP Server Local Process · Reads ~/projects GitHub MCP Server Remote · Hosted By GitHub Postgres MCP Server Remote · Wraps The Database stdio · JSON-RPC 2.0 Streamable HTTP · JSON-RPC Streamable HTTP + OAuth 2.1 One Host Runs Many Clients — Each Client Pins Exactly One Server

Server Primitives — What A Server Offers

🔧

Tools Model-Controlled

Executable functions the LLM chooses to invoke — create_issue, query_db. Discovered via tools/list, invoked via tools/call. This is the primitive that powers agents.

📄

Resources App-Controlled

Read-only context identified by URI — file contents, schemas, log streams. The host application decides what to attach; the model doesn’t fetch these on its own.

💬

Prompts User-Controlled

Reusable prompt templates the server publishes — surfaced to users as slash commands or menu entries.

Client Primitives — What The Host Offers Back

🔮

Sampling

A server can ask the host’s model to complete something — servers get LLM access without shipping their own API key. The host mediates and can require approval.

📁

Roots

The host tells the server which filesystem locations are in scope — a soft boundary for where the server should operate.

Elicitation

Mid-operation, a server can ask the user for structured input (“which environment?”) through the host UI. Added in the 2025-06-18 revision.

Capabilities are negotiated at initialize — each side declares what it supports, and only negotiated features may be used during the session.

Transports

TransportHowUse For
stdioHost spawns the server as a child process; JSON-RPC over stdin/stdoutLocal servers — filesystem, shell, dev tools
Streamable HTTPSingle HTTP endpoint; responses can upgrade to SSE streams; session via Mcp-Session-IdRemote / hosted servers
HTTP + SSETwo-endpoint scheme from the original specDeprecated — replaced by Streamable HTTP (2025-03-26)
// .mcp.json one remote, one local
{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/"
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "~/projects"]
    }
  }
}

Connection Lifecycle

1

Initialize

Client sends initialize with its protocol version and capabilities; server replies with its own. Versions are date-stamped (e.g. 2025-06-18).

2

Ready

Client sends notifications/initialized. The session is live.

3

Discover

Client calls tools/list, resources/list, prompts/list. Servers push list_changed notifications when offerings change.

4

Operate

The agent loop calls tools/call as the model requests; results flow back as content blocks (text, structured JSON, images).

5

Terminate

Transport closes; stdio servers exit with the host.

// a tool, as the model sees it (tools/list)
{
  "name": "create_issue",
  "description": "Create a GitHub issue",
  "inputSchema": {
    "type": "object",
    "properties": {
      "repo":  { "type": "string" },
      "title": { "type": "string" }
    },
    "required": ["repo", "title"]
  }
}

Spec Evolution — Date-Stamped Revisions

RevisionWhat Changed
2024-11-05Initial release: stdio + HTTP/SSE transports, tools, resources, prompts, sampling
2025-03-26Streamable HTTP transport, OAuth 2.1 authorization framework, tool annotations (e.g. read-only hints), audio content
2025-06-18Elicitation, structured tool output, servers classified as OAuth resource servers (RFC 8707 resource indicators), JSON-RPC batching removed
2025-11-25Tasks — call a tool asynchronously and poll for the result of long-running operations

Governance moved from Anthropic alone to open stewardship under the Linux Foundation (announced December 2025), alongside an official MCP Registry for discovering published servers.

Security reality check: every MCP server you connect is code that feeds text straight into your model’s context. That enables prompt injection via tool results, tool poisoning (malicious instructions hidden in tool descriptions), and rug pulls (a server silently changing a tool’s behaviour after you approved it). One laptop with three servers is manageable by inspection. Fifty agents and two hundred servers is not — that is the problem the next tab exists to solve.

Gateways · A2A · Glossary

Gateways — Running Agents At Scale

One agent on one laptop needs nothing from this tab. The moment an organisation runs many agents against many models, many MCP servers, and each other, the old microservices lesson repeats: unmanaged point-to-point traffic becomes a security and operations nightmare. A gateway is the choke point where identity, policy, and observability attach — the same role the API gateway played for REST, rebuilt for agent traffic.

The enterprise agentic stack — one governed data plane

Agent Layer Support Agent LLM Loop + Tools Coding Agent Claude Code / SDK Research Agent Web + RAG Agent Gateway AuthN/Z · Rate Limits · Quotas · Audit · Tracing · Guardrails · Failover One Data Plane For All Agent Traffic LLM Traffic Tool Traffic — MCP Agent Traffic — A2A LLM Providers Claude API Fallback / Other Models MCP Gateway Virtual MCP Servers GitHub · Jira · DB · 100s More Peer Agents Internal / Partner Agents Agent Cards · Tasks Every Hop An Agent Makes — To A Model, A Tool, Or Another Agent — Passes One Governed Control Point

Agent Gateway

A data plane purpose-built for agentic traffic. Where an API gateway understands HTTP requests, an agent gateway natively understands the three protocols agents speak:

🧠

Agent → LLM

Provider APIs (Anthropic, OpenAI, …). The gateway can route by model, enforce token budgets, fail over between providers.

🔧

Agent → Tool (MCP)

Proxies and multiplexes MCP sessions, applies per-tool authorization, inspects payloads for policy violations.

🤝

Agent → Agent (A2A)

East–west traffic between agents — identity propagation and audit for delegation chains.

Reference open-source implementation: agentgateway (Rust, originated at Solo.io, now a Linux Foundation project, integrated with the Envoy/kgateway ecosystem).

MCP Gateway

A narrower, very common specialisation: a reverse proxy that sits between MCP clients and a fleet of MCP servers.

1️⃣

Aggregation

Agents configure one endpoint; the gateway federates hundreds of upstream servers behind it.

🎭

Virtual Servers

Compose curated tool subsets per team or per agent — “deploy-bot sees these 6 tools”, regardless of what upstreams expose.

🔐

Central Auth + Audit

One OAuth flow at the gateway instead of N credentials scattered across agents; every tools/call logged and traced.

🛡️

Policy Enforcement

Tool allow-lists, rate limits, payload scanning — the practical mitigation for tool poisoning and rug pulls from the previous tab.

Examples: Docker MCP Gateway, IBM ContextForge MCP Gateway.

MCP gateway — agents see one server, operators govern hundreds

Claude Code .mcp.json → One URL Internal Agent Service Identity CI Pipeline Headless Runs MCP Gateway Single MCP Endpoint Central OAuth + Identity Tool Allow-Lists / Filtering Rate Limits + Quotas Audit Log + OTEL Tracing Virtual Server Composition GitHub MCP Remote · OAuth Jira MCP Remote · SaaS Postgres MCP Internal Network Internal API MCP Team-Built Server One URL · One Token Add Or Revoke An Upstream Server Once — Every Agent Inherits The Change

The Four Gateways, Side By Side

API GatewayLLM GatewayMCP GatewayAgent Gateway
TrafficClients → REST/gRPC servicesApps/agents → model provider APIsMCP clients → MCP serversAll of it: LLM + MCP + A2A
SpeaksHTTP, gRPCAnthropic / OpenAI-style APIsMCP (JSON-RPC over stdio / HTTP)MCP, A2A, provider APIs
GovernsRoutes, keys, rate limitsModel choice, cost, caching, fallbackWhich tools exist and who may call themEnd-to-end agent traffic policy
ExamplesTraefik, Kong, EnvoyLiteLLM, Portkey, OpenRouter, Envoy AI GatewayDocker MCP Gateway, IBM ContextForgeagentgateway

They compose, not compete. A realistic stack runs an agent gateway as the front door, an LLM gateway function for model routing, and an MCP gateway function for tool federation — sometimes three products, increasingly one.

A2A — Agent2Agent Protocol

Where MCP connects an agent to tools, A2A connects an agent to other agents — opaque peers that hold their own state and reasoning. Announced by Google in April 2025, donated to the Linux Foundation in June 2025.

1

Discover

Each agent publishes an Agent Card — a JSON document at a well-known URL describing identity, skills, endpoint, and auth requirements.

2

Delegate A Task

The client agent sends a task (JSON-RPC over HTTPS). Tasks are the unit of work, with a lifecycle: submitted → working → input-required → completed / failed.

3

Stream Progress

Long tasks stream status updates over SSE or deliver webhooks via push notifications.

4

Collect Artifacts

Results come back as artifacts — text, files, structured data. The remote agent’s internals stay private; only the task interface is shared.

MCP vs A2A — Which Wire When

MCPA2A
ConnectsAgent ↔ tools & dataAgent ↔ agent
Remote Side IsDeterministic functions you describe with schemasAn autonomous peer with its own reasoning
InteractionCall → result, usually secondsTask lifecycle, possibly hours, may ask questions back
DiscoveryConfig / registry of serversAgent Cards at well-known URLs
Mental Model”Plug in a capability""Delegate to a colleague”

A useful test: if you can fully describe the remote thing with a JSON Schema, it’s a tool — use MCP. If you’d brief it like a coworker, it’s an agent — use A2A.

Glossary — The Rest Of The Vocabulary

ConceptWhat It Is
Function Calling / Tool UseThe model-API feature underneath everything here: the LLM emits a structured request naming a function and JSON arguments; your code executes it
ReActThe 2022 paper pattern (Reason + Act) that became the agent loop: interleave thinking traces with actions and observations
Context EngineeringSuccessor discipline to prompt engineering: curating everything in the window — instructions, tools, retrievals, history — for the current step
CompactionSummarising older conversation turns to reclaim context window space so long-running agents don’t run out of memory mid-task
Agentic RAGRetrieval driven by the agent loop — the model decides what to search, reads results, and searches again — instead of one fixed retrieve-then-answer pass
SkillsPackaged procedural knowledge (instructions + scripts + resources) an agent loads on demand — teaching workflows without retraining or bloating the system prompt
Computer UseAn agent operating a GUI directly — screenshots in, mouse/keyboard actions out — for software that has no API
SandboxingExecuting agent tool calls inside containers/VMs with restricted filesystem and network so a bad action is contained
Human-In-The-Loop (HITL)Approval checkpoints on consequential actions — deploys, payments, deletions — while routine steps run autonomously
GuardrailsInput/output validation around the model: schema checks, content filters, policy rules — enforced by code, not by asking nicely
EvalsRepeatable test suites for agent behaviour — graded tasks and LLM-as-judge scoring; the agent world’s regression tests
Agent ObservabilityTraces of every loop iteration, tool call, and token spent — converging on OpenTelemetry GenAI semantic conventions
MCP RegistryThe official catalog for discovering published MCP servers (with private sub-registries inside enterprises)
Agent RuntimeThe managed place agents execute — loop scheduling, state persistence, scaling — e.g. cloud agent platforms or your own harness on k8s
Tool PoisoningAttack: hostile instructions hidden inside a tool’s description or output, hijacking the model when they enter context
Confused DeputyAttack: tricking a privileged agent into using its authority for the attacker’s request — why per-user, per-tool authorization beats one god-token
Rug PullAttack: an MCP server changes a tool’s behaviour after the user approved the original — mitigated by version pinning and gateway policy

How it all composes: a model becomes an agent when a harness runs it in a tool loop · MCP standardises how that loop reaches tools and data · A2A standardises how agents delegate to each other · and gateways put identity, policy, and observability on every one of those wires. Four layers — reasoning, tooling, collaboration, governance.

Enjoyed this post?

Get the next one in your inbox — only when I ship something worth reading.

Newsletter form not configured.

Or follow on Substack for the newsletter.

Comments via GitHub Discussions

Comments not configured. Set GISCUS env vars to enable.