Skip to content

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🤖 ecommerce_mcp — MCP Server for Chatram

A Model Context Protocol (MCP) server that exposes the entire Chatram e-commerce backend as structured AI tools — powering the AI Shopping Assistant widget built into the storefront.

🌐 Live MCP Endpoint: mcp.chatram.in
🛒 Storefront: ecommerce.chatram.in
🔗 Backend API: api.chatram.in


📌 What is MCP?

The Model Context Protocol is an open standard that lets AI models (like Claude) call real APIs through structured tools. Instead of Claude hallucinating answers about your cart or orders, it calls the actual backend and returns real data.

User: "What's in my cart?"
         │
         ▼
   Claude (AI Model)
         │  calls tool
         ▼
   ecommerce_mcp  (this server)
         │  HTTP request with user's JWT
         ▼
   Django API (api.chatram.in)
         │
         ▼
   Returns real cart data → Claude formats and replies

🏗️ Architecture

┌─────────────────────────────────────────────────────────────────┐
│                    React Frontend (ecommerce.chatram.in)         │
│                                                                  │
│   AIChatWidget ──► POST /user/ai/  (with Authorization: Bearer)  │
└───────────────────────────────┬─────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│               Django Backend (api.chatram.in)                    │
│                                                                  │
│   anthropic_proxy_view  ──►  Anthropic Claude API               │
│        │ forwards tool calls to ─────────────────────────────┐  │
└────────┼────────────────────────────────────────────────────-─┘  │
         │                                                      │
         ▼                                                      │
┌─────────────────────────────────────────────────────────────────┐
│              ecommerce_mcp  (mcp.chatram.in)  ◄────────────────┘ │
│                                                                  │
│   FastMCP server — Streamable HTTP transport                     │
│   Per-request JWT auth via Authorization: Bearer header          │
│   Calls Django API on behalf of the logged-in user              │
│                                                                  │
│   tools/products.py   tools/cart.py    tools/wishlist.py        │
│   tools/orders.py     tools/reviews.py tools/customers.py       │
└─────────────────────────────────────────────────────────────────┘

🛠️ Available Tools (30 total)

📦 Products

Tool Auth Description
list_products Public List all products with filters
get_product Public Get single product by ID
search_products Public Search by name, category, brand, price range
create_product Seller Create a new product with variants
update_product Seller Update product fields
delete_product Seller Delete a product
get_product_image_upload_url Seller Get S3 pre-signed URL for image upload
save_product_image Seller Link uploaded S3 image to product
list_categories Public List all product categories
create_category Seller Create a new category
list_brands Public List all brands

🛒 Cart

Tool Auth Description
get_cart Buyer Get current user's cart items
add_to_cart Buyer Add a product/variant to cart
update_cart_item Buyer Change quantity of a cart item
remove_from_cart Buyer Remove item from cart

❤️ Wishlist

Tool Auth Description
get_wishlist Buyer Get saved wishlist products
add_to_wishlist Buyer Save a product to wishlist
remove_from_wishlist Buyer Remove product from wishlist

⭐ Reviews & Q&A

Tool Auth Description
create_review Buyer Write a review for a product
update_review Buyer Edit an existing review
delete_review Buyer Delete your review
ask_question Buyer Ask a question on a product
get_seller_question Seller Get questions for your products
answer_question Seller Answer a buyer's question

📦 Orders & Payments

Tool Auth Description
list_orders Buyer Get order history
create_order Buyer Place a new order
list_payments Buyer Get payment history
create_payment Buyer Initiate a payment

📍 Addresses

Tool Auth Description
list_addresses Buyer Get saved delivery addresses
create_address Buyer Add a new delivery address
update_address Buyer Edit a saved address

🔐 Authentication

The MCP server uses a per-request JWT passthrough strategy — it never stores any user credentials.

React Frontend
  └─► includes "Authorization: Bearer <JWT>" header on every AI request
        │
        ▼
Django Proxy (/user/ai/)
  └─► forwards the token to MCP server
        │
        ▼
ecommerce_mcp (_resolve_token in client.py)
  └─► reads token from Authorization header
  └─► attaches it as Cookie: access=<token> when calling Django API
        │
        ▼
Django backend validates cookie → scopes response to request.user

Token priority order in client.py:

  1. Authorization: Bearer <token> header (production — sent by React chatbot)
  2. Cookie: access=<token> (direct browser WebSocket connections)
  3. API_TOKEN environment variable (local dev / CLI scripts only)

📁 Project Structure

ecommerce_mcp/
├── server.py          # FastMCP entry point — registers all tools
├── client.py          # Shared async httpx helpers, auth resolution, error handling
├── config.py          # Environment variable config (URL, timeout, token)
├── requirements.txt   # Python dependencies
├── Dockerfile         # Container definition
│
├── tools/
│   ├── products.py    # 11 product/category/brand tools
│   ├── cart.py        # 4 cart management tools
│   ├── wishlist.py    # 3 wishlist tools
│   ├── reviews.py     # 6 review + Q&A tools
│   ├── orders.py      # 4 order + payment tools
│   └── customers.py   # 3 address tools
│
└── claude_desktop_config.json  # Config for local Claude Desktop testing

🚀 Running Locally

Option 1 — Python directly

git clone https://github.com/jagadeesh-sagar/ecommerce_mcp
cd ecommerce_mcp

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

pip install -r requirements.txt

# Set env vars
export DJANGO_BASE_URL=http://localhost:8000/   # or https://api.chatram.in/
export API_TOKEN=your_jwt_token_here            # local dev only

python server.py
# Server runs at: http://localhost:8001/

Option 2 — Docker

docker build -t ecommerce_mcp .
docker run -p 8001:8001 \
  -e DJANGO_BASE_URL=https://api.chatram.in/ \
  -e API_TOKEN=your_jwt_token \
  ecommerce_mcp

Environment Variables

Variable Default Description
DJANGO_BASE_URL https://api.chatram.in/ Django backend URL
API_TOKEN (empty) JWT token — local dev only, empty in prod
REQUEST_TIMEOUT 20 HTTP request timeout in seconds

🖥️ Using with Claude Desktop (Local Testing)

Add to your claude_desktop_config.json (usually at ~/Library/Application Support/Claude/):

{
  "mcpServers": {
    "ecommerce": {
      "command": "/path/to/venv/bin/python",
      "args": ["/path/to/ecommerce_mcp/server.py"],
      "cwd": "/path/to/ecommerce_mcp",
      "env": {
        "DJANGO_BASE_URL": "http://localhost:8000/",
        "API_TOKEN": "your_jwt_token_here"
      }
    }
  }
}

Then restart Claude Desktop — you'll see all 30 tools available under the 🔨 hammer icon.


🐳 Production Deployment

The MCP server runs as a Docker container behind Nginx on the same EC2 instance as the Django backend.

docker-compose service:

mcp:
  image: jagadeesh20134/ecommerce_mcp:latest
  container_name: mcp_container
  expose:
    - "8001"
  environment:
    - DJANGO_BASE_URL=http://drf_app:8000/   # internal Docker network
    - API_TOKEN=                              # empty — auth from request headers
    - REQUEST_TIMEOUT=20
  depends_on:
    - drf_app
  networks:
    - ecommerce_network

Nginx proxies mcp.chatram.in → container port 8001.

Deploy / Update

# Build and push
docker build -t jagadeesh20134/ecommerce_mcp:latest .
docker push jagadeesh20134/ecommerce_mcp:latest

# On EC2
docker compose pull mcp
docker compose up -d mcp

⚙️ How Tools Are Built

Each tool is a plain Python async def function with typed parameters and a docstring. FastMCP automatically:

  • Generates the JSON schema from the type hints
  • Exposes the function as an MCP tool with the docstring as its description
  • Handles SSE streaming to the AI model

Example tool:

async def search_products(
    query: str,
    category: str | None = None,
    min_price: float | None = None,
    max_price: float | None = None,
) -> list:
    """Search products by name. Optionally filter by category or price range."""
    params = {"n": query}
    if category:   params["ct"] = category
    if min_price:  params["min_price"] = min_price
    if max_price:  params["max_price"] = max_price
    return await api_get("/user/products/", params=params, require_auth=False)

🔗 Related Projects


📬 Contact

Built by Jagadeesh Sagar
🌐 ecommerce.chatram.in

About

A Model Context Protocol (MCP) server that exposes the entire Chatram e-commerce backend as structured AI tools — powering the AI Shopping Assistant widget built into the storefront.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages