DEV Community

Bhimashankar Patil
Bhimashankar Patil

Posted on

1

Understanding MCP (Model Context Protocol) with Examples

Introduction

The Model Context Protocol (MCP) is a structured way to manage and exchange contextual information between AI models and applications. It allows AI systems to maintain state, remember previous interactions, and improve response relevance in multi-turn conversations.

Why is MCP Needed?

Most AI models process each request independently. Without context, they cannot recall previous interactions, leading to disjointed conversations. MCP solves this by providing a framework to:

  • Maintain conversation history
  • Track user preferences
  • Improve response accuracy
  • Call external tools and APIs to enhance responses

How MCP Works

MCP operates using context objects that store relevant details about an interaction. These context objects can include:

  • Session ID: Unique identifier for a conversation
  • User Information: Preferences, history, and settings
  • Previous Queries & Responses: Helps maintain continuity
  • Domain-Specific Knowledge: Relevant facts that improve AI accuracy
  • API & Tool Calls: Enables dynamic responses by fetching real-time data

Example of MCP in Action

Let's say we are building an AI assistant for customer support. Without MCP, the conversation might look like this:

Without MCP

User: "What's my order status?"

AI: "Please provide your order ID."

User: "It's #12345."

AI: "Your order is in transit."

Here, the AI forgets the user after every message and needs additional input each time.

With MCP

Using MCP, we store the session details and user data:

{
  "session_id": "abc123",
  "user": {
    "name": "John Doe",
    "email": "john@example.com"
  },
  "context": {
    "last_order_id": "12345",
    "last_query": "order_status"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, the conversation is smoother:

User: "What's my order status?"

AI: "Your last order (#12345) is in transit."

Since the AI remembers the order ID from context, it eliminates the need to ask again.

Using Tools and APIs in MCP

MCP also allows AI systems to call external APIs and tools dynamically. For example, if a user asks for real-time weather updates, MCP can fetch data from a weather API:

{
  "session_id": "xyz789",
  "user": {"name": "Alice"},
  "context": {"last_query": "weather"},
  "api_call": {
    "endpoint": "https://weatherapi.com/current",
    "parameters": {"location": "New York"}
  }
}
Enter fullscreen mode Exit fullscreen mode

The AI can then return:

User: "What's the weather like in New York?"

AI: "It's 72°F and sunny in New York."

By integrating API calls, MCP enables AI assistants to provide real-time, accurate responses beyond static knowledge.

Implementing MCP

To implement MCP, you need:

  1. Session Management – Store session data using a database or memory cache (e.g., Redis).
  2. Context Storage – Maintain a structured context object.
  3. Stateful APIs – Modify API calls to include and update context data.
  4. Tool and API Integration – Enable AI to fetch external data dynamically.

Example: Context-Aware API in Python

from flask import Flask, request, jsonify

app = Flask(__name__)
context_store = {}

@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    session_id = data.get("session_id")
    user_message = data.get("message")

    if session_id not in context_store:
        context_store[session_id] = {"history": []}

    context_store[session_id]["history"].append(user_message)

    response = generate_response(user_message, context_store[session_id])
    return jsonify({"response": response})

def generate_response(message, context):
    return f"You said: {message}. Context length: {len(context['history'])}"

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Conclusion

MCP helps AI models maintain state and improve conversational flow. By structuring context information efficiently and integrating tools and APIs, AI assistants can provide more meaningful and personalized responses, leading to better user experiences.


What are your thoughts on MCP? Have you implemented something similar? Let me know in the comments!

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay