Feat: Agregar MCP Server para agentes IA
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 1m10s

- Endpoint JSON-RPC 2.0 en /api/mcp
- 8 herramientas: list_instances, list_chats, get_chat, search_chats, send_message, get_messages, react_message, get_guide
- Soporte para todos los tipos de mensaje (text, image, video, audio, document, sticker, contact, poll, event)
- Guías de uso integradas con ejemplos JSON
- Autenticación via NUXT_MASTER_API_KEY
This commit is contained in:
2025-12-04 14:05:27 -06:00
parent 23e78fb0b2
commit 7abad2b6c3
3 changed files with 1323 additions and 0 deletions

59
README.md Normal file
View File

@@ -0,0 +1,59 @@
# WhatsApp Nucleo
Sistema de gestión centralizada de múltiples instancias de WhatsApp para Nucleo V3.
## MCP Server para Claude Code
Agregar el MCP a tu proyecto (usa tu NUXT_MASTER_API_KEY):
```bash
claude mcp add --transport http whatsapp https://whatsapp.nucleoriofrio.com/api/mcp --header "Authorization: Bearer <NUXT_MASTER_API_KEY>"
```
---
## Setup
```bash
npm install
```
## Development
```bash
npm run dev
```
## Production
```bash
npm run build
node .output/server/index.mjs
```
---
## API Endpoints
### Instancias
- `GET /api/instances` - Lista instancias
- `POST /api/instances` - Crear instancia
- `POST /api/instances/:id/connect` - Conectar instancia
- `POST /api/instances/:id/disconnect` - Desconectar
### Mensajes
- `POST /api/messages/:instanceId/:chatId/send` - Enviar mensaje
- `GET /api/messages/:instanceId/:chatId` - Obtener mensajes
- `POST /api/messages/:instanceId/react` - Reaccionar a mensaje
### MCP
- `POST /api/mcp` - Endpoint JSON-RPC para agentes IA
---
## Stack
- **Frontend:** Nuxt 3, Vue 3, Nuxt UI, TailwindCSS
- **Backend:** Nitro, PostgreSQL
- **WhatsApp:** Baileys v6.7.9
- **Auth:** Authentik + Traefik

View File

@@ -0,0 +1,127 @@
// MCP Server Endpoint - JSON-RPC 2.0 over HTTP
// Protocolo MCP para agentes de IA - WhatsApp Nucleo
import { MCP_TOOLS, handleToolCall } from '../../utils/mcp'
interface JsonRpcRequest {
jsonrpc: '2.0'
id: string | number
method: string
params?: any
}
interface JsonRpcResponse {
jsonrpc: '2.0'
id: string | number | null
result?: any
error?: {
code: number
message: string
data?: any
}
}
export default defineEventHandler(async (event) => {
// Validar token de autenticación (usa la misma API key del sistema)
const authHeader = getHeader(event, 'Authorization')
const expectedToken = process.env.NUXT_MASTER_API_KEY
if (expectedToken) {
const providedToken = authHeader?.replace('Bearer ', '')
if (!providedToken || providedToken !== expectedToken) {
setResponseStatus(event, 401)
return createJsonRpcError(null, -32000, 'Unauthorized: Invalid or missing token')
}
}
try {
const body = await readBody(event) as JsonRpcRequest
// Validar JSON-RPC
if (body.jsonrpc !== '2.0') {
return createJsonRpcError(body.id, -32600, 'Invalid Request: jsonrpc must be "2.0"')
}
if (!body.method) {
return createJsonRpcError(body.id, -32600, 'Invalid Request: method is required')
}
// Manejar métodos MCP
switch (body.method) {
case 'initialize': {
// Handshake inicial del protocolo MCP
return createJsonRpcResponse(body.id, {
protocolVersion: '2024-11-05',
capabilities: {
tools: {}
},
serverInfo: {
name: 'whatsapp-nucleo-mcp',
version: '1.0.0'
}
})
}
case 'initialized': {
// Notificación de que el cliente está listo
return createJsonRpcResponse(body.id, {})
}
case 'tools/list': {
// Listar todas las tools disponibles
return createJsonRpcResponse(body.id, {
tools: MCP_TOOLS
})
}
case 'tools/call': {
// Ejecutar una tool
const { name, arguments: args } = body.params || {}
if (!name) {
return createJsonRpcError(body.id, -32602, 'Invalid params: tool name is required')
}
// Verificar que la tool existe
const tool = MCP_TOOLS.find(t => t.name === name)
if (!tool) {
return createJsonRpcError(body.id, -32602, `Tool not found: ${name}`)
}
// Ejecutar la tool
const result = await handleToolCall(name, args || {})
return createJsonRpcResponse(body.id, result)
}
case 'ping': {
return createJsonRpcResponse(body.id, {})
}
default:
return createJsonRpcError(body.id, -32601, `Method not found: ${body.method}`)
}
} catch (err: any) {
console.error('MCP Error:', err)
return createJsonRpcError(null, -32603, `Internal error: ${err.message}`)
}
})
function createJsonRpcResponse(id: string | number | null, result: any): JsonRpcResponse {
return {
jsonrpc: '2.0',
id: id ?? null,
result
}
}
function createJsonRpcError(id: string | number | null, code: number, message: string, data?: any): JsonRpcResponse {
return {
jsonrpc: '2.0',
id: id ?? null,
error: {
code,
message,
...(data && { data })
}
}
}

1137
server/utils/mcp.ts Normal file

File diff suppressed because it is too large Load Diff