A API e o servidor MCP da StockAI

Quase tudo o que você faz dentro da StockAI também pode ser feito pela API: enviar vendas, treinar e ler a previsão, ler o semáforo, registrar pedidos, gerenciar fornecedores e depósitos. Assim você a conecta ao seu ERP, ao seu POS ou a qualquer sistema próprio. E com o servidor MCP, o Claude, o ChatGPT ou o seu assistente de IA faz isso conversando com você.

URL base
https://app.stockai.es/api/v1
Servidor MCP
https://app.stockai.es/api/v1/mcp
Autenticação
Authorization: Bearer sk_live_…
Endpoints
308 documentados176 de leitura132 de escrita
GET/api/v1/planning
Requisição
curl "$STOCKAI/planning" \
  -H "Authorization: Bearer $STOCKAI_KEY"
Resposta
200 OK application/json
{
  "success": true,
  "data": {},
  "meta": {
    "timestamp": "2026-10-02T08:00:00Z"
  }
}

Autenticação

Cada chamada leva uma chave de API no cabeçalho Authorization. As chaves são criadas no aplicativo, em Automação → API Keys, e mostradas uma única vez: a StockAI guarda somente um hash.

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

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

Uma chave age como ela mesma, não como a pessoa que a criou: continua funcionando se essa pessoa deixar a empresa.

Chaves de leitura e de escrita

Ao criar uma chave, você escolhe o que ela pode fazer. Cada endpoint da referência diz que tipo de chave ele exige.

LeituraLê tudo o que um usuário leitor vê: semáforo, previsões, fornecedores, pedidos, relatórios.
Leitura e escritaAlém disso, cria e altera, como um analista: envia arquivos, treina, registra pedidos, edita estoque e fornecedores.

Uma chave de leitura que tenta escrever recebe 403 com error_code api_key_scope_insufficient, e nada muda.

O que uma chave nunca pode fazer

Algumas ações são de pessoas, não de sistemas. Com uma chave de API, elas respondem 403 api_key_route_not_exposed:

  • Entrar, renovar tokens ou recuperar senhas.
  • Criar, convidar ou alterar usuários e suas permissões.
  • Criar, listar ou revogar chaves de API: uma chave não pode criar outra.
  • Configurar a instalação ou os canais da conta.
  • Exportar ou excluir a conta.
  • O que pertence a uma pessoa: sua caixa de mensagens, suas conversas com o assistente, suas preferências.
  • O que só um administrador pode fazer (por exemplo, trocar a moeda ou o período ativo).

Enviar um pedido ou um alerta por e-mail ou WhatsApp com uma chave de escrita exige que a conta tenha pelo menos um administrador com o e-mail verificado (caso contrário: 403 api_key_tenant_unverified).

Limites

Autenticação
/ min120 chamadas por minuto por chave.
APIA API e o servidor MCP vêm com os planos Pro, Max e Corporativo; o plano Grátis não os inclui.

Ao ultrapassar o limite, você recebe 429 com o cabeçalho Retry-After (em segundos). O mesmo 429 serve para o limite por minuto e para o teto diário, e o corpo dele não traz error_code.

Não há cabeçalhos X-RateLimit-*: o único sinal é o 429 com Retry-After. Conte as suas chamadas ou espere o 429.

Medição e compra

A API vem com os planos Pro (2.000 chamadas por dia por chave), Max (20.000) e Corporativo (sem teto diário). Contamos cada chamada feita com uma chave de API que chegou a um endpoint, por dia (UTC) e por chave; as recusadas (chave inválida, sem permissão ou acima do limite) não contam. Um administrador vê o consumo do mês no aplicativo, na tela API.

Erros

Quase todo erro traz um error_code estável e, quando aplicável, error_params com os valores: ramifique pelo código, não pelo texto de detail, que é uma dica em inglês e pode mudar. As respostas do próprio framework (cabeçalho ausente, rota inexistente, método incorreto) e o 429 trazem apenas detail.

api_key_invalid401 a chave não existe, foi revogada ou venceu.
api_key_route_not_exposed403 esse endpoint não pode ser usado com uma chave de API.
api_key_scope_insufficient403 a chave é de leitura e o endpoint escreve.
api_key_tenant_unverified403 enviar algo para fora da StockAI exige um administrador verificado.
validation_error422 o corpo ou os parâmetros são inválidos; detail é uma lista com um objeto por campo.
PLAN_LIMIT_REACHED403 você atingiu um teto de uso; detail é um objeto e error_params diz qual.
server_busy503 o servidor está saturado; tente de novo após Retry-After.
(sem error_code)401 o cabeçalho Authorization falta ou não é “Bearer sk_live_…”: detail é “Not authenticated”.
(sem error_code)429 limite por minuto ou teto diário: aguarde Retry-After segundos.
(sem error_code)404 / 405 rota inexistente ou método não permitido.

A forma de detail

textoA maioria dos erros: uma frase em inglês.
lista422 validation_error: [{ type, loc, msg, input }], um por campo inválido; loc diz onde (por exemplo ["body", "name"]).
objetoPLAN_LIMIT_REACHED: { code, limit, current, max, tier }, o mesmo conteúdo de error_params.
403 Exemplo: chave de leitura que escreve
{
  "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" }
}

O formato da resposta

Toda resposta JSON vem envolvida: { "success": true, "data": …, "meta": { "timestamp": … } }. O conteúdo útil está em data, que, conforme o endpoint, é um objeto ou uma lista; as listas paginadas trazem a lista em data.items.

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

Os endpoints que devolvem um arquivo (Excel, PDF, CSV) respondem o próprio arquivo, sem envoltório.

O endpoint MCP (POST /mcp) fala JSON-RPC 2.0 e não usa esse envoltório.

Tipos e formatos

DatasAs datas são YYYY-MM-DD; os instantes, ISO 8601 em UTC, por exemplo 2026-10-01T08:00:00+00:00.
NúmerosQuantidades e valores são números JSON, não textos. Os valores ficam na moeda da conta (GET /tenant/currency).
Sem valorUm campo sem valor geralmente chega como null em vez de ser omitido.
IdentificadoresTextos opacos com prefixo (sess_…, ds_…, sup_…): guarde-os como estão.
SinaisO semáforo usa PEDIR_YA, PEDIR_PRONTO, OK e SOBRESTOCK: valores fixos que não se traduzem.

Paginação

Há três formas, e cada endpoint declara a sua nos parâmetros:

skip e limitExecuções, resumo das execuções, fontes de dados e datasets. A resposta traz items, total, skip e limit.
limit e offsetA atividade de alertas (/alerts/activity). A resposta traz items, total, limit e offset.
somente limitOs mais recentes primeiro, até limit: alertas, histórico de pedidos, lacunas de configuração, perdas de estoque e histórico de retreinamentos.
sem paginaçãoOs demais devolvem o conjunto completo e são restringidos pelos seus filtros, por exemplo signal ou supplier em /inventory/status.

Idempotência

POST /inventory/log-po e POST /inventory/po aceitam o cabeçalho Idempotency-Key: um valor único (um UUID) por pedido que você quer fazer. Se repetir a requisição com a mesma chave, você recebe o pedido que já foi criado (200 com replayed: true) em vez de um segundo; a mesma chave com outras linhas responde 409 po_idempotency_key_reused. Os demais endpoints de escrita não são idempotentes: antes de repetir uma escrita cujo resultado você não viu, consulte se ela já foi aplicada.

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

A StockAI no seu assistente de IA (MCP)

A StockAI se conecta ao Claude, ao ChatGPT e a qualquer assistente de IA que fale MCP (Model Context Protocol). Por essa conexão o assistente pode fazer o mesmo que a API, conversando com você: dizer o que pedir, preparar e enviar pedidos de compra, conferir a precisão da previsão ou iniciar um retreinamento. As mudanças, quem aprova é você.

Servidor MCP
https://app.stockai.es/api/v1/mcp
Acesso
Você entra com a sua conta da StockAI (OAuth) ou usa uma chave de API
Ferramentas
Juntas alcançam as 307 operações da API21 de leitura8 de escrita

O que você pode pedir

  • “O que eu preciso pedir hoje, e por quê?”
  • “Monte o pedido para a Distribuidora Andina com as quantidades sugeridas.”
  • “Envie o pedido da Distribuidora Andina ao fornecedor.”
  • “Quão precisa foi a previsão do mês passado?”
  • “Quais produtos estão com excesso de estoque, e quanto dinheiro está parado neles?”
  • “Retreine a previsão com as vendas desta semana.”

Como a sua conta fica protegida

Ler ou escreverCom uma credencial de leitura o assistente só consulta. Para criar ou mudar algo ele precisa de uma de escrita: a mesma regra da API.
Confirmação no que é destrutivoUma ação que não se desfaz, como cancelar um pedido, é recusada se não chegar com confirm: true. O assistente pergunta a você antes de enviá-la.
Medido e registradoCada chamada conta no consumo da API, com o mesmo limite por minuto, e cada mudança fica no registro de atividade da conta.
RevogávelVocê retira o acesso pelo aplicativo quando quiser, e a chamada seguinte já não entra.
O que ele nunca fazNada que uma chave de API não possa fazer: nem usuários, nem chaves, nem a configuração da instalação.
PlanosVem com os planos Pro, Max e Corporativo, igual à API.

Conecte o seu cliente

A mesma URL serve para todos. Escolha o seu cliente:

  1. No claude.ai abra Customize → Connectors, clique em “+ Add” e escolha “Add custom connector”.
  2. Dê o nome StockAI, cole a URL abaixo e clique em “Add”. Não precisa mexer em “Advanced settings”.
  3. Clique em “Connect” ao lado da StockAI. O Claude leva você à StockAI: você entra com a sua conta e aprova o acesso.
  4. Ative-o em uma conversa pelo “+” → Connectors. No Claude Desktop ele aparece sozinho, porque os conectores ficam na sua conta do Claude.
URL
https://app.stockai.es/api/v1/mcp

Nos planos Team e Enterprise do Claude, quem adiciona o conector é um Owner, em Organization settings → Connectors; depois cada pessoa clica em “Connect”.

Detalhes técnicos

  • Transporte Streamable HTTP sem estado: cada mensagem é um POST com JSON-RPC 2.0 e a resposta volta no mesmo POST. Um GET responde 405: o servidor não abre um fluxo para o cliente.
  • Divide com a API o limite por minuto e o teto diário, e responde 429 com Retry-After quando você passa deles.
  • Uma ferramenta que se recusa responde com um erro que o assistente consegue ler, com o seu error_code, e não com uma falha de transporte.
  • Revisão do protocolo: 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05.

Ferramentas

Gerada a partir do próprio servidor: se uma ferramenta está aqui, o seu assistente a vê. As ferramentas do grupo “Toda a API” buscam, descrevem e chamam qualquer operação da referência de endpoints. As descrições estão em inglês, como o código.

29 ferramentas: 21 de leitura e 8 de escrita (4 destrutivas, que pedem confirmação).

Planejamento 3

get_planning_contextLeituraStart 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

Sem argumentos.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_planning_context",
    "arguments": {}
  }
}
get_morning_briefingLeituraThe 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.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_morning_briefing",
    "arguments": {}
  }
}
get_purchase_planLeituraThe 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.

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

Estoque 3

get_inventory_statusLeituraThe 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. 500padrão 50

    How many SKUs to return, most urgent first.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_inventory_status",
    "arguments": {
      "signal": "PEDIR_YA",
      "limit": 20
    }
  }
}
search_productsLeituraFind 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. 500padrão 50
  • offsetintegeropcionalmín. 0padrão 0
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_products",
    "arguments": {
      "query": "oil",
      "limit": 10
    }
  }
}
get_sku_detailLeituraEverything 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
  • skustringobrigatório

    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.

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

Pedidos de compra 7

list_purchase_ordersLeituraThe 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. 100padrão 50
  • offsetintegeropcionalmín. 0padrão 0
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_purchase_orders",
    "arguments": {}
  }
}
get_purchase_orderLeituraOne purchase order's lines: SKU, ordered and received quantities, unit cost and supplier. `po_log_id` comes from list_purchase_orders.
Argumentos
  • po_log_idstringobrigatório

    The order's id.

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

Sem argumentos.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_overdue_purchase_orders",
    "arguments": {}
  }
}
create_purchase_orderDestrutiva · pede confirmaçãoRecords 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_idstringobrigatório

    The supplier's id.

  • linesarray of objectobrigatório
    Cada item da lista
    • skustringobrigatório
    • qtynumberobrigatóriomí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.

Exemplo de chamada
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_orderDestrutiva · pede confirmaçãoEmails 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_idstringobrigatório

    The order's id.

  • request_confirmationbooleanopcionalpadrão 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.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "send_purchase_order",
    "arguments": {}
  }
}
receive_purchase_orderEscritaRecords 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_idstringobrigatório

    The order's id.

  • linesarray of objectopcional

    Received quantity per SKU. Omit for a full reception.

    Cada item da lista
    • skustringobrigatório
    • received_qtynumberobrigatóriomín. 0
  • received_atstringopcional

    ISO date it arrived (default: today).

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

Fornecedores 3

list_suppliersLeituraThe 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. 200padrão 50
  • offsetintegeropcionalmín. 0padrão 0
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_suppliers",
    "arguments": {}
  }
}
get_supplier_scorecardLeituraHow 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

Sem argumentos.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_supplier_scorecard",
    "arguments": {}
  }
}
create_supplierEscritaAdds 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
  • namestringobrigatório
  • emailstringopcional
  • phonestringopcional
  • whatsappstringopcional
  • lead_time_daysintegeropcionalmín. 1máx. 365
  • payment_termsstringopcional
  • notesstringopcional
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "create_supplier",
    "arguments": {
      "name": "Distribuidora Andina",
      "lead_time_days": 7
    }
  }
}

Previsões 2

get_sku_forecastLeituraThe 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
  • skustringobrigatório

    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).

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_sku_forecast",
    "arguments": {
      "sku": "SKU-001"
    }
  }
}
get_forecast_accuracyLeituraHow 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.

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

Treinamento 3

list_sessionsLeituraThe 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. 500padrão 20
  • offsetintegeropcionalmín. 0padrão 0
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_sessions",
    "arguments": {}
  }
}
get_training_statusLeituraWhether 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_idstringobrigatório

    The session to report on. Required.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_training_status",
    "arguments": {}
  }
}
start_trainingEscritaQueues 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_idstringobrigatório
  • horizon_daysintegeropcionalmín. 1máx. 365

    How many days ahead to forecast.

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

Dados 2

list_data_sourcesLeituraThe 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. 200padrão 50

    How many sources to return.

Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "list_data_sources",
    "arguments": {}
  }
}
upload_sales_csvEscritaCreates 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_textstringobrigatório

    The CSV file's full content.

  • filenamestringopcional

    File name to store (default sales.csv).

  • namestringopcional

    Name for the data source.

  • descriptionstringopcional
Exemplo de chamada
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"
    }
  }
}

Relatórios 1

get_dashboard_summaryLeituraThe 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.

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

Alertas 1

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

Toda a API 4

search_operationsLeituraFinds 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. 50padrão 20
  • offsetintegeropcionalmín. 0padrão 0
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_operations",
    "arguments": {
      "query": "transfer",
      "kind": "read"
    }
  }
}
describe_operationLeituraEverything 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_idstringobrigatório
Exemplo de chamada
POST /api/v1/mcp
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "describe_operation",
    "arguments": {
      "operation_id": "get-inventory-transfers"
    }
  }
}
call_operationLeituraRuns 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_idstringobrigatório

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

  • path_paramsobjectopcional

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

    Objeto livre: não declara campos.

  • queryobjectopcional

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

    Objeto livre: não declara campos.

  • bodyanyopcional

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

Exemplo de chamada
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_operationDestrutiva · pede confirmaçãoRuns 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_idstringobrigatório

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

  • path_paramsobjectopcional

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

    Objeto livre: não declara campos.

  • queryobjectopcional

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

    Objeto livre: não 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.

Exemplo de chamada
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"
      }
    }
  }
}

Referência de endpoints

Gerada a partir do próprio serviço: se um endpoint está aqui, ele pode ser chamado com uma chave de API. As respostas de exemplo são chamadas reais a uma conta de teste. As descrições estão em inglês, como o código.

POST Explain a SKU's recommendation
Narrativas com IA

Explain a SKU's recommendation

POST/api/v1/ai/narrative/forecast-explanation
Chave de leituraResponde 200 · application/json

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

Requisição

Cabeçalhos
  • AuthorizationBearer sk_live_…obrigatório

    Sua chave de API. Sempre obrigatória.

  • Content-Typeapplication/jsonobrigatório
Corpo

application/jsonO corpo é obrigatório.

object Um objeto.
  • skustringobrigatório
  • session_idstringobrigatório
  • profilestringopcionalpadrão "distributor"
  • languagestringopcionalpadrão "es"

Respostas

200 Se der certo

Para este endpoint não foi capturada uma resposta de exemplo. Toda resposta JSON traz este envoltório; o que vem em data depende do endpoint.

Erros possíveis

Além dos erros de cada endpoint, toda chamada feita com uma chave pode 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
Erros
Requisição
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"}'
Resposta
200 OK application/json
{
  "success": true,
  "data": {},
  "meta": {
    "timestamp": "2026-10-02T08:00:00Z"
  }
}

Ponha sua própria IA para prever suas vendas. Hoje.

Três formas de começar, conforme o quanto você quer se comprometer agora. As três chegam ao mesmo produto.

Crie sua conta

Com o motor completo. Envie seu arquivo de vendas e veja sua primeira previsão, e com ela a sua primeira lista do que pedir.

Criar minha conta

Veja antes de dar seu e-mail

Uma conta de teste na hora, com dados de exemplo. Dura 24 horas e depois é apagada.

Testar sem se cadastrar

Fale com a gente

Para o plano corporativo, o código-fonte, ou para ver com os seus dados e acompanhado. Respondemos em menos de 24 horas.

Vendas e contato: contacto@stockai.es. Telefone: +506 7186 2820.

Previsão de vendas feita na Costa Rica, para empresas da América Latina.