# FLOW (AIFLOW) API — full reference for agents > Multi-channel messaging automation (WhatsApp official/personal/desktop, Messenger, Instagram, Telegram, email, website widget). API version 2.0.0. 30 operations, 21 webhook events. - Human docs: https://flow.txi.co.il/developers - OpenAPI 3.1 JSON (authoritative, machine-readable): https://flow.txi.co.il/api/openapi.json - MCP endpoint: https://flow.txi.co.il/api/mcp — live tool catalog: https://flow.txi.co.il/api/mcp-tools.json - Short index: https://flow.txi.co.il/llms.txt Agent rules of thumb: authenticate with the credential the endpoint names; branch on `ok`/`status` for /api/external/send (it answers 200 even on failure); never retry a send that got any response; dedupe webhooks on X-AIFLOW-Delivery; ask the human before anything that publishes, deletes or messages many people. ## Quickstart Three steps from zero to a sent WhatsApp message. **1. Get credentials.** A business owner copies the external API key from **Settings → Webhooks** (`/settings/webhooks`). A platform that onboards many businesses calls the partner endpoint once per business instead — it returns the API key, an MCP key, a login-free connect link and an embed widget: ```bash curl -X POST https://flow.txi.co.il/api/partner/provision \ -H "Authorization: Bearer $FLOW_PARTNER_KEY" -H "Content-Type: application/json" \ -d '{"projectName":"My Clinic","source":"myplatform","externalRef":"acct_42"}' ``` **2. Connect a channel.** The owner opens `connectUrl` (no login) and connects WhatsApp / Facebook — or does it in the app. List what is connected with `GET /api/external/desktop-lines`, `GET /api/external/wa-templates`, or the `availableChannels` block on webhooks. **3. Send.** ```bash curl -X POST https://flow.txi.co.il/api/external/send \ -H "Authorization: Bearer $FLOW_API_KEY" -H "Content-Type: application/json" \ -d '{"channel":"whatsapp_official","to":"972501234567","type":"template","templateName":"order_ready","templateParams":["Dana"]}' ``` Then subscribe a webhook (Settings → Webhooks) to `conversation.message_received` and answer with the `platform.replyEndpoint.url` it gives you. ## Authentication Every family of endpoints takes its own credential. All are sent as `Authorization: Bearer …` over HTTPS. | Credential | Endpoints | Where to get it | |---|---|---| | External API key (64 hex) | `/api/external/*` | Settings → Webhooks, or partner provision `apiKey` | | API token (JWT) or per-flow token | `/api/webhook/outbound`, `/outbound-status`, lead triggers | `POST /api/auth/api-token` with client credentials from Settings → API access | | Partner key | `/api/partner/*` | Issued by the FLOW team | | MCP key — sent as `username:mcp_key` | `/api/mcp` | Settings → MCP, or partner provision `mcp.key` (shown once) | | Embed site key (public) | `/api/embed/*` | Settings → Embed, or partner provision `embed.siteKey` | One API key per tenant. Rotating it (partner `want.regenerateApiKey`, or regenerate in settings) breaks every integration using the old one. `?apiKey=` and a body `apiKey` are accepted but leak into logs — use the header. All `/api/external/*` calls are hard-scoped to the key's tenant: an id from another tenant answers 404 `conversation_not_found_or_not_yours`, never someone else's data. ## Sending and replying **Send** (`POST /api/external/send`) starts a message to anyone; **reply** (`POST /api/external/conversations/{id}/reply`) answers inside an existing conversation and picks the right line itself. Prefer reply whenever you have a conversation id — from a webhook or from the list endpoint. | channel | to | Notes | |---|---|---| | `whatsapp_green` | phone | needs `instanceId` (line UUID). Text, media, personal templates. No 24h window. Desktop lines too. | | `whatsapp_official` | phone | `type: "template"` only — an APPROVED Meta template. Free text goes through reply inside 24h. | | `messenger` | PSID | text + media. 24h window. | | `instagram` | IGSID | text + media. 24h window. | | `telegram` | chat id | text, image, video, document. | | `email` | address | needs `configId`. Text only. | **Send answers 200 after auth, even on failure.** Branch on `ok` / `status` (`sent`, `invalid_params`, `config_error`, `provider_error`, or a line-health code such as `instance_warming`). Keep `requestId`: the async `message.sent` / `message.failed` webhook carries it. **Reply uses real HTTP statuses**: 400 bad params / missing config, 404 not yours, 409 outside the 24h window or line warming, 501 media not supported on that channel yet, 502 provider error. **Who is handling the thread.** A send (WhatsApp personal) or reply is a human takeover by default: the conversation is claimed (`external_api:`) and the bot is paused until someone resumes it. Pass `agentName` / `agentId` so operators see the real agent. For informational notices (opening hours, "all agents busy") pass `system: true` — no claim, no pause, the "waiting for agent" state stays. To undo a takeover: `POST /api/external/conversations/{id}/unclaim` or, in bulk, `/unclaim-bulk` with `claimedByPrefix`. Unclaim releases only claims the API made; a claim held by an operator answers 409 `claimed_by_human` unless you pass `force: true`. Every send — on any channel — is written to the conversation transcript; pass `conversationId` to pick the thread. **Groups (desktop lines).** Group conversations are keyed by the group jid; reply works as usual and `replyToMessageId` quotes the message a `group.mention` event named. **Comments.** Conversations whose channel is `fb_comment:*` / `ig_comment:*` take `replyMode: "public"` (under the comment) or `"private"` (the single DM Meta allows per comment, within 7 days). ## Reading conversations `GET /api/external/conversations?limit=50&offset=0&status=active` lists conversations newest-activity first (max 200 per page, `pagination.hasMore`). `GET /api/external/conversations/{id}?limit=100` returns the conversation and its most recent messages, oldest first (max 500). Channel strings: `whatsapp` (official), `whatsapp_unofficial:` (personal / desktop), `messenger`, `instagram_dm`, `telegram:`, `email:`, `fb_comment:*`, `ig_comment:*`. The `channel` filter takes a family (`whatsapp`, `whatsapp_unofficial`, `messenger`, `instagram`, `telegram`, `email`) and matches the bare name plus any `:`; a value with `:` matches that one channel exactly. Message `direction` is always `incoming` or `outgoing` in these responses (older rows stored inbound/outbound; they are normalised). **Stable reply handle.** A flow ending opens a new conversation for the same customer. Turn on "stable reply handle" on your webhook and `replyEndpoint.url` carries the customer's Lead id instead; reply and unclaim resolve it to whatever conversation is live. ## Templates and quick replies - `GET /api/external/wa-templates` — Meta (official) templates per line, live from Meta, with `status`, `bodyText`, `paramCount`, `buttons`. Use `?status=APPROVED`. Send one with `channel: whatsapp_official, type: template, templateParams: [...]` — one value per `{{n}}`, or a full Meta `components` array for headers/buttons. - `GET /api/external/templates` — personal WhatsApp templates (bodies with `#variable#` tokens), grouped by category. Send with `channel: whatsapp_green, type: template, templateName`. - `GET /api/external/quick-replies` — the operators' "/" shortcuts, to show the same canned answers in your own inbox. Creating and submitting Meta templates for approval is done through MCP (`create_wa_template`), not REST. ## Starting flows from your system To run a whole bot flow (not one message) for a customer — e.g. a CRM stage change — call the outbound trigger with an API token: ```bash TOKEN=$(curl -s -X POST https://flow.txi.co.il/api/auth/api-token -H "Content-Type: application/json" \ -d '{"clientId":"cli_…","apiKey":"…","ttlSec":3600}' | jq -r .accessToken) curl -X POST https://flow.txi.co.il/api/webhook/outbound -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"phone":"972501234567","flowId":"","data":{"name":"Dana"},"FETCH_DATA":{"crmLeadId":"L-991"}}' ``` The call answers **202** with a `queueId` (poll `GET /api/webhook/outbound-status?queueId=`). `data.*` become flow variables; `FETCH_DATA` comes back as `data.fetchData` on every webhook for that conversation — use it to correlate. A recipient who already completed this flow is skipped (`skipped: true`) unless `_allowResend: true`. For web forms and landing pages use the flow's **API lead trigger**: `POST /api/webhook/flow/{flowId}/lead` with whatever auth the trigger node is set to (none, API-key header, Basic, Bearer or HMAC-SHA256). ## Reporting webhooks Add an endpoint in **Settings → Webhooks**: URL, events (empty or `*` = all), optional secret, security mode, attempts (1–10, default 3), filters by line / media type / personal lines, "include channels", "stable reply handle". The full event list with payloads is in the reference below (OpenAPI `webhooks`). Every delivery is a `POST` with `Content-Type: application/json`, a 10-second timeout and: | Header | Value | |---|---| | `X-AIFLOW-Event` | event name | | `X-AIFLOW-Delivery` | event id (= body `id`; the same on every retry — dedupe on it) | | `X-AIFLOW-Timestamp` | unix seconds of this attempt | | `X-AIFLOW-Signature` | only when a secret is set — see below | Body: `{ id, event, createdAt, userId, platform, data }`. `platform` always says which channel/line the event belongs to and, when there is a conversation, `replyEndpoint`. **Signatures.** Always verify against the **raw request bytes**, before parsing JSON. - `standard`: `X-AIFLOW-Signature: sha256=` - `strict`: `X-AIFLOW-Signature: t=,v1=` — also reject when the timestamp is more than 5 minutes from now (replay protection). Node.js (Express): ```js import crypto from "node:crypto"; import express from "express"; const app = express(); app.post("/flow-webhook", express.raw({ type: "application/json" }), (req, res) => { const raw = req.body; // Buffer const header = req.get("X-AIFLOW-Signature") || ""; const secret = process.env.FLOW_WEBHOOK_SECRET; let expected, given; if (header.startsWith("t=")) { // strict const parts = Object.fromEntries(header.split(",").map((p) => p.split("="))); if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return res.sendStatus(401); expected = crypto.createHmac("sha256", secret).update(parts.t + "." + raw).digest("hex"); given = parts.v1; } else { // standard expected = crypto.createHmac("sha256", secret).update(raw).digest("hex"); given = header.replace(/^sha256=/, ""); } const ok = given && given.length === expected.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected)); if (!ok) return res.sendStatus(401); const event = JSON.parse(raw); res.sendStatus(200); // ack fast, work async queue.push(event); // dedupe on event.id }); ``` Python (Flask): ```python import hmac, hashlib, json, os, time from flask import Flask, request, abort app = Flask(__name__) SECRET = os.environ["FLOW_WEBHOOK_SECRET"].encode() @app.post("/flow-webhook") def flow_webhook(): raw = request.get_data() # bytes, before parsing header = request.headers.get("X-AIFLOW-Signature", "") if header.startswith("t="): # strict parts = dict(p.split("=", 1) for p in header.split(",")) if abs(time.time() - int(parts["t"])) > 300: abort(401) expected = hmac.new(SECRET, parts["t"].encode() + b"." + raw, hashlib.sha256).hexdigest() given = parts.get("v1", "") else: # standard expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest() given = header.removeprefix("sha256=") if not hmac.compare_digest(given, expected): abort(401) event = json.loads(raw) # enqueue(event) - dedupe on event["id"] return "", 200 ``` Shell (checking a captured delivery, standard mode): ```bash # body.json = the exact bytes received; SIG = the X-AIFLOW-Signature header EXPECTED="sha256=$(openssl dgst -sha256 -hmac "$FLOW_WEBHOOK_SECRET" -hex < body.json | sed 's/^.* //')" [ "$EXPECTED" = "$SIG" ] && echo valid || echo INVALID # strict mode: sign "." printf '%s.' "$T" | cat - body.json | openssl dgst -sha256 -hmac "$FLOW_WEBHOOK_SECRET" -hex ``` **Retries.** Any non-2xx answer or timeout is retried until the endpoint's attempt budget is spent (default 3), sleeping 10 s, 60 s, 5 min, 15 min, 1 h, 2 h, 4 h, 8 h, 16 h between attempts. Then the event is dropped; the endpoint is never auto-disabled (its failure count shows in settings). Retries are held in server memory — a deploy or restart drops pending retries, so reconcile with `GET /api/external/conversations` if you missed a window. Deliveries are not ordered. **No secrets in payloads.** "include channels" adds `availableChannels` and a `_sendApi` pointer (endpoint + example body) — never your API key. Call the send / reply endpoints with the key you already store. ## MCP for AI agents FLOW runs a remote MCP server at `https://flow.txi.co.il/api/mcp` (stateless streamable HTTP, JSON-RPC 2.0). It is the **full builder**: create and edit flows, create Meta templates and submit them for approval, manage lines and template groups, debug conversations, publish to Facebook / Instagram, read ads and leads, and leave work requests for the FLOW team. Everything is scoped to one tenant and audited. Auth: `Authorization: Bearer :` (key from Settings → MCP or partner provision). The live tool list, with input schemas, is public: [`/api/mcp-tools.json`](https://flow.txi.co.il/api/mcp-tools.json). An agent should call the `get_started` tool first — it returns the current working rules. **Claude Code** ```bash claude mcp add --transport http flow https://flow.txi.co.il/api/mcp \ --header "Authorization: Bearer :" ``` **Claude Desktop** (`claude_desktop_config.json`, via the `mcp-remote` bridge): ```json { "mcpServers": { "flow": { "command": "npx", "args": ["-y", "mcp-remote", "https://flow.txi.co.il/api/mcp", "--header", "Authorization:${FLOW_AUTH}"], "env": { "FLOW_AUTH": "Bearer :" } } } } ``` **Claude API** — MCP connector: add `{ "type": "url", "url": "https://flow.txi.co.il/api/mcp", "name": "flow", "authorization_token": ":" }` to `mcp_servers`. **OpenAI / ChatGPT** — in the Responses API add a tool `{ "type": "mcp", "server_label": "flow", "server_url": "https://flow.txi.co.il/api/mcp", "headers": { "Authorization": "Bearer :" }, "require_approval": "always" }`. ChatGPT's UI connectors need OAuth or no-auth, which this server does not offer — use the API or a bridge. **Raw JSON-RPC** ```bash curl -s https://flow.txi.co.il/api/mcp -H "Authorization: Bearer $FLOW_MCP_AUTH" -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_flows","arguments":{}}}' ``` Results come back as `result.content[0].text` (JSON text); failures as `result.isError: true`. Scoped extra keys (issued by the FLOW team per connected system) see only their allow-listed tools; draft-only keys cannot publish. Ask the user before destructive tools (`delete_flow`, `set_flow_status`, `restore_flow_version`) and before any public post. **Rate limit: 60 requests per minute per tenant** by default. `initialize`, `ping`, `tools/list` and notifications are free; a batch counts once. Back off on HTTP 429 / error -32002 (`Retry-After` is set). ## Partner provisioning (PARSI, platforms) A platform that onboards many businesses (PARSI, SITISELL, an agency) uses one partner key and keeps one FLOW tenant per business. **Always send `source` + `externalRef`.** The pair is a one-to-one link: the same record always gets the same tenant, whatever the name, and one tenant cannot be linked to two records of the same source. Conflicts answer 409, never a guess. Without a link, a name never selects an existing tenant: an exact name match answers 409 `tenant_name_taken` and a near match 409 `possible_duplicate_tenant` — neither returns credentials or userIds. Attach with `mode: "attach", existingUserId` (the userId from the FLOW admin) or resend with `confirmNew: true` for a separate tenant. Provision is safe to repeat: it returns the same API key, keeps an existing MCP key (`mcp.existing: true`, prefix only — the full key is shown only when minted), and reuses the embed site. Rotate with `want.regenerateApiKey` / `want.regenerateMcpKey`; opt out of parts with `want.embed: false` etc. **PARSI store mode.** Add `store: { host, apiKey }` (a `pmk_` site key with `site:catalog` + `site:orders:create`). FLOW tests the key against PARSI, checks the host — and with `source: "parsi"` that the key's siteId equals `externalRef` — then stores it encrypted on that tenant and never returns it. The result is in `store` (`ok:false` + `store_apiKey_required | store_key_rejected | store_host_mismatch | store_site_mismatch` does not fail the whole call). Store mode starts disabled and in test mode; the owner connects a WhatsApp Cloud line via `connectUrl` and enables it in Settings → Store. ```bash curl -X POST https://flow.txi.co.il/api/partner/provision -H "Authorization: Bearer $FLOW_PARTNER_KEY" \ -H "Content-Type: application/json" -d '{ "projectName": "Flower Shop", "source": "parsi", "externalRef": "site_8812", "store": { "host": "flowers.parsi.co.il", "apiKey": "pmk_…" } }' ``` `GET /api/partner/tenant-link?source=&externalRef=` shows the link and health (API key, MCP, embed count). `DELETE` with the same pair unlinks; `revoke` (default true) replaces the API key and switches off the MCP key so your stored credentials stop working — the tenant and its data stay. ## Website widget Drop the script the provision call (or Settings → Embed) gives you: ```html ``` Options as `data-*` attributes or `window.AIFLOW_CONFIG`: `mode` (`chatbot` default, `search` on `[data-aiflow-search]`, `form` on `[data-aiflow-form]`), `position`, `theme`, `primaryColor`, `openDelaySec`, `locale`. When the site has a flow attached, widget visitors become real conversations (operator takeover, webhooks); otherwise the widget answers from the knowledge base. Set allowed origins on the site — requests from other origins get 403. The backend (`/api/embed/*`) is documented below for custom front-ends. A `/api/embed/form` submission becomes a lead (source `embed_form`) and fires `embed.form_submitted`; include a hidden, empty `_hp` field in custom forms — a filled one is treated as a bot. ## Rate limits, idempotency, errors | Endpoint | Limit | |---|---| | `POST /api/external/send` | 100 / minute / tenant → 429 | | other `/api/external/*` | none enforced — keep it reasonable | | `POST /api/webhook/outbound` | 50 / second / IP | | `POST /api/mcp` | 60 / minute / tenant (setup calls free) | | `/api/embed/*` | per siteKey + IP per minute: chat 30, search 60, session 120, verify-key 60, form 10 | Counters live in server memory and reset on restart; treat them as ceilings, not guarantees. **Idempotency.** `/api/external/send` and reply have no idempotency key — a retried request sends twice. Retry only on network errors before a response, or on 429 / 5xx from reply. `/api/webhook/outbound` dedupes an identical body for the same flow + recipient for 10 minutes. Desktop-line commands accept `id` as an idempotency key. Webhook receivers must dedupe on `X-AIFLOW-Delivery`. **Error shapes.** `/api/external/*`: `{ ok: false, error, message?, hint?, docs }`. Partner: `{ ok: false, error }` with snake_case codes. Triggers and embed: `{ error }`. MCP: JSON-RPC `error` objects, and tool failures as `isError` results. **Phones.** Digits only, international format without `+` (`972501234567`). Send converts a leading `0` to `972`. ## Endpoint reference ### POST /api/external/send Send a proactive message on any channel. Auth: externalApiKey or externalApiKeyQuery. Operation: `sendMessage`. Source: `src/pages/api/external/send.js`. Sends one message to a recipient on WhatsApp personal (Green / desktop lines), WhatsApp official (template only), Messenger, Instagram DM, Telegram or email. After authentication the HTTP status is ALWAYS 200 (except 429): read `ok` and `status`. Every attempt also fires a `message.sent` or `message.failed` reporting webhook carrying the same `requestId`. WhatsApp personal sends are logged into the conversation, stamped `sentBy: external_api` and — unless `system: true` — claim the thread for `external_api` and pause the bot permanently (an operator resumes it, or call /unclaim). Body: - `channel` ("whatsapp_green" | "whatsapp_official" | "messenger" | "instagram" | "telegram" | "email"): Channel family. Omit and pass `instanceId` for legacy WhatsApp-personal sends. Dashes are accepted (whatsapp-green). - `to` (string): Recipient. E.164 digits for WhatsApp/Telegram (0-prefixed Israeli numbers are converted to 972), email address for email, PSID for Messenger, IGSID for Instagram, chat id for Telegram. Required except for messenger/instagram when psid/igsid is given. - `type` ("text" | "image" | "video" | "document" | "template", default "text"): Message type. WhatsApp official accepts only `template`; Messenger/Instagram reject `template`. - `text` (string): Body, or caption for media. Required for type=text (except Messenger/Instagram, where it is not checked). - `mediaUrl` (string): Public HTTPS URL. Required for image/video/document on WhatsApp personal and Telegram. - `fileName` (string): Display file name for documents (WhatsApp personal). - `instanceId` (string): whatsapp_green: the line id (GreenApiWhatsappInstance.id UUID — NOT the numeric idInstance). Desktop lines from GET /api/external/desktop-lines use their `id` here too. - `templateName` (string): type=template. whatsapp_green: a personal template name (GET /api/external/templates). whatsapp_official: an APPROVED Meta template name (GET /api/external/wa-templates). - `templateLanguage` (string, default "he"): whatsapp_official template language. - `templateParams` (string[] or object[]): whatsapp_official: either a flat array of body values (["Dana","10:30"]) — wrapped into one body component — or a ready Meta `components` array. - `phoneNumberId` (string): whatsapp_official: pick a line when the tenant has more than one active Cloud line (required in that case). - `psid` (string): messenger: recipient PSID (alias of `to`). - `pageId` (string): messenger: pick a Facebook Page config. - `igsid` (string): instagram: recipient IGSID (alias of `to`). - `igAccountId` (string): instagram: pick an Instagram account config. - `chatId` (string): telegram: chat id (alias of `to`). - `configId` (string): telegram: bot config id (optional). email: EmailConfig.id (required). - `emailSubject` (string, default "(no subject)"): email subject. - `emailThreadId` (string): email: thread to reply in. - `conversationId` (string): Log the send into this conversation (must be the tenant's and the same recipient; otherwise ignored, see conversationIdIgnored). - `system` (boolean, default false): Informational notice (hours, overload). Logged with authorType system; does not claim the thread or pause the bot (only whatsapp_green ever claims). - `senderName` (string): Shown as the author of a system notice (max 120 chars). - `apiKey` (string): Discouraged: the API key in the body instead of the Authorization header. ```json {"channel":"whatsapp_green","instanceId":"3f0c…-uuid","to":"972501234567","type":"text","text":"שלום! ההזמנה שלך מוכנה"} ``` Responses: - 200: Attempt finished. `ok` tells success; `status` tells why not. - 401: Missing or invalid credentials. - 405: Wrong HTTP method (Allow header lists the right one). - 429: More than 100 requests/minute for this tenant (in-memory, per server process). Body includes requestId. Success fields: - `ok` (boolean, required) - `requestId` (string, required): UUID on every post-auth response. Matches `data.requestId` on the message.sent / message.failed webhook. - `status` ("sent" | "failed" | "invalid_params" | "config_error" | "provider_error" | "instance_warming" | "instance_flagged_low_delivery" | "instance_requires_warmup", required) - `error` (string): Present when ok=false. - `messageId` (string): Provider message id (WhatsApp wamid / Green idMessage / Telegram message_id). Messenger/Instagram fall back to a random UUID when the provider returns none. - `channel` (string): Channel the message went out on. For whatsapp_green this is the raw conversation channel `whatsapp_unofficial:`. - `instancePhone` (string): whatsapp_green: the sending line number. - `templateName` (string) - `templateLanguage` (string) - `phoneNumberId` (string) - `pageId` (string) - `igAccountId` (string) - `chatId` (string) - `botUsername` (string) - `emailTo` (string) - `emailSubject` (string) - `conversationId` (string): Conversation the send was logged into (every channel). - `conversationIdIgnored` ("not_found" | "recipient_mismatch"): Set when the body's conversationId was not used. - `docs` (string) Watch out: - Rate limit is 100/min per tenant (the old docs said 60). - A line in warm-up or flagged by WhatsApp answers ok=false with status = the gate code (instance_warming, instance_flagged_low_delivery, instance_requires_warmup). - Every channel is written to the conversation transcript (message_sent, direction outgoing) and the response carries `conversationId`. Only whatsapp_green claims the thread and pauses the bot (unless system:true); other channels log without claiming. - `conversationId` in the body is used when it is this tenant's and the same recipient; otherwise it is ignored and the response says `conversationIdIgnored` (not_found / recipient_mismatch). Without it the recipient's active conversation on that channel is used, else a new one (status completed for non-personal channels, so the customer's reply still starts the channel's flow). - channel=email answers provider_error when the mail provider rejects the message (it used to report sent). - channel=email ignores type/mediaUrl (text only). - messenger/instagram do not validate that `text` / `mediaUrl` is present. ### GET /api/external/conversations List conversations (newest activity first). Auth: externalApiKey or externalApiKeyQuery. Operation: `listConversations`. Source: `src/pages/api/external/conversations/index.js`. Parameters: - `limit` (query, integer) - `offset` (query, integer) - `channel` (query, string): `email` and `whatsapp_unofficial` match by prefix; any other value must equal the stored channel string exactly (e.g. `whatsapp`, `telegram`, or `messenger:`). - `status` (query, "active" | "completed" | "abandoned" | "error") Responses: - 200: Page of conversations. - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). - 500: list_failed Success fields: - `ok` (true) - `conversations` (ConversationSummary[]) - `pagination` (object) Watch out: - `channel` is a family: it matches the bare name and any `:` (messenger, telegram:, email:, whatsapp_unofficial:); instagram also matches instagram_dm; whatsapp_official / whatsapp_green are accepted aliases. A value containing ":" matches that one stored channel exactly. - No rate limit on this endpoint. ### GET /api/external/conversations/{id} Get a conversation with its latest messages. Auth: externalApiKey or externalApiKeyQuery. Operation: `getConversation`. Source: `src/pages/api/external/conversations/[id]/index.js`. Messages are returned oldest-first; `limit` takes the most recent N. Parameters: - `id` (path, required, string): Conversation id. (Unlike reply/unclaim, a Lead handle is NOT accepted here.) - `limit` (query, integer) Responses: - 200: Conversation and messages. - 401: Missing API key / Invalid API key. - 404: conversation_not_found_or_not_yours - 405: Wrong HTTP method (Allow header lists the right one). - 500: fetch_failed Success fields: - `ok` (true) - `conversation` (ConversationSummary) - `messages` (Message[]) - `pagination` (object) Watch out: - No cursor: only the newest 500 messages are reachable (hasMore=true but no `before` parameter). ### POST /api/external/conversations/{id}/reply Reply into an existing conversation (channel-aware). Auth: externalApiKey or externalApiKeyQuery. Operation: `replyToConversation`. Source: `src/pages/api/external/conversations/[id]/reply.js`. Routes by the conversation's own channel — the caller does not need to know the line. | Channel | Supports | |---|---| | WhatsApp personal / desktop | text + media, no 24h window, groups, `replyToMessageId` | | WhatsApp official | text inside 24h, template any time; media → 501 | | Messenger | text + media, 24h (7d with Human Agent tag once approved) | | Instagram DM | text + media, 24h | | Telegram | text + image/video/document | | Email | text, threaded; media → 501 | | fb_comment / ig_comment | text; `replyMode` public/private | Unless `system: true`, a reply claims the thread as `external_api:` and pauses the bot permanently. Parameters: - `id` (path, required, string): Conversation id OR a stable Lead id (the reporting webhook emits a Lead id when "stable reply handle" is on). A Lead id resolves to the live conversation for that phone. Body: - `type` ("text" | "image" | "video" | "document" | "template", default "text") - `text` (string): Required for type=text; caption for media. - `mediaUrl` (string): Required for image/video/document. - `fileName` (string): Document display name. - `templateName` (string): type=template (WhatsApp official only). - `templateLanguage` (string, default "he") - `templateParams` (any[]): Flat values or Meta components (see SendRequest). - `system` (boolean, default false): Informational notice: no claim, no bot pause, "waiting for agent" kept. - `senderName` (string): Author shown for a system notice. - `agentName` (string): Real human agent name shown as the thread handler (instead of the API account). - `agentId` (string): Stable agent id; the claim marker becomes external_api:. - `replyToMessageId` (string): WhatsApp personal / desktop lines: quote this message id (e.g. the one a group.mention named). - `replyMode` ("public" | "private", default "public"): fb_comment / ig_comment conversations: public reply under the comment, or the one private DM Meta allows per comment (7 days). ```json {"type":"text","text":"היי, אני דנה מהמוקד — איך אפשר לעזור?","agentName":"דנה","agentId":"crm-17"} ``` Responses: - 200: Sent. - 400: Bad params or missing config: type_must_be_text_image_video_document_template, text_required_for_text_type, mediaUrl_required_for_media_types, templateName_required_for_template_type, template_only_for_cloud, template_not_found, template_not_approved, *_config_missing, instance_not_active, channel_not_yet_supported, comment_replies_are_text_only, … - 401: Missing API key / Invalid API key. - 404: conversation_not_found_or_not_yours - 405: Wrong HTTP method (Allow header lists the right one). - 409: Outside the send window (outside_24h_window, outside_messenger_window) or the line is warming/flagged. - 501: media_via_cloud_not_yet_supported_in_external_api / media_via_email_not_yet_supported - 502: Upstream provider error (provider_error: …, email_send_failed: …, comment_graph_error). Success fields: - `ok` (true) - `messageId` (string) - `channel` (string) - `type` (string) - `instancePhone` (string): WhatsApp personal only. - `templateName` (string) - `templateLanguage` (string) - `replyMode` (string): Comment threads only. Watch out: - No rate limit on reply (send has one). - Reply and send both log direction `outgoing`. Older rows may hold inbound/outbound; the read endpoints return incoming/outgoing only, and receivers of reporting webhooks should accept both spellings. ### POST /api/external/conversations/{id}/unclaim Release a conversation the API claimed (and resume the bot). Auth: externalApiKey or externalApiKeyQuery. Operation: `unclaimConversation`. Source: `src/pages/api/external/conversations/[id]/unclaim.js`. Parameters: - `id` (path, required, string): Conversation id or Lead id. Body: - `resumeBot` (boolean, default true): Also clear the bot pause. - `force` (boolean, default false): Release a human operator's claim too. Responses: - 200: Released. - 401: Missing API key / Invalid API key. - 404: conversation_not_found_or_not_yours - 405: Wrong HTTP method (Allow header lists the right one). - 409: claimed_by_human — an operator (or someone answering from the phone) holds the conversation. Resend with force:true to release it anyway. - 500: unclaim_failed Success fields: - `ok` (true) - `id` (string) - `cleared` (true) - `resumedBot` (boolean) - `released` ("not_claimed" | "external_api_claim" | "forced") Watch out: - Only claims the API made (claimedBy external_api or external_api:) are released by default; a human claim needs force:true. ### POST /api/external/conversations/unclaim-bulk Release every conversation claimed by a given marker prefix. Auth: externalApiKey or externalApiKeyQuery. Operation: `unclaimConversationsBulk`. Source: `src/pages/api/external/conversations/unclaim-bulk.js`. Body: - `claimedByPrefix` (string, required): Required guard: only rows whose claimedBy starts with this (e.g. "external_api:"). - `since` (string): Only rows claimed at/after this ISO time. - `resumeBot` (boolean, default true) ```json {"claimedByPrefix":"external_api:","since":"2026-11-18T00:00:00Z"} ``` Responses: - 200: Done. - 400: claimedByPrefix_required / bad_since_iso - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). - 500: unclaim_bulk_failed Success fields: - `ok` (true) - `updated` (integer): Rows changed. - `resumedBot` (boolean) - `filter` (object) ### GET /api/external/device-jobs TikTok drafts waiting to be finished on the tenant's phone (device runner). Auth: externalApiKey or externalApiKeyQuery. Operation: `listDeviceJobs`. Source: `src/pages/api/external/device-jobs.js`. Responses: - 200: Waiting jobs: post id, target id, caption with its attributed link, AI-label flag, upload time. - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). Success fields: - `ok` (boolean) - `jobs` (object[]) ### POST /api/external/device-jobs Mark a job live after publishing, or raise an alert to the owner. Auth: externalApiKey or externalApiKeyQuery. Operation: `deviceJobAction`. Source: `src/pages/api/external/device-jobs.js`. Body: - `action` (string): mark-live | alert - `targetId` (string): Target to mark live (mark-live). - `kind` (string): Alert kind (alert). - `message` (string): Alert text (alert). Responses: - 200: Done. - 400: Bad request. - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). Success fields: - `ok` (boolean) ### GET /api/external/quick-replies List the tenant's quick replies ("/" shortcuts). Auth: externalApiKey or externalApiKeyQuery. Operation: `listQuickReplies`. Source: `src/pages/api/external/quick-replies.js`. Responses: - 200: Items. - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). - 500: server_error (ok=false, empty items). Success fields: - `ok` (boolean) - `items` (QuickReply[]) ### GET /api/external/templates List personal WhatsApp templates, grouped by category. Auth: externalApiKey or externalApiKeyQuery. Operation: `listPersonalTemplates`. Source: `src/pages/api/external/templates.js`. Responses: - 200: Items + groups (uncategorised → "כללי"). - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). - 500: server_error (ok=false, empty items/groups). Success fields: - `ok` (boolean) - `items` (PersonalTemplate[]) - `groups` (object) ### GET /api/external/wa-templates List Meta (WhatsApp official) templates per line, live from Meta. Auth: externalApiKey or externalApiKeyQuery. Operation: `listWhatsAppTemplates`. Source: `src/pages/api/external/wa-templates.js`. Parameters: - `phoneNumberId` (query, string): Restrict to one line. - `status` (query, string): e.g. APPROVED (case-insensitive). Responses: - 200: One entry per WABA. - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). - 500: server_error (ok=false, empty lines). Success fields: - `ok` (boolean) - `lines` (WaTemplateLine[]) Watch out: - Only the first 100 templates per WABA (no paging). - Lines sharing a WABA are listed once, under the first line's phoneNumberId. - A line whose Graph call fails is still listed, with templates: [] and error: graph_unreachable (the call itself answers 200). ### GET /api/external/desktop-lines List desktop lines (WhatsApp on an agent's computer) with live device status. Auth: externalApiKey or externalApiKeyQuery. Operation: `listDesktopLines`. Source: `src/pages/api/external/desktop-lines/index.js`. Responses: - 200: Lines. - 401: Missing API key / Invalid API key. - 405: Wrong HTTP method (Allow header lists the right one). - 500: read_failed Success fields: - `ok` (true) - `lines` (DesktopLine[]) ### POST /api/external/desktop-lines/command Run one command on a desktop line's device. Auth: externalApiKey or externalApiKeyQuery. Operation: `runDesktopCommand`. Source: `src/pages/api/external/desktop-lines/command.js`. Allowed methods — read: account.info, account.sendStats, message.get, message.downloadMedia, chat.list, chat.get, chat.messages, contact.check, contact.get, contact.profilePic, contact.resolve, group.info, group.inviteCode, label.list. Write: account.logout, message.send/reply/forward/react/edit/delete, chat.markRead/markUnread/archive/unarchive/pin/unpin/mute/unmute/presence, contact.block/unblock, group.create/addParticipants/removeParticipants/promote/demote/setSubject/setDescription/setSettings/revokeInvite/join/leave, label.setForChat. Param shapes: LINK_PROTOCOL.md §4. Body: - `lineId` (string, required): Desktop line id. - `method` (string, required): Allow-listed method name. - `params` (object) - `id` (string): Idempotency key (≤100 chars): resending the same id returns the device's cached result instead of running twice. - `timeoutMs` (integer): Wait for the device this long. ```json {"lineId":"line-uuid","method":"chat.list","params":{"limit":20},"id":"crm-req-0001"} ``` Responses: - 200: Device answered: ok=true with `result`, or ok=false with the device's refusal { code: NOT_READY | NOT_ON_WHATSAPP | BAD_PARAMS | … }. - 400: lineId and method are required / method_not_allowed - 401: Missing API key / Invalid API key. - 403: Access denied for this line. - 404: line_not_found - 405: Wrong HTTP method (Allow header lists the right one). - 503: device_offline / device_timeout Success fields: - `ok` (boolean) - `id` (string) - `result` (any) - `error` (object) ### POST /api/external/desktop-lines/import-groups Pull every WhatsApp group of a desktop line into the inbox. Auth: externalApiKey or externalApiKeyQuery. Operation: `importDesktopGroups`. Source: `src/pages/api/external/desktop-lines/import-groups.js`. Body: - `lineId` (string, required) - `messagesPerGroup` (integer, default 30): 0–200. Responses: - 200: Imported. - 401: Missing API key / Invalid API key. - 404: line_not_found - 405: Wrong HTTP method (Allow header lists the right one). - 502: Device error. - 503: device_offline Success fields: - `ok` (true) - `groups` (integer) - `createdConversations` (integer) - `importedMessages` (integer) ### POST /api/auth/api-token Exchange API client credentials for a short-lived JWT. Auth: none. Operation: `issueApiToken`. Source: `src/pages/api/auth/api-token.js`. Client credentials are created at /settings/api-access. The JWT authorises /api/webhook/outbound and /api/webhook/outbound-status (and lead triggers) for flows the client's owner owns. Body: - `clientId` (string, required) - `apiKey` (string, required) - `ttlSec` (integer, default 3600): 600–86400. Responses: - 200: Token. - 400: clientId and apiKey are required - 401: Invalid API credentials - 429: Rate limited (per IP). Success fields: - `success` (true) - `tokenType` ("Bearer") - `accessToken` (string) - `expiresInSec` (integer) - `clientNumber` (any) - `clientId` (string) ### POST /api/webhook/outbound Start a flow for a recipient (proactive WhatsApp). Auth: outboundToken. Operation: `triggerOutboundFlow`. Source: `src/pages/api/webhook/outbound.js`. Queues the flow for the recipient and answers 202 immediately (default queue mode). Poll /api/webhook/outbound-status?queueId= or subscribe to reporting webhooks. Everything inside `data` becomes a flow variable ({{key}}). `FETCH_DATA` (aliases fetchData, fetch_data; object, array or JSON string) is stored on the conversation and echoed as `data.fetchData` on every reporting webhook for it. Idempotency: an identical body for the same flow + recipient within 10 minutes is not enqueued again — the first queueId is replayed with `deduplicated: true`. Case file guard: if the recipient already completed this flow (station) the call answers 200 `skipped: true` — pass `_allowResend: true` to force. Disabled while the flow is in debug mode. Body: - `phone` (string, required): Recipient: digits with or without +, or a WhatsApp BSUID. - `flowId` (string, required): Flow to start. Required. Must be active. - `data` (object): Flow variables. `text` here goes through the compliance check. - `templateId` (string): Shortcut for data.templateId. - `templateGroupId` (string): Shortcut for data.templateGroupId. - `templateName` (string): Shortcut for data.templateName. - `FETCH_DATA` (any): Opaque correlation payload echoed on webhooks. - `forceSend` (boolean): Send although compliance answered "review". - `allowMarketing` (boolean): Evaluate data.text as marketing-allowed. - `_allowResend` (boolean): Bypass the case-file "already completed" guard. ```json {"phone":"972501234567","flowId":"flow-uuid","data":{"name":"דנה","code":"1234"},"FETCH_DATA":{"crmLeadId":"L-991"}} ``` Responses: - 200: Synchronous mode result (OUTBOUND_QUEUE_MODE=0) or `skipped: true` (station_already_completed). - 202: Queued (or deduplicated replay). - 400: Valid phone number is required / Flow ID is required / Invalid phone number format / Flow is not active / WhatsApp not configured for the flow owner / template / start-trigger validation. - 401: Missing or invalid token. - 403: Token is valid but not allowed for this flow owner. - 404: Flow not found. - 409: Compliance requires review — resubmit with forceSend=true. Body includes `compliance`. - 422: Compliance blocked the text/template. - 429: Rate limited: 50 requests/second per IP. - 500: Failed to trigger outbound flow. Success fields: - `success` (boolean) - `skipped` (boolean) - `reason` (string) - `hint` (string) Watch out: - Error shape here is { error } (no ok/docs), unlike /api/external/*. - Idempotency memory is per server process and lost on restart. ### GET /api/webhook/outbound-status Status of a queued outbound trigger. Auth: outboundToken. Operation: `getOutboundStatus`. Source: `src/pages/api/webhook/outbound-status.js`. Parameters: - `queueId` (query, required, string) Responses: - 200: Queue row. - 400: queueId is required - 401: Invalid token. - 403: Not allowed for this flow owner. - 404: Queue item / flow not found. Success fields: - `queueId` (string) - `status` (string): pending / processing / done / failed … - `success` (boolean|null) - `queuedAt` (string) - `startedAt` (string|null) - `completedAt` (string|null) - `attempts` (integer) - `error` (string|null) - `result` (any) ### POST /api/webhook/flow/{flowId}/lead Push a lead into a flow's "API lead" trigger. Auth: leadTriggerAuth or outboundToken or none. Operation: `submitLead`. Source: `src/pages/api/webhook/flow/[flowId]/lead.js`. The flow's API-lead start node decides auth (none / api_key header / basic / bearer / hmac-sha256 of the JSON body, header default X-Signature-256, optional "sha256=" prefix) and maps body fields (dot paths) to variables. An API JWT from /api/auth/api-token is also accepted. The whole body is kept as `_leadData`. `secondarySource` (integer 0–1,000,000) tags the lead. Parameters: - `flowId` (path, required, string) Body: ```json {"phone":"972501234567","name":"דנה","source":"landing-a","secondarySource":12} ``` Responses: - 200: Lead received and flow started. - 400: Missing flowId / Flow does not have an API Lead Trigger node. - 401: Auth failed (message names the reason). - 404: Flow not found. - 500: Failed to process lead. Success fields: - `success` (true) - `message` (string) - `variables` (string[]) Watch out: - HMAC-SHA256 is verified over the raw request bytes (hex, optional sha256= prefix, any case). Signatures over the compact JSON re-serialisation are still accepted for older senders. - A missing, malformed or wrong-length signature answers 401. Body limit 1 MB (413). - Only the first engine result of type "message" is sent, directly via the Cloud API. ### POST /api/webhook/external/{stream} Inbound capture endpoint for a third-party system (GET/PUT/PATCH/DELETE also accepted). Auth: externalStreamToken or none. Operation: `captureExternalWebhook`. Source: `src/pages/api/webhook/external/[stream].js`. Accepts JSON, urlencoded or text-only multipart (≤5 MB), logs it, and — when the stream is configured by FLOW for the tenant — dispatches it (e.g. a call-center event that starts a flow). Always answers 200 so the sender does not retry. Streams are provisioned by the FLOW team. Parameters: - `stream` (path, required, string) Body: Responses: - 200: Captured. - 400: invalid stream slug - 401: unauthorized (only when the server has EXTERNAL_WEBHOOK_TOKEN set) Success fields: - `ok` (true) - `stream` (string) - `received` (object) Watch out: - Open (no auth) unless the server sets EXTERNAL_WEBHOOK_TOKEN — one token for all streams. ### POST /api/partner/provision Create or attach a FLOW tenant and return every credential it needs. Auth: partnerKey. Operation: `provisionTenant`. Source: `src/pages/api/partner/provision.js`. One call connects a project: tenant + external API key + login-free connect link + embed widget site + MCP key (+ optional PARSI store). With `source` + `externalRef` the tenant is linked one-to-one to your record: the same pair always returns the same tenant, whatever the name. Without a link, a name never selects an existing tenant: a taken name answers 409 tenant_name_taken (no credentials); attach with mode=attach + existingUserId. Repeat calls are safe: the API key is returned as-is, the MCP key is kept (only its prefix is returned), the embed site is reused. Use want.regenerate* to rotate. Body: - `projectName` (string): Tenant display name. Required for mode=new. - `mode` ("new" | "attach", default "new") - `existingUserId` (string): Required for mode=attach. - `email` (string): Owner email (optional). - `confirmNew` (boolean): Create even when a similar tenant exists (otherwise 409 possible_duplicate_tenant). - `source` (string): One-to-one link: partner system name, ^[a-z][a-z0-9_-]{1,39}$ (e.g. parsi). - `externalRef` (string): One-to-one link: the record id in that system (≤191 chars). Same pair → same tenant, always. - `connectTtlMinutes` (integer, default 10080): Lifetime of the connect link. - `want` (object) - `apiKey` (boolean, default true) - `connectLink` (boolean, default true) - `embed` (boolean, default true) - `mcp` (boolean, default true) - `regenerateApiKey` (boolean, default false): Rotate the external API key (old one stops working). - `regenerateMcpKey` (boolean, default false): Rotate the MCP key (old one stops working). - `newEmbed` (boolean, default false): Create another embed site instead of reusing the first. - `store` (object): PARSI store for WhatsApp store mode (one tenant per store). - `host` (string): Store host, e.g. shop.example.com (checked against the key's store). - `apiKey` (string): PARSI site key (pmk_…) with site:catalog + site:orders:create. Validated live, stored encrypted, never returned. ```json {"projectName":"My Clinic","email":"owner@clinic.co.il"} ``` Responses: - 200: Provisioned. - 400: projectName_required / existingUserId_required_for_attach / invalid_source / invalid_external_ref - 401: invalid_partner_key - 404: tenant_not_found (attach) - 409: tenant_name_taken (an existing tenant has this name — no credentials are returned; attach by userId or resend with confirmNew:true) / possible_duplicate_tenant (candidates without userId — attach by userId or resend with confirmNew:true) / linked_tenant_missing / external_ref_linked_to_other_tenant / tenant_already_linked / link_race - 500: Unexpected error (message truncated to 200 chars). - 503: partner_provisioning_disabled (FLOW_PARTNER_KEY not set on the server) Success fields: - `ok` (true) - `tenant` (object) - `link` (PartnerLink) - `endpoints` (object) - `apiKey` (string): External API key (64 hex). Returned every call; an existing key is returned as-is. - `connectUrl` (string): Login-free WhatsApp/Facebook connect link for the owner. - `connectExpiresAt` (string) - `connectWarning` (string) - `embed` (object) - `embedWarning` (string) - `mcp` (object) - `mcpWarning` (string) - `store` (object): Only when `store` was sent. A store failure does not fail the provision (HTTP stays 200). Watch out: - A name never selects an existing tenant: mode=new whose slug matches an existing username answers 409 tenant_name_taken with no credentials. Credentials come back only for a tenant the call creates, the tenant linked to source+externalRef, or mode=attach + existingUserId. - Duplicate-candidate 409s list username/displayName but not userId; get the userId from the FLOW admin to attach. - confirmNew:true with a taken name creates a separate tenant under a free username (name-2, …). ### GET /api/partner/tenant-link Look up a linked tenant and its integration health. Auth: partnerKey. Operation: `getTenantLink`. Source: `src/pages/api/partner/tenant-link.js`. Parameters: - `source` (query, required, string) - `externalRef` (query, required, string) Responses: - 200: Linked. - 400: invalid_source / invalid_external_ref - 401: invalid_partner_key - 404: not_linked - 409: linked_tenant_missing - 503: partner_provisioning_disabled (FLOW_PARTNER_KEY not set on the server) Success fields: - `ok` (true) - `link` (PartnerLink) - `tenant` (object) - `health` (object) ### DELETE /api/partner/tenant-link Unlink (and by default revoke the partner's credentials). Auth: partnerKey. Operation: `deleteTenantLink`. Source: `src/pages/api/partner/tenant-link.js`. revoke (default true) replaces the tenant's external API key and turns off its MCP key. The tenant, its conversations and flows are kept. The embed site key is NOT revoked. Body: - `source` (string, required) - `externalRef` (string, required) - `revoke` (boolean, default true) Responses: - 200: Unlinked. - 400: invalid_source / invalid_external_ref - 401: invalid_partner_key - 404: not_linked - 503: partner_provisioning_disabled (FLOW_PARTNER_KEY not set on the server) Success fields: - `ok` (true) - `unlinked` (PartnerLink) - `revoked` (boolean) ### POST /api/mcp MCP server (stateless streamable HTTP, JSON-RPC 2.0). Auth: mcpKey or mcpHeaders. Operation: `mcpJsonRpc`. Source: `src/pages/api/mcp.js`. Methods: `initialize`, `ping`, `tools/list`, `tools/call`. Notifications (no id) answer 202 with no body. Batches (arrays) are supported. Live tool catalog without auth: https://flow.txi.co.il/api/mcp-tools.json. A scoped (extra) key sees only its allow-listed tools; a draft-only key cannot publish social posts. Tool results come back as `content[0].text` = pretty JSON; tool failures as `isError: true` with the error text. Every tools/call is audited per tenant (see the get_mcp_audit tool). Request body limit 36 MB (upload_media sends base64). Body: - `jsonrpc` ("2.0", required) - `id` (string|integer) - `method` ("initialize" | "ping" | "tools/list" | "tools/call", required) - `params` (object) ```json {"jsonrpc":"2.0","id":1,"method":"tools/list"} ``` Responses: - 200: JSON-RPC response (also used for -32603 internal errors). - 202: Notification accepted (no body). - 400: Parse error (-32700). - 401: Unauthorized (-32001). WWW-Authenticate: Bearer realm="aiflow-mcp". - 405: Only POST (-32600). - 429: Rate limited (-32002). Watch out: - Rate limit: 60 requests per minute per tenant by default (server env MCP_RATE_LIMIT_PER_MIN). initialize, ping, tools/list, resources/list, prompts/list and notifications/* do not count; a batch counts once if it holds any other call. 429 carries Retry-After. - The handler's header comment still describes the retired 3-factor, read-only phase. ### GET /api/mcp-tools.json Public catalog of every MCP tool (name, group, description, input schema). Auth: none. Operation: `listMcpTools`. Source: `src/pages/api/mcp-tools.json.js`. Responses: - 200: Catalog generated from the running server's tool registry. Success fields: - `ok` (true) - `endpoint` (string) - `count` (integer) - `groups` (object) - `tools` (object[]) ### GET /api/openapi.json This OpenAPI document. Auth: none. Operation: `getOpenApiSpec`. Source: `src/pages/api/openapi.json.js`. Responses: - 200: OpenAPI 3.1 JSON (CORS open, cached 1h). ### POST /api/embed/verify-key Check a site key (plugin "test connection"). Origin is not enforced. 60/min.. Auth: embedSiteKey or embedSiteKeyHeader. Operation: `embedVerifyKey`. Source: `src/pages/api/embed/verify-key.js`. Body: - `siteKey` (string, required): Public site key from /settings/embed or partner provision (may also be sent as ?siteKey= or the X-AIFLOW-SiteKey header). - `host` (string): Informational. Responses: - 200: Valid. - 400: missing_site_key / bad input - 403: origin_not_allowed — the request Origin is not in the site's allowed origins. - 404: site_not_found - 405: method_not_allowed - 429: rate_limited (per siteKey + IP, per minute). - 500: internal_error Success fields: - `valid` (true) - `displayName` (string) - `mode` (string) - `primaryColor` (string) - `locale` (string) ### POST /api/embed/session Create or resume a widget session. 120/min.. Auth: embedSiteKey or embedSiteKeyHeader. Operation: `embedSession`. Source: `src/pages/api/embed/session.js`. Body: - `siteKey` (string, required): Public site key from /settings/embed or partner provision (may also be sent as ?siteKey= or the X-AIFLOW-SiteKey header). - `sessionId` (string): Resume this session (must belong to the site). Responses: - 200: Session + widget appearance. - 400: missing_site_key / bad input - 403: origin_not_allowed — the request Origin is not in the site's allowed origins. - 404: site_not_found - 405: method_not_allowed - 429: rate_limited (per siteKey + IP, per minute). - 500: internal_error Success fields: - `sessionId` (string) - `openingMessage` (string) - `locale` (string) - `primaryColor` (string) - `mode` (string): chatbot / search / form - `position` (string) - `theme` (string) - `appearance` (object) - `displayName` (string) ### POST /api/embed/chat One chat turn. Runs the site's flow, or knowledge-base RAG when no flow is attached. 30/min.. Auth: embedSiteKey or embedSiteKeyHeader. Operation: `embedChat`. Source: `src/pages/api/embed/chat.js`. Body: - `siteKey` (string, required): Public site key from /settings/embed or partner provision (may also be sent as ?siteKey= or the X-AIFLOW-SiteKey header). - `sessionId` (string) - `message` (string, required): ≤4000 chars. - `customerName` (string) Responses: - 200: Reply. Flow sites add menu/ended/handover/media fields; RAG sites return sources. - 400: missing_site_key / bad input - 403: origin_not_allowed / session_mismatch - 404: site_not_found - 405: method_not_allowed - 429: rate_limited (per siteKey + IP, per minute). - 500: internal_error Success fields: - `reply` (string) - `sources` (object[]) - `menu` (array|null) - `menuDisplayType` (string|null) - `headerText` (string|null) - `ended` (boolean) - `handover` (boolean) - `mediaUrl` (string) - `mediaType` (string) - `conversationId` (string) ### POST /api/embed/search Semantic search over the site's knowledge base. 60/min.. Auth: embedSiteKey or embedSiteKeyHeader. Operation: `embedSearch`. Source: `src/pages/api/embed/search.js`. Body: - `siteKey` (string, required): Public site key from /settings/embed or partner provision (may also be sent as ?siteKey= or the X-AIFLOW-SiteKey header). - `query` (string, required): Short queries return [] without cost. Responses: - 200: Results (empty on any internal failure). - 400: missing_site_key / bad input - 403: origin_not_allowed — the request Origin is not in the site's allowed origins. - 404: site_not_found - 405: method_not_allowed - 429: rate_limited (per siteKey + IP, per minute). - 500: internal_error Success fields: - `results` (object[]) ### POST /api/embed/form Contact-form submission from the widget. 10/min.. Auth: embedSiteKey or embedSiteKeyHeader. Operation: `embedForm`. Source: `src/pages/api/embed/form.js`. Body: - `siteKey` (string, required): Public site key from /settings/embed or partner provision (may also be sent as ?siteKey= or the X-AIFLOW-SiteKey header). - `sessionId` (string) - `formData` (object, required): name + message + (email or phone ≥6 chars) required; ≤30 fields. - `name` (string) - `email` (string) - `phone` (string) - `message` (string) Responses: - 200: Accepted. - 400: missing_site_key / bad input - 403: origin_not_allowed — the request Origin is not in the site's allowed origins. - 404: site_not_found - 405: method_not_allowed - 429: rate_limited (per siteKey + IP, per minute). - 500: internal_error Success fields: - `ok` (true) Watch out: - Stored as a Lead of the site's tenant (source embed_form), keyed by the phone (E.164) or, without one, the email. The text and any consent fields (consent / agree / marketing / privacy / terms …) are appended to the lead notes; a phone also creates the contact when missing. - With a sessionId whose widget chat already has a conversation, the submission is logged there as an incoming message. - Emits embed.form_submitted, plus lead.created / lead.updated. - Spam guard: a filled _hp / _gotcha honeypot is answered ok and dropped; the same contact + message on the same site within 10 minutes is stored once (per server process). - phone must be 9–15 digits (local 05x is converted to 972…) and email a valid address; otherwise 400 missing_required_fields. ## Webhook events Envelope: `{ id, event, createdAt, userId, platform, data }`. Conversation events share one data shape: conversationId, flowId, phone, customerName, channel, status, currentNodeId, action, direction, nodeId, nodeType, timestamp, message, messageType, mediaUrl, phoneNumberId, waMessageId, fetchData. - `conversation.created`: A flow started for a customer (log action flow_started). - `conversation.message_received`: Inbound customer message. The richest event: with "include channels" it also carries availableChannels + _sendApi. - `conversation.message_sent`: Outbound message logged (bot, operator, API). - `conversation.ai_response`: AI node answered. - `conversation.agent_requested`: Customer asked for a human. - `conversation.flow_completed`: Flow reached its end — also fired by the idle worker together with conversation.abandoned. - `conversation.flow_paused`: Flow paused / failed. - `conversation.abandoned`: Customer stopped answering (idle worker). - `conversation.operator_action`: Operator released / marked spam / marked handled. data: { conversationId, kind, by, byUserId, … }. - `group.mention`: A desktop-line WhatsApp group addressed the line (mention, reply, keyword). data: { conversationId, groupId, groupName, line, sender, message, messageType, messageId }. Reply with replyToMessageId. - `message.sent`: /api/external/send succeeded. data: { requestId, channel, to, type, sentAt, messageId, … }. - `message.failed`: /api/external/send failed. data: { requestId, channel, to, type, reason, error }. - `lead.created`: A lead row was created (new customer conversation, API lead trigger, embed form, operator). Bulk imports do not emit. data: { leadId, phone, status, secondarySource, source, createdAt, updatedAt }. - `lead.updated`: A lead was written again (status, notes, secondary source). Same data plus previousStatus. - `lead.status_changed`: Sent together with lead.updated when the status changed. data.previousStatus holds the old value. - `embed.form_submitted`: Website widget contact form. data: { siteKey, siteName, leadId, conversationId, name, phone, email, message, consent, fields, submittedAt }. - `social.post_published`: Facebook / Instagram post went live. data: { postId, targetId, platform, accountId, accountName, format, seriesId, … }. - `social.post_failed`: Publishing failed. Same data as social.post_published plus the error. - `facebook.lead_received`: Facebook / Instagram lead form submission. data: { leadgenId, pageId, pageName, formId, createdAt, fields }. - `outbound.duplicate_burst_blocked`: The same message to one customer was blocked as a burst. data: { phone, flowId, flowName, count, threshold, windowMinutes }. - `billing.charge.notified`: A WhatsApp charge notice went out. data: { chargeId, billingPeriod, amountIls, channels, … }. ## MCP tools (85, live) ### Read: flows, conversations, channels, docs - `get_started`: ⭐ קרא/י את זה ראשון בכל שיחה חדשה. - `get_conversation_view`: מחזיר את הגדרות דף השיחות (תיבת הנציגים) — שדות מוצגים, סדר תוכן, מיקומי תגיות, צבעים וכפתורים — יחד עם ה-schema. - `list_flows`: רשימת התהליכים (הבוטים/האוטומציות) של המשתמש: id, שם, סטטוס (active=פעיל / draft=טיוטה), תיאור. - `get_flow`: המבנה המלא של תהליך אחד שלך — כל הצמתים (הודעות, תנאים, תפריטים, פרומפטים ל-AI) והחיבורים ביניהם. - `get_flow_settings`: הגדרות ברמת התהליך: סטטוס, מצב דיבוג, שם הבוט (botName), השהיית "הקלדה אנושית" בשניות (humanDelaySeconds), ותאריכים. - `list_flow_versions`: היסטוריית הגרסאות השמורות של תהליך שלך: מספר גרסה, שם, הערת-שינוי, ומתי נשמרה. - `get_tenant_resources`: מפת החשבון של המשתמש: הבוטים (לכל אחד התהליך + ספק/מודל ה-AI), ספקי ה-AI (ללא מפתחות), הערוצים המחוברים (וואטסאפ וכו׳), ומאגרי הידע. - `get_ai_usage`: צריכת ה-AI והחיוב של המשתמש: ספק/מודל נוכחי, חינמי מול בתשלום, טוקנים/עלות להיום ולחודש, פירוט לפי מודל, ומגבלות מכסה אם יש. - `list_knowledge_bases`: מאגרי הידע (RAG) של המשתמש — המסמכים שה-AI שולף מהם תשובות: id, שם, ספק/מודל ה-embedding. - `search_knowledge_base`: חיפוש וקטורי במאגר ידע אחד של המשתמש (לפי knowledgeBaseId + query). - `list_node_types`: קטלוג סוגי הצמתים שאפשר להשתמש בהם בבנייה/עריכה של תהליך: מפתח הסוג (type), תווית, קטגוריה, מספר כניסות/יציאות, תיאור, ומבנה ה-data ברירת-המחדל. - `get_recent_conversation_logs`: לוגי שיחה אחרונים של תהליך שלך — לדיבוג: "למה הבוט לא ענה", "איפה הלקוח נתקע", "איזה צומת נכשל". - `get_conversation_transcript`: תמלול נקי של שיחה אחת — "מי אמר מה" בלי רעש payload. - `list_conversations`: השיחות האחרונות של המשתמש עם לקוחות-קצה: id, התהליך (flowId), סטטוס, ערוץ, הצומת הנוכחי, וזמן הפעילות האחרון. - `get_bot_turns`: תורות AI אחרונים של הבוטים של המשתמש — מה הלקוח כתב, מה הבוט ענה, התוצאה, ספק/מודל, וטוקנים. - `get_mcp_audit`: יומן הפעילות שלך דרך MCP — כל קריאת כלי: שם הכלי, הפרמטרים, הצלחה/שגיאה, latency וזמן. - `get_documentation`: ADMIN ONLY. - `get_whatsapp_channels`: הקווים (ערוצי WhatsApp לא-רשמיים) של המשתמש — לכל קו: שם, מספר טלפון, מזהה (idInstance), מצב החיבור (state: authorized=מחובר / yellowCard=מוגבל / notAuthorized=לא מחובר / blocked=… - `desktop_line_read`: קורא נתונים חיים מקו מחשב (provider=desktop ב-get_whatsapp_channels), ישירות מה-WhatsApp שרץ באפליקציה במחשב של הנציג. - `list_line_automations`: האוטומציות (no-code) של קווי המחשב (provider=desktop) של המשתמש: לכל קו — החוקים (trigger, תנאים, פעולות, enabled, dryRun), 20 ההרצות האחרונות (יומן: מתי, איזה חוק, מצב dry_run/do… - `list_my_tasks`: המשימות/הבקשות שהשארת לצוות FLOW (submit_task) והסטטוס שלהן. ### Read: Facebook / Instagram / social - `list_social_accounts`: דפי הפייסבוק, חשבונות האינסטגרם וערוצי היוטיוב שמחוברים למשתמש: האם אפשר לפרסם מהם (canPublish), אילו פורמטים נתמכים, ומצב בריאות החיבור (ok/warning/broken + פירוט + מתי יפוג אישו… - `list_social_posts`: הפוסטים האחרונים של המשתמש (טיוטה/מתוזמן/מתפרסם/פורסם/נכשל/בוטל) עם התוצאה לכל דף: סטטוס, קישור לפוסט (permalink), שגיאה אם הייתה, ומדדים (לייקים, תגובות, שיתופים, חשיפה, צפיות — … - `get_social_post`: פוסט אחד עם התוצאה והמדדים לכל דף. - `list_post_comments`: התגובות על פוסט שפורסם, חי מ-Meta, לפי targetId (מ-list_social_posts — פוסט אחד שפורסם לשני דפים = שני targets). - `list_content_series`: סדרות התוכן החוזרות של המשתמש (למשל "טיפ יומי"): נושאים, דפים, שעה (שעון ישראל), ימים (0=ראשון…6=שבת), מצב approve (טיוטה לאישור) או auto (פרסום ישיר), מתי רצה לאחרונה ושגיאה אחרו… - `list_facebook_leads`: לידים שהגיעו מטפסי פייסבוק/אינסטגרם (Lead Ads) של המשתמש: שם, טלפון, מייל, הטופס, המודעה, כל שדות הטופס, וסטטוס. - `get_facebook_lead`: ליד אחד מטופס פייסבוק עם כל השדות, והיסטוריית המסירה שלו (לאן הועבר ומה התוצאה). - `get_page_settings`: ההגדרות של דף מחובר: אילו ערוצים פעילים (messenger, facebookComments, leadAds, instagramDM, instagramComments) ואיזה תהליך (flowId) מטפל בכל ערוץ. - `list_comment_rules`: כללי התגובות של המשתמש — איך מטפלים בתגובה על פוסט ספציפי / עם מילים מסוימות: תהליך משלו, תגובה פומבית/פרטית, או התעלמות. - `list_integrations`: מערכות עסקיות שאפשר לחבר (Fireberry, Priority …) — לכל אחת: שדות החיבור והפעולות שהיא תומכת בהן (findByPhone, upsertContact, createLead, createNote, createTask, listDocuments, get… - `list_ad_creatives`: מאגר הקריאייטיב לפרסום של החשבון — וידאו ותמונות (גם מה שמערכות מחוברות כמו PARSI שלחו). - `get_ad_creative`: סטטוס קריאייטיב אחד לפי externalRef: status (pending_review / approved / rejected), reviewNote (סיבת הדחייה), reviewedAt. ### Read: paid ads (Meta / LinkedIn / TikTok) - `list_ad_accounts_shared`: חשבונות הפרסום שאפשר לקרוא: שלך ושל מי ששיתף איתך את הפרסום שלו (ownerUserId, שם, חשבון מודעות, אזור זמן ומטבע). - `list_ad_campaigns`: קמפיינים חיים מ-Meta עם ערכות המודעות והמודעות: סטטוס, מטרה, תקציב יומי/כולל (במטבע החשבון), תאריכים, טקסט המודעה. - `get_ad_insights`: תוצאות מ-Meta: הוצאה, חשיפות, טווח הגעה, תדירות, קליקים, CTR, CPM, שיחות וואטסאפ שנפתחו ועלות לשיחה. - `list_ad_launch_plans`: תוכניות ההשקה (קליק-לוואטסאפ) שנבנו במערכת: שם, סטטוס, תקציב, קהלים, מודעות והמסר המוכן מראש, קמפיין ב-Meta. - `list_ads_engine_recommendations`: מנוע הפרסום: ההגדרות (רמת אוטונומיה ותקרות הוצאה), ההמלצות של האופטימייזר (מה לעשות ולמה, סטטוס אישור) וההרצות האחרונות. - `list_ad_leads`: שיחות וואטסאפ שהגיעו ממודעות: איזו מודעה (adId + כותרת), מתי, סטטוס השיחה, סטטוס הליד, אילו אירועי המרה דווחו ל-Meta (_capiSent) וההודעות האחרונות (ליד/בוט/נציג). - `get_sales_playbook`: מאגר הידע של המכירות: איך עונים ללידים מהמודעות — שאלות סינון, הסברים פשוטים (למה קו נוסף, למה פייסבוק), שלבי חיבור, דוגמאות לפי עיסוק, התנגדויות ותשובות מהירות. - `list_linkedin_campaigns`: קמפיינים בלינקדאין של בעל החשבון (או של מי ששיתף איתך): סטטוס, סוג, תקציב, תאריכים, וגם מצב החיבור וחשבונות הפרסום. - `get_linkedin_insights`: תוצאות לינקדאין לפי קמפיין ויום: הוצאה (במטבע החשבון), חשיפות, קליקים, לידים מטפסים, המרות. - `list_linkedin_leads`: לידים מטפסי הלידים של לינקדאין: מתי, מאיזה קמפיין וטופס, השדות שמולאו (שם, חברה, תפקיד; טלפון ומייל מוסתרים חלקית) והסכמות. - `list_tiktok_campaigns`: קמפיינים בטיקטוק של בעל החשבון (או של מי ששיתף איתך): סטטוס, יעד, תקציב, וגם מצב החיבור וחשבונות הפרסום. - `get_tiktok_insights`: תוצאות טיקטוק לפי קמפיין או מודעה, ליום או לכל הטווח: הוצאה (במטבע החשבון), חשיפות, קליקים, המרות לפי יעד הקמפיין. - `list_tiktok_leads`: לידים מטפסי הלידים של טיקטוק. ### Write: flows, templates, lines, conversations, tasks - `create_whatsapp_channel`: פותח קו WhatsApp חדש (Green API instance) עבור המשתמש ומחזיר קוד QR לסריקה. - `delete_whatsapp_channel`: מוחק קו WhatsApp (Green API instance) לצמיתות — גם ב-Green (עוצר את החיוב) וגם מקומית. - `replace_whatsapp_channel`: מחליף קו WhatsApp מת בקו חדש: יוצר instance חדש עם אותן הגדרות (שם, תהליך, שיוך-עובדים, קצב-שליחה), ממפה מחדש הרשאות-עובדים, ומוחק את הישן. - `desktop_line_command`: מריץ פעולה על קו מחשב (provider=desktop), דרך ה-WhatsApp שבאפליקציה במחשב של הנציג: שליחה, תגובה, ריאקציה, עריכה ומחיקה של הודעות, ניהול צ׳אטים, חסימת אנשי קשר, קבוצות ותוויות. - `manage_desktop_line_device`: ניהול קו מחשב (provider=desktop). - `configure_group_bot`: מגדיר איך קו מחשב מגיב בקבוצת WhatsApp — רק כשפונים אליו (תיוג @ של הקו, ציטוט של הודעה שהקו שלח, או מילת פנייה), לעולם לא להודעות של עצמו ולא לכל הודעה. - `save_line_automation`: יוצר או מעדכן אוטומציה (no-code) על קו מחשב (provider=desktop): "כשקורה X ומתאים לתנאים — בצע פעולות". - `resolve_conversation`: סוגר שיחה (status→completed) ומשחרר claim. - `mark_all_read`: מסמן שיחות כ"נקראו" (lastReadAt=now) — מאפס מונה ההודעות-שלא-נקראו. - `acknowledge_conversation`: מסמן שיחה כטופלה — מאפס מצב נציג מלא בלי לשלוח הודעה ללקוח. - `resume_bot_on_conversation`: מחזיר את הבוט לפעולה בשיחה — איפוס מלא של pause/claim/agent_handling, וההזרמה הבאה תפתח את ה-flow מההתחלה. - `set_conversation_view`: מעצב את דף השיחות (תיבת הנציגים) של המשתמש. - `apply_conversation_view_template`: מחליף את תבנית-התצוגה ("תבנית ביצוע") של דף השיחות לתבנית מוכנה בשם — מיזוג מלא של ההגדרות. - `list_wa_templates`: רשימת תבניות ה-WhatsApp של המשתמש: שם, קטגוריה, שפה, סטטוס אישור מול Meta, ו-WABA. - `create_wa_template`: יצירת תבנית WhatsApp והגשתה ל-Meta לאישור, עבור המשתמש. - `create_template_group`: יצירה/עדכון של קבוצת תבניות — מקבצת תבניות מאושרות לשליחה מרוכזת (למשל שרשרת fallback ל-OTP, או סבב תבניות UTILITY). - `list_template_groups`: רשימת כל קבוצות התבניות של המשתמש, ובכל קבוצה — התבניות שבתוכה (שם, שפה, קטגוריה), אסטרטגיית הבחירה, ה-WABA וסטטוס פעיל. - `rename_template_group`: שינוי שם של קבוצת תבניות (לפי groupId — הרץ/י list_template_groups כדי לקבל את ה-id). - `delete_template_group`: מחיקת קבוצת תבניות (את הקבוצה בלבד — התבניות עצמן נשארות, הן ישות נפרדת). - `create_flow`: יצירת תהליך חדש וריק עבור המשתמש (נוצר כ-draft/טיוטה, לא פעיל). - `apply_flow_edits`: עריכה כירורגית של תהליך שלך — אצווה (batch) של פעולות בטרנזקציה אחת. - `set_flow_status`: הפעלה/כיבוי של תהליך שלך: "active" (פעיל — מטפל בהודעות אמיתיות מלקוחות) או "draft" (כבוי). - `restore_flow_version`: שחזור תהליך שלך לגרסה שמורה (מחליף את כל הגרף). - `delete_flow`: מחיקה לצמיתות של תהליך שלך. - `submit_task`: השאר/י משימה מפורטת לצוות FLOW — מה אתם צריכים שנעשה עבורך. - `update_my_task`: עדכן/י משימה קיימת שאתה הגשת: להוסיף פרטים (`details` — מוחלף), לשנות `priority`, או לבטל (`status:"cancelled"`). ### Write: social publishing, comments, pages, integrations - `save_ad_creative`: שומר קריאייטיב מוכן (וידאו או תמונה) במאגר הפרסום של החשבון, כדי שישמש בקמפיינים. - `connect_integration`: מחבר מערכת עסקית של המשתמש (provider מ-list_integrations) עם פרטי הגישה שלו (credentials) והגדרות (settings), ובודק את החיבור מיד. - `integration_action`: מריץ פעולה במערכת העסקית המחוברת: connection = id או שם הספק (fireberry/priority); action = findByPhone (phone) · upsertContact (phone, name, email) · createLead (phone, name, not… - `save_comment_rule`: יצירה/עדכון של כלל תגובות — "בוט בתוך התגובות" לפי פוסט או מילת מפתח. - `delete_comment_rule`: מוחק כלל תגובות לפי id (אפשר גם לכבות עם save_comment_rule enabled:false). - `get_connect_link`: קישור חיבור ללא התחברות (תקף 7 ימים) שבעל העסק פותח כדי לחבר את דפי הפייסבוק, חשבונות האינסטגרם והוואטסאפ שלו. - `set_page_channels`: מדליק/מכבה ערוצים בדף מחובר וקובע איזה תהליך מטפל בכל ערוץ. - `upload_media`: מעלה תמונה או וידאו לאחסון של המערכת ומחזיר url ציבורי לשימוש ב-create_social_post (media). - `create_social_post`: יצירת פוסט לפייסבוק, אינסטגרם, יוטיוב, לינקדאין, טיקטוק ו/או ערוץ טלגרם, לכמה חשבונות בבת אחת. - `social_post_action`: פעולה על פוסט: publish (טיוטה/מתוזמן → לפרסם עכשיו), cancel (טיוטה/מתוזמן → לבטל; מה שכבר פורסם נשאר), retry (לנסות שוב דפים שנכשלו — לעולם לא דף שתוצאתו לא ידועה, כדי לא לפרסם פע… - `moderate_comment`: טיפול בתגובה על פוסט שלנו: reply (תגובה פומבית מתחת לתגובה, message חובה), hide / unhide (הסתרה — הכותב וחבריו עדיין רואים), delete (פייסבוק בלבד, בלתי הפיך — אשר/י עם המשתמש). - `save_content_series`: יצירה/עדכון של סדרת תוכן חוזרת ("טיפ היום"): בכל יום שנבחר, בשעה שנבחרה (שעון ישראל), המערכת בוחרת את הנושא שלא דובר הכי הרבה זמן, ה-AI כותב פוסט קצר בעברית בלי להמציא מספרים, נוצ… - `run_content_series`: מריץ סדרת תוכן פעם אחת עכשיו (בלי לחכות לשעה): בוחר נושא, כותב, יוצר כרטיס, ושומר טיוטה או מפרסם לפי mode של הסדרה. Input schemas: https://flow.txi.co.il/api/mcp-tools.json ## Changelog - 2026-11-19 (2.0.0): Complete OpenAPI 3.1 spec: every external, partner, MCP, embed and trigger endpoint (was 5 paths). OpenAPI 3.1 `webhooks` section for all reporting events, with signature modes and retry policy. New developer portal at /developers and an agent-oriented reference at /llms-full.txt. Public live MCP tool catalog at /api/mcp-tools.json. Partner provision no longer returns credentials for a tenant matched only by name (409 tenant_name_taken); duplicate candidates no longer carry userId. Reporting webhooks: the tenant API key is no longer sent in _sendApi; lead.created / lead.updated / lead.status_changed and embed.form_submitted are emitted; outbound.duplicate_burst_blocked and billing.charge.notified are selectable. Embed form submissions are stored as leads (source embed_form). /api/external/send logs every channel to the transcript and honours conversationId. Conversation list channel filter matches suffixed channels (messenger, instagram_dm, telegram:, …). Lead trigger HMAC verifies the raw body; a malformed signature answers 401. Message direction in the external API is always incoming / outgoing. Quick replies / templates / WA templates answer 500 on server errors. /unclaim leaves a human operator's claim alone unless force:true (409 claimed_by_human). MCP rate limit: 60/min/tenant (MCP_RATE_LIMIT_PER_MIN); initialize, tools/list, ping and notifications are free. - 2026-11 (1.9): Desktop lines: GET /api/external/desktop-lines, POST .../command, POST .../import-groups. Partner provision accepts `store` (PARSI store mode). - 2026-10 (1.8): Partner one-to-one links (`source` + `externalRef`) and GET/DELETE /api/partner/tenant-link. - 2026-09 (1.7): `system: true` on send/reply: informational notices that do not claim the thread or mute the bot. POST /api/external/conversations/{id}/unclaim and /unclaim-bulk.