Search This Blog

Wednesday, June 4, 2025

📘 Beginner-Friendly AI Backend Tutorial with Model Context Protocol (MCP)

 Welcome! In this tutorial, we will build a simple AI-powered backend application that integrates an AI model with tools and data using the Model Context Protocol (MCP) — all on your local machine.

No experience with AI or coding? No problem! This guide will walk you through every step, like a friendly tutor.


🧠 What is Model Context Protocol (MCP)?

Imagine you’re talking to a super-smart assistant (like ChatGPT). Now imagine that assistant can look things upcalculate results, and read data from your files — just like a helpful human would.

MCP is the set of rules that tells the AI:

  • "Hey, if you see a question that needs a calculator, use it!"

  • "If the user asks about data, check the file first before guessing."

Think of it as a walkie-talkie between the AI and real tools/data.


🛠️ Step 1: Set Up Your Environment

1.1 Install Python

If you don’t already have Python:

To check if Python is installed:

python --version

1.2 Create a Folder for Your Project

mkdir mcp-ai-demo
cd mcp-ai-demo

1.3 Set Up a Virtual Environment (Optional but Recommended)

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

1.4 Install Required Packages

pip install openai pandas

📦 Step 2: Prepare Your Data (CSV File)

We’ll use a simple product catalog as our "database."

Create a file called products.csv:

id,name,price,stock
1,Red T-shirt,19.99,25
2,Blue Jeans,49.99,10
3,Green Hat,14.99,5
4,Black Sneakers,89.99,2

🧠 Step 3: Set Up AI Access (GPT Model)

3.1 Get an OpenAI API Key

3.2 Store the Key in Your Code (DO NOT share it)

We’ll use a .env-style setup for this tutorial.

Create a file config.py:

# config.py
OPENAI_API_KEY = "your-api-key-here"  # Replace this with your real key

🧰 Step 4: Create Tools the AI Can Use

4.1 Data Tool (Search CSV File)

# data_tool.py
import pandas as pd

def search_products(keyword):
    df = pd.read_csv('products.csv')
    results = df[df['name'].str.contains(keyword, case=False)]
    return results.to_dict(orient='records')

4.2 Calculator Tool

# calculator_tool.py
def calculate(expression):
    try:
        return eval(expression)
    except Exception as e:
        return str(e)

🧠 Step 5: Connect AI via MCP Logic

5.1 Main Script

# main.py
import openai
from config import OPENAI_API_KEY
from data_tool import search_products
from calculator_tool import calculate

openai.api_key = OPENAI_API_KEY

def ai_call(user_input):
    print("\nUser asked:", user_input)

    # Step 1: Let AI decide what to do
    prompt = f"""
You are a smart AI assistant. You can:
1. Search product data using 'search_products(keyword)'
2. Use a calculator with 'calculate(expression)'

If the user asks something like "find red shirt" -> call search_products('red shirt')
If the user says "what's 5 * 20" -> call calculate('5 * 20')
Otherwise, reply directly.

Now, here's what the user asked:
"{user_input}"
What should you do?
"""
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=150,
        temperature=0
    )

    action = response.choices[0].text.strip()
    print("\nAI decided:", action)

    # Step 2: Execute based on AI decision
    if "search_products(" in action:
        keyword = action.split("(")[1].split(")")[0].strip("'\"")
        result = search_products(keyword)
        print("\nSearch Results:", result)
    elif "calculate(" in action:
        expr = action.split("(")[1].split(")")[0].strip("'\"")
        result = calculate(expr)
        print("\nCalculation Result:", result)
    else:
        print("\nAI Response:", action)

# Simple CLI Loop
if __name__ == "__main__":
    while True:
        user_input = input("\nAsk something (or type 'exit'): ")
        if user_input.lower() == 'exit':
            break
        ai_call(user_input)

▶️ Step 6: Run and Test It Locally

In your terminal:

python main.py

Try typing:

  • Find red t-shirt

  • How much is 15 * 3.5?

  • Show green hat

🎉 You’ve just built a mini AI system that talks to tools and data!


💡 What to Try Next

  • Add a second data file (like customer info).

  • Add a weather tool using a public API.

  • Let the AI update your CSV (e.g., mark item as "out of stock").

  • Try switching the AI model to something open-source (e.g., using HuggingFace Transformers).


📦 Summary

ComponentDescription
CSV FileActs as your mock database
AI ModelInterprets user queries
ToolsExecute actions (search, calculate, etc.)
MCP LogicBridges AI intent with tool invocation

You now understand the basics of Model Context Protocol — using plain Python and local files. 🧠🔌📊

Happy hacking!

No comments:

My Profile

My photo
can be reached at 09916017317