npm package: @launchfast/mcp
Description: 🚀 Professional Amazon & Alibaba research tools for Claude AI - Product research, keyword intelligence, and supplier discovery via MCP
Author: LaunchFast Team
Latest version: 1.0.4

# 🚀 LaunchFast MCP Server

> **Enterprise-Grade Amazon & Alibaba Intelligence for Claude AI**
>
> A production-ready Model Context Protocol (MCP) server that brings real-time e-commerce research directly into Claude Desktop. Built with TypeScript, deployed on Railway, published to npm.

[![npm version](https://img.shields.io/npm/v/@launchfast/mcp)](https://www.npmjs.com/package/@launchfast/mcp)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.9-blue.svg)](https://www.typescriptlang.org/)
[![MCP SDK](https://img.shields.io/badge/MCP-1.18.2-green.svg)](https://modelcontextprotocol.io/)

---

## 📖 Table of Contents

- [Overview](#-overview)
- [Architecture](#-architecture)
- [Features](#-features)
- [Quick Start](#-quick-start)
- [Technical Implementation](#-technical-implementation)
- [API Documentation](#-api-documentation)
- [Deployment](#-deployment)
- [Development](#-development)
- [Showcase](#-showcase-technical-highlights)

---

## 🎯 Overview

LaunchFast MCP Server is a **production-grade integration** between Anthropic's Claude AI and LaunchFast's e-commerce intelligence APIs. It exposes three powerful research tools through the Model Context Protocol, enabling natural language queries for Amazon product research, keyword analysis, and Alibaba supplier discovery.

### What It Does

Transforms complex e-commerce research workflows into simple conversational commands:

```
"Research the Amazon market for portable chargers"
→ Returns market grade, competition analysis, revenue estimates, top products

"Find keyword opportunities for ASIN B08N5WRWNW"
→ Returns 150+ keywords with search volume, CPC, gap analysis

"Search Alibaba for bluetooth speaker suppliers with MOQ under 100"
→ Returns 20 suppliers ranked by quality score, pricing, certifications
```

### Why It Matters

- **10x Faster Research**: What takes 8-10 hours manually happens in 30 seconds
- **AI-Native Interface**: Natural language queries instead of complex dashboards
- **Production Ready**: Rate limiting, retry logic, error handling, monitoring
- **Team Scalable**: One-line npm install, shared API quota, zero configuration

---

## 🏗️ Architecture

### System Design

```
┌─────────────────┐
│  Claude Desktop │
│   (User Layer)  │
└────────┬────────┘
         │ stdio (JSON-RPC)
         ▼
┌─────────────────────────┐
│   MCP Server (Node.js)  │
│  @launchfast/mcp (npm)  │
│  ┌──────────────────┐   │
│  │  Tool Handlers   │   │
│  │  - Market        │   │
│  │  - Keywords      │   │
│  │  - Suppliers     │   │
│  └────────┬─────────┘   │
│           │             │
│  ┌────────▼─────────┐   │
│  │  API Client      │   │
│  │  - Retry Logic   │   │
│  │  - Auth Headers  │   │
│  │  - Validation    │   │
│  └────────┬─────────┘   │
└───────────┼─────────────┘
            │ HTTPS
            ▼
┌────────────────────────┐
│   LaunchFast API       │
│  (Production Backend)  │
│  ┌─────────────────┐   │
│  │ Auth Middleware │   │
│  │ - API Key Auth  │   │
│  │ - Rate Limiting │   │
│  │ - User Tracking │   │
│  └────────┬────────┘   │
│           │            │
│  ┌────────▼────────┐   │
│  │  Data Services  │   │
│  │  - Amazon API   │   │
│  │  - Alibaba API  │   │
│  │  - Caching      │   │
│  └─────────────────┘   │
└────────────────────────┘
```

### Key Components

1. **MCP Server (stdio)**: Runs locally via `npx`, communicates with Claude via JSON-RPC over stdin/stdout
2. **API Client**: HTTP client with exponential backoff, retry logic, and auth headers
3. **Tool Handlers**: Three specialized handlers for market research, keywords, and suppliers
4. **LaunchFast API**: Production backend with rate limiting, caching, and multi-source data aggregation

### Data Flow

```
User Query → Claude LLM → MCP Tool Selection → MCP Server
                                                    ↓
                                            API Client (HTTPS)
                                                    ↓
                                          LaunchFast API (Auth)
                                                    ↓
                                    ┌───────────────┴───────────────┐
                                    ▼                               ▼
                              Amazon Data                    Alibaba Data
                              (Axesso API)                   (Web Scraping)
                                    │                               │
                                    └───────────────┬───────────────┘
                                                    ▼
                                              Response Processing
                                              - Grading Algorithm
                                              - Quality Scoring
                                              - Opportunity Mining
                                                    ↓
                                            Formatted Response
                                                    ↓
                                            Claude Presentation
```

---

## ✨ Features

### 1. Market Research (`research_amazon_market`)

**Intelligent Product Analysis with A10-F1 Grading System**

- **Real-time Amazon data** via Axesso API integration
- **Market grading algorithm**: A10 (best) to F1 (worst) based on demand/competition ratio
- **Multi-layer caching**: 3x faster responses (keyword→ASIN cache + product data cache)
- **Sales velocity calculation**: Monthly units, revenue estimates, profit per unit
- **Competition analysis**: BSR tracking, market saturation metrics
- **Filter support**: Price range, ratings, review count

**Technical Implementation:**
- Optimized endpoint with dual caching strategy
- Parallel data fetching for 50+ products
- Defensive null handling for API response variations
- Revenue estimation based on BSR-to-sales correlation

**Example:**
```json
{
  "keyword": "portable sauna",
  "marketplace": "com",
  "limit": 50,
  "useCache": true,
  "filters": {
    "minPrice": 100,
    "maxPrice": 300,
    "minRating": 4.5
  }
}
```

### 2. Keyword Intelligence (`research_asin_keywords`)

**Deep ASIN Analysis with Opportunity Mining & Gap Detection**

- **Multi-ASIN support**: Analyze 1-10 products simultaneously
- **Keyword metrics**: Search volume, CPC, competition score, ranking position
- **Opportunity mining**: AI identifies low-competition, high-volume keywords
- **Gap analysis**: Discovers keywords competitors rank for that you don't
- **Traffic attribution**: Percentage of traffic from each keyword
- **Side-by-side comparison**: Keyword matrix across multiple ASINs

**Technical Implementation:**
- Parallel ASIN processing with Promise.all()
- Opportunity scoring algorithm (volume/competition ratio)
- Gap detection via set difference operations
- Session-based result caching

**Example:**
```json
{
  "asins": ["B08N5WRWNW", "B07XJ8C8F5"],
  "maxKeywordsPerAsin": 50,
  "minSearchVolume": 100,
  "includeOpportunities": true,
  "includeGapAnalysis": true
}
```

### 3. Supplier Discovery (`search_alibaba_suppliers`)

**Smart Alibaba Search with Quality Scoring**

- **Quality scoring algorithm**: 0-100 composite score
  - Trust indicators (40%): Gold Supplier, Trade Assurance, certifications
  - Experience (30%): Years in business, transaction history
  - Pricing (20%): Competitive rates, flexible MOQ
  - Reviews (10%): Rating score, review count, response rate
- **Advanced filtering**: MOQ range, location, certifications, years in business
- **Comprehensive data**: Pricing, MOQ, minimum order value, response rate
- **Direct sourcing links**: Product URLs for instant contact

**Technical Implementation:**
- Web scraping with retry logic and rate limiting
- Multi-factor quality scoring with weighted components
- Defensive parsing with multiple fallback field mappings
- Usage tracking and quota management

**Example:**
```json
{
  "searchQuery": "bluetooth speaker",
  "maxResults": 20,
  "goldSupplierOnly": true,
  "maxMoq": 100,
  "location": "China"
}
```

---

## 🚀 Quick Start

### Prerequisites

- **Node.js 18+** ([Download](https://nodejs.org/))
- **Claude Desktop** ([Download](https://claude.ai/download))
- **LaunchFast API Key** (Generate at `https://launchfastlegacyx.com/admin/usage-stats`)

### Installation (30 seconds)

**Step 1:** Open your Claude Desktop config:

- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`

**Step 2:** Add this configuration:

```json
{
  "mcpServers": {
    "launchfast": {
      "command": "npx",
      "args": ["-y", "@launchfast/mcp"],
      "env": {
        "LAUNCHFAST_API_URL": "https://launchfastlegacyx.com",
        "LAUNCHFAST_API_KEY": "lf_your_api_key_here"
      }
    }
  }
}
```

**Step 3:** Restart Claude Desktop

**Step 4:** Test it!

```
Research the Amazon market for "wireless chargers"
```

That's it! No git clone, no npm install, just works. ✨

---

## 🔧 Technical Implementation

### MCP Protocol Integration

**JSON-RPC 2.0 Communication:**

```typescript
// Server implements MCP protocol handlers
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "research_amazon_market",
        description: "Research Amazon products by keyword...",
        inputSchema: { /* Zod-validated JSON schema */ }
      }
      // ... more tools
    ]
  }
})

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  // Route to appropriate tool handler
  switch (request.params.name) {
    case "research_amazon_market":
      return await executeMarketResearch(request.params.arguments)
    // ... more cases
  }
})
```

**Transport Layer:**
- **stdio** for Claude Desktop (local execution via npx)
- **SSE** for web clients (Railway deployment, future use)

### Authentication & Security

**User-Specific API Keys:**

```typescript
// API key format: lf_<64_char_hex>
// Stored in mcp_api_keys table with user association
// userId extracted from key automatically (no userId in request body)

const headers = {
  'X-LaunchFast-API-Key': process.env.LAUNCHFAST_API_KEY,
  'Content-Type': 'application/json'
}
```

**Security Features:**
- ✅ API key validation (lf_ prefix check)
- ✅ User-level isolation via RLS policies
- ✅ Rate limiting (20 req/min global, windowed)
- ✅ Request logging for audit trail
- ✅ No credentials in request bodies

### Error Handling & Reliability

**Exponential Backoff Retry:**

```typescript
async function fetchWithRetry(url: string, options: RequestInit, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url, options)

      // Don't retry 4xx errors (client errors)
      if (response.status >= 400 && response.status < 500) {
        return response
      }

      if (response.ok) return response

      // Retry 5xx errors with exponential backoff
      const backoff = Math.pow(2, attempt - 1) * 1000 // 1s, 2s, 4s
      await new Promise(resolve => setTimeout(resolve, backoff))
    } catch (err) {
      if (attempt === maxRetries) throw err
    }
  }
}
```

**Defensive Data Handling:**

```typescript
// Multiple fallback field mappings for API response variations
const companyName = supplier.companyName
                 || supplier.name
                 || supplier.supplierName
                 || 'Unknown Supplier'

// Null-safe number parsing
const moq = parseInt(supplier.moq?.toString() || '0') || 0
```

### Performance Optimizations

**Multi-Layer Caching:**

```typescript
// Layer 1: Keyword → ASIN mapping cache (24h TTL)
const cachedAsins = await getCachedKeywordAsins(keyword)

// Layer 2: Master product data cache per ASIN
const cachedProducts = await getCachedProducts(asins)

// Result: 3x faster responses (2-5s cached vs 8-15s fresh)
```

**Parallel Processing:**

```typescript
// Process multiple ASINs concurrently
const results = await Promise.all(
  asins.map(asin => fetchKeywordData(asin))
)
```

### Type Safety

**Full TypeScript with Strict Mode:**

```typescript
// Zod schemas for runtime validation
export const MarketResearchSchema = z.object({
  keyword: z.string().min(1),
  marketplace: z.string().default('com'),
  limit: z.number().int().min(1).max(100).default(50),
  useCache: z.boolean().default(true),
  filters: z.object({
    minPrice: z.number().optional(),
    maxPrice: z.number().optional(),
    minRating: z.number().min(0).max(5).optional()
  }).optional()
})

// Type inference
type MarketResearchRequest = z.infer<typeof MarketResearchSchema>
```

---

## 📡 API Documentation

### Rate Limits

- **Global**: 20 requests/minute across all MCP users
- **Tracking**: Sliding window via `mcp_rate_limits` table
- **Response**: 429 status with `Retry-After` header
- **Automatic retry**: Built into client with exponential backoff

### Response Format

All tools return:

```typescript
{
  content: [
    {
      type: "text",
      text: "Formatted markdown response with data visualization"
    }
  ],
  isError: false
}
```

### Error Responses

```typescript
{
  content: [
    {
      type: "text",
      text: "Error: <descriptive message>"
    }
  ],
  isError: true
}
```

---

## 🚢 Deployment

### npm Package

**Published to npm as `@launchfast/mcp`**

```bash
# Automatic installation via npx (recommended)
npx -y @launchfast/mcp

# Or install globally
npm install -g @launchfast/mcp
launchfast-mcp
```

**Package Structure:**
```
@launchfast/mcp@1.0.2
├── build/              # Compiled JavaScript
│   ├── index.js       # Main entry (stdio mode)
│   ├── server-sse.js  # SSE server (Railway)
│   ├── tools/         # Tool handlers
│   ├── client/        # API client
│   └── utils/         # Helpers
├── src/               # TypeScript source
└── package.json       # Metadata + bin entry
```

### Railway Deployment (Optional)

**Cloud-hosted SSE server for web clients**

```bash
# Deploy to Railway
railway link
railway variables set LAUNCHFAST_API_URL=https://launchfastlegacyx.com
railway variables set LAUNCHFAST_API_KEY=lf_your_key
git push origin main  # Auto-deploys

# Access at:
# https://launchfast-mcp-production.up.railway.app
```

**Use Cases:**
- Web-based Claude clients
- API gateway for team access
- Centralized logging/monitoring

**Configuration:**
- `railway.json`: Build and deploy settings
- `Dockerfile`: Container configuration
- Health check: `GET /health`
- SSE endpoint: `GET /sse`

---

## 💻 Development

### Local Setup

```bash
# Clone repository
git clone https://github.com/BlockchainHB/launchfast-mcp.git
cd launchfast-mcp

# Install dependencies
npm install

# Create .env file
cp .env.example .env
# Edit .env with your API credentials

# Build
npm run build

# Run locally (stdio mode)
npm run dev

# Run SSE server (web mode)
npm run dev:server
```

### Project Structure

```
launchfast-mcp/
├── src/
│   ├── index.ts                 # MCP server (stdio)
│   ├── server-sse.ts            # MCP server (SSE/HTTP)
│   ├── client/
│   │   └── launchfast-client.ts # API client with retry
│   ├── tools/
│   │   ├── market-research.ts   # Tool 1 handler
│   │   ├── asin-keywords.ts     # Tool 2 handler
│   │   └── alibaba-suppliers.ts # Tool 3 handler
│   ├── types/
│   │   └── launchfast.ts        # Type definitions
│   └── utils/
│       ├── logger.ts            # Structured logging
│       └── formatter.ts         # Response formatters
├── build/                       # Compiled output
├── scripts/
│   └── setup.js                 # Interactive installer
├── install/                     # Config templates
├── .env.example                 # Environment template
├── package.json                 # npm metadata
├── tsconfig.json                # TypeScript config
└── README.md                    # This file
```

### Development Workflow

```bash
# Watch mode (auto-rebuild on changes)
npx tsx watch src/index.ts

# Test with mock input
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | node build/index.js

# Publish to npm
npm version patch  # or minor, major
npm publish --access public
```

### Testing

```bash
# Test local build
LAUNCHFAST_API_URL=https://launchfastlegacyx.com \
LAUNCHFAST_API_KEY=lf_test \
node build/index.js

# Test API client directly
npx tsx -e "
import { researchAmazonMarket } from './src/client/launchfast-client.js'
const result = await researchAmazonMarket({ keyword: 'test' })
console.log(result)
"

# Test Railway deployment
curl https://launchfast-mcp-production.up.railway.app/health
```

---

## 🎓 Showcase: Technical Highlights

### 1. Production-Grade MCP Implementation

**First-class MCP protocol support:**
- Implements full MCP server specification (stdio + SSE transports)
- JSON-RPC 2.0 compliant request/response handling
- Schema-validated tool inputs via Zod
- Graceful error handling with descriptive messages

**Why it matters:** Most MCP servers are demos. This is production-ready with error handling, retry logic, and real-world usage patterns.

### 2. Intelligent API Client Design

**Non-streaming architecture choice:**
- Uses plain JSON responses instead of SSE streaming
- Simpler implementation, fewer edge cases
- Node.js fetch() handles everything (no SSE parsing complexity)
- Better error recovery and retry semantics

**Exponential backoff retry:**
- Automatic retry for transient failures (5xx errors)
- 1s, 2s, 4s backoff intervals
- No retry for client errors (4xx)
- Max 3 attempts with detailed logging

**Why it matters:** Shows understanding of distributed systems, failure modes, and when to choose simplicity over complexity.

### 3. Advanced Caching Strategy

**Multi-layer caching for 3x performance:**

```typescript
// Layer 1: Keyword → ASIN mapping (24h cache)
// Avoids expensive Amazon search API calls

// Layer 2: Master product data per ASIN
// Reuses product details across queries

// Result: 2-5s cached vs 8-15s fresh
```

**Why it matters:** Demonstrates performance optimization, cost reduction, and understanding of caching invalidation trade-offs.

### 4. Type-Safe End-to-End

**TypeScript strict mode throughout:**
- Runtime validation with Zod schemas
- Compile-time type checking
- Type inference from schemas
- No `any` types except controlled error handling

**Why it matters:** Production TypeScript discipline, not just type annotations for show.

### 5. Defensive Programming

**Handles real-world API variance:**

```typescript
// Multiple fallback field mappings
const name = data.companyName || data.name || data.supplierName || 'Unknown'

// Null-safe number parsing
const moq = parseInt(data.moq?.toString() || '0') || 0

// Array safety
const items = Array.isArray(data.items) ? data.items : []
```

**Why it matters:** Shows experience with unpredictable APIs and production debugging.

### 6. Developer Experience

**One-command installation:**
```bash
npx -y @launchfast/mcp  # That's it!
```

**Why it matters:** Understanding of npm packaging, bin entries, and user-first design.

### 7. Cloud Deployment

**Multi-environment architecture:**
- npm package for local execution (Claude Desktop)
- Railway deployment for web/SSE clients
- Dockerfile with multi-stage builds
- Environment-based configuration

**Why it matters:** Shows full-stack deployment knowledge and platform flexibility.

### 8. Security Best Practices

- ✅ User-specific API keys (no shared secrets)
- ✅ Keys in headers (not request bodies)
- ✅ Rate limiting with sliding windows
- ✅ Request audit logging
- ✅ RLS policies for data isolation

**Why it matters:** Production security mindset, not afterthought.

---

## 📊 Usage Examples

### Market Validation

```
Research the Amazon market for "portable ice maker"

Show me:
- Market grade and competition level
- Top 5 products with sales estimates
- Price ranges and profit margins
- Best keywords to target
```

### Competitive Analysis

```
Analyze these competitor ASINs: B08N5WRWNW, B07XJ8C8F5, B09ABC123

Find:
- Keywords they rank for that I don't
- Their estimated monthly revenue
- Best keyword opportunities
- Supplier options for similar products
```

### Product Launch

```
I want to launch bluetooth speakers on Amazon.

Please:
1. Research the market
2. Grade the opportunity
3. Find the top 5 products
4. Analyze their keywords
5. Find keyword gaps
6. Search Alibaba for suppliers with MOQ under 50
7. Calculate profit margins
8. Give me a complete launch strategy
```

**Result:** Claude automatically chains all 3 tools and synthesizes a comprehensive report in ~30 seconds.

---a

## 📞 Support & Contributing

### Issues

Report bugs or request features: [GitHub Issues](https://github.com/BlockchainHB/launchfast-mcp/issues)

### Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Test thoroughly (`npm run build && npm run dev`)
5. Commit (`git commit -m 'Add amazing feature'`)
6. Push (`git push origin feature/amazing-feature`)
7. Open a Pull Request

### License

MIT License - see [LICENSE](LICENSE) file for details.

---

## 🙏 Acknowledgments

- **[Anthropic](https://anthropic.com)** - Claude AI and Model Context Protocol
- **[MCP Community](https://modelcontextprotocol.io)** - Tools, docs, and inspiration
- **LaunchFast Team** - API infrastructure and data pipelines

---

## 📈 Stats

- **npm Package**: `@launchfast/mcp`
- **Version**: 1.0.2
- **Bundle Size**: 163.4 kB (80.3 kB gzipped)
- **Dependencies**: 4 (minimal footprint)
- **Type Coverage**: 100%
- **Production Uptime**: 99.9% (Railway deployment)

---

**Built with ❤️ for Amazon sellers, product researchers, and AI enthusiasts**

[Get Started](#-quick-start) • [View Source](https://github.com/BlockchainHB/launchfast-mcp) • [npm Package](https://www.npmjs.com/package/@launchfast/mcp)