Claude Code & MCP MasterclassModule 3

3.3Capstone: Deploy Your Own AI Bot Empire

40 min 7 code blocks Practice Lab Quiz (4Q)

Capstone: Deploy Your Own AI Bot Empire

Your capstone: Build and deploy a complete AI bot system serving Pakistani businesses. This isn't a toy project — it's a production system with MCP servers, Claude intelligence, monetization, and real users. By the end, you'll have a deployed, revenue-generating bot that demonstrates everything you've learned.

Capstone Project: "Karachi Business Bot"

A WhatsApp/Discord bot that helps Karachi businesses with:

  • Business registration guidance (SECP, FBR, WEBOC)
  • Tax calculations (income tax slabs, GST, withholding)
  • Market analysis (competitor lookup, pricing intelligence)
  • Customer support templates (industry-specific response generation)
  • Document generation (basic invoices, quotations, contracts)

Architecture

code
USER (WhatsApp/Discord)
    │
    ▼
┌─────────────────────────────────┐
│  BOT SERVER (FastAPI)            │
│  Receives messages, routes to    │
│  Claude via MCP orchestrator     │
└───────────┬─────────────────────┘
            │
            ▼
┌─────────────────────────────────┐
│  MCP HUB (orchestrates 3 MCPs)   │
│                                   │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐
│  │Database   │ │ API MCP  │ │Template  │
│  │MCP        │ │          │ │MCP       │
│  │           │ │ FBR tax  │ │          │
│  │Business   │ │ SECP     │ │Response  │
│  │records,   │ │ market   │ │templates │
│  │user prefs │ │ data,    │ │invoices  │
│  │usage logs │ │ PKR/USD  │ │contracts │
│  └──────────┘ └──────────┘ └──────────┘
│                                   │
└───────────┬─────────────────────┘
            │
            ▼
┌─────────────────────────────────┐
│  CLAUDE SONNET (decision-making) │
│  Understands user intent,        │
│  calls appropriate MCP tools,    │
│  generates responses              │
└─────────────────────────────────┘

Implementation

Step 1: Build Your MCP Servers

Database MCP — stores business data, user preferences, and usage logs:

python
# mcps/database_mcp.py
from mcp.server import Server
from mcp.types import Tool
import sqlite3

server = Server("business-db")

@server.tool()
async def save_business(name: str, ntn: str, industry: str, city: str):
    """Save a business profile to the database."""
    conn = sqlite3.connect("businesses.db")
    conn.execute(
        "INSERT OR REPLACE INTO businesses (name, ntn, industry, city) VALUES (?, ?, ?, ?)",
        (name, ntn, industry, city)
    )
    conn.commit()
    return {"status": "saved", "business": name}

@server.tool()
async def get_business(ntn: str):
    """Retrieve a business profile by NTN number."""
    conn = sqlite3.connect("businesses.db")
    row = conn.execute("SELECT * FROM businesses WHERE ntn = ?", (ntn,)).fetchone()
    if row:
        return {"name": row[0], "ntn": row[1], "industry": row[2], "city": row[3]}
    return {"error": "Business not found"}

@server.tool()
async def log_usage(user_id: str, action: str, tier: str):
    """Log user actions for analytics and billing."""
    conn = sqlite3.connect("businesses.db")
    conn.execute(
        "INSERT INTO usage_log (user_id, action, tier, timestamp) VALUES (?, ?, ?, datetime('now'))",
        (user_id, action, tier)
    )
    conn.commit()
    return {"logged": True}

API MCP — connects to external services for tax and market data:

python
# mcps/api_mcp.py
@server.tool()
async def calculate_tax(annual_income: float, tax_year: int = 2026):
    """Calculate Pakistan income tax based on FBR slabs."""
    slabs = [
        (600000, 0),        # Up to 6 lakh: 0%
        (1200000, 0.025),   # 6-12 lakh: 2.5%
        (2400000, 0.125),   # 12-24 lakh: 12.5%
        (3600000, 0.225),   # 24-36 lakh: 22.5%
        (6000000, 0.275),   # 36-60 lakh: 27.5%
        (float('inf'), 0.35) # Above 60 lakh: 35%
    ]
    tax = 0
    remaining = annual_income
    prev_limit = 0
    for limit, rate in slabs:
        taxable = min(remaining, limit - prev_limit)
        tax += taxable * rate
        remaining -= taxable
        prev_limit = limit
        if remaining <= 0:
            break
    return {
        "annual_income": annual_income,
        "tax_amount": round(tax),
        "effective_rate": f"{(tax/annual_income)*100:.1f}%",
        "monthly_tax": round(tax / 12)
    }

@server.tool()
async def gst_calculator(amount: float, gst_rate: float = 0.17):
    """Calculate GST (17% standard rate in Pakistan)."""
    gst = amount * gst_rate
    return {
        "base_amount": amount,
        "gst_rate": f"{gst_rate*100}%",
        "gst_amount": round(gst),
        "total_with_gst": round(amount + gst)
    }

Template MCP — generates business documents:

python
# mcps/template_mcp.py
@server.tool()
async def generate_invoice(
    business_name: str, client_name: str,
    items: list, ntn: str
):
    """Generate a professional invoice with Pakistani tax compliance."""
    subtotal = sum(item["amount"] for item in items)
    gst = subtotal * 0.17
    total = subtotal + gst

    invoice = f"""
    ╔══════════════════════════════════════╗
    ║           TAX INVOICE                 ║
    ╠══════════════════════════════════════╣
    ║ From: {business_name}                ║
    ║ NTN:  {ntn}                          ║
    ║ To:   {client_name}                  ║
    ║ Date: {datetime.now().strftime('%d-%m-%Y')}    ║
    ╠══════════════════════════════════════╣"""

    for item in items:
        invoice += f"\n    ║ {item['description']:<25} PKR {item['amount']:>8,} ║"

    invoice += f"""
    ╠══════════════════════════════════════╣
    ║ Subtotal:                 PKR {subtotal:>8,} ║
    ║ GST (17%):                PKR {gst:>8,.0f} ║
    ║ TOTAL:                    PKR {total:>8,.0f} ║
    ╚══════════════════════════════════════╝"""

    return {"invoice_text": invoice, "total": total}

Step 2: Bot Integration (Discord)

python
# bot.py
import discord
import anthropic
import json

client = discord.Client(intents=discord.Intents.default())
claude = anthropic.Anthropic()

SYSTEM_PROMPT = """You are the Karachi Business Bot — an AI assistant
helping Pakistani businesses with registration, tax, market analysis,
and document generation.

You have access to these tools:
- save_business: Store business details
- get_business: Look up business by NTN
- calculate_tax: Pakistan income tax calculation
- gst_calculator: GST calculation
- generate_invoice: Create tax-compliant invoices
- log_usage: Track user actions

Always respond in a professional but friendly tone.
Use PKR for all amounts. Reference Pakistani laws and regulations.
If unsure about tax law, recommend consulting a registered tax advisor."""

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    user_query = message.content
    user_id = str(message.author.id)

    # Determine tier (check database for subscription)
    tier = await check_user_tier(user_id)

    if tier == "free" and await daily_limit_reached(user_id):
        await message.reply(
            "You've reached your free tier limit (10 queries/day). "
            "Upgrade to Pro for unlimited access: PKR 1,500/month"
        )
        return

    # Query Claude with MCP tools
    response = claude.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1000,
        system=SYSTEM_PROMPT,
        tools=get_mcp_tools(),  # Load tool definitions from MCP servers
        messages=[{"role": "user", "content": user_query}]
    )

    # Handle tool use if Claude wants to call an MCP
    if response.stop_reason == "tool_use":
        tool_result = await execute_mcp_tool(response)
        # Send tool result back to Claude for final response
        final = claude.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=1000,
            system=SYSTEM_PROMPT,
            messages=[
                {"role": "user", "content": user_query},
                {"role": "assistant", "content": response.content},
                {"role": "user", "content": [{"type": "tool_result", **tool_result}]}
            ]
        )
        await message.reply(final.content[0].text)
    else:
        await message.reply(response.content[0].text)

    # Log usage
    await log_usage(user_id, "query", tier)

client.run(DISCORD_TOKEN)

Step 3: Deploy to Production

code
DEPLOYMENT ARCHITECTURE:

┌─────────────────────┐
│ Railway/Render       │ ← Bot server ($5/month)
│ Python + Discord.py  │
└──────────┬──────────┘
           │
┌──────────┴──────────┐
│ MCP Servers          │ ← Same server or separate
│ (3 processes)        │    (PM2 manages all)
└──────────┬──────────┘
           │
┌──────────┴──────────┐
│ PostgreSQL           │ ← Supabase free tier or
│ (Vercel Postgres)    │    Railway PostgreSQL
└─────────────────────┘

DEPLOYMENT STEPS:

1. Push code to GitHub (never commit .env)
2. Create Railway project → connect GitHub repo
3. Set environment variables:
   DISCORD_TOKEN=...
   ANTHROPIC_API_KEY=sk-ant-...
   DATABASE_URL=postgresql://...
4. Configure build: pip install -r requirements.txt
5. Configure start: python bot.py
6. Enable auto-deploy on push
7. Set up health check endpoint (/health)
8. Configure Sentry for error tracking
9. Set up UptimeRobot for uptime monitoring ($0)
10. Test with 10 real queries from your phone

Monetization Model

code
FREE TIER:
├── 10 queries/day
├── Basic tax calculations
├── Simple business guidance
├── Target: 100,000 users (brand awareness)
└── Cost to serve: ~$0.001/query × 10 × 100K = $1,000/month

PRO TIER (PKR 1,500/month or $5/month):
├── Unlimited queries
├── Invoice generation
├── Market analysis reports
├── Priority response
├── Target: 1,000 paying users
└── Revenue: $5,000/month

BUSINESS TIER (PKR 15,000/month or $50/month):
├── Everything in Pro
├── Custom document templates
├── Dedicated support channel
├── API access for integration
├── White-label option
├── Target: 100 businesses
└── Revenue: $5,000/month

═══════════════════════════════════════════════
TOTAL POTENTIAL: $10,000/month (PKR 2.8M/month)
INFRASTRUCTURE COST: ~$100-200/month + Claude API
MARGIN: 95%+
═══════════════════════════════════════════════

Deployment Checklist

#ItemStatusNotes
1Code pushed to GitHubNever commit .env or API keys
2.env.example createdDocument all required variables
3Database migrations testedRun on fresh DB to verify
4Unit tests writtenTarget 80%+ coverage on MCP tools
5Error logging (Sentry)Catch Claude API errors, DB failures
6Monitoring (UptimeRobot)Alert if bot goes offline
7Rate limitingPer-user daily limits by tier
8Rollback planCan revert to previous deploy in <5 min
9SLA defined99% uptime target for paid users
10Documentation writtenREADME: setup, architecture, MCP tools
Practice Lab

Practice Lab

Task 1: Bot Design Design your own bot serving Pakistani businesses. Document: (1) Target users and their pain point, (2) Core features (5+), (3) Which MCP servers you need, (4) Revenue model (free/pro/business tiers with PKR pricing), (5) Growth strategy for first 100 users.

Task 2: Build & Deploy Implement your bot end-to-end: (1) Build at least 2 MCP servers with 3+ tools each, (2) Create Discord or WhatsApp integration, (3) Deploy to Railway or Render, (4) Test with 10 real queries, (5) Document the entire setup in a README.

Task 3: Growth Experiment Post your bot in 3 Pakistani business Facebook groups or Discord servers. Track: users in first 48 hours, most common queries, error rate, and feedback. Write a 1-page report analyzing what worked and what needs improvement.

Pakistan Case Study

Meet Zohaib — CS grad from FAST Lahore, built a "Lahore Startup Mentor Bot" as his capstone.

The concept: A Discord bot helping Lahore startup founders with funding guidance, hiring help, tech stack advice, and founder networking.

His MCP architecture:

  • Database MCP: Founder profiles, startup details, interaction history
  • API MCP: VC database lookup, salary benchmarks (Rozee.pk data), tech stack comparisons
  • Template MCP: Pitch deck outlines, one-pager generators, job posting templates

Development timeline:

  • Week 1: Built 3 MCP servers, tested all tools individually
  • Week 2: Built Discord bot + Claude integration, connected MCP tools
  • Week 3: Deployed to Railway, set up Sentry + UptimeRobot, launched in 3 Lahore startup groups

Growth trajectory:

  • Month 1: 500 founders signed up (free tier)
  • 50 converted to Pro (PKR 2,000/month) = PKR 100,000/month
  • Most popular feature: salary benchmark tool ("kitni salary doon developer ko?")
  • Unexpected hit: pitch deck outline generator (founders loved it)

Month 6 numbers:

  • Total users: 3,200 (20% monthly growth)
  • Pro subscribers: 280 = PKR 560,000/month
  • Business subscribers: 15 = PKR 225,000/month (PKR 15,000/month each)
  • Total revenue: PKR 785,000/month
  • Infrastructure cost: PKR 28,000/month (Railway + Claude API + Supabase)
  • Net profit: PKR 757,000/month

Team: Still just Zohaib. Claude handles 95% of queries. He spends 2 hours/day on customer feedback and feature improvements.

His key insight: "MCP servers are the secret weapon — they let Claude access REAL data instead of making things up. When a founder asks 'What's the average developer salary in Lahore?', my bot pulls from actual Rozee.pk data through the API MCP. That's why founders trust it — it's not hallucinating, it's looking up facts. Claude Code built the whole thing in 3 weeks. Ab mera bot mere liye kama raha hai."

Key Takeaways

  • The capstone combines everything: Claude Code (development), MCP (data access), multi-agent patterns (orchestration), and SaaS principles (monetization)
  • Three MCP servers cover most business bots: Database (storage), API (external data), Template (document generation)
  • Start with Discord (easier to build) before WhatsApp (needs WATI/business API)
  • Free tier acquires users, Pro tier generates revenue — the conversion funnel is your growth engine
  • Deploy on Railway/Render ($5/month) with Sentry (error tracking) and UptimeRobot (monitoring) — production-grade for under $20/month
  • Pakistani business bot niches are underserved: tax guidance, registration help, salary benchmarks, document generation
  • A single developer with Claude Code + MCP can build, deploy, and monetize a bot generating PKR 500K+/month
  • The bot works 24/7 — you build it once, it serves thousands while you sleep

Congratulations! You've completed the Claude Code & MCP course. You now have the skills to build AI-powered products that Pakistani businesses will pay for. The tools are free, the market is hungry, and you have the knowledge. Go build your empire.

Lesson Summary

Includes hands-on practice lab7 runnable code examples4-question knowledge check below

Capstone: Deploy Your Own AI Bot Empire Quiz

4 questions to test your understanding. Score 60% or higher to pass.