# MCP Skills Library

This directory contains **reusable skills** - specialized instructions and workflows that Claude can load on-demand to perform tasks with expert-level quality.

## What are Skills?

Skills are documents (SKILL.md files) containing:

- **Instructions:** How to perform specific tasks
- **Patterns:** Proven approaches and templates
- **Code:** Helper scripts that work reliably
- **Context:** Domain knowledge and constraints

Skills provide **dynamic context loading** - Claude loads specialized guidance exactly when needed, without permanent context overhead.

## Benefits

- **Expert-level output:** Skills encode institutional knowledge and best practices
- **Token efficiency:** Progressive disclosure minimizes context window usage
- **Consistency:** Use the same proven approach every time
- **Reliability:** Pre-tested scripts reduce errors
- **Composability:** Multiple skills work together seamlessly
- **Token savings:** 10,000-30,000+ tokens per skill execution

## Implemented Skills (25 Skills)

### Token Optimization Skills (2 Skills)

These advanced skills provide massive context windows and extreme token savings for research and data processing:

#### 1. gemini-cli-assistant/SKILL.md

Use Gemini CLI for large-scale codebase analysis with massive 2M token context window.

**Location:** `.claude/mcp/skills/gemini-cli-assistant/SKILL.md`

**Key Features:**

- 2M token context (gemini-2.5-pro) vs Claude's 200K
- 80-90% token savings for large-scale analysis
- Load entire codebases with @ file syntax
- Six specialized brainstorming methodologies
- Security audits across 84+ API routes
- Repository-wide pattern detection
- Architectural analysis and planning

**When to Use:**

- Analyzing 50+ files or entire directories
- Security audits across all API routes
- Finding patterns, inconsistencies, vulnerabilities project-wide
- Architecture planning and design decisions
- Repository-wide refactoring research
- Translation gap analysis across 70+ pages
- Test coverage analysis and gap identification
- Database migration planning
- Performance bottleneck detection across services

**Token Savings:** 80,000-150,000+ tokens per analysis

**Golden Rule:** Gemini = Research & Analysis (READ-HEAVY) | Claude = Implementation & Execution (WRITE-HEAVY)

#### 2. codex-mcp-assistant/SKILL.md

Master guide for Claude Code's MCP ecosystem with 8 servers, 67+ tools, and 23 skills.

**Location:** `.claude/mcp/skills/codex-mcp-assistant/SKILL.md`

**Key Features:**

- 8 MCP servers (database, testing, files, api, stripe, email, commands, i18n)
- 67+ specialized tools
- 98%+ token reduction on common operations
- Progressive discovery patterns
- Workspace for intermediate results
- Multi-step workflow automation

**When to Use:**

- Large dataset operations (100+ records)
- Testing workflows (unit, E2E, coverage)
- Database queries (Prisma/Supabase)
- Analytics and aggregations
- Multi-step operations (3+ sequential steps)
- Progressive discovery (exploring codebase)
- File system operations

**Token Savings:** 50,000-100,000+ tokens per operation

**Examples:**

- Check pending bookings: 137,000 → 1,050 tokens (99.2% reduction)
- Run unit tests: 120,000 → 1,250 tokens (99.0% reduction)
- Analyze revenue: 150,000 → 1,200 tokens (99.2% reduction)
- Search files: 45,000 → 2,000 tokens (95.6% reduction)

---

### NEW: SKILL.md Format Skills (12 Skills)

These skills follow the new SKILL.md format with YAML frontmatter for better triggering:

#### 1. frontend-design/SKILL.md ⭐ NEW

Create distinctive, production-grade frontend interfaces that avoid "AI slop" aesthetics.

**Location:** `.claude/mcp/skills/frontend-design/SKILL.md`

**Key Features:**

- Typography guidelines (avoid Inter/Roboto, use distinctive fonts)
- Color & theme patterns (dominant + accent, avoid purple gradients)
- Motion & animation (staggered reveals, micro-interactions)
- Background treatment (gradients, grids, atmosphere)
- AI slop avoidance checklist

#### 2. frontend-artifact-builder/SKILL.md ⭐ NEW

Build elaborate multi-component React artifacts with shadcn/ui.

**Location:** `.claude/mcp/skills/frontend-artifact-builder/SKILL.md`

**Key Features:**

- React 18 + TypeScript + Tailwind + shadcn/ui
- 40+ pre-installed components
- Single HTML bundle output
- Design guidelines integration

#### 3. brand-guidelines/SKILL.md ⭐ NEW

Apply Mawidi's official brand identity consistently.

**Location:** `.claude/mcp/skills/brand-guidelines/SKILL.md`

**Key Features:**

- Mawidi color palette (green, ink, sand)
- Typography (Plus Jakarta Sans, Inter, IBM Plex Sans Arabic)
- RTL/LTR support patterns
- Component styling guides

#### 4. api-development/SKILL.md ⭐ NEW

Create production-grade API endpoints with all best practices.

**Location:** `.claude/mcp/skills/api-development/SKILL.md`

**Key Features:**

- Authentication patterns (NextAuth, Staff, API Key)
- Zod validation schemas
- Rate limiting configuration
- Error handling patterns
- Test generation templates

#### 5. i18n-management/SKILL.md

Manage Arabic/English translations and RTL/LTR support.

**Location:** `.claude/mcp/skills/i18n-management/SKILL.md`

**Key Features:**

- Translation key management
- RTL/LTR direction handling
- Bilingual validation
- Translation gap detection

#### 6. email-composer/SKILL.md

Professional email drafts and templates.

**Location:** `.claude/mcp/skills/email-composer/SKILL.md`

**Key Features:**

- Bilingual email templates
- Professional formatting
- OTP email patterns
- Transactional email best practices

#### 7. database-migration/SKILL.md

Safe Prisma + Supabase schema changes.

**Location:** `.claude/mcp/skills/database-migration/SKILL.md`

**Key Features:**

- Dual-database migration patterns
- Schema validation
- Rollback procedures
- Data integrity checks

#### 8. testing-patterns/SKILL.md

Unit, integration, E2E test templates.

**Location:** `.claude/mcp/skills/testing-patterns/SKILL.md`

**Key Features:**

- Jest test patterns
- E2E test workflows
- Coverage thresholds
- Test organization

#### 9. seo-optimization/SKILL.md

Meta tags, structured data, SEO best practices.

**Location:** `.claude/mcp/skills/seo-optimization/SKILL.md`

**Key Features:**

- Meta tag patterns
- OpenGraph integration
- Structured data schemas
- SEO checklist

#### 10. error-handling/SKILL.md

Consistent error patterns across the application.

**Location:** `.claude/mcp/skills/error-handling/SKILL.md`

**Key Features:**

- Error class hierarchies
- Error boundary patterns
- API error responses
- Logging integration

#### 11. onboarding-ux/SKILL.md

Signup flows & user activation patterns.

**Location:** `.claude/mcp/skills/onboarding-ux/SKILL.md`

**Key Features:**

- Multi-step onboarding
- User activation flows
- Welcome email sequences
- First-time user experience

#### 12. staff-dashboard/SKILL.md

Data-rich clinic dashboards for admin users.

**Location:** `.claude/mcp/skills/staff-dashboard/SKILL.md`

**Key Features:**

- Admin dashboard patterns
- Data visualization
- Metrics and analytics
- Staff-only features

---

### TypeScript Skills (11 Skills)

### 1. dual-database-save.ts

Save data to both Prisma and Supabase databases automatically.

**Token Savings:** 10,000+ tokens (complex multi-step operation)

**Example Usage:**

```typescript
import { saveToBothDatabases } from "./.claude/mcp/skills/dual-database-save";

await saveToBothDatabases("users", {
  email: "user@example.com",
  name: "John Doe",
  companyName: "Acme Corp",
});
```

### 2. send-bilingual-email.ts

Send email in both Arabic and English based on user preference.

**Token Savings:** 8,000+ tokens (template rendering + dual send)

**Example Usage:**

```typescript
import { sendBilingualEmail } from "./.claude/mcp/skills/send-bilingual-email";

await sendBilingualEmail({
  to: "user@example.com",
  template: "welcome",
  language: "ar",
  data: { name: "أحمد" },
});
```

### 3. create-api-endpoint.ts

Create a new API endpoint following Mawidi's standard patterns.

**Token Savings:** 15,000+ tokens (scaffolding + validation + docs)

**Example Usage:**

```typescript
import { createAPIEndpoint } from "./.claude/mcp/skills/create-api-endpoint";

await createAPIEndpoint({
  path: "api/bookings/cancel",
  method: "POST",
  auth: true,
  rateLimit: { requests: 10, window: "15m" },
  validation: { bookingId: "string" },
});
```

### 4. add-translation.ts

Add a translation key to all language files.

**Token Savings:** 12,000+ tokens (multiple file operations)

**Example Usage:**

```typescript
import { addTranslation } from "./.claude/mcp/skills/add-translation";

await addTranslation({
  key: "booking.cancelSuccess",
  values: {
    ar: "تم إلغاء الحجز بنجاح",
    en: "Booking cancelled successfully",
  },
});
```

### 5. run-full-test-suite.ts

Run all tests (unit + E2E) and generate comprehensive report.

**Token Savings:** 25,000+ tokens (multiple test runs + parsing)

**Example Usage:**

```typescript
import { runFullTestSuite } from "./.claude/mcp/skills/run-full-test-suite";

const report = await runFullTestSuite();
console.log(
  `Tests: ${report.unitTests.passed}/${report.unitTests.total} passed`,
);
console.log(`Coverage: ${report.coverage.lines}% lines`);
console.log(`E2E: ${report.e2eTests.passed}/${report.e2eTests.total} passed`);
```

### 6. stripe-checkout-flow.ts

Create standard Stripe checkout session with Mawidi patterns.

**Token Savings:** 10,000+ tokens (Stripe setup + webhook + db save)

**Example Usage:**

```typescript
import { createStripeCheckout } from "./.claude/mcp/skills/stripe-checkout-flow";

const session = await createStripeCheckout({
  priceId: "price_xxx",
  userId: "user_123",
  successUrl: "/success",
  cancelUrl: "/cancel",
});
```

### 7. analyze-performance.ts

Analyze application performance metrics and identify bottlenecks.

**Example Usage:**

```typescript
import { analyzePerformance } from "./.claude/mcp/skills/analyze-performance";

const analysis = await analyzePerformance();
console.log("Slowest endpoints:", analysis.slowestAPIs);
console.log("Database query times:", analysis.dbPerformance);
```

### 8. generate-api-docs.ts

Generate OpenAPI documentation for all API routes.

**Token Savings:** 18,000+ tokens (route discovery + parsing)

**Example Usage:**

```typescript
import { generateAPIDocs } from "./.claude/mcp/skills/generate-api-docs";

const docs = await generateAPIDocs("docs/api-reference.json");
console.log(`Documented ${docs.routesDocumented} API routes`);
```

### 9. security-audit.ts

Run comprehensive security audit checking for vulnerabilities.

**Token Savings:** 20,000+ tokens (multiple scans + analysis)

**Example Usage:**

```typescript
import { runSecurityAudit } from "./.claude/mcp/skills/security-audit";

const audit = await runSecurityAudit();
console.log(`Security Score: ${audit.overall.score}/100`);
console.log(`Vulnerabilities: ${audit.overall.vulnerabilities}`);

if (audit.findings.length > 0) {
  console.log(
    "Critical issues:",
    audit.findings.filter((f) => f.severity === "critical"),
  );
}
```

### 10. deploy-checklist.ts

Pre-deployment validation checklist with go/no-go decision.

**Token Savings:** 30,000+ tokens (comprehensive validation)

**Example Usage:**

```typescript
import { runDeployChecklist } from "./.claude/mcp/skills/deploy-checklist";

const checklist = await runDeployChecklist();
console.log(`Ready to deploy: ${checklist.readyToDeploy ? "YES" : "NO"}`);
console.log(`Score: ${checklist.score}/100`);

if (checklist.blockers.length > 0) {
  console.log("Blockers:", checklist.blockers);
}
```

### 11. frontend-artifact-builder.ts

Create elaborate multi-component HTML artifacts using React + Tailwind + shadcn/ui.

**Token Savings:** 15,000+ tokens (setup + bundling automation)

**Stack:** React 18 + TypeScript + Vite + Parcel + Tailwind CSS + shadcn/ui (40+ components)

**Design Guidelines (Avoid AI Slop!):**

- ❌ NO: Centered layouts, purple gradients, Inter/Roboto fonts, uniform corners
- ✅ YES: Distinctive fonts, sharp accents, meaningful animations, atmosphere

**Example Usage:**

```typescript
import {
  buildFrontendArtifact,
  getDesignGuidelines,
} from "./.claude/mcp/skills/frontend-artifact-builder";

// Get design guidelines first
const guidelines = getDesignGuidelines();
console.log("Fonts to try:", guidelines.fontSuggestions);

// Build artifact
const artifact = await buildFrontendArtifact({
  projectName: "analytics-dashboard",
  components: ["Card", "Tabs", "Table", "Button", "Chart"],
});

// Follow next steps
console.log(artifact.nextSteps);
// 1. cd analytics-dashboard
// 2. Edit src/App.tsx
// 3. bash scripts/bundle-artifact.sh
// 4. Share bundle.html as artifact
```

**Quick Start:**

```bash
# 1. Initialize
bash scripts/init-artifact.sh my-project
cd my-project

# 2. Develop (edit src/App.tsx)

# 3. Bundle
bash scripts/bundle-artifact.sh

# 4. Share bundle.html
```

**shadcn/ui Reference:** https://ui.shadcn.com/docs/components

## Quick Reference

| Skill                     | Token Savings   | Primary Use Case                                    |
| ------------------------- | --------------- | --------------------------------------------------- |
| gemini-cli-assistant      | 80,000-150,000+ | Large-scale codebase analysis with 2M token context |
| codex-mcp-assistant       | 50,000-100,000+ | Local data processing with 8 MCP servers            |
| dual-database-save        | 10,000+         | Data consistency across Prisma + Supabase           |
| send-bilingual-email      | 8,000+          | Sending emails in Arabic/English                    |
| add-translation           | 12,000+         | Adding UI text to all language files                |
| run-full-test-suite       | 25,000+         | Pre-deployment test validation                      |
| stripe-checkout-flow      | 10,000+         | Standard Stripe payment flow                        |
| analyze-performance       | 15,000+         | Performance bottleneck detection                    |
| create-api-endpoint       | 15,000+         | Scaffolding new APIs with best practices            |
| frontend-artifact-builder | 15,000+         | React + shadcn/ui artifact creation                 |
| generate-api-docs         | 18,000+         | OpenAPI documentation generation                    |
| security-audit            | 20,000+         | Security vulnerability scanning                     |
| deploy-checklist          | 30,000+         | Pre-deployment validation                           |

**Total: 25 Skills | Average Savings: 20,000+ tokens per skill**

## Creating a New Skill

### The SKILL.md Format

Skills use a markdown file with YAML frontmatter:

```markdown
---
name: my-skill-name
description: A detailed description that tells Claude WHEN to trigger this skill. Include action verbs, specific scenarios, and clear use cases. This is the most critical field.
---

# My Skill Name

## Overview

Brief description of what the skill does and why it's valuable.

## When to Use

- Specific scenario 1
- Specific scenario 2
- NOT for: scenarios where this doesn't apply

## Instructions

Step-by-step guidance for executing the skill.

## Examples

Concrete examples showing correct usage.

## Limitations

What this skill cannot do.
```

### Step 1: Identify the Need

Find a task you perform repeatedly that:

- Uses multiple tools or steps
- Has a consistent workflow
- Benefits from expert guidance
- Would save tokens if codified

**Good candidates:**

- "Extract financial data from PDFs and format as CSV"
- "Create API endpoint with auth, validation, rate limiting"
- "Build distinctive frontend avoiding AI slop aesthetics"

**Bad candidates:**

- "Help with my finance stuff" (too vague)
- "Add comment to function" (too simple)

### Step 2: Write the Description (CRITICAL)

The description determines when your skill activates. It's the most important field.

**Weak description:**

```
description: Helps with documents and PDFs
```

**Strong description:**

```
description: Extract text and tables from PDF documents, convert to structured CSV format, and handle OCR for scanned pages. Use when processing PDF financial statements, invoices, or reports for data analysis. Not for simple PDF viewing or basic conversions.
```

**Description checklist:**

- [ ] Specific verbs (extract, create, analyze, build)
- [ ] Concrete file types or domains
- [ ] Clear use cases
- [ ] Explicit boundaries (what it's NOT for)

### Step 3: Create the Skill Directory

```bash
mkdir -p .claude/mcp/skills/my-skill
```

Create `SKILL.md` with proper structure:

````markdown
---
name: my-skill
description: [Strong description following guidelines above]
---

# My Skill

## Overview

[What it does, why it matters, token savings estimate]

## When to Use

Use this skill when:

- [Specific scenario 1]
- [Specific scenario 2]

NOT for:

- [What this skill doesn't handle]

## Workflow

1. [First step]
2. [Second step]
3. [Third step]

## Examples

### Example 1: [Scenario Name]

```[language]
[Concrete code or usage example]
```
````

### Example 2: [Another Scenario]

```[language]
[Another example]
```

## Reference

[Additional context, links, helper scripts]

## Limitations

- [What the skill cannot do]
- [Edge cases to be aware of]

```

### Step 4: Add Supporting Files (Optional)

For complex skills, add helper scripts:

```

.claude/mcp/skills/my-skill/
├── SKILL.md # Main skill file
├── helper.ts # TypeScript helper
├── templates/ # Template files
└── examples/ # Example outputs

```

### Step 5: Test the Skill

Test with realistic scenarios:

**Normal operations:**
- Test typical requests the skill should handle

**Edge cases:**
- Test incomplete or unusual inputs
- Verify graceful degradation

**Out-of-scope:**
- Test requests that seem related but shouldn't trigger
- Verify skill stays dormant appropriately

### Step 6: Document and Share

Update [SKILLS_INDEX.md](./SKILLS_INDEX.md) with:
- Skill name and purpose
- Trigger phrases
- Token savings estimate

## Skills Best Practices

### 1. Description Field is Critical
The description determines when skills trigger. Write it from Claude's perspective with specific verbs, concrete use cases, and clear boundaries. Avoid vague keywords.

### 2. Progressive Disclosure Architecture
Structure skills in three tiers:
- **Tier 1 (Always loaded):** Name + description (~100 tokens)
- **Tier 2 (On activation):** Full SKILL.md instructions (~2-5k tokens)
- **Tier 3 (On demand):** Reference files loaded only if needed

### 3. Single Responsibility
Each skill should do one thing well. "Create API endpoint with auth and tests" is good. "Help with backend stuff" is too broad.

### 4. Right-Altitude Prompting
Avoid two extremes:
- ❌ **Too specific:** "Use hex #10B981 for buttons" (too rigid)
- ❌ **Too vague:** "Make it look nice" (assumes shared context)
- ✅ **Just right:** "Use Mawidi green for primary actions" (clear intent, flexible execution)

### 5. Concrete Examples
Include working code examples, not just descriptions. Show the before/after, the input/output, the correct pattern to follow.

### 6. Define Boundaries
Explicitly state what the skill does NOT handle. This prevents misactivation and sets expectations.

### 7. Composability
Design skills to work together. Reference other skills when appropriate. A frontend skill can reference the brand-guidelines skill.

### 8. Test Triggering
Before finalizing, test that the skill triggers when expected AND stays dormant when not relevant.

## Measuring Skill Effectiveness

Track these metrics for each skill:
- **Token savings:** Before vs After
- **Usage frequency:** How often is it used
- **Success rate:** How often it completes without errors
- **Time savings:** Development time saved

## Skills Roadmap

### Phase 3 (Week 3) - Priority Skills
1. dual-database-save.ts - Critical for data consistency
2. send-bilingual-email.ts - Used frequently
3. create-api-endpoint.ts - Development acceleration
4. add-translation.ts - i18n management
5. run-full-test-suite.ts - Testing workflow

### Phase 4 (Week 4) - Advanced Skills
6. stripe-checkout-flow.ts - Payment integration
7. analyze-performance.ts - Performance monitoring
8. generate-api-docs.ts - Documentation automation
9. deploy-to-production.ts - Deployment workflow
10. security-audit.ts - Security scanning

## Contributing Skills

When you develop a new successful pattern:
1. Extract it into a skill file
2. Add comprehensive documentation
3. Test it thoroughly
4. Update this SKILLS.md
5. Share with the team

## Frontend Design Quick Reference

When building any frontend, apply these principles to avoid "AI slop":

### ❌ AVOID (Generic AI Aesthetics)
- Inter, Roboto, Arial fonts
- Purple gradients on white backgrounds
- Excessive centered layouts
- Uniform rounded corners everywhere
- Clichéd color schemes
- Predictable cookie-cutter patterns

### ✅ EMBRACE (Distinctive Design)
- Distinctive fonts (Outfit, Clash Display, JetBrains Mono)
- Dominant color + sharp accent palette
- CSS variables for consistency
- Staggered load animations
- Atmospheric backgrounds (gradients, grids, noise)
- Asymmetry and unexpected layouts

**See:** [frontend-design/SKILL.md](./frontend-design/SKILL.md) for full guidelines.

---

## Current Status

**Phase 1-3:** ✅ Complete (11 TypeScript skills)
**Phase 4:** ✅ Complete (14 SKILL.md format skills added)
**Skills Library:** ✅ Production Ready (25 total skills)

**Total Implementation:**
- 8 MCP Servers
- 67+ Tools
- 25 Reusable Skills (14 SKILL.md + 11 TypeScript)
- Average 90-99% token reduction
- Frontend design system integrated
- Full Mawidi project coverage

**Token Optimization Skills:**
- `gemini-cli-assistant/` - 2M token context for large-scale analysis (80-90% savings)
- `codex-mcp-assistant/` - 8 MCP servers for local processing (98%+ savings)

**SKILL.md Format Skills:**
- `frontend-design/` - Avoid AI slop, create distinctive UI
- `frontend-artifact-builder/` - Complex React artifacts
- `brand-guidelines/` - Mawidi visual identity
- `api-development/` - Production API patterns
- `i18n-management/` - Arabic/English translations & RTL
- `email-composer/` - Professional bilingual email templates
- `database-migration/` - Safe Prisma + Supabase migrations
- `testing-patterns/` - Unit, integration, E2E tests
- `seo-optimization/` - Meta tags, structured data
- `error-handling/` - Consistent error patterns
- `onboarding-ux/` - Signup flows & activation
- `staff-dashboard/` - Data-rich admin dashboards

See [SKILLS_INDEX.md](./SKILLS_INDEX.md) for complete catalog.
See [MCP_CODE_EXECUTION_IMPLEMENTATION_PLAN.md](../../MCP_CODE_EXECUTION_IMPLEMENTATION_PLAN.md) for complete roadmap.
```
