UNPKG

launchfast-mcp

Version:

🚀 Professional Amazon & Alibaba research tools for Claude AI - Product research, keyword intelligence, and supplier discovery via MCP

344 lines (271 loc) 9.37 kB
# LaunchFast MCP Integration Summary ## 🚨 BREAKING CHANGES - IMPORTANT FOR MCP SERVER **Legacy Authentication Removed:** - Global `process.env.MCP_API_KEY` is **DEPRECATED** and no longer accepted - All MCP requests must now use **user-specific API keys** generated via admin UI - Old requests with `X-LaunchFast-API-Key: $MCP_API_KEY` will return **401 Unauthorized** **Action Required for MCP Server:** 1. Remove any hardcoded `MCP_API_KEY` from environment variables 2. Use user-specific API keys from admin UI (`lf_` prefix) 3. Update all API calls to use new authentication format 4. Do NOT send `userId` in request body anymore (extracted from API key) ## Overview Complete MCP (Model Context Protocol) authentication system for LaunchFast API with admin management UI. ## Production Configuration ### Required Environment Variable Set in Vercel production environment: ``` NEXT_PUBLIC_SITE_URL=https://launchfastlegacyx.com ``` This ensures the MCP config generator returns the correct production base URL instead of localhost. ## API Endpoints Available for MCP Server ### 1. Product Research **Endpoint:** `POST https://launchfastlegacyx.com/api/products/research` **Headers:** ```json { "X-LaunchFast-API-Key": "lf_<user_api_key>", "Content-Type": "application/json" } ``` **Request Body:** ```json { "keyword": "wireless headphones", "filters": { "minPrice": 20, "maxPrice": 100, "minReviews": 100 }, "limit": 30 } ``` **Response:** Complete product market analysis with scoring, competition data, supplier info --- ### 2. Keyword Research **Endpoint:** `POST https://launchfastlegacyx.com/api/keywords/research` **Request Body:** ```json { "asins": ["B08N5WRWNW", "B07XJ8C8F5"], "options": {} } ``` **Response:** Keyword data, search volume, CPC metrics **⚠️ Breaking Change:** Do NOT include `userId` in request body - it's now extracted from the API key automatically. --- ### 3. Supplier Search **Endpoint:** `POST https://launchfastlegacyx.com/api/suppliers/search` **Request Body:** ```json { "keyword": "bluetooth speaker", "filters": { "minOrderQuantity": 100 } } ``` **Response:** Supplier listings with pricing, MOQ, ratings **⚠️ Breaking Change:** Do NOT include `userId` in request body - it's now extracted from the API key automatically. --- ## Rate Limiting **Global Limit:** 20 requests per minute across ALL MCP users - Enforced via `mcp_rate_limits` database table - Sliding window implementation - Returns 429 with `Retry-After` header when exceeded **Rate Limit Headers (all responses):** ``` X-RateLimit-Limit: 20 X-RateLimit-Remaining: 15 X-RateLimit-Reset: 1704067200 ``` --- ## Admin UI Features ### Location `https://launchfastlegacyx.com/admin/usage-stats` "MCP API Keys" tab ### Capabilities 1. **Generate API Keys** - Enter any user's email to create a key 2. **View All Keys** - Table showing all active/disabled keys 3. **Copy API Keys** - One-click copy from table 4. **Generate MCP Config** - One-click config.json generation for any key 5. **Delete Keys** - Revoke access for any user 6. **Usage Tracking** - View last used timestamps ### Key Generation Flow 1. Admin enters user email (e.g., `user@example.com`) 2. System finds user via pagination (supports 1000+ users) 3. Generates unique key: `lf_<64_char_hex>` 4. Returns key with copy-paste config --- ## MCP Server Config Format When admin clicks "View Config" for a key, they get: ```json { "name": "launchfast", "version": "1.0.0", "description": "LaunchFast Amazon Product Intelligence API", "api": { "baseUrl": "https://launchfastlegacyx.com", "apiKey": "lf_abc123...", "headers": { "X-LaunchFast-API-Key": "lf_abc123...", "Content-Type": "application/json" } }, "rateLimit": { "maxRequests": 20, "windowMs": 60000, "scope": "global" }, "tools": [ { "name": "research_product", "description": "Research Amazon products by keyword with complete market analysis", "endpoint": "https://launchfastlegacyx.com/api/products/research", "method": "POST", "parameters": { "keyword": { "type": "string", "required": true }, "filters": { "type": "object", "required": false }, "limit": { "type": "number", "required": false, "default": 30 } } }, { "name": "research_keywords", "description": "Research keywords for given ASINs", "endpoint": "https://launchfastlegacyx.com/api/keywords/research", "method": "POST", "parameters": { "asins": { "type": "array", "required": true }, "options": { "type": "object", "required": false } } }, { "name": "search_suppliers", "description": "Search for suppliers using keyword or product details", "endpoint": "https://launchfastlegacyx.com/api/suppliers/search", "method": "POST", "parameters": { "keyword": { "type": "string", "required": true }, "filters": { "type": "object", "required": false } } } ], "user": { "userId": "uuid-here", "email": "user@example.com", "keyName": "Production MCP Server" }, "documentation": { "rateLimits": "Global limit: 20 requests/minute across all MCP users", "authentication": "Include X-LaunchFast-API-Key header in all requests" } } ``` --- ## Database Schema ### Tables Created (via migration) **`mcp_api_keys`** - Stores user API keys - Columns: id, user_id, api_key, name, is_active, created_at, last_used_at, expires_at - RLS policies for user isolation **`mcp_usage_logs`** - Tracks all MCP API requests - Columns: id, user_id, api_key_id, endpoint, status_code, processing_time_ms, keyword, asin_count, result_count, created_at - Used for analytics and debugging **`mcp_rate_limits`** - Global rate limiting - Columns: window_start, window_end, request_count - Sliding window implementation **Function:** `generate_mcp_api_key()` - Generates unique keys with `lf_` prefix - Returns: `lf_<64_char_hex>` --- ## Middleware Implementation **File:** `lib/mcp-middleware.ts` **Functions:** 1. `withMCPMiddleware(request)` - Validates API key, checks rate limits 2. `checkMCPRateLimit()` - Global 20 req/min enforcement 3. `logMCPUsage(data)` - Records request metrics 4. `getMCPRateLimitHeaders()` - Returns rate limit headers **✅ COMPLETED - All Non-Streaming MCP Endpoints Secured:** - `/api/products/research/route.ts` - `/api/products/research/optimized/route.ts` - `/api/keywords/research/route.ts` - `/api/suppliers/search/route.ts` **Streaming Endpoints (NOT USED BY MCP - No Changes Made):** - `/api/products/research/stream/route.ts` - Skipped (still uses legacy auth) - `/api/keywords/research/stream/route.ts` - Skipped (still uses legacy auth) - `/api/suppliers/search/stream/route.ts` - Skipped (still uses legacy auth) - `/api/products/research/multi-asin/stream/route.ts` - Skipped (still uses legacy auth) **Note:** Streaming endpoints retain legacy `MCP_API_KEY` authentication since they're not used by the MCP server. --- ## Error Handling ### 401 Unauthorized ```json { "error": "Missing or invalid API key" } ``` ### 429 Too Many Requests ```json { "error": "Rate limit exceeded. Global limit: 20 requests per minute." } ``` Headers: `Retry-After: 45` (seconds) ### 403 Forbidden ```json { "error": "API key is disabled" } ``` --- ## Usage Tracking Each successful MCP request logs: - User ID - API Key ID - Endpoint called - Status code - Processing time (ms) - Request parameters (keyword, ASIN count, etc.) - Result count - Timestamp Viewable in admin dashboard for analytics. --- ## Security Notes 1. **Admin Access:** Only users with `role = 'admin'` in `user_profiles` can access MCP management 2. **API Key Storage:** Keys stored in plaintext (needed for validation) but only accessible via admin or owning user 3. **Rate Limiting:** Global enforcement prevents abuse 4. **Usage Logging:** Full audit trail of all MCP requests 5. **Key Revocation:** Admins can disable keys instantly via is_active flag --- ## Testing in MCP Server Workspace 1. Get API key from admin UI or via key generation 2. Use config.json provided by admin UI 3. Make test request: ```bash curl -X POST https://launchfastlegacyx.com/api/products/research \ -H "X-LaunchFast-API-Key: lf_your_key_here" \ -H "Content-Type: application/json" \ -d '{"keyword": "test product", "limit": 5}' ``` 4. Check response includes rate limit headers 5. Verify usage logged in admin dashboard --- ## Next Steps 1. Set `NEXT_PUBLIC_SITE_URL=https://launchfastlegacyx.com` in Vercel 2. Run database migration in production (if not already done) 3. Apply MCP middleware to all non-streaming API routes 4. **Update MCP Server to use new authentication:** - Remove `MCP_API_KEY` from environment - Generate user-specific API key from admin UI - Update all API calls to use `lf_` prefixed keys - Remove `userId` from request bodies 5. Test end-to-end with MCP server workspace 6. Monitor rate limits and usage patterns in admin dashboard --- ## Support For issues with MCP integration: - Check admin UI for key status - Review `mcp_usage_logs` table for errors - Verify `NEXT_PUBLIC_SITE_URL` is set correctly - Confirm rate limit headers in responses