What you'll build: By the end of this guide, you will have a working AI agent powered by Claude that remembers your entire conversation. No more re-explaining yourself. No more pasting raw JSON. You'll build a stateful assistant using the Model Context Protocol (MCP) — a standardized system that manages context for you, so you can focus on building, not babysitting.

Prerequisites

  • A computer with internet access.
  • Python (version 3.8 or higher) installed. (Python is a programming language that lets you run AI tools locally.)
  • An Anthropic API key — your personal password to access Claude's brain.
  • Basic comfort with the command line (the black text window on your computer).
  • A text editor (like VS Code, Sublime Text, or even Notepad).

1. What is MCP and Why It Matters

Think of MCP as a trained librarian — your personal context manager — versus the old way of shoving crumpled papers into Claude's hands every time you talk.

When you ask Claude to summarize a long sales call, build a report from past conversations, or act as a customer support agent, the AI needs context — the history of what was said before. Traditionally, developers had to manually collect that history, format it into a strict JSON structure, and paste it into every single API call. That approach is fragile, wastes time, and burns through your token budget (the cost of running the AI).

The Model Context Protocol (MCP) automates this entire process. It is an open standard created by Anthropic that defines exactly how an AI model should store, retrieve, and manage its conversation history. Instead of writing custom code for every new app, you connect your app to an MCP server, and the server acts as a central source of truth for context.

Why this matters for you:

  • Efficiency: Stop reinventing the wheel. MCP handles the boring parts of context management so you can focus on your product.
  • Scalability: Want to add memory to your app? MCP makes it trivial to move from a simple chatbot to a complex agent that uses tools, databases, and APIs.
  • Reproducibility: Your app behaves the same way every time because context is managed by a predictable protocol, not a bunch of messy scripts.

Here's the hard truth: if you are still manually stitching together conversation history in a text file, you are building a house of cards. MCP is the concrete foundation. It transforms chaos into a system.

2. Prerequisites: What You Need Before Starting

Let's get your environment ready. This is the fastest MCP setup prerequisites checklist you will find.

Step 1: Install Python and Pip
Open your command line (Terminal on Mac, Command Prompt on Windows).
Type: python --version
If you see Python 3.8+, you're good. If not, download it from the Python Official Website.

Step 2: Install the Required Libraries
Think of pip as an app store for code. Run this one command:

pip install anthropic mcp

Step 3: Get Your API Key
Go to the Anthropic Console and create an account. Navigate to the API Keys section and generate a new key. Copy it somewhere safe — this is your VIP pass to use Claude.

Step 4: Set Up a Project Folder
Create a new folder on your desktop called mcp_demo. Inside, create two empty files: server.py and client.py. These will hold your MCP server and your Claude integration.

3. Setting Up the MCP Server

Now the fun begins. The MCP server is the "librarian" running in the background, storing and retrieving context on demand. Follow this MCP server setup tutorial to get it running in minutes.

Step 1: Write the Server Code
Open server.py in your text editor and paste the following:

# server.py
from mcp.server import Server
import json

app = Server("my_chat_server")

@app.on("get_context")
async def get_context(session):
    # In a real app, this would fetch from a database
    return json.dumps({"history": []})

@app.on("set_context")
async def set_context(session, context):
    # Stores the conversation history
    print(f"Context saved: {context}")
    return {"status": "ok"}

if __name__ == "__main__":
    app.run()

Step 2: Run the Server
In your command line, navigate to your mcp_demo folder and type:

python server.py

You should see a message saying the server is running on http://localhost:8000. Your MCP librarian is now live!

Step 3: Test the Server
Open a new terminal window (keep the server running) and send a test command using curl:

curl -X POST http://localhost:8000/ \
-H "Content-Type: application/json" \
-d '{"method": "get_context"}'

Expected output:

{"history": []}

You now have a dedicated context manager running on your machine. This server will store any conversation history you send it and serve it back when needed.

4. Connecting Claude to MCP

The Claude MCP integration is where the magic happens. Instead of hardcoding context into every API call, your client script asks the MCP server for the history before talking to Claude.

Open client.py and paste the following:

# client.py
import anthropic
import requests

client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")

def send_message(user_input):
    # Step 1: Get history from MCP server
    resp = requests.get("http://localhost:8000/get_context")
    history = resp.json().get("history", [])

    # Step 2: Send user input + history to Claude
    message = client.messages.create(
        model="claude",
        max_tokens=1024,
        messages=history + [{"role": "user", "content": user_input}]
    )

    # Step 3: Extract Claude's reply
    reply = message.content[0].text
    print(f"Claude: {reply}")

    # Step 4: Save the updated context back to MCP
    new_history = history + [
        {"role": "user", "content": user_input},
        {"role": "assistant", "content": reply}
    ]
    requests.post("http://localhost:8000/set_context", json={"history": new_history})

    return reply

# Test it
send_message("Hi Claude, my name is Alex.")
send_message("What is my name?")

Run the script:

python client.py

Expected output:

Claude: Hello Alex! How can I help you today?
Claude: Your name is Alex.

Notice what happened: the second message remembered the first, even though you never manually stored anything. MCP managed the context behind the scenes. This is the core loop that powers every stateful AI application.

5. Building a Simple Agent with MCP

Let's turn this into a real MCP agent tutorial. A true agent doesn't just chat — it takes actions. We will give Claude a tool: a function that checks the weather. MCP will store the tool results seamlessly in the conversation history.

Create a new file called agent.py:

# agent.py
import anthropic
import requests
import json

client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")

def get_weather(location):
    # Simulated weather lookup
    return json.dumps({"temperature": 72, "condition": "Sunny", "location": location})

tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            },
            "required": ["location"]
        }
    }
]

print("Agent started. Type 'quit' to exit.")
while True:
    user_input = input("\nYou: ")
    if user_input.lower() == "quit":
        break

    # Get context from MCP
    resp = requests.get("http://localhost:8000/get_context")
    history = resp.json().get("history", [])

    # Send to Claude with tools
    response = client.messages.create(
        model="claude",
        max_tokens=1024,
        messages=history + [{"role": "user", "content": user_input}],
        tools=tools
    )

    # Check if Claude wants to use a tool
    if response.stop_reason == "tool_use":
        tool_input = json.loads(response.content[0].input)
        tool_result = get_weather(tool_input["location"])
        reply = f"The weather in {tool_input['location']} is 72°F and sunny."
    else:
        reply = response.content[0].text

    print(f"Claude: {reply}")

    # Save everything to MCP
    new_history = history + [
        {"role": "user", "content": user_input},
        {"role": "assistant", "content": reply}
    ]
    requests.post("http://localhost:8000/set_context", json={"history": new_history})

Run the agent:

python agent.py

Example interaction:

You: What is the weather in San Francisco?
Claude: The weather in San Francisco is 72°F and sunny.
You: What was the last location I asked about?
Claude: You asked about San Francisco.

The agent remembered the previous exchange because MCP stored the tool call and the response together. This is how you build real applications — customer support bots that remember past issues, writing assistants that track your style, or sales agents that recall prospect details.

6. Best Practices and Troubleshooting

Here are non-negotiable MCP best practices to keep your agent running smoothly.

Keep Context Manageable
Conversations can get long. If you save every word forever, you waste tokens and hit context limits. Implement a trim strategy: keep the last 20 messages, or use Claude to summarize old conversations and store the summary. MCP handles the storage, but you are the architect of the rules.

Protect Your API Key
Never hardcode your API key in a script. Use an environment variable or a .env file. Hardcoding keys is the number one security mistake beginners make.

Handle Errors Gracefully
Network calls fail. MCP servers go down. Wrap your API calls in try...except blocks and implement retries with a delay. A 5-second wait is often enough to recover from a rate limit.

Common Pitfalls to Avoid:

  • Invalid JSON: MCP relies on strict JSON formatting. Use json.dumps and json.loads to avoid nasty syntax errors.
  • Outdated Libraries: Run pip install --upgrade anthropic mcp regularly. Old versions break.
  • Misconfigured Endpoint: Double-check that your MCP server is running on the correct port (localhost:8000). A simple typo here can waste hours of debugging.

For more advanced capabilities, explore the best MCP tools and skills to extend your server's functionality.

7. Next Steps and Resources

You have a working MCP server and a stateful agent. This puts you miles ahead of most beginners. Here are your MCP further resources and next moves.

Dive Deeper:
Read the official Model Context Protocol Official Documentation to understand advanced features like multiple conversation threads, persistence to databases (SQLite, Postgres), and security configurations.

Build Real Products:

  • Customer Support Bot: Give your agent access to a knowledge base. MCP stores the entire support history, allowing the bot to personalize responses across sessions.
  • AI Writing Assistant: Connect MCP to your notes and drafts. The agent will maintain your voice across long documents.
  • Business Dashboard: Use MCP to track user preferences and action items over time.

Explore Community Projects:
Check out the MCP Servers GitHub Repository for pre-built servers that connect to databases, file systems, and external APIs. You can plug these directly into your setup.

Level Up Your Skills:
If you enjoyed this guide, you will love building without the boilerplate. Read about how to build your first AI app and explore no-code Claude automations that scale your workflows without hiring engineers. For founders, the top AI productivity tools can transform how you manage daily operations.

Join the Anthropic Discord community to ask questions and share what you build. The community is friendly, active, and full of people who were exactly where you are right now.

Cover photo by Steve A Johnson on Pexels.