mergeon-mcp 1.78.0 → 1.81.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 (243)](#tools-disponibles)
20
+ 3. [Tools disponibles (217)](#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 243 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**.
39
+ Las 217 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
- 243 tools organizadas en 26 dominios. Cada nombre corresponde a la cadena exacta que verás en Claude Desktop.
131
+ 217 tools organizadas en 25 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
 
@@ -172,9 +172,9 @@ npx mergeon-mcp skills list
172
172
  |---|---|
173
173
  | `products_list` | Catálogo paginado, búsqueda por `search` (nombre/descripción), `sort`, `limit`, `offset`. |
174
174
  | `products_get` | Detalle por `identificator` (ID o slug), incluye variantes, imágenes, inventario. |
175
- | `products_create` | Crea producto. Requiere `name` y `price`. Opcionales: `description`, `available` (pásalo `true` para publicarlo), `brand`, `category` (string o lista — se envía como lista), `discount_price`/`has_discount`, `slug`, `video_url`, `variants`, `duration_minutes`, `capacity`. **Las imágenes, el stock y el precio por tamaño viven en `variants`** (no hay columna `photo_url` a nivel producto): cada variante lleva su `photo_url`, su `stock` y, **nuevo en 1.73.0**, su `price`/`discount_price` propios para cuando el tamaño cambia lo que se cobra (pizza personal vs familiar, talla XS vs XXL). Sin `price`, la variante se vende al precio del producto — que es como se comporta todo el catálogo que ya existe. El **video sí es de producto** (`video_url`). **Servicios agendables (verticales health/services):** un servicio es un producto con `duration_minutes` y `capacity`; su `price` es el valor que se reporta a Meta como el del evento Schedule (0 si la consulta es gratuita). **Funciona donde el catálogo lo maneja MergeOn** (`scratch`, `siigo`, `shopify_synced`); da 403 en las fuentes que se leen en vivo (rol `shopify` o `woocommerce`). |
176
- | `products_update` | PUT parcial de campos del producto: `name`, `price`, `description`, `available`, `brand`, `category`, `discount_price`/`has_discount`, `stock`/`manage_stock`, `slug`, `video_url`, `variants`, `duration_minutes`, `capacity`. Pasar `variants` **reemplaza** el array completo; es la vía para fijar fotos y precios por variante (`price`/`discount_price` propios, **nuevo en 1.73.0**). `video_url` es el video de venta que el agente manda por WhatsApp (menos de 14 MB para que se reproduzca dentro del chat). En un producto que vino de una integración, **cada campo que cambies acá queda marcado como editado a mano y las sincronizaciones dejan de pisarlo**. En servicios agendables, `duration_minutes` y `capacity` mandan sobre los defaults del negocio. |
177
- | `products_bulk_update` | Aplica los mismos cambios a varios productos a la vez. Útil para subir/bajar precios en masa o (des)activar lotes. En productos que vinieron de una integración, marca los campos como editados a mano igual que `products_update`, así que las sincronizaciones no los pisan. |
175
+ | `products_create` | Crea producto. Requiere `name` y `price`. Opcionales: `description`, `available` (pásalo `true` para publicarlo), `brand`, `category` (string o lista — se envía como lista), `discount_price`/`has_discount`, `slug`, `variants`, `duration_minutes`, `capacity`. **Las imágenes y el stock viven en `variants`** (no hay columna `photo_url` a nivel producto): cada variante lleva su `photo_url` y `stock`. **Servicios agendables (verticales health/services):** un servicio es un producto con `duration_minutes` y `capacity`; su `price` es el valor que se reporta a Meta como el del evento Schedule (0 si la consulta es gratuita). **No funciona en fuentes read-only (Shopify).** |
176
+ | `products_update` | PUT parcial de campos del producto: `name`, `price`, `description`, `available`, `brand`, `category`, `discount_price`/`has_discount`, `stock`/`manage_stock`, `slug`, `variants`, `duration_minutes`, `capacity`. Pasar `variants` **reemplaza** el array completo; es la vía para fijar fotos por variante. En servicios agendables, `duration_minutes` y `capacity` mandan sobre los defaults del negocio. |
177
+ | `products_bulk_update` | Aplica los mismos cambios a varios productos a la vez. Útil para subir/bajar precios en masa o (des)activar lotes. |
178
178
  | `products_bulk_create` | Crea MUCHOS productos de una (array `products`, mismos campos que `products_create`). Para cargar un catálogo entero sin subir uno por uno. Crea cada uno por separado (una fila mala falla sola sin frenar el resto) y devuelve `{ total, created, failed, results }` con id o error por ítem. |
179
179
 
180
180
  ### Conversaciones (4 tools)
@@ -182,7 +182,7 @@ npx mergeon-mcp skills list
182
182
  |---|---|
183
183
  | `conversations_list` | Lista sesiones (hilos WhatsApp/Instagram) con paginación. |
184
184
  | `conversations_get` | Mensajes completos de una sesión por `session_id`. Los salientes traen `metadata.origin` (`ai`, `flow`, `nurturing`, `scheduled`, `reminder`, `nps`, `campaign`, `human`) + `metadata.worker` (asesor) y `metadata.origin_name` (flujo/regla). |
185
- | `conversations_search` | Busca texto en mensajes de todas las conversaciones (mínimo 3 caracteres). Filtros: `from_user`, `from_agent`. |
185
+ | `conversations_search` | Busca texto en mensajes de todas las conversaciones. Filtros: `from_user`, `from_agent`. |
186
186
  | `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). |
187
187
 
188
188
  ### Flujos / Flows (6 tools + catálogo descubrible)
@@ -395,7 +395,7 @@ Endpoints HTTP que MergeOn expone para que sistemas externos creen contactos, ve
395
395
  | `admin_channel_conversations_list` | **Nuevo en 1.56.0:** conversaciones de los dueños de negocio con el asistente de MergeOn por el número de administración: una por worker con `admin_phone`, ordenadas por actividad, con preview del último mensaje. Solo lectura. |
396
396
  | `admin_channel_conversation_get` | **Nuevo en 1.56.0:** hilo completo de un cliente con el asistente admin (orden cronológico), por `worker_id`. Solo lectura. |
397
397
 
398
- ### Agentes del negocio — Registro (11 tools)
398
+ ### Agentes del negocio — Registro (7 tools)
399
399
 
400
400
  Un **agente** es un prompt con nombre propio. Los canales (WhatsApp, Instagram, Messenger, comentarios) y las tareas (lectura de imágenes, remarketing por estado del lead) son **usos** que se le asignan. El mismo agente puede atender varios usos, y un negocio puede tener tantos agentes como quiera.
401
401
 
@@ -408,20 +408,9 @@ Un **agente** es un prompt con nombre propio. Los canales (WhatsApp, Instagram,
408
408
  | `agents_delete` | Borra un agente. Los usos que atendía quedan sin agente (caen al fallback del canal o dejan de responder). |
409
409
  | `agents_usages_get` | Todos los usos del sistema y quién atiende cada uno. `resolved_from`: `assigned` \| `fallback` \| `legacy` \| `empty`. |
410
410
  | `agents_usage_assign` | Apunta un uso a un agente (o `agent_id: null` para desasignarlo). Un uso tiene exactamente un agente. |
411
- | `experiments_list` | Los experimentos del negocio, activos y pausados, con sus variantes, pesos y contactos fijados. |
412
- | `experiments_create` | Crea un experimento sobre un canal: reparto A/B por pesos, o prueba dirigida (peso 0 + `pinned_contacts`). |
413
- | `experiments_update` | Edita variantes, pesos, fijados, ventana o on/off. `variants` REEMPLAZA la lista completa. |
414
- | `experiments_delete` | Borra el experimento. Los contactos ya asignados conservan su variante y las ventas siguen atribuidas. |
415
411
 
416
412
  **Cadena de fallback entre canales**: `messenger` → `instagram` → `whatsapp`. Si un canal no tiene agente propio, hereda el del siguiente en la cadena.
417
413
 
418
- **Experimentos: A/B vs dirigida.** Un experimento apunta a un canal y reparte sus contactos entre 2+ variantes, donde cada variante es un agente entero. Dos formas de usarlo:
419
-
420
- - **Reparto A/B** — todas las variantes con peso ≥ 1. El contacto cae de forma determinista (`sha256` de su identificador) y la variante se congela en el CRM la primera vez, así la venta se atribuye aunque llegue semanas después.
421
- - **Prueba dirigida** — el control en peso 1, la variante nueva en peso 0 y sus `pinned_contacts` con los teléfonos o usuarios de IG a probar. Solo esos contactos ven el agente nuevo. Los fijados mandan sobre el reparto y sobre una variante ya congelada, así que sirven para mover a alguien a la rama de prueba a mitad de camino.
422
-
423
- Los resultados de las dos salen en `sales_by_variant` (órdenes, revenue, contactos y conversión por variante).
424
-
425
414
  ### Agente IA — Configuración (15 tools)
426
415
 
427
416
  > ⚠️ Los tools `agent_prompts_*` son la API **anterior** al registro de agentes. Siguen funcionando (escriben en el agente que atiende ese canal), pero para crear o reasignar agentes usa el dominio de arriba.
@@ -492,7 +481,7 @@ Plantillas oficiales (HSM) y libres internas. Para creación avanzada (headers m
492
481
 
493
482
  > **Nuevo en 1.58.0:** el header de media ahora respeta el `mime_type` (video y documento ya no se mandaban como imagen) y el título de texto (`HEADER` format `TEXT`) sí se envía a Meta cuando la plantilla no lleva archivo — antes se descartaba en silencio. `button_types` quedó en los dos que el backend realmente envía: `URL` y `QUICK_REPLY`.
494
483
 
495
- ### Ecommerce (21 tools)
484
+ ### Ecommerce (16 tools)
496
485
  | Tool | Qué hace |
497
486
  |---|---|
498
487
  | `ecommerce_get` | Configuración del ecommerce, incluido el bloque `config` (country, currency, store_address). Default: el tuyo. |
@@ -506,11 +495,6 @@ Plantillas oficiales (HSM) y libres internas. Para creación avanzada (headers m
506
495
  | `ecommerce_resources_set` | **Nuevo en 1.52.0:** define los ESPACIOS reservables del negocio (consultorios, salas, cabinas) en `extra_config.resources`. Es lo que permite responder "qué consultorio está libre a las 2pm" en vez de solo "el negocio está ocupado": dos citas a la misma hora son válidas en espacios distintos. Cada espacio lleva `id` corto y estable, `name`, `calendar_id` de Google propio (sin él solo cuentan las citas de MergeOn, no lo que el equipo agenda a mano) y `services` (vacío = uso mixto). Reemplaza la lista completa; `[]` desactiva el agendamiento por espacio. Se consulta con `calendar_resource_availability` y el bot lo usa con la tool `check_resource_availability`. |
507
496
  | `ecommerce_booking_rules_get` | **Nuevo en 1.53.0:** lee las barreras de agendamiento del negocio (`extra_config.booking_rules`). Úsala para diagnosticar un negocio que reporta citas dobles o duplicadas antes de tocar nada. Devuelve los defaults (desactivado) si nunca se configuraron. |
508
497
  | `ecommerce_booking_rules_set` | **Nuevo en 1.53.0, ampliado en 1.54.0:** barreras DURAS de agendamiento que el agente de IA no puede saltarse (`extra_config.booking_rules`). Sin ellas, lo único que evita que la IA meta cuatro clientes en la franja de las 4:30 es que se acuerde de llamar `check_available_slots` y le haga caso — una sugerencia del prompt, no una regla. Se validan en el servidor ANTES de escribir la cita. Aplican SOLO a la IA: el equipo humano sigue pudiendo sobreagendar desde el dashboard. Campos: `max_per_slot` (citas en la misma hora exacta), `max_per_hour` (2:00 y 2:30 cuentan juntas, 0 = sin tope), `max_per_day`, `allow_same_day` (false = nunca hoy, tampoco al reprogramar), `min_notice_hours`, `max_days_ahead`, `one_active_per_contact` (le mueve la cita que ya tiene en vez de crear otra), `duplicate_window_minutes` (reintento de la IA sobre la misma cita → devuelve la existente en vez de duplicarla), `default_duration_minutes` (con esto el motor detecta solapes REALES: sin duración, una cita de 2:00 de una hora y otra de 2:30 parecían franjas distintas), `allow_parallel_services` (si dos servicios DISTINTOS pueden ocupar la misma franja; false = agenda de un solo profesional) y `max_per_contact_per_day`. Los cupos y la duración de cada servicio se fijan en el catálogo con `products_update` y pisan estos defaults. Merge parcial seguro. |
509
- | `ecommerce_capabilities_get` | **Nuevo en 1.76.0:** qué hace ESTE negocio de verdad: lo que hereda de su vertical más lo que prendió y apagó, ya resuelto. Las capacidades deciden qué pestañas existen, qué campos pide el formulario de venta y qué pantalla de ventas ve — así que es lo primero que se consulta cuando un cliente dice que le falta algo en el dashboard. |
510
- | `ecommerce_capabilities_set` | **Nuevo en 1.76.0:** prende y apaga capacidades sueltas por encima del vertical. Es lo que hace que una tienda tenga además Agenda, o un consultorio tenga además el tablero de Pedidos: **el vertical es un punto de partida, no una jaula**. Se guarda como DELTA contra el vertical, nunca como lista resuelta, para que el negocio siga heredando lo que su vertical gane después. `order_view` cambia la pantalla de ventas (`kanban` = tablero por estado, `ledger` = registro de ventas; vacío = la del vertical). |
511
- | `ecommerce_verticals_list` | **Nuevo en 1.75.0:** los verticales que existen y qué SABE HACER cada uno — sus capacidades (despacha, agenda, tiene cocina, maneja mesas…), los estados de embudo que ofrece y cómo le dice a sus cosas (un restaurante tiene *carta* de *platos*; un consultorio, *servicios* y *pacientes*). Léelo antes de fijar un `business_type`: el vertical decide qué pestañas aparecen y qué campos pide el formulario de venta, así que elegir mal le esconde features reales al cliente. Sale del servidor, así que nunca está desactualizado. |
512
- | `ecommerce_preparation_get` | **Nuevo en 1.74.0:** cuánto se está demorando el negocio AHORA y si está tomando pedidos (`extra_config.preparation`). Resuelve los ajustes temporales: si la demora o la pausa ya vencieron, las devuelve apagadas. Para diagnosticar un agente que cotiza tiempos que no son, o que dice que está cerrado cuando debería estar recibiendo. |
513
- | `ecommerce_preparation_set` | **Nuevo en 1.74.0:** tiempo de preparación que cotiza el agente, y pausa de recepción de pedidos. Para negocios que producen contra pedido (cocina, pastelería, taller), donde el tiempo cambia durante el día. El agente lo lee en cada mensaje, así que cotiza el tiempo de HOY y no uno escrito en el prompt hace meses. `paused: true` es una barrera DURA: la IA no puede cerrar una orden mientras esté activa, por más que el cliente insista, y responde con `paused_message`. Campos: `min_minutes`/`max_minutes` (rango normal), `delivery_extra_minutes` (lo que suma el domicilio), `busy` + `busy_min_minutes`/`busy_max_minutes` + `busy_until` (hoy vamos más lento), `paused` + `paused_until` + `paused_message`, `timezone`. **Los `*_until` caducan solos** — es el punto de la feature: la pausa que hay que quitar a mano se queda puesta y mata las ventas del día siguiente. Merge parcial seguro. |
514
498
  | `connection_link_create` | **Nuevo en 1.50.0:** genera un link de un solo uso para que el dueño del negocio conecte una cuenta desde su celular, sin dashboard ni sesión. Sirve para `whatsapp`, `meta_all`, `instagram`, `shopify`, `woocommerce`, `wompi`, `mercadopago`, `epayco` y `elevenlabs`. Vence a los 30 minutos y el token identifica al negocio, así que el activo de Meta vuelve sin ambigüedad. |
515
499
  | `ecommerce_admin_assistant_set` | **Nuevo en 1.51.0:** modelo y topes del ASISTENTE INTERNO por WhatsApp (canal admin) — no del bot de ventas, ese es `agent_model_set`. Cada conversación arranca con el modelo potente y baja al económico al agotarse el cupo. `smart_requests` es la ráfaga por ventana; `smart_weekly` y `smart_monthly` son topes por persona alineados al calendario y acotan SOLO el modelo caro (0 = sin tope). El que corta el servicio es `max_requests` por `window_minutes`. Con `scope: 'clients'` sobre el ecommerce de un implementador, define el default de todos sus negocios; cada uno lo pisa campo por campo con `scope: 'own'`. |
516
500
  | `ecommerce_whatsapp_catalog_sync` | Vincula el catálogo del negocio a WhatsApp (Meta Commerce): conecta al WABA, lo hace visible y sube los productos (pueden venir de Shopify). Crear/subir productos requiere el permiso `catalog_management` de Meta (App Review). |
@@ -535,15 +519,6 @@ Reseñas y testimonios de clientes. Endpoint público `/reviews/`. Skill: `revie
535
519
  |---|---|
536
520
  | `channels_get_catalog` | Canales de mensajería disponibles y qué puede cada uno: límite de texto, imágenes, botones, plantillas, si el negocio puede escribir primero (`business_initiated`), ventana de respuesta y tope de mensajes seguidos. Consúltala **antes** de crear flows, nurturing o envíos programados para no apuntar a un canal con una capacidad que no tiene. |
537
521
 
538
- ### Shopify (4 tools)
539
- | Tool | Qué hace |
540
- |---|---|
541
- | `shopify_sync_config_get` | Lee la configuración de confirmación de pedidos por WhatsApp: si está activa, qué plantilla se manda, qué pedidos califican y qué pasa al confirmar/cancelar/no responder. Un negocio sin fila devuelve los defaults, que están apagados. |
542
- | `shopify_sync_status` | Si el negocio está listo para confirmar pedidos por WhatsApp: tienda conectada, si está activo y una lista `missing` de lo que falta. Úsala antes de diagnosticar "al cliente nunca le llegó el mensaje". |
543
- | `shopify_sync_config_update` | Configura la confirmación de pedidos. `enabled: true` exige `template_name` (el comprador nunca escribió, así que el primer mensaje solo puede ser plantilla aprobada de Meta). Cancelar en Shopify es irreversible: `on_cancel.cancel_in_shopify` es `false` por defecto y solo etiqueta. |
544
- | `shopify_register_webhooks` | **Nuevo en 1.72.0:** registra en la tienda los webhooks que le falten. El callback de OAuth solo cubre instalaciones NUEVAS, así que un negocio que conectó Shopify antes de que existiera un topic nunca lo recibe — es el caso de los pedidos borrador (`draft_orders/*`), los que crean varias apps de contraentrega en vez de órdenes reales. Sin esto, esos pedidos nunca llegan. Seguro de re-correr (Shopify deduplica por topic + URL). `dry_run` para ver qué registraría. Si la respuesta trae `warning` sobre `SHOPIFY_ORDER_SYNC`, los topics de pedidos NO se registraron. |
545
- | `shopify_sync_products` | **Nuevo en 1.71.0:** copia el catálogo de Shopify a la tabla de productos de MergeOn. Solo aplica con rol de catálogo `shopify_synced` (con `shopify` se lee la API en vivo y no hay filas que sincronizar). Los productos sincronizados ganan embedding —el agente los busca por significado y no por palabra clave— y se vuelven editables, que es la única forma de ponerles video. Repetirla es seguro: empareja por ID de Shopify, **nunca pisa los campos que el negocio editó a mano** y lo que desaparece de Shopify se marca no disponible en vez de borrarse. **Nunca escribe en Shopify.** Usa `dry_run` primero en catálogos grandes. Mientras no existan los webhooks de producto/inventario, el stock es tan fresco como la última corrida. |
546
-
547
522
  ---
548
523
 
549
524
  ## Skills incluidos
@@ -1,5 +1,4 @@
1
1
  import { z } from "zod";
2
- import { VERTICAL_KEYS } from "../verticals.js";
3
2
  function text(data) {
4
3
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
5
4
  }
@@ -13,9 +12,9 @@ export function registerAdminTools(server, client) {
13
12
  password: z.string().describe("Admin worker password"),
14
13
  country_code: z.string().optional().describe("Phone country code, default '57'"),
15
14
  business_type: z
16
- .enum(VERTICAL_KEYS)
15
+ .enum(["ecommerce", "services", "health"])
17
16
  .optional()
18
- .describe("Business vertical. It is not just a label: it decides which dashboard tabs appear, which lead states are offered and which fields the sale form asks for — a business that does not ship never sees address or shipping cost. Call `ecommerce_verticals_list` to see what each one can do before choosing. Default 'ecommerce'."),
17
+ .describe("Business vertical, controls which dashboard tabs and lead states show. 'ecommerce' (store/products), 'services' (professional services: agenda & appointments) or 'health' (clinic/patients: agenda-focused). Default 'ecommerce'."),
19
18
  implementer_id: z
20
19
  .number()
21
20
  .optional()
@@ -55,17 +54,10 @@ export function registerAdminTools(server, client) {
55
54
  // Números que el socio trae de SU cuenta de Meta (demos, operación propia).
56
55
  // El alta pasa por el Embedded Signup en el dashboard; por aquí se mueven.
57
56
  server.tool("admin_portfolio_numbers_list", "List the WhatsApp numbers in your own portfolio (numbers you onboarded from your own Meta business, not your clients'), showing which ecommerce each one serves or that it is free. Also returns 'portfolio': the other numbers Meta reports in the WABAs you already connected, so you can see what else you could bring in.", {}, async () => text(await client.get("/admin/my-numbers")));
58
- server.tool("admin_portfolio_number_assign", "Connect one of your own portfolio numbers to an ecommerce you own. Without 'replace' it fails with 409 if the target already has a number or if this number is still in use elsewhere. With replace:true it is a one-step swap: the number leaves the ecommerce it was in, the WhatsApp the target had is disconnected, and this one takes its place — that is what to use when a business changes its number. Displacing a CLIENT's number still requires superadmin (403 otherwise). A number serves one ecommerce at a time.", {
57
+ server.tool("admin_portfolio_number_assign", "Connect one of your own portfolio numbers to an ecommerce you own that has no WhatsApp linked. Fails with 409 if the target already has a number or if this number is still in use elsewhere (release it first). A number serves one ecommerce at a time.", {
59
58
  number_id: z.number().describe("id of the portfolio number (from admin_portfolio_numbers_list)"),
60
- target_ecommerce_id: z.number().describe("ID of the ecommerce to connect it to (must be one you own)"),
61
- replace: z
62
- .boolean()
63
- .optional()
64
- .describe("true to disconnect whatever is in the way (the target's current WhatsApp and/or the ecommerce this number is serving) and connect this number in the same call"),
65
- }, async ({ number_id, target_ecommerce_id, replace }) => text(await client.post(`/admin/my-numbers/${number_id}/assign`, {
66
- ecommerce_id: target_ecommerce_id,
67
- ...(replace ? { replace: true } : {}),
68
- })));
59
+ target_ecommerce_id: z.number().describe("ID of the ecommerce to connect it to (must be one you own, with no WhatsApp linked)"),
60
+ }, async ({ number_id, target_ecommerce_id }) => text(await client.post(`/admin/my-numbers/${number_id}/assign`, { ecommerce_id: target_ecommerce_id })));
69
61
  server.tool("admin_portfolio_number_release", "Release one of your own portfolio numbers from the ecommerce using it, leaving it free for another one. The ecommerce stops receiving messages through it.", {
70
62
  number_id: z.number().describe("id of the portfolio number (from admin_portfolio_numbers_list)"),
71
63
  }, async ({ number_id }) => text(await client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AI,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,qBAAqB,mBAAmB,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC;IACpF,CAAC,CACF,CAAC;AACJ,CAAC"}
@@ -22,24 +22,6 @@ const USAGE_KEYS = [
22
22
  "remarketing_disqualified",
23
23
  ];
24
24
  const UsageEnum = z.enum(USAGE_KEYS);
25
- // Los experimentos solo corren sobre canales: ahí es donde hay conversación que
26
- // cierra venta y por tanto algo que comparar. El remarketing combina prompt base
27
- // con estado del lead y no se experimenta por variante.
28
- const ExperimentUsageEnum = z.enum(["whatsapp", "instagram", "messenger", "ig_comment"]);
29
- const ExperimentVariantSchema = z.object({
30
- variant_key: z.string().describe("Short id for the branch, e.g. 'a', 'control', 'prueba'"),
31
- agent_id: z.number().describe("Agent that serves this branch (see agents_list)"),
32
- weight: z
33
- .number()
34
- .int()
35
- .min(0)
36
- .optional()
37
- .describe("Relative share of the split. 2 gets twice the contacts of 1. 0 means nobody arrives by split — only pinned contacts"),
38
- pinned_contacts: z
39
- .array(z.string())
40
- .optional()
41
- .describe("Phone numbers, IG handles or CRM ids that always land in this variant, whatever the split says. Phone format is flexible: +57 300 123 4567 and 573001234567 match the same contact"),
42
- });
43
25
  export function registerAgentsRegistryTools(server, client) {
44
26
  server.tool("agents_list", "List the business's AI agents. Each agent is a named prompt (name, description, prompt_text) plus the `usages` it currently serves — the same agent can answer WhatsApp and Instagram at once. Call this before assigning or editing agents.", {}, async () => text(await client.get("/ai-agents")));
45
27
  server.tool("agents_get", "Get one agent by id, including its full prompt_text and the usages it serves.", {
@@ -68,30 +50,5 @@ export function registerAgentsRegistryTools(server, client) {
68
50
  usage_key: UsageEnum.describe("Which usage to assign (see agents_usages_get)"),
69
51
  agent_id: z.number().nullable().describe("Agent that should serve this usage, or null to unassign"),
70
52
  }, async ({ usage_key, agent_id }) => text(await client.put(`/ai-agents/usages/${usage_key}`, { agent_id })));
71
- // ---------------------------------------------------------------------------
72
- // Experimentos: A/B por reparto y pruebas dirigidas a contactos concretos
73
- // ---------------------------------------------------------------------------
74
- server.tool("experiments_list", "List the business's agent experiments, active and paused. An experiment targets one channel and splits its contacts between two or more variants, each variant being a whole agent. Read this before creating one: only the most recent live experiment per channel is applied.", {}, async () => text(await client.get("/ai-agents/experiments")));
75
- server.tool("experiments_create", "Create an agent experiment on one channel. Two shapes: an A/B SPLIT (give every variant a weight >= 1, contacts are divided deterministically and you compare sales per variant), or a TARGETED TEST (leave the control at weight 1, the new variant at weight 0, and list the phone numbers or IG handles in its `pinned_contacts` — only those contacts see the new agent). Pinned contacts always win over the split, and over a variant the contact was already frozen into. Results land in sales_by_variant.", {
76
- usage_key: ExperimentUsageEnum.describe("Channel the experiment runs on"),
77
- variants: z
78
- .array(ExperimentVariantSchema)
79
- .min(2)
80
- .describe("Two or more variants. The first one is treated as the control in a targeted test"),
81
- is_active: z.boolean().optional().describe("Start it right away (default true)"),
82
- starts_at: z.string().optional().describe("ISO 8601 datetime the experiment becomes live"),
83
- ends_at: z.string().optional().describe("ISO 8601 datetime it stops"),
84
- }, async (args) => text(await client.post("/ai-agents/experiments", args)));
85
- server.tool("experiments_update", "Edit an experiment: change variants, weights, pinned contacts, the window, or pause/resume it. Send only what changes. Sending `variants` replaces the whole list, so read experiments_list first and echo back the ones you want to keep — this is how you add a phone number to a running targeted test.", {
86
- experiment_id: z.number().describe("Experiment id (see experiments_list)"),
87
- usage_key: ExperimentUsageEnum.optional().describe("Move it to another channel"),
88
- variants: z.array(ExperimentVariantSchema).min(2).optional().describe("Full replacement list of variants"),
89
- is_active: z.boolean().optional().describe("Pause (false) or resume (true)"),
90
- starts_at: z.string().optional(),
91
- ends_at: z.string().optional(),
92
- }, async ({ experiment_id, ...body }) => text(await client.patch(`/ai-agents/experiments/${experiment_id}`, body)));
93
- server.tool("experiments_delete", "Delete an experiment. Contacts already assigned keep their variant and past sales stay attributed to it — deleting stops new assignments, it does not rewrite history.", {
94
- experiment_id: z.number().describe("Experiment id (see experiments_list)"),
95
- }, async ({ experiment_id }) => text(await client.delete(`/ai-agents/experiments/${experiment_id}`)));
96
53
  }
97
54
  //# sourceMappingURL=agents-registry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agents-registry.js","sourceRoot":"","sources":["../../src/tools/agents-registry.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,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACvF,CAAC;AAED,2EAA2E;AAC3E,0EAA0E;AAC1E,gFAAgF;AAChF,MAAM,UAAU,GAAG;IACjB,UAAU;IACV,WAAW;IACX,WAAW;IACX,YAAY;IACZ,kBAAkB;IAClB,aAAa;IACb,kBAAkB;IAClB,kBAAkB;IAClB,iBAAiB;IACjB,2BAA2B;IAC3B,kBAAkB;IAClB,uBAAuB;IACvB,kBAAkB;IAClB,0BAA0B;CAClB,CAAC;AAEX,MAAM,SAAS,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AAErC,gFAAgF;AAChF,iFAAiF;AACjF,wDAAwD;AACxD,MAAM,mBAAmB,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,WAAW,EAAE,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC;AAEzF,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;IACvC,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,wDAAwD,CAAC;IAC1F,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,iDAAiD,CAAC;IAChF,MAAM,EAAE,CAAC;SACN,MAAM,EAAE;SACR,GAAG,EAAE;SACL,GAAG,CAAC,CAAC,CAAC;SACN,Q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EAAE,QAAQ,EAAE,CAAC,CAAC,CACzE,CAAC;AACJ,CAAC"}
@@ -3,16 +3,15 @@ function text(data) {
3
3
  return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
4
4
  }
5
5
  export function registerAppointmentRemindersTools(server, client) {
6
- server.tool("appointment_reminders_list", "Lista las REGLAS de recordatorio de cita configuradas para este ecommerce (tabla configurable, no hardcodeada). Cada regla tiene: kind (day_before|same_day|at_time|after), at_hour (hora de envío para day_before/same_day/after), minutes_before (para at_time), days_after (para after), action (plantilla o mensaje), is_active.", {}, async () => text(await client.get("/appointment-reminders/flows")));
7
- server.tool("appointment_reminders_create", "Crea una REGLA de recordatorio de cita. kind: 'day_before' (día anterior a la cita, a las at_hour), 'same_day' (mismo día, a las at_hour), 'at_time' (a la hora de la cita, minutes_before minutos antes) o 'after' (days_after días DESPUÉS de la cita, a las at_hour: seguimiento post-cita, rescate de no-shows). Usa 'after' —y no un flow de hidratación— para cualquier seguimiento posterior a la cita: la hidratación ancla en el último mensaje del lead y se desfasa cuando el negocio agenda con días o semanas de anticipación. action: {\"send_template\":\"nombre\"} (obligatorio fuera de la ventana de 24h, que es siempre el caso de 'after') o {\"send_message\":\"texto con {nombre} {fecha} {hora}\"}.", {
6
+ server.tool("appointment_reminders_list", "Lista las REGLAS de recordatorio de cita configuradas para este ecommerce (tabla configurable, no hardcodeada). Cada regla tiene: kind (day_before|same_day|at_time), at_hour (hora de envío para day_before/same_day), minutes_before (para at_time), action (plantilla o mensaje), is_active.", {}, async () => text(await client.get("/appointment-reminders/flows")));
7
+ server.tool("appointment_reminders_create", "Crea una REGLA de recordatorio de cita. kind: 'day_before' (día anterior a la cita, a las at_hour), 'same_day' (mismo día, a las at_hour) o 'at_time' (a la hora de la cita, minutes_before minutos antes). action: {\"send_template\":\"nombre\"} (recomendado para fuera de la ventana de 24h) o {\"send_message\":\"texto con {nombre} {fecha} {hora}\"}.", {
8
8
  name: z.string().describe("Nombre de la regla, ej: 'Día antes 6pm'"),
9
- kind: z.enum(["day_before", "same_day", "at_time", "after"]),
9
+ kind: z.enum(["day_before", "same_day", "at_time"]),
10
10
  action: z.record(z.any()).describe('{"send_template":"recordatorio_cita_villa"} o {"send_message":"..."}'),
11
- at_hour: z.number().int().min(0).max(23).optional().describe("Hora 0-23 (solo day_before/same_day/after)"),
11
+ at_hour: z.number().int().min(0).max(23).optional().describe("Hora 0-23 (solo day_before/same_day)"),
12
12
  minutes_before: z.number().int().min(0).optional().describe("Minutos antes de la cita (solo at_time; 0 = exacto)"),
13
- days_after: z.number().int().min(1).optional().describe("Días DESPUÉS de la cita (solo after; 1 = al día siguiente)"),
14
13
  is_active: z.boolean().optional().default(true),
15
- }, async ({ name, kind, action, at_hour, minutes_before, days_after, is_active }) => {
14
+ }, async ({ name, kind, action, at_hour, minutes_before, is_active }) => {
16
15
  // El backend (AppointmentReminderFlowCreate) exige ecommerce_id en el body;
17
16
  // el router lo sobreescribe igual con el autenticado.
18
17
  const body = {
@@ -26,16 +25,14 @@ export function registerAppointmentRemindersTools(server, client) {
26
25
  body.at_hour = at_hour;
27
26
  if (minutes_before !== undefined)
28
27
  body.minutes_before = minutes_before;
29
- if (days_after !== undefined)
30
- body.days_after = days_after;
31
28
  return text(await client.post("/appointment-reminders/flows", body));
32
29
  });
33
- server.tool("appointment_reminders_update", "Edita una regla de recordatorio existente. Envía solo los campos a cambiar (name, kind, at_hour, minutes_before, days_after, action, is_active).", {
30
+ server.tool("appointment_reminders_update", "Edita una regla de recordatorio existente. Envía solo los campos a cambiar (name, kind, at_hour, minutes_before, action, is_active).", {
34
31
  flow_id: z.number().int().describe("ID de la regla a editar"),
35
32
  fields: z.record(z.any()).describe("Campos a actualizar, ej: {\"at_hour\": 7} o {\"is_active\": false}"),
36
33
  }, async ({ flow_id, fields }) => text(await client.patch(`/appointment-reminders/flows/${flow_id}`, fields)));
37
34
  server.tool("appointment_reminders_delete", "Elimina una regla de recordatorio de cita por su id.", { flow_id: z.number().int().describe("ID de la regla a eliminar") }, async ({ flow_id }) => text(await client.delete(`/appointment-reminders/flows/${flow_id}`)));
38
- server.tool("appointment_reminders_preview", "Muestra las reglas activas + las citas con el estado de sus recordatorios (cuáles ya salieron y cuáles faltan por cada cita). Si hay reglas 'after' también incluye las citas ya pasadas que todavía tienen seguimiento pendiente.", {
35
+ server.tool("appointment_reminders_preview", "Muestra las reglas activas + las próximas citas con el estado de sus recordatorios (cuáles ya salieron y cuáles faltan por cada cita).", {
39
36
  days: z.number().optional().default(3).describe("Días hacia adelante a revisar (default 3)"),
40
37
  }, async ({ days }) => text(await client.get("/appointment-reminders/preview", { days: String(days ?? 3) })));
41
38
  server.tool("appointment_reminders_run", "Dispara AHORA los recordatorios de cita pendientes según las reglas configuradas (sin esperar al cron horario; útil para probar). Idempotente: no reenvía un recordatorio ya enviado.", {}, async () => text(await client.post("/appointment-reminders/run")));
@@ -1 +1 @@
1
- {"version":3,"file":"appointment-reminders.js","sourceRoot":"","sources":["../../src/tools/appointment-reminders.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,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACvF,CAAC;AAED,MAAM,UAAU,iCAAiC,CAAC,MAAiB,EAAE,MAAqB;IACxF,MAAM,CAAC,IAAI,CACT,4BAA4B,EAC5B,sUAAsU,EACtU,EAAE,EACF,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC,CACnE,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,8BAA8B,EAC9B,4rBAA4rB,EAC5rB;QACE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,yC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C,KAAK,CAAC,gCAAgC,OAAO,EAAE,EAAE,MAAM,CAAC,CAAC,CAC9E,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,8BAA8B,EAC9B,sDAAsD,EACtD,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,2BAA2B,CAAC,EAAE,EACnE,KAAK,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,gCAAgC,OAAO,EAAE,CAAC,CAAC,CAC5F,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,+BAA+B,EAC/B,wIAAwI,EACxI;QACE,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,2CAA2C,CAAC;KAC7F,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,CACjB,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,CAAC,gCAAgC,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CACxF,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,2BAA2B,EAC3B,uLAAuL,EACvL,EAAE,EACF,KAAK,IAAI,EAAE,CAAC,IAAI,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC,CAClE,CAAC;AACJ,CAAC"}
@@ -26,8 +26,8 @@ export function registerConversationsTools(server, client) {
26
26
  qp["offset"] = String(offset);
27
27
  return text(await client.get(`/conversations/${session_id}`, qp));
28
28
  });
29
- server.tool("conversations_search", "Search messages across all conversations by text content. Useful for finding specific customer requests or keywords. Needs at least 3 characters; shorter searches are rejected because the database index cannot serve them.", {
30
- search_text: z.string().min(3).describe("Text to search for in messages (minimum 3 characters)"),
29
+ server.tool("conversations_search", "Search messages across all conversations by text content. Useful for finding specific customer requests or keywords.", {
30
+ search_text: z.string().describe("Text to search for in messages"),
31
31
  from_user: z.boolean().optional().describe("Only search in user messages"),
32
32
  from_agent: z.boolean().optional().describe("Only search in agent messages"),
33
33
  limit: z.number().optional().default(20).describe("Max results"),
@@ -1 +1 @@
1
- {"version":3,"file":"conversations.js","sourceRoot":"","sources":["../../src/tools/conversations.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,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACvF,CAAC;AAED,MAAM,UAAU,0BAA0B,CAAC,MAAiB,EAAE,MAAqB;IACjF,MAAM,CAAC,IAAI,CACT,oBAAoB,EACpB,iIAAiI,EACjI;QACE,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,aAAa,CAAC;QAChE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,mBAAmB,CAAC;KACvE,EACD,KAAK,EAAE,MAAM,EAAE,EAAE;QACf,MAAM,EAAE,GAA2B,EAAE,CAAC;QACtC,IAAI,MAAM,CAAC,KAAK;YAAE,EAAE,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACrD,IAAI,MAAM,CAAC,MAAM;YAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACxD,OAAO,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC,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KAAK,EAAE,MAAM,EAAE,EAAE;QACf,MAAM,EAAE,GAA2B,EAAE,CAAC;QACtC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YAC5C,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,IAAI;gBAAE,EAAE,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QACvD,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,CAAC,sBAAsB,EAAE,EAAE,CAAC,CAAC,CAAC;IAC5D,CAAC,CACF,CAAC;AACJ,CAAC"}
@@ -64,6 +64,33 @@ export function registerEcommerceTools(server, client) {
64
64
  }
65
65
  return text(await client.patch(`/ecommerce/${id}/config`, body));
66
66
  });
67
+ server.tool("ecommerce_product_visibility_set", "Choose which products the AI agent is allowed to OFFER, out of everything loaded in the catalog. Since the Shopify sync imports the FULL catalog — drafts and archived included, 248 of UGREEN's 264 products — the table holds plenty the business keeps around to manage but does not sell. This decides what reaches the agent's search; it does not hide anything from the dashboard.\n\nThe three criteria combine. Defaults: only available products (same as the agent saw before drafts were imported), stock not required (a business that doesn't track inventory would lose half its catalog), featured not required.\n\nNotes worth knowing: a product with no inventory tracking always counts as in stock, and negative stock counts as zero — UGREEN has variants at -1 and -16 from inventory adjustments, and a naive 'not zero' check would treat those as available. Send only the field you want to change.", {
68
+ require_available: z.boolean().optional().describe("Only offer products marked available (active in Shopify). Default true"),
69
+ require_stock: z.boolean().optional().describe("Only offer products with stock left. Default false"),
70
+ require_featured: z.boolean().optional().describe("Only offer the business's featured products. Default false"),
71
+ ecommerce_id: z.string().optional().describe("Ecommerce ID (defaults to your own)"),
72
+ }, async ({ require_available, require_stock, require_featured }) => {
73
+ const id = client.getResolvedEcommerceId();
74
+ const patch = {};
75
+ if (require_available !== undefined)
76
+ patch.require_available = require_available;
77
+ if (require_stock !== undefined)
78
+ patch.require_stock = require_stock;
79
+ if (require_featured !== undefined)
80
+ patch.require_featured = require_featured;
81
+ // extra_config mergea shallow en backend → se manda product_visibility
82
+ // completo para no pisar los criterios que no se están tocando.
83
+ const cfg = await client.get(`/ecommerce/${id}/config`);
84
+ const current = cfg?.extra_config?.product_visibility ?? {};
85
+ const merged = {
86
+ require_available: true,
87
+ require_stock: false,
88
+ require_featured: false,
89
+ ...current,
90
+ ...patch,
91
+ };
92
+ return text(await client.patch(`/ecommerce/${id}/config`, { extra_config: { product_visibility: merged } }));
93
+ });
67
94
  server.tool("ecommerce_worker_visibility_set", "Set what advisors (role 'asesor') see in the dashboard. `chats` and `attention` each accept 'all' (see everything), 'own' (their assigned clients + still-unassigned ones so they can take them), or 'strict' (ONLY their assigned clients — full isolation, not even unassigned ones). Admin/manager/adev always see everything. Send only the field you want to change.", {
68
95
  chats: z.enum(["all", "own", "strict"]).optional().describe("Chat list visibility for advisors"),
69
96
  attention: z.enum(["all", "own", "strict"]).optional().describe("Human-attention (atención requerida) visibility for advisors"),
@@ -182,100 +209,6 @@ export function registerEcommerceTools(server, client) {
182
209
  }
183
210
  return text(await client.patch(`/ecommerce/${id}/config`, { extra_config: { booking_rules } }));
184
211
  });
185
- server.tool("ecommerce_capabilities_get", "Read what this business actually DOES: the capabilities it inherits from its vertical plus whatever it turned on or off, already resolved. Capabilities decide which dashboard tabs exist, which fields the sale form asks for and which sales screen it gets — so this is the first thing to read when a client says a feature is missing from their dashboard.", {
186
- ecommerce_id: z.string().optional().describe("Ecommerce ID (defaults to your own)"),
187
- }, async ({ ecommerce_id }) => {
188
- const id = ecommerce_id || client.getResolvedEcommerceId();
189
- const [cfg, verticals] = await Promise.all([
190
- client.get(`/ecommerce/${id}/config`),
191
- client.get(`/ecommerce/verticals`),
192
- ]);
193
- const key = cfg?.business_type || "ecommerce";
194
- const spec = (verticals?.verticals || []).find((v) => v.key === key);
195
- const overrides = cfg?.extra_config?.capabilities ?? { enabled: [], disabled: [] };
196
- const effective = new Set(spec?.capabilities ?? []);
197
- (overrides.enabled ?? []).forEach((c) => effective.add(c));
198
- (overrides.disabled ?? []).forEach((c) => effective.delete(c));
199
- return text({
200
- business_type: key,
201
- from_vertical: spec?.capabilities ?? [],
202
- overrides,
203
- effective: [...effective].sort(),
204
- order_view: cfg?.extra_config?.order_view || spec?.order_view,
205
- });
206
- });
207
- server.tool("ecommerce_capabilities_set", "Turn capabilities on or off for a business, beyond what its vertical gives it. This is how a store also gets an appointment book, or a clinic also gets the orders board — the vertical is a starting point, not a cage. Pass `enable`/`disable` with capability names (get them from `ecommerce_verticals_list`). Stored as a DELTA against the vertical, never as a resolved list, so the business keeps inheriting whatever its vertical gains later. Turning something on makes its tabs and its sale-form fields appear; turning something off hides them. Use `order_view` to change how the sales screen looks ('kanban' for a board by order status, 'ledger' for a sales register) — pass an empty string to go back to the vertical's default.", {
208
- ecommerce_id: z.string().optional().describe("Ecommerce ID (defaults to your own)"),
209
- enable: z.array(z.string()).optional().describe("Capabilities to turn ON for this business"),
210
- disable: z.array(z.string()).optional().describe("Capabilities from its vertical to turn OFF"),
211
- order_view: z.string().optional().describe("Sales screen: 'kanban', 'ledger', or '' to use the vertical's default"),
212
- }, async ({ ecommerce_id, enable, disable, order_view }) => {
213
- const id = ecommerce_id || client.getResolvedEcommerceId();
214
- // extra_config mergea SHALLOW: se lee y se mezcla para no borrar el otro lado.
215
- let current = { enabled: [], disabled: [] };
216
- try {
217
- const cfg = await client.get(`/ecommerce/${id}/config`);
218
- current = cfg?.extra_config?.capabilities || current;
219
- }
220
- catch {
221
- /* config nueva: se parte de vacío */
222
- }
223
- const enabled = new Set(current.enabled ?? []);
224
- const disabled = new Set(current.disabled ?? []);
225
- // Prender algo lo saca de la lista de apagados y viceversa: nunca puede
226
- // quedar en las dos, que sería una config sin significado.
227
- (enable ?? []).forEach((c) => { enabled.add(c); disabled.delete(c); });
228
- (disable ?? []).forEach((c) => { disabled.add(c); enabled.delete(c); });
229
- const body = {
230
- capabilities: { enabled: [...enabled].sort(), disabled: [...disabled].sort() },
231
- };
232
- if (order_view !== undefined)
233
- body.order_view = order_view.trim() || null;
234
- return text(await client.patch(`/ecommerce/${id}/config`, { extra_config: body }));
235
- });
236
- server.tool("ecommerce_verticals_list", "List the business verticals the platform supports and what each one can DO — its capabilities (ships, books appointments, has a kitchen, runs tables…), the lead states it offers and the words it uses for its own things (a restaurant has a 'carta' of 'platos', a clinic has 'servicios' and 'pacientes'). Read this before setting a business_type: the vertical decides which dashboard tabs appear and which fields the sale form asks for, so picking the wrong one hides real features from the client. This is the server's own catalog, so it is always current.", {}, async () => {
237
- return text(await client.get(`/ecommerce/verticals`));
238
- });
239
- server.tool("ecommerce_preparation_get", "Read how long the business currently takes to have an order ready, and whether it is taking orders at all. Resolves the temporary overrides, so what you get back is the state RIGHT NOW: if a rush or a pause already expired, it shows as gone. Use it to diagnose a business whose agent is quoting the wrong wait, or that says it is closed when it should be open. Returns the defaults (disabled) when the business never configured it.", {
240
- ecommerce_id: z.string().optional().describe("Ecommerce ID (defaults to your own)"),
241
- }, async ({ ecommerce_id }) => {
242
- const id = ecommerce_id || client.getResolvedEcommerceId();
243
- const cfg = await client.get(`/ecommerce/${id}/config`);
244
- return text(cfg?.extra_config?.preparation ?? { enabled: false });
245
- });
246
- server.tool("ecommerce_preparation_set", "Set the preparation time the agent quotes, and pause or resume taking orders. For businesses that make things to order — a kitchen, a bakery, a workshop — where the wait changes during the day. The agent reads this on every message, so it quotes today's real wait instead of a number written into the prompt months ago. `paused: true` is a HARD barrier: the agent cannot close an order while it is on, no matter how the customer insists, and it replies with `paused_message`. ALWAYS pass `busy_until`/`paused_until` (ISO 8601, business timezone) when the situation is temporary — they expire on their own, which is the whole point: a pause nobody remembers to lift kills the next day's sales. Only the fields you pass change; the rest keep their current value.", {
247
- ecommerce_id: z.string().optional().describe("Ecommerce ID (defaults to your own)"),
248
- enabled: z.boolean().optional().describe("Whether the business handles preparation times at all. false (default) = the agent never mentions a wait and no order is ever blocked."),
249
- min_minutes: z.number().int().min(0).max(10080).optional().describe("Low end of the normal preparation time, in minutes."),
250
- max_minutes: z.number().int().min(0).max(10080).optional().describe("High end of the normal preparation time, in minutes."),
251
- delivery_extra_minutes: z.number().int().min(0).max(10080).optional().describe("Minutes delivery adds on top of preparation. 0 = pickup and delivery are quoted the same."),
252
- busy: z.boolean().optional().describe("Running late right now: while on, the busy range below replaces the normal one and the agent volunteers the delay."),
253
- busy_min_minutes: z.number().int().min(0).max(10080).optional().describe("Low end while running late. 0 = keep the normal one."),
254
- busy_max_minutes: z.number().int().min(0).max(10080).optional().describe("High end while running late. 0 = keep the normal one."),
255
- busy_until: z.string().optional().describe("When the delay ends, ISO 8601 in the business timezone (e.g. '2026-08-20T21:00:00'). After it passes the normal time comes back by itself. Empty = until someone turns it off by hand."),
256
- paused: z.boolean().optional().describe("The business is NOT taking orders. Enforced server-side: the agent cannot create an order while this is on."),
257
- paused_until: z.string().optional().describe("When the pause lifts, ISO 8601 in the business timezone. Empty = until someone lifts it by hand."),
258
- paused_message: z.string().optional().describe("Exactly what the agent tells customers during the pause. Empty = a generic 'not taking orders right now'."),
259
- timezone: z.string().optional().describe("IANA timezone used to read busy_until and paused_until. Default America/Bogota."),
260
- }, async ({ ecommerce_id, ...fields }) => {
261
- const id = ecommerce_id || client.getResolvedEcommerceId();
262
- // extra_config mergea SHALLOW: mismo cuidado que booking_rules — mandar un
263
- // preparation parcial reemplazaría el objeto entero.
264
- let current = {};
265
- try {
266
- const cfg = await client.get(`/ecommerce/${id}/config`);
267
- current = cfg?.extra_config?.preparation || {};
268
- }
269
- catch {
270
- current = {};
271
- }
272
- const preparation = { ...current };
273
- for (const [k, v] of Object.entries(fields)) {
274
- if (v !== undefined)
275
- preparation[k] = v;
276
- }
277
- return text(await client.patch(`/ecommerce/${id}/config`, { extra_config: { preparation } }));
278
- });
279
212
  server.tool("ecommerce_resources_set", "Configure the bookable SPACES of a business (consultorios, treatment rooms, booths, chairs). This is what lets the AI answer 'which room is free at 2pm' instead of only 'is the business busy at 2pm' — two bookings at the same hour are valid in different rooms. Give each space its own Google calendar_id so its real occupancy counts, including what the team books by hand outside MergeOn. Replaces the whole list; pass [] to turn per-space booking off.", {
280
213
  ecommerce_id: z.string().optional().describe("Ecommerce ID (defaults to your own)"),
281
214
  resources: z