La API y el servidor MCP de StockAI

Casi todo lo que haces dentro de StockAI también se puede hacer por API: subir ventas, entrenar y leer el pronóstico, leer el semáforo, registrar órdenes, administrar proveedores y bodegas. Así puedes conectarlo a tu ERP, tu POS o cualquier sistema propio. Y con el servidor MCP, Claude, ChatGPT o tu asistente de IA lo hace conversando contigo.

URL base
https://app.stockai.es/api/v1
Servidor MCP
https://app.stockai.es/api/v1/mcp
Autenticación
Authorization: Bearer sk_live_…
Endpoints
308 documentados176 de lectura132 de escritura
GET/api/v1/planning
Petición
curl "$STOCKAI/planning" \
  -H "Authorization: Bearer $STOCKAI_KEY"
Respuesta
200 OK application/json
{
  "success": true,
  "data": {},
  "meta": {
    "timestamp": "2026-10-02T08:00:00Z"
  }
}

Autenticación

Cada llamada lleva una API key en la cabecera Authorization. Las claves se crean en la app, en Automatización → API Keys, y se muestran una sola vez: StockAI guarda solo un hash.

shell
export STOCKAI=https://app.stockai.es/api/v1
export STOCKAI_KEY=sk_live_…

curl "$STOCKAI/planning" \
  -H "Authorization: Bearer $STOCKAI_KEY"

Una clave actúa como sí misma, no como la persona que la creó: sigue funcionando si esa persona deja la empresa.

Claves de lectura y de escritura

Al crear una clave eliges qué puede hacer. Cada endpoint de la referencia dice qué tipo de clave necesita.

LecturaLee todo lo que un usuario visor ve: semáforo, pronósticos, proveedores, órdenes, reportes.
Lectura y escrituraAdemás crea y modifica, como un analista: sube archivos, entrena, registra órdenes, edita inventario y proveedores.

Una clave de lectura que intenta escribir recibe 403 con error_code api_key_scope_insufficient, y no cambia nada.

Lo que una clave nunca puede hacer

Algunas acciones son de personas, no de sistemas. Con una API key responden 403 api_key_route_not_exposed:

  • Iniciar sesión, refrescar tokens o recuperar contraseñas.
  • Crear, invitar o modificar usuarios y sus permisos.
  • Crear, listar o revocar API keys: una clave no puede crear otra.
  • Configurar la instalación o los canales de la cuenta.
  • Exportar o borrar la cuenta.
  • Lo que es de una persona: su bandeja de mensajes, sus conversaciones con el asistente, sus preferencias.
  • Lo que solo un administrador puede hacer (por ejemplo, cambiar la moneda o el período activo).

Enviar una orden o una alerta por correo o WhatsApp con una clave de escritura exige que la cuenta tenga al menos un administrador con el correo verificado (si no: 403 api_key_tenant_unverified).

Límites

Autenticación
/ min120 llamadas por minuto por clave.
APILa API y el servidor MCP vienen con los planes Pro, Max y Corporativo; el plan Gratis no los incluye.

Al pasarte recibes 429 con la cabecera Retry-After (segundos). El mismo 429 sirve para el límite por minuto y para el tope diario, y su cuerpo no trae error_code.

No hay cabeceras X-RateLimit-*: la única señal es el 429 con Retry-After. Cuenta tus llamadas o espera el 429.

Medición y compra

La API viene con los planes Pro (2.000 llamadas al día por clave), Max (20.000) y Corporativo (sin tope diario). Contamos cada llamada con una API key que llegó a un endpoint, por día (UTC) y por clave; las rechazadas (clave inválida, sin permiso o por encima del límite) no cuentan. Un administrador ve el consumo del mes en la app, en la pantalla API.

Errores

Casi todo error trae un error_code estable y, si aplica, error_params con los valores: ramifica por el código, no por el texto de detail, que es una ayuda en inglés y puede cambiar. Las respuestas del propio framework (cabecera ausente, ruta inexistente, método incorrecto) y el 429 solo traen detail.

api_key_invalid401 la clave no existe, fue revocada o venció.
api_key_route_not_exposed403 ese endpoint no se puede usar con una API key.
api_key_scope_insufficient403 la clave es de lectura y el endpoint escribe.
api_key_tenant_unverified403 enviar algo fuera de StockAI exige un administrador verificado.
validation_error422 el cuerpo o los parámetros no son válidos; detail es una lista con un objeto por campo.
PLAN_LIMIT_REACHED403 llegaste a un tope de uso; detail es un objeto y error_params dice cuál.
server_busy503 el servidor está saturado; reintenta según Retry-After.
(sin error_code)401 falta la cabecera Authorization o no es “Bearer sk_live_…”: detail es “Not authenticated”.
(sin error_code)429 límite por minuto o tope diario: espera Retry-After segundos.
(sin error_code)404 / 405 ruta inexistente o método no permitido.

La forma de detail

textoLa mayoría de los errores: una frase en inglés.
lista422 validation_error: [{ type, loc, msg, input }], uno por campo inválido; loc dice dónde (por ejemplo ["body", "name"]).
objetoPLAN_LIMIT_REACHED: { code, limit, current, max, tier }, el mismo contenido que error_params.
403 Ejemplo: clave de lectura que escribe
{
  "detail": "This endpoint writes and the API key is read-only. Use a write key.",
  "error_code": "api_key_scope_insufficient",
  "error_params": { "required_scope": "write", "key_scope": "read" }
}

El formato de respuesta

Toda respuesta JSON viene envuelta: { "success": true, "data": …, "meta": { "timestamp": … } }. Lo tuyo está en data, que según el endpoint es un objeto o una lista; los listados paginados traen la lista en data.items.

200 application/json
{
  "success": true,
  "data": {},
  "meta": {
    "timestamp": "2026-10-02T08:00:00Z"
  }
}

Los endpoints que devuelven un archivo (Excel, PDF, CSV) responden el archivo directamente, sin envoltorio.

El endpoint MCP (POST /mcp) habla JSON-RPC 2.0 y no usa este envoltorio.

Tipos y formatos

FechasLas fechas son YYYY-MM-DD; los instantes, ISO 8601 en UTC, por ejemplo 2026-10-01T08:00:00+00:00.
NúmerosCantidades y montos son números JSON, no textos. Los montos van en la moneda de la cuenta (GET /tenant/currency).
Sin valorUn campo sin valor suele llegar como null en lugar de omitirse.
IdentificadoresCadenas opacas con prefijo (sess_…, ds_…, sup_…): guárdalas tal cual.
SeñalesEl semáforo usa PEDIR_YA, PEDIR_PRONTO, OK y SOBRESTOCK: valores fijos que no se traducen.

Paginación

Hay tres formas, y cada endpoint la declara en sus parámetros:

skip y limitSesiones, resumen de sesiones, fuentes de datos y datasets. La respuesta trae items, total, skip y limit.
limit y offsetLa actividad de alertas (/alerts/activity). La respuesta trae items, total, limit y offset.
solo limitLos más recientes primero, hasta limit: alertas, historial de órdenes, brechas de configuración, mermas e historial de reentrenamientos.
sin paginaciónEl resto devuelve el conjunto completo y se acota con sus filtros, por ejemplo signal o supplier en /inventory/status.

Idempotencia

POST /inventory/log-po y POST /inventory/po aceptan la cabecera Idempotency-Key: un valor único (un UUID) por orden que quieres colocar. Si repites la petición con la misma clave recibes la orden que ya se creó (200 con replayed: true) en vez de una segunda; la misma clave con otras líneas responde 409 po_idempotency_key_reused. Los demás endpoints de escritura no son idempotentes: antes de reintentar una escritura cuyo resultado no viste, consulta si ya se aplicó.

HTTP
Idempotency-Key: 3f1c9a5e-7d62-4b0e-9d6a-2c8f4a1b5e70

StockAI en tu asistente de IA (MCP)

StockAI se conecta a Claude, ChatGPT y cualquier asistente de IA que hable MCP (Model Context Protocol). Por esa conexión el asistente puede hacer lo mismo que la API, conversando contigo: decirte qué pedir, preparar y enviar órdenes de compra, revisar la precisión del pronóstico o lanzar un reentrenamiento. Los cambios los apruebas tú.

Servidor MCP
https://app.stockai.es/api/v1/mcp
Acceso
Inicias sesión con tu cuenta de StockAI (OAuth) o usas una API key
Herramientas
Alcanzan las 307 operaciones de la API21 de lectura8 de escritura

Lo que le puedes pedir

  • «¿Qué tengo que pedir hoy, y por qué?»
  • «Arma la orden para Distribuidora Andina con las cantidades sugeridas.»
  • «Envía la orden de Distribuidora Andina al proveedor.»
  • «¿Qué tan preciso fue el pronóstico del mes pasado?»
  • «¿Qué productos están en sobrestock y cuánto dinero tienen parado?»
  • «Reentrena el pronóstico con las ventas de esta semana.»

Cómo se protege tu cuenta

Leer o escribirCon una credencial de lectura el asistente solo consulta. Para crear o cambiar algo necesita una de escritura: la misma regla que en la API.
Confirmación en lo destructivoUna acción que no se deshace, como cancelar una orden, se rechaza si no llega con confirm: true. El asistente te pregunta antes de enviarla.
Medido y registradoCada llamada cuenta en el consumo de la API, con el mismo límite por minuto, y cada cambio queda en el registro de actividad de la cuenta.
RevocableRetiras el acceso desde la app cuando quieras, y la siguiente llamada ya no entra.
Lo que nunca haceNada que una API key no pueda hacer: ni usuarios, ni llaves, ni la configuración de la instalación.
PlanesViene con los planes Pro, Max y Corporativo, igual que la API.

Conecta tu cliente

La misma URL sirve para todos. Elige tu cliente:

  1. En claude.ai abre Customize → Connectors, pulsa «+ Add» y elige «Add custom connector».
  2. Ponle de nombre StockAI, pega la URL de abajo y pulsa «Add». No hace falta nada en «Advanced settings».
  3. Pulsa «Connect» junto a StockAI. Claude te lleva a StockAI: entras con tu cuenta y apruebas el acceso.
  4. Actívalo en un chat desde «+» → Connectors. En Claude Desktop aparece solo, porque los conectores van con tu cuenta de Claude.
URL
https://app.stockai.es/api/v1/mcp

En los planes Team y Enterprise de Claude, el conector lo agrega un Owner en Organization settings → Connectors; cada persona luego pulsa «Connect».

Detalles técnicos

  • Transporte Streamable HTTP sin estado: cada mensaje es un POST con JSON-RPC 2.0 y la respuesta vuelve en el mismo POST. Un GET responde 405: el servidor no abre un flujo hacia el cliente.
  • Comparte con la API el límite por minuto y el tope diario, y responde 429 con Retry-After al pasarte.
  • Una herramienta que se niega responde con un error que el asistente puede leer, con su error_code, no con un fallo de transporte.
  • Revisión del protocolo: 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05.

Herramientas

Generada a partir del propio servidor: si una herramienta está aquí, tu asistente la ve. Las herramientas del grupo «Toda la API» buscan, describen y llaman cualquier operación de la referencia de endpoints. Las descripciones están en inglés, como el código.

29 herramientas: 21 de lectura y 8 de escritura (4 destructivas, piden confirmación).

Planificación 3

get_planning_contextLecturaStart here. Returns which forecast session is active, at what granularity (daily/weekly/monthly) and over how many periods the numbers in the other tools were computed. `active_session_id` is what the other tools accept as `session_id`; read it each time rather than storing it, because it changes when a new run trains.
Argumentos

Sin argumentos.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_planning_context",
    "arguments": {}
  }
}
get_morning_briefingLecturaThe day's purchasing work: the risks worth acting on, the reason behind each recommendation, the suggested supplier and the estimated value. This is the tool for "what should I buy today?"; get_inventory_status is for "what is the state of X?".
Argumentos
  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_morning_briefing",
    "arguments": {}
  }
}
get_purchase_planLecturaThe purchase plan grouped by supplier, after the constraints are applied (MOQ, order multiples, joint replenishment, budget). Use it for "what should I order from each supplier?" — it returns what to buy per supplier with quantities and values, not the per-SKU traffic light.
Argumentos
  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

  • window_daysintegeropcionalmín. 1máx. 90

    How far ahead a product counts as 'needs ordering soon' when grouping a supplier's order.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_purchase_plan",
    "arguments": {}
  }
}

Inventario 3

get_inventory_statusLecturaThe stock traffic light for every product: what state it is in and how much to order. Signals: PEDIR_YA (order now), PEDIR_PRONTO (order soon), OK, SOBRESTOCK (too much), SIN_DATOS (no stock on record — which means unknown, NOT safe). Per row, `recommended_qty` is how much to order, `coverage_days` how long the stock lasts at the forecast rate, and `lead_time_source` / `unit_cost_source` / `moq_source` say where each assumption came from: `user` (typed into StockAI), `file` (their own export), `supplier_rule`, `learned` (from their receptions) or `default` (StockAI had nothing and assumed). Treat a `default` as an assumption when you report it, not as the customer's own figure. Answers are capped and ordered by urgency; `summary` always counts the whole matching set, and `truncated` says when rows were left out. Filter with `signal` or `supplier` rather than raising `limit` when you can. If a filter matches nothing the answer carries `empty_reason`. That is the filter finding nothing, NOT a catalogue with nothing to order — never report stock as fine on the strength of it.
Argumentos
  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

  • signalenumopcional

    Return only SKUs carrying this signal.

    PEDIR_YAPEDIR_PRONTOOKSOBRESTOCKSIN_DATOS
  • supplierstringopcional

    Return only SKUs whose supplier matches this name.

  • limitintegeropcionalmín. 1máx. 500por defecto 50

    How many SKUs to return, most urgent first.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_inventory_status",
    "arguments": {
      "signal": "PEDIR_YA",
      "limit": 20
    }
  }
}
search_productsLecturaFind products in the stock catalogue by SKU, category or supplier text, with stock on hand, minimum, lead time, cost and supplier per row. Paged: `total` says how many matched. Use it to find the exact SKU code before calling a per-SKU tool.
Argumentos
  • querystringopcional

    Text matched against SKU, category or supplier.

  • warehousestringopcional

    Only this warehouse's rows.

  • limitintegeropcionalmín. 1máx. 500por defecto 50
  • offsetintegeropcionalmín. 0por defecto 0
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_products",
    "arguments": {
      "query": "oil",
      "limit": 10
    }
  }
}
get_sku_detailLecturaEverything about one SKU in one call: its traffic-light signal, coverage and recommended order quantity from the active forecast (`signal_and_recommendation`), and its stock record — on hand, minimum, lead time, cost, MOQ and supplier (`stock_record`). Use the exact SKU code (search_products finds it).
Argumentos
  • skustringobligatorio

    The exact SKU code.

  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_sku_detail",
    "arguments": {
      "sku": "SKU-001"
    }
  }
}

Órdenes de compra 7

list_purchase_ordersLecturaThe tenant's purchase orders, newest first, with number, supplier, status, value, sent and reception state. Paged (`limit`/`offset`); filter by `status` or search the order number with `query`. get_purchase_order returns one order's lines.
Argumentos
  • statusstringopcional

    Status filter, e.g. all, pending, received (default all).

  • querystringopcional

    Matches the PO number.

  • limitintegeropcionalmín. 1máx. 100por defecto 50
  • offsetintegeropcionalmín. 0por defecto 0
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_purchase_orders",
    "arguments": {}
  }
}
get_purchase_orderLecturaOne purchase order's lines: SKU, ordered and received quantities, unit cost and supplier. `po_log_id` comes from list_purchase_orders.
Argumentos
  • po_log_idstringobligatorio

    The order's id.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_purchase_order",
    "arguments": {}
  }
}
list_overdue_purchase_ordersLecturaOrders whose expected arrival date has passed without a full reception, with how many days late each is. The list to chase suppliers with.
Argumentos

Sin argumentos.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_overdue_purchase_orders",
    "arguments": {}
  }
}
create_purchase_orderDestructiva · pide confirmaciónRecords a purchase order written by hand: one supplier, the lines typed in, no forecast behind it. DESTRUCTIVE: a recorded order cannot be voided through the API and its units start counting as stock on the way. Without `confirm: true` it only describes what it would record. It does NOT send anything to the supplier (send_purchase_order does). Get `supplier_id` from list_suppliers.
Argumentos
  • supplier_idstringobligatorio

    The supplier's id.

  • linesarray of objectobligatorio
    Cada elemento de la lista
    • skustringobligatorio
    • qtynumberobligatoriomín. > 0
    • unit_costnumberopcionalmín. 0
  • destination_warehousestringopcional

    Warehouse it goes to (default: the default warehouse).

  • idempotency_keystringopcional

    Optional. A unique value (a UUID) for this one order. Retrying with the same value returns the order already created instead of creating a second one.

  • confirmbooleanopcional

    Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "create_purchase_order",
    "arguments": {
      "supplier_id": "<supplier_id>",
      "lines": [
        {
          "sku": "SKU-001",
          "qty": 24,
          "unit_cost": 3.5
        }
      ]
    }
  }
}
send_purchase_orderDestructiva · pide confirmaciónEmails and WhatsApps the order's PDF to each of its suppliers and marks it sent. DESTRUCTIVE: a message that left cannot be recalled. Without `confirm: true` it only describes what it would send. Lines whose supplier has no contact details are reported as not sent.
Argumentos
  • po_log_idstringobligatorio

    The order's id.

  • request_confirmationbooleanopcionalpor defecto false

    Ask the supplier to confirm the date.

  • confirmbooleanopcional

    Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "send_purchase_order",
    "arguments": {}
  }
}
receive_purchase_orderEscrituraRecords that an order arrived — fully (no `lines`) or partially (the received quantity per SKU). Stock on hand rises by the received units and the supplier's real lead time is learned. Reversible: the REST operation post-inventory-po-po_log_id-unreceive undoes it.
Argumentos
  • po_log_idstringobligatorio

    The order's id.

  • linesarray of objectopcional

    Received quantity per SKU. Omit for a full reception.

    Cada elemento de la lista
    • skustringobligatorio
    • received_qtynumberobligatoriomín. 0
  • received_atstringopcional

    ISO date it arrived (default: today).

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "receive_purchase_order",
    "arguments": {}
  }
}

Proveedores 3

list_suppliersLecturaThe tenant's suppliers with id, contact details, lead time and payment terms. Paged; `query` matches name, phone or email. The `id` is what create_purchase_order takes as `supplier_id`.
Argumentos
  • querystringopcional
  • limitintegeropcionalmín. 1máx. 200por defecto 50
  • offsetintegeropcionalmín. 0por defecto 0
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_suppliers",
    "arguments": {}
  }
}
get_supplier_scorecardLecturaHow each supplier actually performs: promised vs learned lead time, on-time and fill rate from the receptions recorded. Use it to answer "which supplier is reliable?".
Argumentos

Sin argumentos.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_supplier_scorecard",
    "arguments": {}
  }
}
create_supplierEscrituraAdds a supplier with contact details, lead time and payment terms. Returns the new supplier with its id. Not destructive: a supplier can be edited or deactivated later.
Argumentos
  • namestringobligatorio
  • emailstringopcional
  • phonestringopcional
  • whatsappstringopcional
  • lead_time_daysintegeropcionalmín. 1máx. 365
  • payment_termsstringopcional
  • notesstringopcional
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "create_supplier",
    "arguments": {
      "name": "Distribuidora Andina",
      "lead_time_days": 7
    }
  }
}

Pronósticos 2

get_sku_forecastLecturaThe demand forecast for one SKU: past actuals and forecast values per period, with the prediction interval and the model that produced it. Periods are in the session's granularity (get_planning_context says which).
Argumentos
  • skustringobligatorio

    The exact SKU code.

  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

  • modelstringopcional

    Only this model's forecast (default: the selected one).

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_sku_forecast",
    "arguments": {
      "sku": "SKU-001"
    }
  }
}
get_forecast_accuracyLecturaHow accurate the forecast session is: error metrics overall and per SKU, compared against simple baselines, and which SKUs are least reliable. Use it before trusting a recommendation for a product with a large error.
Argumentos
  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_forecast_accuracy",
    "arguments": {}
  }
}

Entrenamiento 3

list_sessionsLecturaThe tenant's forecast sessions (training runs) with id, name, status, dataset and dates, newest first. `status` filters, e.g. COMPLETED, RUNNING, FAILED.
Argumentos
  • querystringopcional

    Search name, description or dataset.

  • statusarray of stringopcional
  • limitintegeropcionalmín. 1máx. 500por defecto 20
  • offsetintegeropcionalmín. 0por defecto 0
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_sessions",
    "arguments": {}
  }
}
get_training_statusLecturaWhether a forecast session has finished training. `status` goes QUEUED -> RUNNING -> COMPLETED or FAILED. Useful to say whether the numbers being read are the latest run or the previous one.
Argumentos
  • session_idstringobligatorio

    The session to report on. Required.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_training_status",
    "arguments": {}
  }
}
start_trainingEscrituraQueues a training run for a configured session, or a retrain of a completed one (same configuration, current data). Returns at once; poll get_training_status. Training takes minutes and counts against the plan's job limits.
Argumentos
  • session_idstringobligatorio
  • horizon_daysintegeropcionalmín. 1máx. 365

    How many days ahead to forecast.

  • granularityenumopcional
    autodailyweeklymonthly
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "start_training",
    "arguments": {}
  }
}

Datos 2

list_data_sourcesLecturaThe sales-history sources this tenant's forecasts are trained on, with the id, the file name and when each was last updated. Use it to answer whether the numbers are based on fresh data.
Argumentos
  • limitintegeropcionalmín. 1máx. 200por defecto 50

    How many sources to return.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_data_sources",
    "arguments": {}
  }
}
upload_sales_csvEscrituraCreates a NEW data source from sales history given as CSV text (header row first; columns such as date, sku, quantity). StockAI detects the columns. It replaces nothing: existing sources and forecasts are untouched. Train on it by creating a session that uses it.
Argumentos
  • csv_textstringobligatorio

    The CSV file's full content.

  • filenamestringopcional

    File name to store (default sales.csv).

  • namestringopcional

    Name for the data source.

  • descriptionstringopcional
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "upload_sales_csv",
    "arguments": {
      "csv_text": "date,sku,quantity\n2026-10-01,SKU-001,12\n",
      "name": "October sales"
    }
  }
}

Reportes 1

get_dashboard_summaryLecturaThe headline numbers of the inventory dashboard for a forecast session: how many SKUs are in each signal, the value to order, stock value and coverage. One call for "how are we doing?".
Argumentos
  • session_idstringopcional

    Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_dashboard_summary",
    "arguments": {}
  }
}

Alertas 1

list_alertsLecturaThe tenant's recent alerts (stockouts coming, overdue orders, failed runs, data problems), newest first.
Argumentos
  • limitintegeropcionalmín. 1máx. 100por defecto 20
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_alerts",
    "arguments": {}
  }
}

Toda la API 4

search_operationsLecturaFinds any of StockAI's ~300 public API operations by text, beyond the curated tools: warehouses, transfers, stock counts, demand events, scenarios, webhooks, reports, data-source SQL, inventory sync and more. Returns operation ids with a one-line summary and their kind (read / write / destructive), paginated. Then describe_operation, then call_operation or call_write_operation.
Argumentos
  • querystringopcional

    Words to match, e.g. "transfer warehouse".

  • tagstringopcional

    Only this API area (e.g. inventory, sessions, webhooks).

  • kindenumopcional
    readwritedestructive
  • limitintegeropcionalmín. 1máx. 50por defecto 20
  • offsetintegeropcionalmín. 0por defecto 0
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_operations",
    "arguments": {
      "query": "transfer",
      "kind": "read"
    }
  }
}
describe_operationLecturaEverything needed to call one operation: method and path, each parameter with its type, the request body's shape, the scope it needs, whether it is destructive (and why), and ready-to-use example arguments for call_operation / call_write_operation.
Argumentos
  • operation_idstringobligatorio
Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "describe_operation",
    "arguments": {
      "operation_id": "get-inventory-transfers"
    }
  }
}
call_operationLecturaRuns any READ operation of the public API by id (kind=read in search_operations), exactly as the REST API would with this connection's credential. Large answers are cut with a note saying how to page; file downloads are described, not returned. Operations that change data are refused here — they run through call_write_operation.
Argumentos
  • operation_idstringobligatorio

    The operation id from search_operations, e.g. "get-inventory-stock-sku".

  • path_paramsobjectopcional

    Values for the {placeholders} in the operation's path.

    Objeto libre: no declara campos.

  • queryobjectopcional

    Query parameters, by name. Only the operation's declared ones.

    Objeto libre: no declara campos.

  • bodyanyopcional

    JSON body, for the few read operations that take one (previews, simulations).

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "call_operation",
    "arguments": {
      "operation_id": "get-inventory-stock-sku",
      "path_params": {
        "sku": "SKU-001"
      }
    }
  }
}
call_write_operationDestructiva · pide confirmaciónRuns any operation that CHANGES data (kind=write or destructive in search_operations), exactly as the REST API would with this connection's credential; needs a write-scope credential. A destructive operation (every delete, recording or sending a purchase order, overwriting stock, and the others describe_operation marks) does not run without `confirm: true`: without it the answer states exactly what would happen and nothing changes. Form uploads take the file in `body` as its text, or as {filename, content | content_base64}.
Argumentos
  • operation_idstringobligatorio

    The operation id from search_operations, e.g. "get-inventory-stock-sku".

  • path_paramsobjectopcional

    Values for the {placeholders} in the operation's path.

    Objeto libre: no declara campos.

  • queryobjectopcional

    Query parameters, by name. Only the operation's declared ones.

    Objeto libre: no declara campos.

  • bodyanyopcional

    The JSON body (object or list), or for a form upload an object of form fields.

  • idempotency_keystringopcional

    Sent as Idempotency-Key, for operations that accept one: a retry with the same value does not act twice.

  • confirmbooleanopcional

    Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.

Ejemplo de llamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "call_write_operation",
    "arguments": {
      "operation_id": "post-inventory-warehouses",
      "body": {
        "name": "North warehouse"
      }
    }
  }
}

Referencia de endpoints

Generada a partir del propio servicio: si un endpoint está aquí, se puede llamar con una API key. Las respuestas de ejemplo son llamadas reales a una cuenta de prueba. Las descripciones están en inglés, como el código.

POST Explain a SKU's recommendation
Narrativas con IA

Explain a SKU's recommendation

POST/api/v1/ai/narrative/forecast-explanation
Clave de lecturaResponde 200 · application/json

Explains a specific SKU's inventory signal and recommendation in plain language.

Petición

Cabeceras
  • AuthorizationBearer sk_live_…obligatorio

    Tu API key. Siempre obligatoria.

  • Content-Typeapplication/jsonobligatorio
Cuerpo

application/jsonEl cuerpo es obligatorio.

object Un objeto.
  • skustringobligatorio
  • session_idstringobligatorio
  • profilestringopcionalpor defecto "distributor"
  • languagestringopcionalpor defecto "es"

Respuestas

200 Si sale bien

Para este endpoint no se capturó una respuesta de ejemplo. Toda respuesta JSON trae este envoltorio; lo que va en data depende del endpoint.

Errores posibles

Además de los errores de cada endpoint, toda llamada con clave puede responder:

  • 401Authorization header missing, or API key invalid, revoked or expired.
  • 403Key may not call this endpoint, is read-only on a write, or a permission check refused it.
  • 429Per-minute limit or daily ceiling reached; honour Retry-After.
  • 422Validation Error
Errores
Petición
curl -X POST "$STOCKAI/ai/narrative/forecast-explanation" \
  -H "Authorization: Bearer $STOCKAI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"sku":"SKU-001","session_id":"<session_id>","profile":"distributor","language":"es"}'
Respuesta
200 OK application/json
{
  "success": true,
  "data": {},
  "meta": {
    "timestamp": "2026-10-02T08:00:00Z"
  }
}

Pon tu propia IA a pronosticar tus ventas. Hoy.

Tres formas de empezar, según cuánto quieras comprometer ahora. Las tres llegan al mismo producto.

Crea tu cuenta

Con el motor completo. Sube tu archivo de ventas y ve tu primer pronóstico, y con él tu primera lista de qué pedir.

Crear mi cuenta

Mira antes de dar tu correo

Una cuenta de prueba al instante, con datos de ejemplo. Dura 24 horas y después se borra.

Probar sin registrarme

Habla con nosotros

Para el plan corporativo, el código fuente, o para verlo con tus datos y acompañado. Respondemos en menos de 24 horas.

Ventas y contacto: contacto@stockai.es. Teléfono: +506 7186 2820.

Predicción de ventas hecha en Costa Rica, para las empresas de Latinoamérica.