# MCH-010: MCP Server ## Metadata - **Codigo:** MCH-010 - **Fase:** 3 - Asistente IA - **Prioridad:** P0 - **Estado:** Completado - **Fecha completado:** 2026-01-10 ## Descripcion Gateway LLM agnostico usando el protocolo MCP (Model Context Protocol) de Anthropic. Permite conectar multiples proveedores de LLM (Claude, GPT-4, Llama) con tools especificos para el negocio. ## Objetivos 1. Gateway LLM agnostico (OpenRouter) 2. Tools MCP para operaciones del negocio 3. Contexto por tenant (productos, ventas) 4. Rate limiting por tokens 5. Logging de conversaciones ## Alcance ### Incluido - MCP Server con TypeScript - Tools para: productos, ventas, inventario, clientes - Routing a multiples LLMs via OpenRouter - Contexto del negocio en prompts - Control de consumo de tokens ### Excluido - Entrenamiento de modelos propios - Fine-tuning - Vision/imagenes (fase posterior) ## Arquitectura ``` ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ Mobile │ │ WhatsApp │ │ Web │ │ App │ │ Service │ │ Dashboard │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ │ │ └───────────────────┼───────────────────┘ │ ┌──────▼──────┐ │ MCP Server │ │ (Gateway) │ └──────┬──────┘ │ ┌────────────┼────────────┐ │ │ │ ┌──────▼──────┐ ┌───▼───┐ ┌─────▼─────┐ │ OpenRouter │ │ Claude│ │ GPT-4 │ │ (Default) │ │ API │ │ API │ └─────────────┘ └───────┘ └───────────┘ ``` ## Tools MCP ### Products ```typescript { name: "search_products", description: "Buscar productos en el catalogo", parameters: { query: string, category?: string } } { name: "get_product_stock", description: "Obtener stock de un producto", parameters: { product_id: string } } { name: "update_product_price", description: "Actualizar precio de producto", parameters: { product_id: string, new_price: number } } ``` ### Sales ```typescript { name: "get_daily_sales", description: "Obtener ventas del dia", parameters: { date?: string } } { name: "get_sales_report", description: "Reporte de ventas por periodo", parameters: { start_date: string, end_date: string } } ``` ### Inventory ```typescript { name: "get_low_stock_products", description: "Productos con stock bajo", parameters: {} } { name: "get_inventory_value", description: "Valor total del inventario", parameters: {} } ``` ### Customers ```typescript { name: "search_customers", description: "Buscar clientes", parameters: { query: string } } { name: "get_customer_balance", description: "Saldo de fiado de cliente", parameters: { customer_id: string } } ``` ## Endpoints API | Metodo | Endpoint | Descripcion | |--------|----------|-------------| | POST | /mcp/chat | Enviar mensaje al LLM | | GET | /mcp/tools | Listar tools disponibles | | GET | /mcp/history | Historial de conversacion | | POST | /mcp/feedback | Feedback de respuesta | ## Modelo de Datos ### Tablas (schema: ai) **conversations** - id, tenant_id, user_id, channel - started_at, last_message_at **messages** - id, conversation_id, role, content - tokens_used, model, created_at **tool_calls** - id, message_id, tool_name - parameters, result, duration_ms ## Entregables | Entregable | Estado | Archivo | |------------|--------|---------| | MCP Server base | En progreso | `apps/mcp-server/` | | Tools products | Pendiente | `tools/products.tool.ts` | | Tools sales | Pendiente | `tools/sales.tool.ts` | | Tools inventory | Pendiente | `tools/inventory.tool.ts` | | OpenRouter client | En progreso | `clients/openrouter.ts` | ## Dependencias ### Depende de - MCH-001 (Infraestructura) - MCH-002 (Auth) - para context del tenant - MCH-003 (Productos) - para tools - MCH-004 (Sales) - para tools ### Bloquea a - MCH-011 (WhatsApp usa MCP) - MCH-012 (Chat dueno) - MCH-013 (Chat cliente) ## Criterios de Aceptacion - [x] MCP Server responde correctamente - [x] Tools ejecutan operaciones reales - [x] Contexto del tenant se incluye - [x] Rate limiting por tokens funciona - [x] Logs de conversacion completos ## Configuracion ```typescript // config/mcp.config.ts { defaultProvider: 'openrouter', providers: { openrouter: { apiKey: process.env.OPENROUTER_API_KEY, defaultModel: 'anthropic/claude-3-haiku' }, anthropic: { apiKey: process.env.ANTHROPIC_API_KEY } }, maxTokensPerRequest: 4000, maxTokensPerDay: 50000 } ``` ## Puerto - **MCP Server:** 3142 --- **Ultima actualizacion:** 2026-01-10