Analify Core
Overview
These Core API domains have no external platform behind them — the data is Analify's own. They live under the same /api/core prefix and share its envelope and auth, but two conventions differ from the platform-mirror pages:
- Money here IS integer piasters (EGP × 100), matching the rest of the Analify API rather than a platform's unit.
- There is no "raw platform body" —
datais Analify's own shape, and it is stable.
Base paths: /api/core/cogs · /api/core/finance · /api/core/organization · /api/core/integrations · /api/core/brain (the Assets Library and the Business Brain) · /api/core/metrics · /api/core/money · /api/core/connectors
Every request: requires ?organizationId=<uuid>.
API Endpoints
Not pass-throughs — there is no external platform behind these. Money here
IS integer piasters (EGP × 100), like the rest of the Analify API.
COGS — 4 routes
| Route | Methods | Note |
|---|---|---|
/cogs | GET, POST | list · upsert one SKU. Body { sku, productName, costPerUnit } — costPerUnit in piasters. 0 is a valid cost |
/cogs/{sku} | GET, DELETE | 404 COGS_NOT_FOUND when unpriced |
/cogs/bulk | POST | { items: [...] } — non-empty, else 400 |
/cogs/coverage | GET | how much of the catalogue is priced — the gate between a profit number and a guess |
GET /cogs takes limit, offset, search, and
sort = sku · cost_asc · cost_desc · updated.
Finance — 14 routes
The org's money sheet: every row is integer piasters (amountMinor), in
the org currency. Writes from a member (clientKind: app) are saved; writes
from any AI caller (the Agent, an MCP client) are forced to drafts a member
approves in Analify. An AI can edit or remove only drafts, and gets 403 on
categories, imports and auto-sources writes.
| Route | Methods | Note |
|---|---|---|
/finance/entries | GET, POST | list a range (from, to YYYY-MM-DD) · add one row { entryDate, entryType: income|expense, categoryId?, description?, paymentMethod, amountMinor }. POST returns possibleDuplicate (same type + category + date + amount) |
/finance/entries/{entryId} | PATCH, DELETE | edit any field, approve: true (member only), duplicateOk, or restoreSource: true — puts an edited Meta/Bosta row back to the app's values. Editing a synced row's amount/date/type sets edited and exposes the app's values as original. DELETE soft-removes |
/finance/entries/{entryId}/restore | POST | undo a removal (an AI caller: drafts only, else 403) |
/finance/summary | GET | from+to (any window; optional compareFrom+compareTo, default the same number of days just before) or month=YYYY-MM (vs the month before); neither = current month, org timezone. Returns range, cards (income, expenses, recorded net, cashMinor — all saved income − expenses in the org's history up to to, with previous.cashMinor at compareTo, keptPct null without income, entryCount, 6-month series, previous month), paid-via split, category totals, 6-month grid and attention (duplicate · drafts · uncategorized · usual · no_income) — all decided server-side |
/finance/categories | GET, POST | list (seeds defaults once) · add { entryType, name, color } — 409 on a name clash within the type |
/finance/categories/{categoryId} | PATCH | rename / recolour / hide |
/finance/imports/preview | POST | Read (stores nothing; a read-only token may call it). Multipart file (xlsx/csv, ≤ 10 MB) — or JSON { googleSheet: { fileId } } for a Google Sheet picked in Analify (fetched from Drive as .xlsx) — or JSON { csv: "<text>" } / { rows: [[…], …] } (+ fileName?) with the sheet inline (one sheet, Sheet1) → sheets, headers, sample rows, suggested column mapping |
/finance/imports | POST | multipart file + options (mapping, date order, category words) — or JSON { googleSheet: { fileId }, options } / { csv | rows, fileName?, options } (same options, as an object). dryRun=1 (JSON: dryRun: true) returns the check (ready / possible duplicates / unmatched category / skipped with reasons); without it saves in one transaction. Re-importing the same rows adds nothing. Member only — an AI caller gets 403, dry run included |
/finance/export | GET | Read. from, to, locale → .xlsx of the rows. With Accept: application/json: { fileName, from, to, rowCount, csv } — the same rows as CSV text (columns Date · Type · Category · Description · Paid via · Amount (major units, exact) · Currency · Source) |
/finance/template | GET | Read. locale → the fill-in template with category dropdowns. With Accept: application/json: { fileName, headers, csv, types, categories, paymentMethods } — the template as data |
/finance/auto-sources | GET | Meta and Bosta auto-add: enabled (OFF by default), accountOptions + selectedAccountIds (null = all), startDate, mode (saved|draft), rule, last sync, health (off · failed · never · stale (12h+) · ok) |
/finance/auto-sources/{meta|bosta} | PATCH | switch on/off, start date, mode, Meta rule (auto · topups · charges), accountIds (the ad accounts to read; null = all connected — the sync and the Meta check both follow it). Or { history: 'all' } alone: switch the app on from 37 months back and queue the finance.history background job; returns { history } at once, progress on the GET list (history.status queued · running · done · failed, through, added) |
/finance/auto-sources/{meta|bosta}/sync | POST | sync now; returns rows added and any per-account error |
/finance/auto-sources/meta/check | GET | from+to or month=YYYY-MM → Meta's own spend (Ads Insights, live) beside what the sheet recorded as paid to Meta, from the auto-add start date: { from, to, spendMinor, paidMinor, gapMinor, failed, otherCurrency }. A failed or other-currency account is named and the gap withheld — never counted as zero. null when Meta auto-add is off |
Both import routes take any of the bodies; Content-Type: application/json
selects the inline sheet (csv or rows, not both — 400 otherwise, and over
10 MB is 400) or the Google Sheet. A bad googleSheet (missing, or not a Drive file id) is
400 BAD_REQUEST. When the sheet can't be fetched the error code is the Google
Sheets one: NOT_CONNECTED 409 (no connected Google Sheets, or its access
can't refresh) · NOT_FOUND 404 (usually picked with a different Google
account than the connected one) · NO_ACCESS 403 · NOT_A_SPREADSHEET
400 (Finance takes a Google Sheet, or an Excel or CSV file in Drive) ·
TOO_LARGE 413 (over 10 MB) · UPSTREAM 502.
A fetched sheet then follows the same path as an upload (FINANCE_IMPORT_*
codes, 400).
MCP tools — every Finance route is one: reads analify_finance_summary,
analify_finance_entries_get, analify_finance_categories_get,
analify_finance_auto_sources_get, analify_finance_auto_sources_by_source_check,
analify_finance_export (CSV text), analify_finance_template (the template
as data), analify_finance_imports_preview (a read-style POST); writes
(mcp:write) analify_finance_entries_post, analify_finance_entries_by_entryId_patch,
analify_finance_entries_by_entryId_delete, analify_finance_entries_by_entryId_restore,
and — refused with 403 for every AI caller until a member decision says
otherwise — analify_finance_categories_post, analify_finance_categories_by_categoryId,
analify_finance_imports, analify_finance_auto_sources_by_source,
analify_finance_auto_sources_by_source_sync. The MCP worker sends
Accept: application/json, which is how export and template answer it JSON.
Organization & integrations — 5 routes
| Route | Methods | Note |
|---|---|---|
/organization | GET | name, slug, description, settings, timezone. credits and purchased_credits are stripped — billing state never leaves this route |
/organization/members | GET | |
/organization/invitations | GET | pending only |
/organization/roles | GET | the role registry as defined in code, not org-scoped rows — the response is identical for every org (still requires organizationId, like every route) |
/integrations | GET | which platforms are connected and their state. Never returns encrypted_credentials. Useful as the discovery call before any of the above |
Brain — 21 routes
The org's own knowledge store, read through the same retrieval engine the
in-app agent uses. This is what an external agent (MCP client, Claude Code,
Codex) should read instead of committing business context to markdown in a
repo: the answers here are dated, sourced, and re-computed as the store
changes, which a committed file is not.
| Route | Methods | Note |
|---|---|---|
/brain/search | GET | The one tool that answers a question. q (required, ≤500 chars) · depth = agent (default, parity with Analify's own agent) or deep (ranks the whole store, ~8k tokens) · optional kinds (CSV — an unknown kind is 400 INVALID_KIND, never silently ignored), entityType, entityKey, maxChunks. Read-only. Retrieval reaches the ENTIRE vector store, including unanswered questions (stored prefixed [No answer yet]), so "what don't you know about X" is answerable |
/brain/answers | GET | every battery question with this org's current answer. Optional section, answered = true/false, summary=true (coverage counts only, no question rows — what analify_get_context uses to orient). The unknowns carry withheldReason — the code, so a caller can tell "we looked and there is nothing" from "we could not look" |
/brain/memories | GET | founder statements and durable memories, highest authority in the store. Optional limit |
/brain/operating-contract | GET | what the org optimises for now and what it will never do. When none is set the response says so explicitly — absent is not the same as unconstrained. adLimits keeps the two ad limits apart: maxDailyAdSpend (piasters — the daily ad SPEND ceiling; the raw row stores it in max_daily_ad_loss, which despite its name is not a loss cap) and maxDailyAdNetLoss (a daily ad LOSS cap — not collected yet, always null, netLossCollected: false) |
/brain/remember | POST | the only Brain write. Body { question, answer, toolsUsed[] } — toolsUsed is required and a finding with no lookup behind it is 400 NO_TOOLS_USED. Stored as an in-app chat turn is: authority 0.5, date stamped into the text. Actions need no deposit — every Core API write already becomes an episode via recordCoreAction; this is for the reasoning |
/brain/session-start | POST | opens a local-work capture session for the person behind the connection and answers which organization it is bound to. Body { sessionId, forOrganizationId? }. Capture is on by default per person (since 2026-09-27): someone who switched it off or paused it gets outcome: capture_off and nothing is stored |
/brain/capture | POST | one changed business fact / decision / constraint / experiment / procedure. Body { sessionId, eventId, kind, statement, date, decisionItImproves, entities?, forOrganizationId? }. Code, diffs, terminal dumps and .env contents are refused; a statement or decision containing a secret, phone, email, national id or card number is refused whole (sensitive); a deterministic value gate keeps only dated facts tied to an ecommerce entity/process. Saved straight to the Brain (outcome: saved, authority 0.5); kept for review (staged) only when the claim check refuses the text. Idempotent on (sessionId, eventId) and on the fact itself — a fact already saved is a duplicate |
/brain/session-finish | POST | closes the session and returns what it saved (digest.saved) and kept for review (digest.staged). Body { sessionId, summary?, forOrganizationId? }. The summary is stored with the session only and never becomes (or corroborates) a candidate |
/brain/files | GET | the Library's files (newest first) with status (staged / imported / discarded), kind and preview — what the app's Assets Library shows this member. Scope ai.chat |
/brain/files | POST | add a document to the Brain — the app's "Add to Brain". Body { filename, text } (.md / .txt / .csv as plain text) or { filename, contentBase64, contentType? } (PDF, DOCX, XLSX, CSV, TXT; ≤ 20 MB) or { googleDrive: { fileId } } (a file in the org's connected Google Drive — Docs, Sheets, Slides, PDF, Word, text, Excel, CSV; Drive's own refusal keeps its code: 409 NOT_CONNECTED, 404 NOT_FOUND, 403 NO_ACCESS, 413 TOO_LARGE). Parsed and stored privately, then imported (import defaults to true; false stages it for review in the app). Same bytes twice → duplicate: true. Needs a person behind the connection. Scope ai.chat |
/brain/creatives | GET | the Library's Creatives tab: uploaded creatives (newest first) with mediaType, size, a 5-minute signed url (never public), productId/productName, plus the org's products (id, name) for the product pick. Read-only. Scope ai.chat |
/brain/creatives | POST | add an ad creative to the Library. Body { filename, contentBase64, contentType? } (JPG, PNG, WebP, GIF, MP4, MOV, WebM; ≤ 50 MB). Deduplicated by content; usable at once. Scope ai.chat |
/brain/statements | POST | save a founder rule or answer (highest authority) — the app's statements service. Body { text, title?, questionKey?, entityType?, entityKey?, correctsDocumentId? }. questionKey answers that Brain question; correctsDocumentId supersedes a wrong document. A volatile figure → 400 BRAIN_VOLATILE_FIGURE. Needs a person behind the connection. Scope ai.chat. The operating contract is changed in the app only (it bounds what agents may do) |
/brain/library | GET | the Assets Library as the app shows it to this member — the same readLibrary and query parser as the app: counters (items, gaps, sources, uploads30d, itemsDelta30d), departments (the "part of the store" folders: key, known, gaps, needsYou, chapters), areas, facets, one page of items, total, truncated, and viewer (restricted, hiddenChapters, hiddenDepartments — what this member's role hides). Optional area (01–21 or other), department, source (founder · file · data · decision · analify · chat), platform, state (known default = Knowledge · gaps = Open questions · all · needs_you · not_enough_data · not_yet · unconfirmed), dated (dated · evergreen), q (title search, ≤ 120 chars), limit, offset. A bad filter → 400 INVALID_PARAMETER. Read-only. Scope ai.chat |
/brain/library/{id} | GET | one Library document — the app's drawer: item, body, asOf, periodStart/periodEnd, confidence, entities (what it is about), history (newest first; earlier versions superseded, never deleted), decision. Hidden from the member's role or missing → 404 (indistinguishable on purpose). To send a person to it in the app: /orgs/{slug}/assets-library?doc={id} (the Library page also opens on ?area=01–21 or ?department=<key>; these are app links, not API routes). Read-only. Scope ai.chat |
/brain/library/{id}/move | POST | re-file a free-standing document (founder rule, memory, decision, learning) under another chapter. Body { chapter: "01".."21" } (else 400 INVALID_CHAPTER). Battery answers, a hidden document, or a target chapter hidden from the member → 404. Needs a person behind the connection (403 LIBRARY_NEEDS_PERSON). Write. Scope ai.chat |
/brain/library/{id}/forget | POST | "Forget": the memory and its chunks are retired (never deleted) and stop reaching any answer — the app's forget. Only items with forgettable: true; a battery answer, hidden or missing document → 404. Write. Scope ai.chat |
/brain/files/{id}/import | POST | add a staged file to the Brain (the app's approve). Not staged → 409 BRAIN_FILE_WRONG_STATE. A restricted role acts only on files they uploaded. Write. Scope ai.chat |
/brain/files/{id}/discard | POST | reject a staged file: the original is deleted from private storage, the row stays as a record. Write. Scope ai.chat |
/brain/files/{id}/remove | POST | "Remove from Brain" for an imported file: its documents are superseded (never deleted), the file is marked discarded, the original is kept. Owner/admin or the uploader; hidden or missing → 404. Write. Scope ai.chat |
/brain/files/{id}/apply-costs | GET | preview what a supplier price list would change in Product Costs, row by row (changes[]: action update · insert · unchanged · skipped, sku, name, fromPiasters, toPiasters, reason). Writes nothing. Needs the member's settings:update permission (else 403), like the app. Read-only. Scope ai.chat |
/brain/files/{id}/apply-costs | POST | apply it: writes only the rows that change through the Product Costs upsert (a second apply writes nothing; written says how many). Needs settings:update and finance.costs (the COGS write's own check) — else 403. Money in piasters. Write. Scope ai.chat |
/brain/creatives/{id}/product | POST | which product an uploaded creative is for. Body { productId: uuid | null } (a product id from GET /brain/creatives → products; null clears; else 400 INVALID_PRODUCT). Writes a confirmed creative → product link in the Brain. Not this org's creative/product → 404. Write. Scope ai.chat |
/brain/creatives/{id}/discard | POST | delete an uploaded creative from private storage; the row stays as a record. Write. Scope ai.chat |
Assets Library parity (2026-10-15). Every read and write the app's Assets
Library page offers is on this API, through the same service functions and the
same gates as the app routes (ai.chat; the reader is the member's own,
mandate-narrowed scopes, so "hidden for your role" holds over MCP too):
counters, folders and chapters, the Knowledge and Open questions tables and
their filters (/brain/library), the drawer (/brain/library/{id}), Move and
Forget, Add knowledge (/brain/statements), Upload / Google Drive
(POST /brain/files), approve / reject / remove a file, apply supplier costs,
and the Creatives tab (list, upload, link to a product, delete). Two things stay
in the app on purpose: Connect a source (an OAuth consent in the browser —
/integrations lists what is connected) and approving local-work captures
(/brain/capture review): a person approves what an agent captured, so the
agent cannot approve its own captures.
Capture (/brain/session-start, /brain/capture, /brain/session-finish). These need a connection granted write
access (an anlfy_ org token is read-only and cannot capture). A refusal the
caller can act on — capture_off, refused (looks like code/diff/terminal/
.env), rejected (value gate) — answers 200 with outcome + note and is
recorded as denied in the audit; only a capture declared for another
organization (forOrganizationId ≠ the connection's org) is a 403
WRONG_ORGANIZATION, also audited. The org field is named
forOrganizationId on purpose: organizationId in a body is read by the auth
layer. Nothing captured is embedded or retrievable before approval; approval
(in the app) writes one Brain document with the candidate's classified scopes
at authority 0.5.
/brain/search returns the same block the in-app agent receives; inject it
verbatim. Three fields decide whether the answer is safe to quote:
-
lowConfidence— no stored passage cleared the similarity floor (0.20
cosine, calibrated on the real corpus). The in-app formatter returns an EMPTY
block here, because the agent has live tools and should not be fed shaky
stored context. This endpoint instead renders the closest passages with
their similarity scores under an explicit "not established fact" header:
an external model handed an empty block answers from its own priors, which
is the opposite of retrieval-augmented. Treat these as leads to confirm. -
state—GOOD·WEAK·EMPTY·CONFLICTED·UNAVAILABLE·LOCKED.UNAVAILABLEmeans
the embedding provider failed, which is not "this org knows nothing".
LOCKED(alsolocked: true, added 2026-09-28) means this business's Brain
is not trained yet: until a Brain Training run unlocks it, no stored
knowledge is returned — theblocksays so beside the manifest,chunksis
empty, and/brain/answersand/brain/memoriesreturnlocked: true, a
noteand no rows. Answer from the live platform routes. The operating
contract stays readable. -
needsLive— the question asked for a CURRENT figure. The Brain stores
dated history, so a client that ignores this will quote a stored number as
today's. Fetch the live number through the platform routes instead.
manifest (added 2026-09-27) — what Analify can read RIGHT NOW, per source,
the same Data Availability Manifest the in-app agent starts every turn with; the
block already opens with it. Shape: { version: 1, asOf: "YYYY-MM-DD", rows: [{ source, status, lastUpdated, detail }], hiddenSources },
source in fixed order shopify · meta_ads · tiktok_ads · google_ads · bosta ·
courier_fees · cogs · brain, status one of available · partial · pending ·
stale · error · missing · unknown. A source that could not be checked is
unknown, never available; courier_fees: pending means Blended Profit for those
days is withheld, not zero. Sources outside the caller's role are not listed, only
counted in hiddenSources. null when the manifest could not be built — the search
still answers. A source not marked available cannot carry a verdict on its own numbers.
Metric catalog and Money — 7 routes
What each Analify number means — the semantic layer (roadmap S1). Not a
value: no store data is read, and the response is identical for every
organization. Code-defined in modules/analytics/shared/metric-catalog.ts.
The six /money/* routes run the in-app agent's own money tools (same
function, same answer). A tool's refusal maps by cause: 400 INVALID_PERIOD
(impossible window — the reason is kept), 404 STORE_NOT_FOUND,
400 USE_STORE_TOOLS, 409 RECONNECT_REQUIRED, 502 STORE_FETCH_FAILED
(fixed message; an upstream's own text never reaches the body).
| Route | Methods | Note |
|---|---|---|
/metrics/catalog | GET | every metric: id, version, unit (money = integer piasters), grain, timezone, codStages, sources, freshness, formula, compute (the Numbers Engine module + export that computes it), related, caveats, and label / definition in en + ar. Optional metric = one entry by id (blended_profit), product name (Profit Today, nROAS after RTO) or dashboard widget key (cod_pending); unknown → 404 METRIC_NOT_FOUND, empty or over 100 characters → 400 INVALID_METRIC. Scope analytics. Cache-Control: private, max-age=3600, ETag = the catalog version |
/money/blended-profit | GET | Blended Profit (blended_profit@3) — the in-app agent's get_blended_profit, same function, same answer: Total Sales − Ad Spend − Shipping (Shopify shipping_charges) − RTO revenue loss − COGS. Components: total_sales, ad_spend, shipping, rto_revenue_loss, cogs (until 2026-09-29: net_sales, courier_delivery_fees, courier_rto_fees). Optional from, to (YYYY-MM-DD; default last 30 days), rankBy=blended_profit (rank the last ≤7 complete days). Every component carries a status; calculable:false = withheld (a failed ad or COGS read — never courier fees). Scope finance.profit |
/money/nroas-after-rto | GET | nROAS after RTO — the in-app get_nroas_after_rto. Optional from, to, campaign (answers that campaign-level is not available). Scope finance.profit |
/money/cash-position | GET | COD cash position — the in-app get_cash_position: collected, in transit (Cash Missing), settled, cash floor; bank/burn/runway missing unless stated. Optional from, to. Scope shipping.cod |
/money/delivery-and-rto | GET | Delivery & RTO overall and per governorate with sample sizes and maturity — the in-app get_delivery_and_rto. Optional from, to, compareFrom, compareTo. Scope shipping |
/money/sales-channels | GET | Sales per store across every sales channel (Shopify, EasyOrders, …) — the in-app get_sales_channels. blended: totalSales, netSales, aov, returns, shipping as money values (status, integer minor of currency, ready display; no number → reason), plus ordersCount. returns is missing when no store in view reports returns (returnsCoverage all/some/none, returnsNotReportedBy); shipping is permission_error without scope shipping. Each store: totalSales, netSales, ordersCount, shareOfSalesPct, historyStartsOn, ordersTool (store_tools / get_store_orders). A store in another currency is never summed or converted — it is in excludedStores; a store that could not be read is in failedStores with status: "partial". No store connected → status: "missing", reason: "store_not_connected", no numbers. Errors: 400 INVALID_PERIOD, 409 RECONNECT_REQUIRED, 502 STORE_FETCH_FAILED (fixed message; the vendor's text is never returned). Optional from, to. Scope shopify |
/money/store-orders | GET | Orders and buyers of stores with no live order API (EasyOrders), from the orders Analify received — the in-app get_store_orders: totalSales / aov money values, then by status, payment, city, product and the latest orders (rows keep *Minor with a *Display twin), buyers with repeat rate (phone masked; withheld without shopify.customers). Optional from, to, store (name or integration id). No such store connected → status: "missing". Errors: 400 INVALID_PERIOD, 404 STORE_NOT_FOUND (no connected store by that name), 400 USE_STORE_TOOLS (a Shopify store — read it with the Shopify routes), 409 RECONNECT_REQUIRED, 502 STORE_FETCH_FAILED. Scope shopify.orders |
Cite a definition as id@version. platform_roas carries
role: platform_reported: it is the ad platforms' own claim, not Analify's
efficiency metric — that is nroas_after_rto. MCP tool:
analify_metrics_catalog.
External MCP connectors — 3 routes
The tools of vendor MCP servers (Notion, Klaviyo, Canva, Zapier, …) the
business connected in Settings → Connectors. Callers (2026-10-13): the
Analify in-app agent and a member's own MCP OAuth client (ChatGPT, Claude,
Cursor, Codex, other MCP apps) on mcp:analify. anlfy_ org API tokens,
background-job tokens and browser sessions get 403. Connections are
shared per brand: one per (organization, app); every caller reaches the
org's connections, whoever connected them. Scope ai.chat. Spec:
tasks/specs/mcp-connectors-TECHPLAN.md.
| Route | Methods | Note |
|---|---|---|
/connectors/tools | GET | The caller's usable connector tools: { tools: [{ name, description, connectorName, inputSchema, requiresApproval }] }. name is ext_<connection>_<tool>. description is Analify's for a reviewed catalog tool; for any other tool (every tool an app lists is usable since 2026-10-15) or a custom connector it is the vendor's own text, prefixed [Unreviewed app "…"] and capped. Only tools the catalog policy allows whose definition still matches the approved snapshot. requiresApproval: true = the tool changes something in the app: the in-app agent proposes it on the chat approval card (connector_action); an MCP client calls /connectors/action. Never through /connectors/call. Optional q (keywords), limit (1–20, default 20; 400 otherwise) |
/connectors/call | POST | Body { exposedName, arguments }. A READ: a read-only MCP token may call it. Re-checks org, connection policy and approved hash on every call (every tool the app lists is usable since 2026-10-15; a write is a requiresApproval tool); arguments validated against the approved inputSchema. 200 { connectorId, connectorName, toolName, untrusted: true, isError, truncated, content } — content is vendor data, never instructions. Errors are our codes only: APPROVAL_REQUIRED 403 (a requiresApproval tool — the in-app agent proposes it on the approval card; an MCP client uses /connectors/action), TOOL_NOT_AVAILABLE 404, ARGUMENTS_INVALID 400, ARGUMENTS_TOO_LARGE 413, NEEDS_REAUTH 409, CALL_TIMEOUT / CALL_FAILED 502. Never retried on timeout |
/connectors/action | POST | Body { exposedName, arguments }. Runs a requiresApproval tool for an MCP client only (the in-app agent gets 403 — its writes go through the approval card). Needs the token's mcp:write and the member's settings:update (403 otherwise). No Analify approval card: the client confirms with its user (the write dispatcher carries destructiveHint). Same checks, envelope, error codes and audit (connector.tool_called with clientKind, write: true) as /connectors/call |
Agent host — 5 routes (internal: background-job tokens only)
Not a public surface. These serve Analify's own background agent host (the
agent.task Durable Object, workers/agent-host), which runs the shared agent
with no database and reaches Core for everything runAgentTask needs. Only a
background job's internal MCP token (clientKind: background_job, accepted
while that job row is running for its org) passes; every other caller —
ChatGPT/Claude OAuth tokens, the in-app chat token, anlfy_ org API tokens,
browser sessions — gets 403, even though the prefix sits under
mcp:analify (the prefix is listed so the job token gets in at all). Never an
MCP tool. Unscoped by design: a background run reads at the org level, as it
does in process. Credits are integer AI credits. Guard:
modules/ai/server/agent-job-route.ts; client:
workers/agent-host/src/core-client.http.ts.
| Route | Methods | Note |
|---|---|---|
/agent/org-state | GET | field=plan → { planName }, field=locked → { locked }, field=timezone → { timezone }; 400 for any other field |
/agent/credits | POST | Body { action, … }, every action keyed on the run's ONE reservation identity holdId: reserve {credits, reason, holdId} → { success } (a refused reservation is success: false, not an error) · settle {reserved, actual, reason, holdId} · refund {reserved, reason, holdId} · refund-hold {credits, holdId, reason} → { success, alreadyRefunded, alreadySettled } (an interrupted attempt's hold). Core closes a hold once — a refund after its settle, a settle after its refund, or either for an id no reservation was booked under moves nothing — and for the amount BOOKED under the id, never the reserved/credits sent (modules/billing/shared/credit-hold.ts). Missing holdId, non-integer or negative amounts 400 |
/agent/runs | POST | Body { title, messages[1–10] } — creates the run's ai_tool conversation and appends the messages in order, filed under the job's own user (never one named in the body) → { conversationId } |
/agent/brain-context | POST | Body { query, today: YYYY-MM-DD | null, bypassTrainingGate? } → { block, manifestBlock } — the agent profile's Brain context at the org level |
/agent/native-tools | GET, POST | GET ?today=&bypassTrainingGate= → { tools: [{ name, description, inputSchema }] } (the money tools + decision history; inputSchema is the AI SDK's JSON Schema of each). POST { name, input, today, bypassTrainingGate? } runs one in Core → { ok: true, output } or { ok: false, error } when the tool threw; 404 unknown tool, 400 input the tool's schema rejects |
Detailed examples for COGS, organization, integrations and the Finance import follow.
Product costs (COGS)
COGS is the input Analify cannot derive for you — and without it, profit is a guess. These endpoints are the programmatic way to keep it current (a nightly sync from your ERP, for example).
costPerUnit is an integer in piasters. 12500 means EGP 125.00, not EGP 12,500. Sending major units understates every cost 100× and silently inflates reported profit.
GET /api/core/cogs
GET /api/core/cogsParams: limit, offset, search, sort — one of sku · cost_asc · cost_desc · updated.
curl "https://analify.scalyax.ai/api/core/cogs?organizationId={organizationId}&limit=50&sort=cost_desc" \
-H "Authorization: Bearer {anlfy_token}"POST /api/core/cogs
POST /api/core/cogsUpserts one SKU. Body: sku, productName, costPerUnit (piasters, integer). All three are required — a missing field returns 400.
curl -X POST "https://analify.scalyax.ai/api/core/cogs?organizationId={organizationId}" \
-H "Authorization: Bearer {anlfy_token}" -H "Content-Type: application/json" \
-d '{
"sku": "DEEP-COUPLES-AR",
"productName": "Deep Couples",
"costPerUnit": 12500
}'costPerUnit: 0 is valid and is stored, not treated as missing — a genuinely free item (a sample, a gift insert) is a real cost of zero. Only an absent or non-numeric field is rejected.
POST /api/core/cogs/bulk
POST /api/core/cogs/bulkBody: { items: [{ sku, productName, costPerUnit }] }. The array must be non-empty — an empty items returns 400 rather than succeeding as a no-op, because an empty bulk write is nearly always a caller bug.
curl -X POST "https://analify.scalyax.ai/api/core/cogs/bulk?organizationId={organizationId}" \
-H "Authorization: Bearer {anlfy_token}" -H "Content-Type: application/json" \
-d '{
"items": [
{ "sku": "DEEP-COUPLES-AR", "productName": "Deep Couples", "costPerUnit": 12500 },
{ "sku": "DEEP-FAMILY-AR", "productName": "Deep Family", "costPerUnit": 9900 }
]
}'GET /api/core/cogs/{sku} and DELETE /api/core/cogs/{sku}
GET /api/core/cogs/{sku} and DELETE /api/core/cogs/{sku}A SKU with no cost on file returns 404 COGS_NOT_FOUND — distinct from a SKU priced at zero, which returns 200 with costPerUnit: 0.
GET /api/core/cogs/coverage
GET /api/core/cogs/coverageHow much of the catalogue actually has a cost. Read this before trusting a profit figure: coverage is the gate between "your profit is EGP 5,023" and the truth that nobody priced half the catalogue.
curl "https://analify.scalyax.ai/api/core/cogs/coverage?organizationId={organizationId}" \
-H "Authorization: Bearer {anlfy_token}"Prefer these endpoints over Shopify's variant-cost when you want costs in Analify without writing to the store. Use PATCH /api/core/shopify/products/variant-cost instead when Shopify should be the system of record.
Organization
GET /api/core/organization
GET /api/core/organizationName, slug, description, settings and timezone.
Billing state is deliberately stripped. credits and purchased_credits are removed from the response before it is serialized — an organization's spendable balance never leaves through this route. Read balances through the billing surfaces instead.
curl "https://analify.scalyax.ai/api/core/organization?organizationId={organizationId}" \
-H "Authorization: Bearer {anlfy_token}"A 404 ORG_NOT_FOUND means the id resolved to no organization.
GET /api/core/organization/members and …/invitations
GET /api/core/organization/members and …/invitationsCurrent members with their roles, and invitations still pending. Both carry personal data, so they sit on the tighter settings.members scope rather than settings.general.
GET /api/core/organization/roles
GET /api/core/organization/rolesThe role registry as defined in code — not org-scoped rows. The response is identical for every organization; it still requires organizationId, like every Core API route. Use it to render a role picker without hard-coding role names.
Integrations
GET /api/core/integrations
GET /api/core/integrationsWhich platforms this organization has connected, and the health of each. This is the cheapest discovery call in the whole API — a plain database read with no date range and no fan-out to any platform.
curl "https://analify.scalyax.ai/api/core/integrations?organizationId={organizationId}" \
-H "Authorization: Bearer {anlfy_token}"One row per connected account:
| Field | Meaning |
|---|---|
id | The integration UUID — what /api/analytics/integration/{id}/… routes take |
platform | meta_ads · tiktok_ads · google_ads · google_analytics · shopify · bosta … |
status | Connection state |
account_id, account_name | The account on the platform's side |
connect_type | How it was connected (OAuth, API key, …) |
account_timezone | The account's own timezone — why two platforms can disagree about "today" |
last_synced_at | Last successful sync |
last_error | The most recent failure, if any |
Credentials are never returned. encrypted_credentials is excluded at the query level, not filtered afterwards — there is no request shape that returns it.
Use this to answer "is Bosta connected before I call a shipping route?" in one request, instead of calling the route and interpreting a *_NOT_CONNECTED error.
Finance import
Bring an income / expense sheet into Finance. Two steps, both stateless: preview reads the sheet and suggests where each column goes; imports checks the rows (?dryRun=1) or saves them with the mapping the member confirmed. Money lands as integer piasters.
Saving is for people. An AI caller (an MCP client or the in-app Agent) may preview, but POST /imports answers 403 for it — a team member checks and saves in Analify.
The sheet arrives one of two ways, on both routes:
| Source | Request |
|---|---|
| A file | multipart/form-data with a file field (.xlsx / .csv, up to 10 MB); imports adds an options field (JSON string) |
| A Google Sheet | Content-Type: application/json with { "googleSheet": { "fileId": "…" } } — a spreadsheet the member picked in Analify with the connected Google account (see Google Sheets); imports adds "options": { … } as an object |
POST /api/core/finance/imports/preview
POST /api/core/finance/imports/previewcurl -X POST "https://analify.scalyax.ai/api/core/finance/imports/preview?organizationId={organizationId}" \
-H "Authorization: Bearer {anlfy_token}" -H "Content-Type: application/json" \
-d '{ "googleSheet": { "fileId": "1AbC…" } }'Returns each tab: name, headers, 5 sample rows, rowCount, suggestedMapping (column index → date, type, category, description, payment, amount, income_amount, expense_amount or skip), the detected dateOrder (dmy / mdy / ymd, with dateAmbiguous), and layout.
Side-by-side Income / Expense sheets. A common template keeps two blocks next to each other — group labels on row 1 (Income … OutCome), column names on row 2. Analify lines them up into one table: a Type column (Income / Expense) followed by each block's own columns, one row per filled block. layout is ledger_blocks and blocks lists the labels; skipped rows still point at the member's own sheet row.
POST /api/core/finance/imports
POST /api/core/finance/importsSame source, plus options: { sheetName, mapping, dateOrder, defaultPayment, categoryMap } (categoryMap: 'income|<word>' / 'expense|<word>' → category id or null). With ?dryRun=1 it only counts — ready, already imported, possible duplicates, uncategorized, skipped by reason (with samples) — and writes nothing; without it, it saves. Re-importing the same sheet never duplicates a row (each row has a stable source key).
Errors
| Code | Status | Meaning |
|---|---|---|
BAD_REQUEST | 400 | No file / no valid googleSheet, or bad options |
FORBIDDEN | 403 | An AI caller on /imports — a team member saves in Analify |
FINANCE_IMPORT_* | 400 | The sheet can't be read, is over 10 MB, has no such tab, or isn't Excel / CSV |
NOT_CONNECTED | 409 | Google Sheets isn't connected (or needs reconnecting) |
NOT_FOUND | 404 | Picked with a different Google account than the connected one — pick it again |
NO_ACCESS | 403 | The connected account can't open that sheet |
NOT_A_SPREADSHEET | 400 | The file isn't a Google Sheets spreadsheet |
TOO_LARGE | 413 | Over Google's 10 MB export limit — split it by year |
UPSTREAM | 502 | Google didn't answer |
Error Shape
These domains use Analify's standard codes rather than a platform taxonomy:
| Code | Status | Meaning |
|---|---|---|
BAD_REQUEST | 400 | Malformed JSON body, missing required field, or empty items |
COGS_NOT_FOUND | 404 | No cost data on file for that SKU |
ORG_NOT_FOUND | 404 | The organization does not exist |
{
"success": false,
"error": {
"message": "sku, productName, and costPerUnit (piasters) are required",
"code": "BAD_REQUEST"
}
}Updated about 1 month ago
