mergeon-mcp 1.56.0 → 1.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,7 @@ Y Claude usa el MCP para hacerlo directamente contra tu backend de MergeOn.
17
17
 
18
18
  1. [¿Qué expone el MCP?](#qué-expone-el-mcp)
19
19
  2. [Setup en Claude Desktop / Claude Code](#setup)
20
- 3. [Tools disponibles (190)](#tools-disponibles)
20
+ 3. [Tools disponibles (195)](#tools-disponibles)
21
21
  4. [Skills incluidos](#skills-incluidos)
22
22
  5. [Variables de entorno](#variables-de-entorno)
23
23
  6. [Desarrollo local](#desarrollo-local)
@@ -36,7 +36,7 @@ Cada tool es una función que Claude puede invocar. Internamente, el MCP autenti
36
36
 
37
37
  > **Cross-tenant (`ecommerce_id` override):** todas las tools aceptan un parámetro opcional `ecommerce_id` para apuntar a otro tenant (ej. `agent_prompts_update({ wpp_prompt_text: "...", ecommerce_id: "57" })`). La key de ecommerce 1 (superadmin) puede apuntar a **cualquier** tenant; una key de **implementador** puede apuntar a los ecommerces que gestiona; cualquier otra key solo opera sobre el suyo. El backend (`authorize_ecommerce_target`) valida la propiedad y devuelve 403 si no aplica.
38
38
 
39
- Las 190 tools cubren los principales dominios de MergeOn: **CRM, pedidos, productos, conversaciones, flujos de automatización (con catálogo de triggers/conditions/actions descubrible y filtros por reel específico via `media_ids`), calendario, marketing masivo, analytics legacy, analítica de ventas (revenue, top productos, comparativas y filtros por canal), eventos a Meta CAPI (auditoría + reenvío), nurturing/hidratación de leads, formularios dinámicos con tracking codes + UTMs, videos sociales con auto-tracking y funnel de conversión, webhooks entrantes, workers, admin, configuración del agente IA (prompts + tools), business context (conocimiento dinámico para el agente), plantillas de WhatsApp avanzadas y configuración general del ecommerce**.
39
+ Las 195 tools cubren los principales dominios de MergeOn: **CRM, pedidos, productos, conversaciones, flujos de automatización (con catálogo de triggers/conditions/actions descubrible y filtros por reel específico via `media_ids`), calendario, marketing masivo, analytics legacy, analítica de ventas (revenue, top productos, comparativas y filtros por canal), eventos a Meta CAPI (auditoría + reenvío), nurturing/hidratación de leads, formularios dinámicos con tracking codes + UTMs, videos sociales con auto-tracking y funnel de conversión, webhooks entrantes, workers, reparto automático de contactos entre asesores con avisos dirigidos por WhatsApp, admin, configuración del agente IA (prompts + tools), business context (conocimiento dinámico para el agente), plantillas de WhatsApp avanzadas y configuración general del ecommerce**.
40
40
 
41
41
  ### B. Skills (guías de experto instalables en `CLAUDE.md`)
42
42
 
@@ -128,7 +128,7 @@ npx mergeon-mcp skills list
128
128
 
129
129
  ## Tools disponibles
130
130
 
131
- 190 tools organizadas en 23 dominios. Cada nombre corresponde a la cadena exacta que verás en Claude Desktop.
131
+ 195 tools organizadas en 24 dominios. Cada nombre corresponde a la cadena exacta que verás en Claude Desktop.
132
132
 
133
133
  > 💡 Los dominios marcados con **(catálogo descubrible)** exponen un tool `<dominio>_get_catalog` que devuelve los enums, shapes y reglas válidas. Llámalo SIEMPRE antes de crear/modificar para no inventar campos.
134
134
 
@@ -183,7 +183,7 @@ npx mergeon-mcp skills list
183
183
  | `conversations_search` | Busca texto en mensajes de todas las conversaciones. Filtros: `from_user`, `from_agent`. |
184
184
  | `conversations_range` | Trae todos los mensajes creados entre `since` y `until` (ISO 8601), orden cronológico. Para sincronización incremental por ventana de tiempo (ej. cron cada 30 min). |
185
185
 
186
- ### Flujos / Flows (6 tools)
186
+ ### Flujos / Flows (6 tools + catálogo descubrible)
187
187
  | Tool | Qué hace |
188
188
  |---|---|
189
189
  | `flows_list` | Lista todos los flows con `id`, `name`, `trigger_type`, `conditions`, `actions[]`, `is_active`, `continue_agent`, `scheduled_at`. |
@@ -191,9 +191,11 @@ npx mergeon-mcp skills list
191
191
  | `flows_update` | PATCH parcial. Re-valida constraints de `story_reply`/`decision_tree`/`scheduled_send`. |
192
192
  | `flows_delete` | Elimina flow por `flow_id` y limpia cache de flows. |
193
193
  | `flows_execute` | Ejecuta flow manualmente con `crm`/`message`/`order`, opcional `template_placeholders` (overrides de campos manuales para `send_template`) y opcional `template_file_url` (override del header image/video/documento del template, ej. guía de envío específica del pedido). Opcional `session_id` + `source` para fijar la conversación destino exacta (evita que el canal se re-derive del contacto). Permite ejecutar flows inactivos manualmente. |
194
- | `flows_get_catalog` | **Catálogo descubrible**: devuelve todos los `trigger_types` con sus condiciones válidas, todos los `action_types` con sus payloads, los `order_statuses` válidos y los `{{placeholders}}` disponibles (order/crm/message/time + aritmética). **Llamar antes de diseñar un flow** para no inventar triggers/actions. |
194
+ | `flows_get_catalog` | **Catálogo descubrible**: devuelve todos los `trigger_types` con sus condiciones válidas, todos los `action_types` con sus payloads, los `order_statuses` válidos y los `{{placeholders}}` disponibles (order/crm/message/event/time + aritmética). **Llamar antes de diseñar un flow** para no inventar triggers/actions. |
195
195
 
196
- > Para escribir flows con recetas y buenas prácticas, instala el skill `flows-creation` (`npx mergeon-mcp skills add flows-creation`). El skill ya cubre los 10 triggers y las 14 actions del backend.
196
+ > **Nuevo en 1.57.0:** triggers `query_created` (el agente creó una consulta) y `human_attention` (el agente escaló a un humano), más las actions `assign_advisor` y `notify_advisor`. Con esto el reparto de asesores y los avisos al equipo dejan de estar hardcodeados: son flows que el negocio edita. Sin flows de esos triggers aplica lo configurado con `advisors_notifications_set`.
197
+
198
+ > Para escribir flows con recetas y buenas prácticas, instala el skill `flows-creation` (`npx mergeon-mcp skills add flows-creation`). El skill ya cubre los 12 triggers y las 16 actions del backend.
197
199
 
198
200
  ### Calendario (9 tools)
199
201
  | Tool | Qué hace |
@@ -325,6 +327,17 @@ Endpoints HTTP que MergeOn expone para que sistemas externos creen contactos, ve
325
327
  | `workers_update` | Actualiza worker por `username`: rol, contacto, password, notificaciones o `admin_phone` (número personal para administrar el negocio por el WhatsApp admin de MergeOn; vacío = desvincular). |
326
328
  | `workers_delete` | Elimina worker por `username`. No permite borrarte a ti mismo ni a usuarios `adev`. |
327
329
 
330
+ ### Asesores — Reparto y avisos (5 tools)
331
+ | Tool | Qué hace |
332
+ |---|---|
333
+ | `advisors_assignment_get` | Cupo de reparto configurado: switch, modo (`weighted`/`equal`), peso de cada asesor, porcentajes resultantes, orden exacto de turnos, config de avisos y workers disponibles. **Llamar antes de cambiar cupos** para no borrarle la cuota a nadie. |
334
+ | `advisors_assignment_set` | Define quién recibe los contactos nuevos y en qué proporción (pesos relativos: 60/40 ≡ 3/2). Prender/apagar `enabled` crea/activa (o desactiva) el flow que ejecuta el reparto (`crm_created` → `assign_advisor`), que después se edita como cualquier flow. Escribe `CRM.attended_by`, la llave de la visibilidad por asesor y de los avisos dirigidos. |
335
+ | `advisors_notifications_set` | Avisos por WhatsApp al asesor desde el número del negocio (consulta, atención humana, orden nueva) con botones **Listo** e **Ir al chat**. `target: 'assigned'` = solo el asesor del contacto, con `fallback` para los contactos sin dueño. `order_created` migra el aviso histórico de orden nueva (`all` = como siempre, `assigned` = dirigido, `off` = lo hace un flow). |
336
+ | `advisors_alert_template_status` | Estado en Meta de la plantilla de aviso (APPROVED/PENDING/REJECTED o inexistente). Sin plantilla aprobada el aviso cae a texto con link y solo dentro de la ventana de 24h del asesor. |
337
+ | `advisors_alert_template_create` | Crea esa plantilla en la WABA del negocio (utility, 3 variables, quick reply `Listo` + botón URL `Ir al chat` con la conversación como sufijo dinámico). Una vez por negocio. |
338
+
339
+ > Reparto y avisos son **configuración + flows**, no lógica fija: `assign_advisor` y `notify_advisor` sirven en cualquier flow (`sold`, `lead_status_change`, `query_created`, `human_attention`…), y la config solo aplica cuando el negocio no tiene flows de ese trigger.
340
+
328
341
  ### Custom Tools (6 tools)
329
342
  | Tool | Qué hace |
330
343
  |---|---|
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ Postura por defecto (aplícala en TODA interacción sobre MergeOn):
17
17
  Conocimiento experto: las skills instaladas en el CLAUDE.md del usuario (prompt-creation, flows-creation, nurturing-creation, forms-creation, templates-creation, webhooks-usage, social-tracking, sales-analysis, meta-events-debug, reviews-usage) contienen la guía detallada de cada dominio. Si el usuario aún no las tiene, puede instalarlas todas con \`npx mergeon-mcp skills add all\`.`;
18
18
  const server = new McpServer({
19
19
  name: "mergeon",
20
- version: "1.45.1",
20
+ version: "1.57.0",
21
21
  }, { instructions: MERGEON_INSTRUCTIONS });
22
22
  // ── Superadmin cross-tenant override ─────────────────────────────────────────
23
23
  // Inyecta un parámetro `ecommerce_id` opcional en TODAS las tools y lo enruta al
@@ -0,0 +1,3 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { MergeOnClient } from "../client.js";
3
+ export declare function registerAdvisorsTools(server: McpServer, client: MergeOnClient): void;
@@ -0,0 +1,76 @@
1
+ import { z } from "zod";
2
+ function text(data) {
3
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
4
+ }
5
+ // Reparto automático de contactos entre asesores + avisos por WhatsApp al asesor.
6
+ // La configuración vive en extra_config; la EJECUCIÓN son las acciones de flow
7
+ // `assign_advisor` / `notify_advisor` (ver flows_get_catalog).
8
+ export function registerAdvisorsTools(server, client) {
9
+ server.tool("advisors_assignment_get", "Get how new contacts are auto-distributed among sales advisors: the on/off switch, the mode (weighted percentages vs equal), each advisor's share, the resulting percentages, the exact turn order the next contacts will follow, plus the current WhatsApp-alert settings and the list of workers available to assign. Read this before changing shares so you don't wipe someone's quota.", {}, async () => text(await client.get("/advisors/assignment")));
10
+ server.tool("advisors_assignment_set", `Set the advisor round-robin: who receives new contacts and in what proportion. Weights are RELATIVE, not a closed 100 — 60/40 and 3/2 distribute identically. Sends the full advisors list, so include every advisor that should keep a share (call advisors_assignment_get first).
11
+
12
+ Turning 'enabled' on/off also creates/activates (or deactivates) the flow that performs the distribution ("Reparto automático de asesores": trigger crm_created → action assign_advisor). Nothing is hardcoded: after enabling it, the business can open that flow with flows_list/flows_update to add conditions (only one city, only ad leads) or move the assignment to another trigger.
13
+
14
+ Assignment writes CRM.attended_by with the advisor's name, which is what the dashboard visibility rules ('own'/'strict', see ecommerce_worker_visibility_set) and the targeted WhatsApp alerts key off.`, {
15
+ enabled: z.boolean().describe("Master switch. false = only manual assignment with the 'Tomar' button"),
16
+ mode: z
17
+ .enum(["weighted", "equal"])
18
+ .optional()
19
+ .default("weighted")
20
+ .describe("'weighted' honors each advisor's weight; 'equal' ignores weights and distributes one by one"),
21
+ advisors: z
22
+ .array(z.object({
23
+ worker_name: z.string().describe("Advisor's full_name exactly as it will be written to CRM.attended_by"),
24
+ weight: z.number().int().min(0).describe("Relative share (e.g. 60 and 40). 0 = receives nothing"),
25
+ is_active: z.boolean().optional().default(true).describe("Whether this advisor takes part in the distribution"),
26
+ worker_id: z.number().optional().describe("Worker id (informational)"),
27
+ }))
28
+ .describe("Full roster with shares. Anyone omitted loses their quota"),
29
+ respect_existing: z
30
+ .boolean()
31
+ .optional()
32
+ .default(true)
33
+ .describe("true = never reassign a contact that already has an advisor; false = every run reassigns"),
34
+ only_active_workers: z
35
+ .boolean()
36
+ .optional()
37
+ .default(true)
38
+ .describe("Skip names that no longer exist as workers of this business"),
39
+ }, async (params) => text(await client.put("/advisors/assignment", params)));
40
+ server.tool("advisors_notifications_set", `Set the WhatsApp alerts sent to advisors from the BUSINESS's own number when the AI creates a query (create_query), escalates to a human (human_attention), or an order comes in. Each alert carries two buttons: "Listo" (marks the query/attention as solved straight from WhatsApp) and "Ir al chat" (deep link to that conversation in the dashboard).
41
+
42
+ 'target: assigned' is the targeted mode the merchant usually wants: only the advisor handling that contact gets pinged, with 'fallback' deciding what happens for contacts nobody has taken yet.
43
+
44
+ The two buttons only exist through an approved Meta template — create it with advisors_alert_template_create and check it with advisors_alert_template_status. Without it the alert still goes out, but as plain text with the chat link and only inside the advisor's 24h window.
45
+
46
+ This is the DEFAULT behavior. Any flow on the query_created / human_attention triggers overrides it, so build a flow when the business wants something different (a different wording, Sheets, escalating to another channel).`, {
47
+ enabled: z.boolean().describe("Master switch for advisor WhatsApp alerts"),
48
+ target: z
49
+ .enum(["assigned", "all", "role_asesor"])
50
+ .optional()
51
+ .default("assigned")
52
+ .describe("'assigned' = only the contact's advisor | 'all' = every worker with notifications on | 'role_asesor' = all advisors"),
53
+ fallback: z
54
+ .enum(["all", "none"])
55
+ .optional()
56
+ .default("all")
57
+ .describe("Who to alert when the contact has no advisor yet"),
58
+ respect_worker_optout: z
59
+ .boolean()
60
+ .optional()
61
+ .default(true)
62
+ .describe("true = only workers with notification_enabled get alerts"),
63
+ template_name: z
64
+ .string()
65
+ .optional()
66
+ .describe("Name of the Meta template with the two buttons (default 'mergeon_aviso_asesor')"),
67
+ order_created: z
68
+ .enum(["all", "assigned", "off"])
69
+ .optional()
70
+ .default("all")
71
+ .describe("New-order alert: 'all' keeps the legacy broadcast to every worker, 'assigned' pings only the contact's advisor, 'off' leaves it to a sold → notify_advisor flow"),
72
+ }, async (params) => text(await client.put("/advisors/notifications", params)));
73
+ server.tool("advisors_alert_template_status", "Check whether the advisor-alert template (the one with the 'Listo' and 'Ir al chat' buttons) exists in this business's WABA and its Meta review status (APPROVED / PENDING / REJECTED). Without an APPROVED template the alerts fall back to plain text inside the 24h window.", {}, async () => text(await client.get("/advisors/alert-template")));
74
+ server.tool("advisors_alert_template_create", "Create the advisor-alert template in this business's WABA: utility category, body with 3 variables (alert type, customer, detail) and buttons 'Listo' (quick reply) + 'Ir al chat' (URL with the conversation as dynamic suffix). Meta reviews it — usually minutes. Requires WhatsApp Business (WABA) connected. Run it once per business.", {}, async () => text(await client.post("/advisors/alert-template", {})));
75
+ }
76
+ //# sourceMappingURL=advisors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"advisors.js","sourceRoot":"","sources":["../../src/tools/advisors.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,SAAS,IAAI,CAAC,IAAS;IACrB,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,E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AAC,MAAM,MAAM,CAAC,GAAG,CAAC,yBAAyB,EAAE,MAAM,CAAC,CAAC,CAC5E,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,gCAAgC,EAChC,gRAAgR,EAChR,EAAE,EACF,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC,CAC/D,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,gCAAgC,EAChC,6UAA6U,EAC7U,EAAE,EACF,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,0BAA0B,EAAE,EAAE,CAAC,CAAC,CACpE,CAAC;AACJ,CAAC"}
@@ -18,6 +18,8 @@ const TRIGGER_TYPES = [
18
18
  "story_reply", // Respuesta a una historia de Instagram
19
19
  "decision_tree", // Chatbot secuencial activado por keyword
20
20
  "scheduled_send", // Envío programado a fecha/hora con send_template
21
+ "query_created", // El agente creó una consulta (create_query). Contexto: consulta + CRM.
22
+ "human_attention", // El agente pidió atención humana (human_attention). Contexto: problema + CRM.
21
23
  ];
22
24
  const ACTION_TYPES = [
23
25
  "send_message", // Envía texto. Soporta {{placeholders}} y aritmética {{amount-10000}}
@@ -35,6 +37,8 @@ const ACTION_TYPES = [
35
37
  "send_appointment_event", // Envía evento Schedule, Lead o Purchase a Meta CAPI con el precio de la cita (trigger appointment_created)
36
38
  "send_to_sheets", // Append fila a Google Sheets {sheet_name, mapping, spreadsheet_id?}
37
39
  "change_order_status", // Cambia status de la orden. Válidos: pending, processing, ready_to_ship, sent, completed, return, change, canceled
40
+ "assign_advisor", // Asigna asesor al contacto (reparto por porcentajes o persona fija)
41
+ "notify_advisor", // Avisa por WhatsApp al asesor con botones Listo / Ir al chat
38
42
  ];
39
43
  const ORDER_STATUSES = [
40
44
  "pending", "processing", "ready_to_ship", "sent",
@@ -61,6 +65,7 @@ Conditions are trigger-specific:
61
65
  - crm_created / first_message / sold: any CRM/order field as { field: value }, { field: [values] } or { field_not_in: [values] }
62
66
  - decision_tree: { start_text: string|string[], ttl_seconds?: 30..86400, farewell_message?: string }
63
67
  - scheduled_send: { target_session_id?: string, target_source?: 'whatsapp'|'instagram'|'messenger', crm_filters?: object } — target_session_id+target_source OR crm_filters (mutually exclusive)
68
+ - query_created / human_attention: { equal_text?: string|string[], similar_text?: string } match the query/problem TEXT; any other key is matched against the CRM contact (city, status, source…)
64
69
 
65
70
  Each action is an object {action_type: payload}. Valid action_type values: ${ACTION_LIST}. See flows_get_catalog for full schemas.`, {
66
71
  name: z.string().describe("Flow name"),
@@ -175,6 +180,16 @@ Each action is an object {action_type: payload}. Valid action_type values: ${ACT
175
180
  description: "Envío programado a fecha/hora. Requiere scheduled_at. Acción única send_template.",
176
181
  conditions: ["target_session_id + target_source (whatsapp|instagram|messenger)", "OR crm_filters (object) — mutuamente excluyentes"],
177
182
  },
183
+ {
184
+ name: "query_created",
185
+ description: "El agente creó una consulta con create_query (ej. disponibilidad en bodega). Contexto: la consulta + el CRM del contacto. Corren TODOS los flows que matchean. Si el negocio no tiene ningún flow de este trigger, se aplica el aviso configurado en extra_config.advisor_notifications; al crear el primer flow, manda el flow.",
186
+ conditions: ["equal_text / similar_text (sobre el texto de la consulta)", "+ any CRM field (city, status, source…)"],
187
+ },
188
+ {
189
+ name: "human_attention",
190
+ description: "El agente pidió atención humana / hubo un error y se creó una atención requerida. Contexto: el problema + el CRM. Misma precedencia que query_created (sin flows → aviso configurado).",
191
+ conditions: ["equal_text / similar_text (sobre la descripción del problema)", "+ any CRM field"],
192
+ },
178
193
  ],
179
194
  action_types: [
180
195
  { name: "send_message", payload: "string with {{placeholders}}", channels: ["whatsapp", "instagram"] },
@@ -192,12 +207,23 @@ Each action is an object {action_type: payload}. Valid action_type values: ${ACT
192
207
  { name: "send_appointment_event", payload: "{event_name?: 'Schedule'|'Lead'|'Purchase'} — envía el evento a Meta CAPI con el precio de la cita como value (default 0). event_name default 'Schedule'; usa 'Lead' si la pauta optimiza por cliente potencial o 'Purchase' para reportar la agenda como compra sin crear un pedido", restriction: "requires appointment context (trigger appointment_created)" },
193
208
  { name: "send_to_sheets", payload: "{sheet_name: string, mapping: {column: 'value or {{placeholder}}'}, spreadsheet_id?: string}", restriction: "requires Google Sheets connected" },
194
209
  { name: "change_order_status", payload: "string status OR {status} — válidos: " + ORDER_STATUSES.join(", "), restriction: "requires order context" },
210
+ {
211
+ name: "assign_advisor",
212
+ payload: "{} para repartir según los cupos de advisors_assignment_get, {worker_name: 'Nombre'} para mandar el caso a una persona fija, {reassign: true} para pisar el asesor que ya tenga",
213
+ restriction: "requires CRM context (se resuelve solo desde order/message si hace falta)",
214
+ },
215
+ {
216
+ name: "notify_advisor",
217
+ payload: "{title?: string, detail?: string (acepta {{placeholders}}), to?: 'assigned'|'all'|'role_asesor', worker_name?: string} — sale del número del negocio con botones Listo / Ir al chat; NO le llega al cliente",
218
+ restriction: "el aviso con botones requiere la plantilla aprobada (advisors_alert_template_*); sin ella cae a texto con link y solo dentro de la ventana de 24h del asesor",
219
+ },
195
220
  ],
196
221
  order_statuses: ORDER_STATUSES,
197
222
  placeholders: {
198
223
  order: ["customer_name", "name", "user_name", "address", "city", "phone", "user_phone", "email", "amount", "total", "provider", "status", "order_id", "id", "observations", "delivery_price", "products", "product_names"],
199
224
  crm: ["name", "customer_name", "user_name", "phone", "cellphone", "user_phone", "city", "country", "source", "status", "ig_id", "ig_user", "messenger_id", "notes", "attended_by", "id", "contacted_at", "last_message"],
200
225
  message: ["content", "message", "session_id", "source", "type"],
226
+ event: ["query_description", "problem_description", "detail", "title", "attended_by (alias: advisor)", "customer_name", "session_id", "kind"],
201
227
  time: ["now", "now_iso", "now_date"],
202
228
  arithmetic: "expressions like {{amount - 10000}}, {{amount * 0.9}}, {{amount + delivery_price}} — only on order numeric fields (amount, total, delivery_price)",
203
229
  },
@@ -1 +1 @@
1
- {"version":3,"file":"flows.js","sourceRoot":"","sources":["../../src/tools/flows.ts"],"names":[],"mappings":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AAC;YACxN,OAAO,EAAE,CAAC,SAAS,EAAE,SAAS,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,CAAC;YAC/D,KAAK,EAAE,CAAC,mBAAmB,EAAE,qBAAqB,EAAE,QAAQ,EAAE,OAAO,EAAE,8BAA8B,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,CAAC;YAC7I,IAAI,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,CAAC;YACpC,UAAU,EAAE,mJAAmJ;SAChK;KACF,CAAC,CACH,CAAC;AACJ,CAAC"}
@@ -8,6 +8,7 @@ import { registerCalendarTools } from "./calendar.js";
8
8
  import { registerMarketingTools } from "./marketing.js";
9
9
  import { registerAnalyticsTools } from "./analytics.js";
10
10
  import { registerWorkersTools } from "./workers.js";
11
+ import { registerAdvisorsTools } from "./advisors.js";
11
12
  import { registerAdminTools } from "./admin.js";
12
13
  import { registerAgentConfigTools } from "./agent-config.js";
13
14
  import { registerAgentsRegistryTools } from "./agents-registry.js";
@@ -36,6 +37,7 @@ export function registerAllTools(server, client) {
36
37
  registerMarketingTools(server, client);
37
38
  registerAnalyticsTools(server, client);
38
39
  registerWorkersTools(server, client);
40
+ registerAdvisorsTools(server, client);
39
41
  registerAdminTools(server, client);
40
42
  registerAgentConfigTools(server, client);
41
43
  registerAgentsRegistryTools(server, client);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAA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,sBAAsB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,2BAA2B,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC5C,uBAAuB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,sBAAsB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,qBAAqB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,yBAAyB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,kBAAkB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,oBAAoB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,kBAAkB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,iCAAiC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClD,gBAAgB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,wBAAwB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mergeon-mcp",
3
- "version": "1.56.0",
3
+ "version": "1.57.0",
4
4
  "description": "MCP server for MergeOn Seller — manage your ecommerce CRM, orders, products, flows, calendar and more from Claude",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -52,6 +52,8 @@ Un flow es una automatización que se dispara ante un evento (trigger) y ejecuta
52
52
  | `story_reply` | Cuando alguien responde una historia de IG | Captar leads de historias |
53
53
  | `decision_tree` | Chatbot secuencial activado por keyword | Menú de opciones, FAQ automática |
54
54
  | `scheduled_send` | Envío programado a fecha/hora | Recordatorios, follow-ups en X horas, campañas con fecha fija |
55
+ | `query_created` | El agente creó una consulta (`create_query`) | Avisar al asesor que hay que confirmar stock, asignar quién la atiende |
56
+ | `human_attention` | El agente pidió atención humana (`human_attention`) | Avisar al asesor asignado, escalar por ciudad, registrar la escalación |
55
57
 
56
58
  > **Estados válidos de pedido** (para `to_status` / `from_status` en `order_status_change` y `change_order_status`): `pending`, `processing`, `ready_to_ship`, `sent`, `completed`, `return`, `change`, `canceled`. **No existen** `shipped` ni `confirmed`.
57
59
 
@@ -142,6 +144,26 @@ Las condiciones son opcionales. Si no hay condiciones, el flow se activa para TO
142
144
 
143
145
  > Reglas: `scheduled_at` es **obligatorio**. `target_session_id`+`target_source` y `crm_filters` son **mutuamente excluyentes**. La única acción permitida es `send_template`.
144
146
 
147
+ ### Para `query_created` y `human_attention`:
148
+
149
+ `equal_text` / `similar_text` se evalúan contra el TEXTO del evento (la consulta o la
150
+ descripción del problema). Cualquier otra clave se evalúa contra el contacto.
151
+
152
+ ```json
153
+ { "similar_text": "talla, disponibilidad, stock" }
154
+ // Solo consultas de disponibilidad
155
+
156
+ { "city": "Bogotá" }
157
+ // Solo escalaciones de clientes de Bogotá
158
+
159
+ { "similar_text": "error, no puedo", "status": "sold" }
160
+ // Problemas de clientes que YA compraron (postventa)
161
+ ```
162
+
163
+ > **Precedencia:** si el negocio tiene flows activos de estos triggers, corren TODOS los que
164
+ > matchean y manda el flow. Si no tiene ninguno, se aplica el aviso configurado
165
+ > (`advisors_notifications_set`). Nunca se duplica el aviso.
166
+
145
167
  ---
146
168
 
147
169
  ## ACTIONS — Qué hace el flow
@@ -406,8 +428,83 @@ Manda el evento a Meta CAPI con el **precio de la cita** como `value` (default 0
406
428
 
407
429
  ---
408
430
 
431
+ ### `assign_advisor` — Asignar asesor al contacto
432
+
433
+ ```json
434
+ { "assign_advisor": {} }
435
+ // Reparte según los cupos del negocio (60/40, equitativo…) configurados con
436
+ // advisors_assignment_set. Escribe attended_by en el CRM.
437
+
438
+ { "assign_advisor": { "worker_name": "Laura Gómez" } }
439
+ // Manda estos casos siempre a una persona fija (ej. flow con condition city=Cali).
440
+
441
+ { "assign_advisor": { "reassign": true } }
442
+ // Reasigna aunque el contacto ya tenga asesor (por defecto NO se pisa).
443
+ ```
444
+
445
+ Requiere contacto en el contexto. En flows de venta o de mensaje el contacto se resuelve solo.
446
+ El reparto es un round-robin ponderado determinista: con 60/40 el turno alterna y la proporción
447
+ se cumple desde los primeros contactos, no "en promedio".
448
+
449
+ ---
450
+
451
+ ### `notify_advisor` — Avisar por WhatsApp al asesor
452
+
453
+ ```json
454
+ {
455
+ "notify_advisor": {
456
+ "title": "Consulta nueva",
457
+ "detail": "{{query_description}}",
458
+ "to": "assigned"
459
+ }
460
+ }
461
+ ```
462
+
463
+ - Sale del **número del negocio** hacia el teléfono del worker. **El cliente no lo ve.**
464
+ - Trae dos botones: **Listo** (marca resuelta la consulta/atención desde WhatsApp) e
465
+ **Ir al chat** (abre esa conversación en el dashboard).
466
+ - `to`: `assigned` (solo el asesor del contacto) | `role_asesor` (todos los asesores) |
467
+ `all` (todo el equipo con notificaciones activas). También acepta `worker_name` para una
468
+ persona fija.
469
+ - Los botones exigen la plantilla aprobada de Meta (`advisors_alert_template_create`). Sin
470
+ ella el aviso llega como texto con el link, y solo si el asesor le escribió al número del
471
+ negocio en las últimas 24h.
472
+
473
+ **Combo típico**: `assign_advisor` + `notify_advisor` en el mismo flow — primero se asigna,
474
+ después se avisa a quien quedó asignado.
475
+
476
+ ---
477
+
409
478
  ## RECETAS — Flows listos para crear
410
479
 
480
+ ### 👥 0. Consulta del agente → aviso al asesor asignado
481
+ **Trigger**: `query_created` | Sin condiciones (todas las consultas)
482
+
483
+ ```json
484
+ {
485
+ "name": "Consulta nueva → aviso al asesor",
486
+ "trigger_type": "query_created",
487
+ "is_active": true,
488
+ "conditions": null,
489
+ "actions": [
490
+ { "assign_advisor": {} },
491
+ {
492
+ "notify_advisor": {
493
+ "title": "Consulta de disponibilidad",
494
+ "detail": "{{query_description}}",
495
+ "to": "assigned"
496
+ }
497
+ }
498
+ ],
499
+ "continue_agent": false
500
+ }
501
+ ```
502
+
503
+ Variante para atención humana: mismo flow con `"trigger_type": "human_attention"` y
504
+ `"detail": "{{problem_description}}"`.
505
+
506
+
507
+
411
508
  ### 🛒 1. Confirmación de venta (post-compra)
412
509
  **Trigger**: `sold` | **Condiciones**: ninguna (aplica a todas las ventas)
413
510
 
@@ -733,6 +830,9 @@ Pregunta al usuario:
733
830
  | "menú de opciones" / "chatbot" | `decision_tree` |
734
831
  | "cuando la historia recibe respuesta" | `story_reply` |
735
832
  | "envíalo en X días" / "recordatorio programado" | `scheduled_send` (con `scheduled_at`) |
833
+ | "cuando el agente pregunta si hay stock" / "cuando crea una consulta" | `query_created` |
834
+ | "cuando el agente pide un humano" / "cuando escala" | `human_attention` |
835
+ | "que le reparta los clientes a los asesores" | `crm_created` + `assign_advisor` |
736
836
 
737
837
  ### Paso 3 — Elegir la action correcta
738
838
 
@@ -750,6 +850,8 @@ Pregunta al usuario:
750
850
  | Trackear conversión en Meta Ads (Lead) | `send_lead_event` |
751
851
  | Trackear conversión en Meta Ads (Purchase) | `send_order_event` |
752
852
  | Registrar en Google Sheets | `send_to_sheets` |
853
+ | Repartir el contacto entre asesores | `assign_advisor` |
854
+ | Avisar al asesor por WhatsApp (no al cliente) | `notify_advisor` |
753
855
  | Añadir contexto a respuesta de historia IG | `story_context` |
754
856
 
755
857
  **⚠️ Recordar siempre**: `send_message` NO necesita template de Meta. Funciona directamente. Solo usar `send_template` cuando el cliente esté fuera de la ventana de 24h.