Claude Code & MCP MasterclassModule 1

1.2Advanced CLI — Hooks, Memory, CLAUDE.md & Permission Modes

35 min 13 code blocks Practice Lab Quiz (4Q)

Advanced CLI — Hooks, Memory, CLAUDE.md

Claude Code's power lies in project-level memory and hooks. This lesson teaches you to leverage these features to build AI agents that retain context across sessions, store institutional knowledge, and automate complex workflows.

CLAUDE.md: Your AI's Brain

CLAUDE.md is a markdown file that tells Claude everything it needs to know about your project. Claude reads it before every command. Think of it as your AI engineer's project brief.

Structure:

markdown
# Project Name

## Purpose
Clear one-sentence description of what this project does.

## Key Files
- main.py: Entry point
- modules/llm.py: Claude integration
- tests/test_main.py: Unit tests

## Architecture
[Diagram or prose explanation]

## Important Rules
- All API keys from .env
- Use error handling for external APIs
- Log all decisions to /logs directory

## Current Status
[What's done, what's in progress]

## Known Issues
[Bugs, limitations, tech debt]

## Recent Changes
[Last 3-5 changes made]

Claude learns from your CLAUDE.md. Every claude run or claude code command references it. Example:

Your CLAUDE.md says: "This is a trading bot. Never commit secrets. Always validate API responses."

You run: claude code "Add a new trading signal"

Claude generates code that:

  1. Doesn't hardcode secrets
  2. Validates API responses
  3. Logs trades to /logs

Without CLAUDE.md, Claude might not follow these rules. With CLAUDE.md, it's automatic.

Pro tip: Keep CLAUDE.md updated. Add "Current Status" section. Every time you make progress, update it. Claude sees this and understands project momentum. Result: Better suggestions, faster code generation.

Project Memory: Persistent Context

Claude Code stores project memory in .claude/memory/. This memory persists across sessions (unlike chat, which resets).

Add memory:

bash
claude memory add "Pakistani users prefer PKR pricing. Diaspora users prefer USD."

View memory:

bash
claude memory show

Output:

code
Project Memory:
- Pakistani users prefer PKR pricing. Diaspora users prefer USD.

Use case: You're building a SaaS with Pakistani and diaspora customers. Save this to memory once. All future AI-assisted development respects this rule.

Advanced memory management:

bash
# Add tagged memory
claude memory add --tag "pricing" "Pakistani tier: PKR 3,000/month. US tier: USD 29/month."

# Add multi-line memory
claude memory add << EOF
API Response Format:
- Always include "status" field
- Nested errors in "error" object
- Timestamp in ISO8601 format
EOF

# View specific tag
claude memory show --tag "pricing"

# Clear memory
claude memory clear

Smart developers treat memory like documentation. Add to memory:

  1. Business rules ("Users must verify email before accessing premium features")
  2. Tech decisions ("We use PostgreSQL, not MongoDB")
  3. Code conventions ("All async functions use async/await, not .then()")
  4. Pakistan context ("SMS costs PKR 0.50 per message via Jazz, Rs 1.00 via Zong")

Result: Claude makes decisions aligned with your project's culture and constraints.

Hooks: Automate Your Workflow

Hooks are scripts that run at specific moments: before code generation, after file changes, before commit, etc.

Create a pre-generation hook:

Create file: .claude/hooks/pre-generation.sh

bash
#!/bin/bash
# Run linter before Claude generates code
echo "Running linter..."
python -m pylint --disable=all --enable=E main.py
if [ $? -ne 0 ]; then
    echo "ERROR: Linting failed. Fix before generating code."
    exit 1
fi
echo "Linter passed. Proceeding..."

Make executable:

bash
chmod +x .claude/hooks/pre-generation.sh

Now, every claude code command runs linting first. If linting fails, Claude doesn't generate code. This prevents garbage code.

Post-generation hook (auto-test):

.claude/hooks/post-generation.sh

bash
#!/bin/bash
# Auto-run tests after code generation
echo "Running tests..."
python -m pytest tests/
if [ $? -eq 0 ]; then
    echo "✓ All tests passed!"
else
    echo "✗ Tests failed. Review generated code."
fi

Pre-commit hook:

.claude/hooks/pre-commit.sh

bash
#!/bin/bash
# Check no secrets are committed
if grep -r "ANTHROPIC_API_KEY\|DATABASE_PASSWORD" . --include="*.py"; then
    echo "ERROR: Secrets found in code. Remove before committing."
    exit 1
fi
echo "✓ No secrets detected."

Multi-Session Memory

Pakistan's internet is unreliable. You might lose connection mid-session. Claude Code's memory saves your progress:

Session 1 (Day 1):

bash
claude run "Create database schema for e-commerce platform"
claude memory add "Schema: users, products, orders, payments tables created"

Connection drops. You come back next day.

Session 2 (Day 2):

bash
claude memory show
# Shows: "Schema: users, products, orders, payments tables created"

claude run "Generate CRUD endpoints for the API"

Claude knows the database schema (from memory), generates correct API endpoints.

Advanced CLAUDE.md: The Institutional Knowledge Engine

Treat CLAUDE.md as your project's Wikipedia. Include:

markdown
# AI Freelance Platform

## Business Model
- Platform fee: 20% (retained)
- Freelancer payout: 80% (within 7 days)
- Currency: PKR for Pakistan, USD for diaspora
- Dispute resolution: 14-day window

## Technical Constraints
- PostgreSQL (not MongoDB)
- async/await (not callbacks)
- Stripe API for payments (fallback: JazzCash)
- 99.9% uptime SLA required

## Pakistan-Specific Rules
- SMS verification via Jazz/Zong (cheaper than international)
- WhatsApp for customer support (higher engagement than email)
- Urdu copy for 80% of users
- Local payment methods: EasyPaisa, HBL, UBL

## Known Issues
- SMS delivery 5-10 min delays during peak hours
- Stripe doesn't support PKR directly (convert via API)
- Urdu text sometimes breaks on iOS 14 (known iOS bug)

## Decisions Log
- Decision 1: Use Prisma ORM (chosen over SQLAlchemy for type safety)
- Decision 2: Queue jobs via Bull (chosen over Celery for Node compatibility)

Claude reads all this. When you ask claude code "Add payment endpoint", it:

  1. Uses PostgreSQL (not MongoDB)
  2. Handles both PKR and USD
  3. Falls back to JazzCash if Stripe fails
  4. Adds appropriate logging for SMS delays

Without CLAUDE.md, you'd need to explain these constraints every time. With it, Claude knows.

Practice Lab

Practice Lab

Task 1: Create CLAUDE.md — Build CLAUDE.md for your project. Include: Purpose, Key Files, Architecture, Rules, Status, Known Issues. Make it 2+ pages. Share it as project documentation.

Task 2: Add Memory & Hooks — Add 5 pieces of memory using claude memory add. Create 2 hooks (pre-generation, post-generation). Test both: Run claude code and verify hooks execute.

Pakistan Example: "Karachi Marketplace Bot"

A freelancer building a Karachi-specific marketplace (like Fiverr but for Pakistan) created comprehensive CLAUDE.md:

markdown
# Karachi Marketplace Bot

## Purpose
Connect Karachi service providers with customers locally.

## Business Rules
- Freelancers: PKR 500-50,000 per project
- Platform fee: 15% (lower than global platforms to incentivize locals)
- Payment: JazzCash or direct bank transfer
- Dispute window: 21 days (Pakistani business standard)

## Tech Stack
- Next.js (frontend), FastAPI (backend)
- PostgreSQL + Redis
- Stripe (for international customers), JazzCash API (for local)

## Pakistan Rules
- All prices in PKR
- WhatsApp messaging (not in-app chat, low adoption)
- SMS notifications via Jazz/Zong
- Require CNIC verification (fraud prevention)

## Lessons Learned
- SMS delivery fails 2% of time (buffer with WhatsApp)
- Most users don't use email (use SMS instead)
- Payment delays 1-3 days (set expectations)

Developer added 5 memories:

  1. "JazzCash integration: Requires merchant account, 3% fee"
  2. "CNIC verification: Use NADRA API when available, fallback to manual"
  3. "Dispute resolution: 80% disputes are work quality, not payment issues"
  4. "User behavior: 60% access via mobile, optimize for small screens"
  5. "Growth: Referral bonus (PKR 500 per successful project) drives acquisition"

When Claude generated code:

  • It auto-configured JazzCash payment
  • Built CNIC verification flow
  • Optimized UI for mobile
  • Added referral bonus logic

Without memory and CLAUDE.md, each code generation would need manual specification.

Result: 60% faster development, fewer bugs, better product-market fit.

Lesson Summary

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

Advanced CLI — Hooks, Memory, CLAUDE.md Quiz

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