Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages

MCP is one standard plug between AI apps and tools: four apps and four tools need 8 connections instead of 16. A tiny Python server named github offers one tool, one resource and one prompt; a client starts it, lists what it offers and calls create_issue, and a raw wire script shows the same three steps as JSON lines.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Explain why MCP turns N times M custom connectors into N plus M
  • Name the three roles, host, client and server, and what a server offers: tools, resources and prompts
  • Read the three steps of an MCP session: initialize, tools/list and tools/call
  • Treat a server as a program that acts with your permissions: trust, scope, secrets and audit

Before you start

  • Basic Python
  • Claude Tool Use: How tool_use and tool_result Work

MCP, the Model Context Protocol, is one plug shape that lets any AI app use any tool. Think of USB-C: phones, laptops and monitors all share one port, so you stop buying a new cable for every pair. In this article we see why that matters, meet the three roles (host, client and server), and run a tiny server and client in Python so you can watch the actual messages go back and forth.

Everything here runs locally with the official mcp Python package (version 2.3.0 in the project). No API key and no model call are needed.

A drawer full of chargers

Say you use three AI apps: Claude Desktop (a chat app on your computer), an assistant inside your code editor, and a small agent you built yourself. All three need the same two things: GitHub, to look at issues and pull requests, and your database, to look up rows.

Without a standard, every app and tool pair needs its own custom connector. That's six already, each with a different plug. It's the drawer full of chargers, one for every device.

One plug, fewer wires

Now make it four apps and four tools. Wired by hand, every app needs a line to every tool: 4 × 4 = 16 custom connectors. Put one shared standard in the middle, and each app plugs into it once and each tool plugs into it once: 4 + 4 = 8 connections.

N times M connectors against N plus M with MCP appappappapp tooltooltooltool 4 × 4 = 16 connectors appappappapp tooltooltooltool MCP 4 + 4 = 8 connections
Wire by hand and the count multiplies. Put one standard in the middle and it only adds up.

Each app learns MCP once, each tool learns it once, and they all fit together. With N apps and M tools, that's N + M instead of N × M.

Host, client, server

Picture a laptop with two USB-C ports and two devices plugged in.

  • The laptop is the host. That's the app you actually use, like Claude Desktop or your editor.
  • Each port is an MCP client. A client is the part inside the host that speaks MCP, and it talks to exactly one server.
  • Each device is an MCP server: a small program that offers something, like a GitHub server or a database server.

So a host holds one client for each server it connects to. Two servers, two clients.

What a server offers

Here's a tiny server, server.py, named github. Think of it as a small shop with three shelves.

from mcp.server.mcpserver import MCPServer

mcp = MCPServer("github")

ISSUES = ["Login button is slow"]


@mcp.tool()
def create_issue(title: str) -> str:
    """Open a new issue with the given title."""
    ISSUES.append(title)
    return f"Created issue #{len(ISSUES)}: {title}"


@mcp.resource("repo://readme")
def readme() -> str:
    """The README of the repository."""
    return "Shop app. Run with: python app.py"


@mcp.prompt()
def review_pr(number: int) -> str:
    """A ready-made message for reviewing a pull request."""
    return f"Review pull request #{number} for bugs and style."


if __name__ == "__main__":
    mcp.run(transport="stdio")
  • Tools are things you can do. A tool is an action the AI can ask for, like create_issue, which takes a title.
  • Resources are things you can read: pieces of data the app can read, each at its own address, like repo://readme.
  • Prompts are ready-made recipes: starting messages the user can pick, like review_pr.

In practice most servers start with tools. Resources and prompts are extras that make a server nicer to use. In older versions of the SDK, MCPServer was called FastMCP, so you may still see that name.

The client side

Now the other side, client.py. This is the part a host runs. It says how to start the server (python server.py, on this computer), then asks questions in order.

import asyncio
import sys

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client


async def main():
    server = StdioServerParameters(
        command=sys.executable, args=["server.py"])
    async with stdio_client(server) as (read, write):
        async with ClientSession(read, write) as session:
            hello = await session.initialize()
            print("server:", hello.server_info.name)
            tools = await session.list_tools()
            print("tools:", [t.name for t in tools.tools])
            res = await session.list_resources()
            print("resources:", [str(r.uri) for r in res.resources])
            prompts = await session.list_prompts()
            print("prompts:", [p.name for p in prompts.prompts])
            args = {"title": "Add dark mode"}
            result = await session.call_tool("create_issue", args)
            print("result:", result.content[0].text)


asyncio.run(main())
server: github
tools: ['create_issue']
resources: ['repo://readme']
prompts: ['review_pr']
result: Created issue #2: Add dark mode

The first call is initialize, and the server says hello with its name. Then the client asks what's on offer: one tool, one resource, one prompt. Then it calls create_issue with the title "Add dark mode", and the result says issue #2, because the server already had one issue. The host never needs to know how GitHub works inside. The client asks, and the server answers.

Two ways to connect

The messages are the same either way. Only the road is different.

stdioStreamable HTTP
Where the server runsOn your machine; the host starts itSomewhere else, at a web address
How messages travelStandard input and outputHTTP requests
Where the secret goesAn environment variable, like an API keyAn OAuth token the client carries
Feels likeA colleague at the next deskA phone call to another office

Pick stdio for tools on your own machine, and Streamable HTTP for a server that many people share. The transport choice has its own details, covered in MCP transports: stdio or Streamable HTTP.

Telling the host about servers

A host learns about its servers from a config file. This one is .vscode/mcp.json, the file the VS Code editor reads. Each entry under servers is one server.

{
  "inputs": [
    {"type": "promptString", "id": "github-token", "password": true}
  ],
  "servers": {
    "github": {
      "type": "stdio",
      "command": "python",
      "args": ["server.py"],
      "env": { "GITHUB_TOKEN": "${input:github-token}" }
    },
    "team-db": {
      "type": "http",
      "url": "https://mcp.example.com/mcp"
    }
  }
}

The github entry is stdio: the host runs python server.py itself. Its token goes into an environment variable, and the input line means the editor asks you for it, so the secret never sits in the file. The team-db entry is http, with just a web address. Same list, two roads. Other hosts use a different file name, but the shape is similar.

What the conversation looks like

To see what the SDK does for us, wire.py starts the same server and writes the messages by hand. Each message is one line of JSON-RPC: a request with a method name and an id.

import json
import subprocess
import sys

server = subprocess.Popen([sys.executable, "server.py"], stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, text=True)
INIT = {"protocolVersion": "2025-06-18", "capabilities": {},
        "clientInfo": {"name": "my-agent", "version": "1.0"}}
CALL = {"name": "create_issue", "arguments": {"title": "Add dark mode"}}


def send(method, params, id=None):
    msg = {"jsonrpc": "2.0", "method": method, "params": params}
    if id:
        msg["id"] = id
    print(json.dumps(msg), file=server.stdin, flush=True)
    if id:
        print("->", method)
        return json.loads(server.stdout.readline())["result"]

hello = send("initialize", INIT, id=1)
caps = sorted(hello["capabilities"])
print("<-", hello["serverInfo"]["name"], "offers", caps)
send("notifications/initialized", {})
tool = send("tools/list", {}, id=2)["tools"][0]
print("<-", tool["name"], "needs", tool["inputSchema"]["required"])
call = send("tools/call", CALL, id=3)
print("<-", call["content"][0]["text"])
server.terminate()
-> initialize
<- github offers ['prompts', 'resources', 'tools']
-> tools/list
<- create_issue needs ['title']
-> tools/call
<- Created issue #2: Add dark mode
The three steps of an MCP session clientserver 1. initialize name, offers prompts, resources, tools notifications/initialized 2. tools/list create_issue, needs title 3. tools/call create_issue Created issue #2 red = what the model sees
Say hello, list the tools, call a tool. The model only ever sees the tool list and the results.

Step one, initialize: the server answers with who it is and what it offers. The client sends a short notifications/initialized note (no id, so no reply), and the session is ready. Step two, tools/list: the server sends each tool and the inputs it needs. Step three, tools/call, with the tool name and arguments, and the server sends back the result.

A server acts as you

A local server runs with your permissions, so treat it like any other program you install. Four habits:

  1. Trust. Install servers only from sources you trust.
  2. Scope. Give the smallest access that works: a read-only database user, or one folder, not the whole disk.
  3. Secrets. With stdio the secret sits in an environment variable. With HTTP it's an OAuth token, and a good token has a narrow scope and an expiry date.
  4. Audit. Keep a log of which tool ran, when and for whom, and ask a person to confirm risky actions, like deleting data.

MCP makes connecting easy, but you still decide what each server may touch. The same thinking about how much one tool can do, if the agent is tricked, is the subject of the agent attack surface and blast radius.

Common mistakes

  • Mixing up client and host. The host is the app. The client is one connection inside it, and it talks to one server.
  • Thinking the model talks to the server. The host's client does. The model sees the tool list and the results, nothing else.
  • Putting a token in the config file. Use an input prompt or an environment variable, so the secret isn't committed with the file.
  • Installing any server you find. It runs as you. Check where it comes from and what it can reach.

Quick recap

IdeaIn one line
Why MCPN + M connections instead of N × M custom connectors
RolesHost (the app), client (one per server), server (offers things)
What a server offersTools to do, resources to read, prompts to start from
The sessioninitialize, tools/list, tools/call
Transportsstdio for local servers, Streamable HTTP for shared ones
SafetyTrust, scope, secrets and audit, because a server acts as you

To turn an API of your own into a server, the next step is building an MCP server with tools, resources and prompts.

Try it yourself

Add a second tool to server.py, say list_issues that returns the titles in ISSUES. Run wire.py again and change it to print every tool from tools/list, not just the first. Then call list_issues and check that "Add dark mode" is in the answer.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 43 of 89

Previous
A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
Next post
Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.

What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table

LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.

Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph

A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.

LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.

On this page

  • A drawer full of chargers
  • One plug, fewer wires
  • Host, client, server
  • What a server offers
  • The client side
  • Two ways to connect
  • Telling the host about servers
  • What the conversation looks like
  • A server acts as you
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.