← All tutorials
Build MCP from scratch

Build MCP from scratch — the app & the task

The Model Context Protocol has two halves you can build. The MCP server (the "app") exposes capabilities — tools, data and prompts. The MCP client / task consumes them to get a job done. This tutorial builds each from scratch, with a runnable example and a when-to-use scenario for both.

MCP server (your app)— exposes tools — MCP protocol— consumed by — MCP client (your task)
New to MCP? Read APIs vs MCP first for the why. This guide is the hands-on how.

Why  The problem it solves

Wiring M AI apps to N tools directly needs up to M×N bespoke integrations, and the model can't discover a tool at runtime — someone hand-codes each one for each assistant. MCP is one open protocol that collapses this to M+N: expose a tool once as a server, and any MCP-aware client (Claude Desktop, an IDE, your agent) can discover and call it.

So "building MCP" means one of two things: writing a server to make a capability available to every AI host, or writing a client/task that uses those servers to accomplish something. You'll do both below.

Architecture  The two sides you build

MCP client and server Your task (an MCP client, inside a host) and your app (an MCP server exposing tools, resources and prompts) talk over the MCP protocol; the server calls the real API, database or files behind it. MCP client — your task in a host: agent · IDE · Claude Desktop MCP server — your app tools · resources · prompts MCP · JSON-RPC stdio or HTTP API · DB · files · code

A server offers three primitives, and the client discovers them at runtime:

PrimitiveWhatControlled by
ToolsActions the model can invoke (with typed inputs)Model
ResourcesRead-only data/context the host can loadApp
PromptsReusable prompt templates a user can triggerUser

Part A  Build the MCP server (the app)

The official Python SDK includes FastMCP — declare a server, decorate functions as tools/resources/prompts, and run. That's the whole thing.

server.py  ·  pip install "mcp[cli]"
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("weather")                 # your MCP app (server)

@mcp.tool()
def get_forecast(city: str) -> str:
    """Get the weather forecast for a city."""   # docstring → shown to the model
    # ...call a real weather API here...
    return f"Sunny, 24°C in {city}."

@mcp.resource("config://units")
def units() -> str:
    """The unit system this server uses."""       # read-only data (a resource)
    return "metric"

@mcp.prompt()
def trip(city: str) -> str:
    """A ready-made prompt users can invoke."""
    return f"Plan a day trip to {city} using the weather tools."

if __name__ == "__main__":
    mcp.run()                            # speaks MCP over stdio

Example & when to use

Build a server when you have a capability or data source — an internal API, a database, a filesystem, a SaaS tool — and you want any AI host to use it, or you're publishing a tool for others' assistants.

Scenario "Let support staff query our ticketing system from Claude." You write a tickets MCP server once (tools: search_tickets, get_ticket, add_note) — and every teammate's assistant, plus your own agents, can use it. Write once, reuse everywhere.

Part B  Build the MCP client (the task)

A client connects to a server, discovers its tools, and calls them. At its simplest:

client.py  ·  connect · discover · call
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    params = StdioServerParameters(command="python", args=["server.py"])
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await session.list_tools()                # runtime discovery
            print("tools:", [t.name for t in tools.tools])
            out = await session.call_tool("get_forecast", {"city": "Wellington"})
            print(out.content[0].text)

asyncio.run(main())

Usually the "task" is agentic: you hand the server's tools to an LLM and let it decide when to call them. Most agent frameworks load MCP servers directly:

agent_task.py  ·  MCP tools → an LLM (conceptual; APIs vary)
# The model gets the server's tools and calls them itself to finish the task.
from your_agent_framework import Agent, MCPServer

agent = Agent(
    model="claude-opus-4-8",
    mcp_servers=[MCPServer(command="python", args=["server.py"])],
)
agent.run("What should I pack for Wellington tomorrow?")   # calls get_forecast on its own

Example & when to use

Build a client/task when you're building the AI app or automation that needs to use tools — orchestrating one or more MCP servers to accomplish a goal.

Scenario A nightly job: read new issues from the GitHub MCP server, summarize them with an LLM, and post to the Slack MCP server. Your task wires several ready-made servers together — you write the goal, the agent calls the tools.

Wire it up  Run & connect them

Test the server on its own

MCP Inspector — poke your server in a browser UI
mcp dev server.py         # opens the Inspector: list & call tools, view resources

Connect it to a host (e.g. Claude Desktop)

claude_desktop_config.json
{
  "mcpServers": {
    "weather": { "command": "python", "args": ["/abs/path/to/server.py"] }
  }
}
// restart the host → your tools appear, ready for the model to call.
Transports. stdio is simplest for local servers (the host launches your script). For remote/shared servers, run over HTTP (streamable HTTP / SSE) with authentication. Same code, different run transport.

Which to build when

MCP server (app)MCP client (task)
You have…a capability/data to exposea goal to accomplish with tools
You write…tools, resources, promptsconnect → discover → call (often via an agent)
Reused by…every MCP host & agentyou — it drives the servers
Examplea "tickets" or "weather" servera nightly GitHub→Slack summarizer
Often you build both: a server to expose your system, and a task/agent that combines it with other servers. And remember — a server is usually a thin adapter over a plain API; MCP standardizes the exposure, not the implementation.

Cheat sheet

QuestionShort answer
What is an MCP server?The "app" — it exposes tools, resources & prompts over MCP.
What is an MCP client?The consumer — it connects, discovers tools, and calls them (often an agent).
Build a server with?FastMCP (Python SDK): decorate functions as @mcp.tool() etc.
The three primitives?Tools (model), Resources (app data), Prompts (user).
How to test a server?The MCP Inspector — mcp dev server.py.
Transports?stdio (local) or HTTP/SSE (remote, with auth).

Knowledge check

Six questions on building MCP. Pick an answer for each, then check your score.

1. What does an MCP server do?

2. What does an MCP client / task do?

3. In FastMCP, how do you expose a function as a tool?

4. What are MCP's three primitives?

5. You have an internal ticketing system you want every assistant to use. You build…

6. How do you quickly test an MCP server on its own?

Next steps

🔌 APIs vs MCP

The why — the M×N problem and how MCP compares to plain APIs.

🕸️ WebMCP & A2A

What's next — MCP in the browser and agent-to-agent protocols.

🧰 Agent Development Kits

Build agents that consume your MCP servers as tools.

📓 All tutorials

The hub — LLMs, agents, APIs, cloud & more.