Your.Store is an AI operations copilot for Shopify merchants. It opens with a morning briefing — revenue, refunds, low stock, thin-margin SKUs — with one-click approve actions, and answers free-form operational questions in chat, adapting how much data it pulls per question. Every action that changes something in the store is proposed first and only runs after an explicit approval.
Design principle: the model plans, deterministic code executes. The LLM
never talks to Shopify directly — it selects a tool name and arguments from
a fixed, versioned registry (app/tools/), and a Python function does the
actual GraphQL call and the actual arithmetic. This keeps every number in
the briefing traceable to a real query, and every write auditable and
reversible up to the approval step.
-
Morning briefing — revenue, refunds, low-stock, and thin-margin alerts computed on open, with one-click approval cards for anything actionable.
-
Intent-aware chat — a greeting gets a plain reply that offers to scan, not a full data pull; only a real question or an accepted scan triggers any tool calls (
app/llm.py:classify_intent). -
Structured, multi-choice offers instead of guessed "yes" — when converse() has something to propose ("want me to check your margins? or run a full scan?"), it returns real
[{action, label}, ...]objects (0 to a few, model's own per-turn choice), never just prose — the UI renders each as an actual button, MCQ-style (same principle as the write-approval Approve/Reject buttons, and Claude Code's own multi-choice prompts). Clicking sends only the action name, never free text, so there's nothing to interpret. Offers accumulate in a small, bounded, keyed queue per session (app/conversation_hints.py— up to 6 distinct actions, oldest evicted first, merged in rather than replaced each turn) instead of a single last-turn variable, so an option offered two turns ago and never clicked is still there, not silently forgotten the moment anything else happens — every completed scan/question also attaches follow-up offers (see below), since converse() only ever runs on the greeting branch and a scan/question answer would otherwise offer no follow-up at all. A bare "yes" still works as a shortcut, but only when the queue holds exactly one candidate — with several pending (the common case) a plain "yes" is genuinely ambiguous and must not guess, so it falls through to normal classification instead. Every action name is validated against a fixed, code-owned registry before anything renders or fires — the model can propose new wording freely, but never a new action; every registered action maps to a read (a scan, or a specific pre-validated question), so none of this can ever reach a write tool or the approval gate, which stays untouched and still requires explicit approval for every write regardless of how a turn's reads were triggered. What gets offered after a scan/question is itself the model's own judgment (narrate()'s "offers" field, based on what THIS answer actually found — e.g. only offering to fix margins when something's actually wrong with them), not a fixed checklist reattached every time;app/conversation_hints.py:derive_offersvalidates that judgment against the same fixed registry and fills in from a deterministic, computed-driven derivation only where the model's list came up short or an exception meant it never got to judge at all. -
The planner is grounded in the real date, and can ask instead of guessing — a live bug: asked for "total sales from July 1 to July 15," the planner (with no idea what day it actually was) guessed a since-date three years off, silently querying the wrong span.
app/llm.py:plan()now tells the model today's real date on every call, and the ShopifyQL tool gained a realuntilparam (previously hardcoded totoday, so an explicit end date could never be expressed at all). For the rarer case where scope is still genuinely ambiguous even with today's date known, the planner returns{"needs_clarification": true, "question", "options"?}instead of guessing, and a newclarifygraph node hard-blocks on the sameinterrupt()/Command(resume=...)mechanism as the write-approval gate — an MCQ or free-text popup, never a silent guess — before folding the merchant's answer back into one retry. -
A shared view layer — sort/filter/limit, resolved in code, never in the model's own text (
core/view.py) — "arrange by most ordered", "just the top 5", "only ones missing cost" now work onlow_stock,product_margins,orders_in_range, and (via ShopifyQL's nativeGROUP BY/ORDER BY/LIMIT)analytics_report. The planner only ever picks a tool-specificsort_byenum/filters/limit- an invalid enum raises rather than silently falling back to default order (same "model plans, deterministic code executes" rule that fixed the earlier sales-total hallucination). Two real constraints shaped this beyond a naive per-tool implementation: (1)low/variants/orderseach double as the raw input to compute_metrics' OWN aggregate math (counts,net_revenue...) - sorting/ limiting them in the tool would silently corrupt those aggregates the moment a view was also requested, so tools stay pure fetchers andcompute_metricsresolves the view on a fresh copy instead; (2) some interestinglow_stocksorts (units_ordered_*,margin_*,reorder_urgency- the default) only exist onceorders_in_range/product_marginsare joined into theplanningrowscompute_planningalready builds, so those apply there, not insidelow_stockalone. A cost-unknown row in a margin sort always lands at the end regardless of direction, never interleaved or silently dropped. (The handoff this was built from also flagged ShopifyQL'ssalesdataset as deprecated - live-verified still working against this store's current API version, so left untouched rather than guessed at.) -
A real "list the catalog" tool (
catalog,app/tools/reads.py) — a live bug: no tool existed for a plain product listing, so "give me our catalog" made the planner reach forproduct_marginsas the closest stand-in, andNARRATE_SYSforced that margin data into an unrelated "Margin unknown SKUs" answer instead of just listing products.catalogis a plain name/sku/price/vendor/type/status/stock listing with its ownsort_by/filters/limit- applied directly in the tool itself (unlike the other three view-layer tools) since nothing else reads this raw list for a separate aggregate, so there's no dual-purpose-list risk to guard against. Also fixed in the same pass:recommend()was composing a full answer into its advisorytextfield when it had nothing to recommend - pure wasted effort, since non-actionable recommendations are never shown to the merchant at all. -
A join+aggregate compose primitive (
core/compose.py) for the next class of gapcatalogalone couldn't close — a live bug: "all products by units sold" needscatalogjoined withorders_in_rangeby variant_id (no single tool does that), and the planner flip-flopped across several inconsistentdecide_enoughcalls before hitting the timeout escape hatch. Rather than a general query-composition engine, this is one small, reusable, fully-tested operation (attach_aggregate— group-and-sum, then left-join the result onto a base list, never dropping a zero-match row) plusapp/metrics.py:_order_line_item_metrics, a single source of truth for "how much did this variant actually sell" built once fromorders_in_range's line items.cataloggained four Tier-2 sorts (units_sold_desc/asc,revenue_desc/asc) on top of it — the planner only ever picks the named sort; the join, the sum, and the arithmetic all happen in code, never in the model's head. Degrades honestly (catalog_view_error) iforders_in_rangewasn't fetched alongside it, rather than defaulting every product to "0 sold" as if that were real. -
Typed clarify interactions — a dedicated Yes/No popup, not generic MCQ for everything —
plan()'sneeds_clarificationresponse now carries a"type": "yesno" | "mcq" | "freetext"(falls back to the old options- present/absent inference for compatibility), andweb/chat.htmlrenders a real Yes/No layout (primary Yes, plain No, free-text escape hatch below) for the common binary case instead of two equal-weight buttons or a bare text box. -
Structured table rendering for a listing — a live ask:
catalog/low_stock"arrange by X"/margins/orders listings only ever reached the merchant asnarrate()'s prose, a wall of "Name: price, Stock: N" lines.persist_nodenow also emits atablefield (whichever ofcatalog/low_stock_view/margins_view/orders_viewis non-empty, plus whichsort_byproduced it) alongside the narrated text; the client renders a real row-per-item table with the sorted column highlighted, andNARRATE_SYSwas told to keep its own text a short summary instead of re-reciting every row now that the table carries the itemized detail. -
Boundary-level input validation for the set_costs form (
app/input_validation.py) — the only prior check (validate_set_cost_action) verified cost is numeric/positive but never checked thatvariant_id/product_id/sku/nameare actually strings.POST /writes/set_costnow rejects a malformed submission (wrong type, or an oversized field) with a clean 400 before a recommendation is even constructed. Not a query-injection fix — Shopify's GraphQL transport takesvariablesas JSON, never string-concatenated into query text, so classic SQL/GraphQL injection isn't the exposure here; this guards against type-confusion crashes and oversized payloads (XSS is handled separately, at render time, byweb/chat.html'sescapeHtml()). -
Bounded, deterministic store memory, not a raw transcript — a short, capped per-session conversation history (
app/conversation_history.py— last 5 exchanges) gives classify_intent/converse enough context for a short follow-up ("yes", "what about last month?"). Separately,app/conversation_memory.pykeeps up to 8 distinct facts about the store (e.g. "Low stock: 8 SKUs", "Margin unknown for 30 SKUs"), derived straight from compute_metrics' own output — never free text, never an extra LLM judgment call. A repeated scan updates an existing fact in place (keyed by kind) instead of piling up near-duplicates; a genuinely new kind of fact evicts the oldest one once the cap is hit. This is "intelligent" by construction rather than by judgment: a greeting never produces a fact (there's no computed data to derive one from), so there's no chit-chat to filter out in the first place. Neither of these reintroduces the kind of unbounded cross-turn state the session-leak fix (app/session_threads.py) deliberately prevents — both are capped, session-scoped, and independent of the LangGraph checkpointer. -
Progressive status, structured replies — a multi-hop scan/question can take 10-30s; instead of one static "Thinking…" the whole time, the UI updates its status line as each graph stage completes ("Gathering your store data…", "Putting together the answer…"). Narrated answers are formatted as a headline line, one line per distinct topic, and (when relevant) a closing "Next:" line — not one dense run-on paragraph.
-
Adaptive chat — ask anything about the store; the agent decides how many tool calls it needs (capped at 3 hops) rather than following a fixed script.
-
Full analytics surface, plan-aware AND cause-aware — sales trends, sessions, conversion funnel, landing-page conversion, returning-customer rate, and cohort retention via ShopifyQL (
app/tools/shopifyql.py), offered only if the store can actually use it. ShopifyQL has two independent gates beyond the store's plan: the app must be granted theread_reportsscope, and — separately — the app must be configured for protected customer data (required for every ShopifyQL query, even ones that touch no customer data). Before this was fixed, all three failure modes collapsed into the same message ("upgrade your plan"), which was simply wrong advice for a missing scope or unconfigured PCD, and unfixable by upgrading anything.app/capabilities.py:detect()now checks scope → plan → a live probe, in that order, and records why along with whether (CapReason:plan_gated/scope_missing/not_configured/unknown) — a Basic-plan store still falls back to operational data instead of the planner ever trying an analytics query, but now for the right stated reason. Because this is a self-hosted app, the person reading the chat is the operator who can fix a scope or PCD config gap — so the narration states the actual fix (which Dev Dashboard setting to change) directly in the reply instead of deferring to logs a merchant-facing install would have to hide it in. If a live attempt still fails anyway, a dedicated node (access_check) flips the capability off and tells the UI live — see Architecture. -
Complete, bounded retrieval — reads paginate fully via cursors instead of silently truncating at the first page, capped at a hard limit (5000 records) with the truncation surfaced to both the reasoning loop and the final answer, never hidden (
app/tools/pagination.py). -
Approve-to-execute — every side-effectful action (reorder, reprice, ...) is gated behind an explicit approval card before it touches the store. Nothing writes silently.
-
Deterministic math, LLM narration — revenue, margin, and inventory thresholds are computed in plain Python (
app/metrics.py); the model is only ever asked to explain numbers it didn't calculate. -
Guardrailed planning — every planning/decision call is constrained to JSON output and an exact tool name from the registry; an uncertain model defaults to stopping, never to guessing (
app/llm.py). -
Cross-session memory — briefing and chat outcomes persist to a Shopify metaobject, so there's no separate database to run or back up.
-
Tested invariants — an offline suite proves the math is exact and, most importantly, that no write can ever bypass the approval gate (
tests/, see Testing below). -
Self-throttling, not blind — every Shopify call reads the response's cost-based
throttleStatusand pre-flight-waits before the bucket runs dry, with exponential backoff on throttling/5xx/transport errors and a one-shot token refresh on an unexpected 401 (app/shopify_client.py). -
Degrades honestly, never crashes — a failed fetch becomes an explicit error entry the summary/answer can name ("couldn't retrieve X"), not a crashed request; a real bug in our own code still surfaces loudly rather than being silently absorbed (
core/graph.py). -
Grounded narration — every generated answer is checked for numbers that don't actually appear in the computed metrics; a mismatch is logged as a signal, not swallowed (
app/grounding.py). -
Scales past the live rate bucket — a whole-catalog scan (low stock, margins) that would need more than one page automatically switches to an async Bulk Operation instead of hammering the cursor loop, which a paginated read alone can't do without burning the rate-limit budget on a large catalog (
app/tools/bulk.py). -
MCP server (local testing) — the same engine is exposed to external MCP clients (Claude, ticketing tools) at
/mcpon this same process: reads run live, writes never execute over MCP — they land in the same approve-to-execute surface as the chat UI (app/mcp_bridge.py,app/mcp_server.py; see "MCP server" below). -
AI-native inventory planning — the Stocky-replacement layer: every low-stock SKU is ranked by lost margin per day where cost is known, lost revenue otherwise (each row's
ranked_bysays which — a high-revenue/low-margin SKU no longer automatically outranks a low-revenue/high-margin one), with a suggested reorder quantity sized from sales velocity, supplier lead time, a percentile-based (not naive max) safety-stock buffer, and netted against stock already incoming (Shopify's ownincominginventory level) — never double-ordering what's already on a purchase order (app/planning.py,app/metrics.py). The reorder threshold itself is per-SKU and dynamic: a fast mover can sit above the old global low-stock cutoff and still be flagged, because it's compared against its own velocity-derived reorder point.Three honesty flags replace a single ambiguous "no velocity" case, each narrated and gated differently:
insufficient_history(product or store too new to trust — no reorder point at all),stockout_suspected/velocity_is_lower_bound(currently at zero stock, so its sales rate is a floor on true demand, not the real number — a reorder point is still shown since urgency doesn't wait on precision), andno_demand(in stock, enough history, genuinely zero sales — advise reviewing it, never reorder). A merchant-editablesupplier_lead_time_daysmetafield is validated and clamped before it ever reaches a quantity calculation — a malformed or out-of-range value silently defaults rather than corrupting the math. Gift-card and untracked variants (no real stockout meaning behindinventoryQuantity: 0) are filtered out of low-stock entirely instead of flooding it with noise.A dedicated guardrail (
app/guardrails.py) sits between the model's recommendation and the approval card: a reorder is rejected back to advisory-only — never silently "corrected" — if it targets a variant not in planning, a quantity that doesn't match planning's ownsuggested_qty, a flagged (insufficient_history/no_demand) row, a quantity over a hardMAX_REORDER_QTYceiling, or a variant that already has a pending draft PO. The approval preview itself is deterministically enriched with the real velocity, lead time, on-hand/on-order figures, and estimated cost — never just an LLM-authored quantity a human can't sanity-check.Computed entirely from data already being pulled (orders, low stock, margins) plus one optional product metafield and one cheap shop-level query (store creation date + timezone, for honest day-bucketing and history-length checks); needs no new Shopify scope.
An optional weekly-briefing scheduler (
app/scheduler.py, off by default) can re-run the exact same briefing on a schedule instead of only on demand — seeWEEKLY_BRIEFING_CRONbelow.
core/ domain-agnostic adaptive agent engine — no Shopify or LLM-vendor code
app/ Shopify Admin API client, OpenRouter calls, tool registry, ops logic
web/ chat + briefing UI
core/ has no knowledge of Shopify or OpenRouter — every dependency (tool
registry, capability map, LLM calls, metrics, persistence) is injected in
app/service.py. That boundary is what makes the engine
reusable beyond Shopify or beyond this LLM provider.
Request flow:
entry -> capabilities -> intent? -+- greeting -> converse (reply + offer to scan) -> END
+- scan -> preset plan -> gather -> access_check -> enough? -> analyze -> recommend -> capability -> [gate -> execute] -> persist
+- question -> plan -> [gather?] -> access_check -> enough? -(adaptive loop, up to 3 hops)-> analyze -> recommend -> capability -> [gate -> execute] -> persist
| Stage | What happens |
|---|---|
| entry | Briefing mode always classifies as scan; chat mode classifies the message as greeting / scan / question (app/llm.py:classify_intent) before pulling any data. |
| capabilities | Detects whether and why a gated tool (ShopifyQL analytics) is available, and caches it per store for 10 minutes (app/capabilities.py:detect()) — checks the granted scope, then the plan, then does a live probe query, in that order (each cheaper and more certain than the next), and records the specific CapReason (plan_gated / scope_missing / not_configured / unknown) rather than a bare yes/no. The planner is never even offered a capability that would just error on this store. A live attempt can still fail even when detection thought it was fine (e.g. PCD access revoked between checks); gather's fallback (below) catches that via access_check and flips the capability off for the rest of that cache window, not permanently — once it expires, the next turn re-checks and picks up a fix (e.g. the scope was granted and the app reinstalled) without needing a process restart. |
| converse | Greetings and vague messages get a plain reply that offers a scan — zero tool calls. |
| plan / scan_plan | scan runs the preset briefing reads; question asks the model which of the currently allowed read tools answer it — a question needing no data routes back to converse instead of gathering. |
| gather | Runs the selected tools against Shopify (app/tools/reads.py). Each read peeks one page first; a small store's single page is the complete result, a large store (more pages exist) switches to an async Bulk Operation (app/tools/bulk.py) instead of looping pages, and orders stay a bounded cursor loop scoped by the LLM's days window (app/tools/pagination.py). A tool call that fails outright degrades to an {tool, error} entry instead of crashing the run; a capability-gated tool (has a .capability, e.g. ShopifyQL) that errors degrades to an honest "not available on this plan" entry and is flagged for the next node. |
| access_check | Dedicated node for "an access/permission wall was hit" — flips the capability off for this store (app/capabilities.py:mark_unavailable, self-heals after the cache's 10-minute TTL) and emits a distinct capability_unavailable SSE event so the UI can show it live, rather than only surfacing it buried inside the eventual narrated answer. A no-op when nothing gated failed this hop. |
| enough? | Model decides whether to stop or pull one more data point, from a compact summary (app/summarize.py) rather than raw rows; hop 3 always stops. Truncated/failed reads are named explicitly in that summary rather than silently read as empty. |
| analyze | compute_metrics does the arithmetic in Python; the model narrates it. |
| recommend | Model may propose an action. |
| capability check | The recommendation only becomes an approval card if a real write tool is registered for it — otherwise it's advisory only. |
| gate / execute | Side-effectful actions pause for approval (/approve) and only commit once approved. |
| persist | Result is written to Shopify metaobject memory and streamed to the UI over SSE. |
The same engine is also reachable as an MCP server, mounted at /mcp on this
same FastAPI process — one deploy unit, two doors in:
local chat UI ────────┐
Claude / MCP client ───┼──► FastAPI (app/service.py)
│ ├─ / /chat /approve /events (chat, unchanged)
│ ├─ /mcp (MCP transport)
│ └─ /pending /pending/{id}/approve (gated-write approvals)
└──────────► same core/ tools ────► Shopify Admin API
- Reads run live:
analytics_report,low_stock,product_margins,orders_in_range,catalog,list_purchase_orders,get_restock_queue,export_purchase_order(app/mcp_bridge.py:READ_TOOLS). - Writes never execute over MCP. Calling
create_purchase_order,receive_purchase_order, orbulk_update_pricecreates a pending item and returnspending_human_approval+ apending_id— conceptually the same gate the chat graph's owninterruptuses (human approval required before anything runs), just a separate mechanism reached from a different door: MCP-originated pending items live inapp/pending.py's queue, chat-originated ones pause via LangGraph's owninterrupt/checkpointer.GET /pendingmirrors a chat-originated pause in for LISTING purposes (an MCP client can see it's outstanding), butPOST /pending/{id}/approverefuses a chat-mirrored id rather than attempting it — approving one that way would mean re-running the write outside the chat graph's own guardrails/validation, a real correctness risk. A chat-originated write is only ever actually approved from the chat UI itself.check_approvallets an MCP client poll the outcome of a write it proposed. - Per-client auth (
app/mcp_auth.py, constant-time key comparison) is permissive by default (MCP_DEV_OPEN=1, for local testing) — set it to0and populateMCP_CLIENT_KEYSbefore exposing this beyond your own machine. The app refuses to start ifMCP_PUBLIC_BIND=1while auth is still permissive, rather than silently serving/mcpopen to the network. - Least-privilege scoping, session binding, rate limits, output scrubbing, and audit logging are all in place beyond the base read/write/approval contract — see SECURITY.md for the full writeup (what each control does, and what's an honest open limitation rather than a false "solved" claim).
Try it locally:
uvicorn app.service:app --reload --port 8000
# point an MCP client (Claude Desktop custom connector, MCP Inspector) at
# http://localhost:8000/mcp — no key needed with MCP_DEV_OPEN=1Call low_stock → real data back. Call create_purchase_order →
pending_human_approval + a pending_id. Open http://localhost:8000/ →
the pending card appears in the same chat UI → Approve → the restock order
is created (a real Shopify inventory transfer + shipment, plus a
Your.Store-only record — not Shopify's native Purchase Orders screen,
see Restock orders below). If Shopify itself rejects the
mutation (e.g. a variant genuinely not stocked at the destination location),
approval honestly reports that failure instead of a false "executed" — see
the runner isolation note below.
Two rounds of external review have gone into this bridge. The full writeup — including the OWASP-MCP-Top-10-mapped hardening pass (session hijacking, per-client rate limits/quotas/timeouts, least-privilege tool scoping, output/ exfiltration scrubbing, audit logging, and the public-bind startup guard) — lives in SECURITY.md. Summary of the first round below; SECURITY.md covers the second round and the current honest-limitations list.
- Preview/execution desync (fixed). The risk: a human approves a
friendly-looking preview (e.g. "reorder 3 SKUs") while a prompt-injected
payload carries hidden extra fields that reach the tool anyway on approval.
Fixed by whitelisting each write tool's args to an exact known set
before a preview is ever built or a pending item ever created
(
mcp_bridge._sanitize) — the preview and the args that execute on approval are now guaranteed to be the same object, not two independently built views that could drift. Verified with the literal reported attack shape (tests/test_mcp_bridge.py): acreate_purchase_ordercall carryingprice/vendorfields alongside the real ones has those fields stripped before the preview is built and never reaches the tool, even on approval. runnerisolation (fixed + tested).mcp_bridge.runner— the function that actually executes an approved write — is never registered as an MCP tool; onlyrequest_write(which only ever creates a pending item) is reachable from the MCP surface.runneris invoked from exactly one place:app/service.py's/pending/{id}/approveroute.tests/test_mcp_bridge.py::test_runner_is_never_registered_as_an_mcp_toolasserts this directly. Same caveat as the rest of this app applies, though: that approve route has no auth of its own yet (see Production checklist).- False-success on a real write failure (fixed). The risk: every write
tool already checks Shopify's
userErrorsand returns{"status": "error", ...}on a genuine rejection (see Security section below) — but the pending-approval layer that sits between "human clicked approve" and "tool ran" was ignoring that field, unconditionally marking the item"approved"regardless of what the tool actually returned. A real MCP-approvedcreate_purchase_ordercould report "approved and executed" while Shopify's own mutation had failed and nothing was actually created. Fixed inapp/pending.py:decide— it now only marks"approved"when the tool's own result isn't"error", otherwise"failed", and/pending/{id}/approvesurfaces that honestly instead of a blanketok:true. Covered bytests/test_pending.pyandtests/test_mcp_integration.py::test_mcp_write_that_fails_to_commit_is_reported_honestly_not_as_success. - Downstream argument validation (partially addressed). Values reaching
Shopify are structured JSON (GraphQL variables), not string-concatenated
SQL/shell — so classic injection doesn't apply the same way — but wrong
values (a malformed variant ID, a nonsensical price) are still only
caught by Shopify's own mutation-level validation, not a schema on our
side.
orders_in_range'sstatusargument specifically was a free string concatenated into a Shopify search-query filter and has been constrained to a fixed enum at the MCP boundary (Literal[...]inapp/mcp_server.py— FastMCP rejects anything outside it before our code runs); the two write tools' args are whitelisted as above. A Pydantic-based schema layer would be the more scalable fix if more write tools are added. - Read-side data exfiltration via prompt injection (not solved, by
design honesty). A compromised LLM client could still request legitimate
read tools (e.g.
product_margins) and exfiltrate the results through its own output channel — no code change here fully closes that; it's an LLM-security frontier problem, not a bug. Mitigations actually in place: reads are still restricted to the fixedREAD_TOOLSallowlist (no arbitrary GraphQL), and per-client auth scoping (app/mcp_auth.py) narrows who can call anything. Per-user (not just per-client) read authorization and abnormal-usage monitoring are real further steps, deferred until this serves more than one trusted local client — the dormantapp/tenancy.pyis the intended hook for that later.
PO records live in Shopify's Content > Metaobjects, not the native
Purchase Orders screen — the underlying stock movement is native. One
sentence, but worth being explicit about: Shopify's admin has a real,
separate "Purchase Orders" screen (Products > Purchase orders — vendor,
cost, draft/ordered status) that has no API at all — not even read
access, confirmed via live schema introspection and Shopify's own developer
community. A restock order created here will never appear there, and one a
merchant creates natively there is invisible to this app. What is real,
native Shopify infrastructure is the stock movement itself: creating a
restock order here creates an actual Inventory Transfer + Shipment
(Products > Transfers in the admin — verifiable independently of this app),
which is what correctly populates Shopify's own incoming inventory field
and is why a reorder no longer keeps resurfacing after being approved (see
app/planning.py's on_order netting). The bookkeeping half (vendor, unit
cost, our own status) lives in a $app:restock_order metaobject instead,
since there's no other place Shopify offers to put it — set up via
python -m scripts.setup_restock_metaobjects, with access.admin: MERCHANT_READ_WRITE so it's genuinely visible/editable in Content >
Metaobjects, not just reachable through this app's own API calls. Every
Shopify-facing label (the transfer's referenceName/note, the
metaobject's display name) says "restock order" / "Your.Store restock",
never bare "Purchase Order" — an ops person searching Shopify's real
Purchase Orders screen for one of these should not come up empty-handed
confused about where it went; they were never meant to find it there.
Required scopes, beyond what this app already uses:
write_inventory_transfers, write_inventory_shipments,
write_inventory_shipments_received_items — now granted on this
installation, and the full write path (activate → transfer → shipment →
metaobject) has been run live end to end, confirmed committed for real,
including incoming correctly reflecting the transfer at the destination
location afterward. (write_metaobjects/write_metaobject_definitions
turned out to already work even before being explicitly granted — see
app/tools/writes.py's module docstring for the full breakdown.)
Idempotency, two layers: Shopify's inventoryTransferCreateAsReadyToShip /
inventoryShipmentCreateInTransit / inventoryShipmentReceive all
require an @idempotent(key:...) directive as of API version 2026-04 —
confirmed via the mutations' own live descriptions (not visible in plain
argument introspection, which is what an earlier pass here checked and
missed it). This app supplies a real key derived from each write's
pending_id on every one of those calls, protecting a single mutation
against being repeated. Layered on top, a $app:restock_order metaobject
looked up by a handle also derived from pending_id protects a retry of
the whole tool (e.g. after an earlier partial failure) from creating a
second real transfer.
Destination location. CreatePurchaseOrder requires a real
destination_location_id — no silent guessing. A single-active-location
store auto-selects it (zero added friction for the common case); a
multi-location store (confirmed live: this app's own dev store has two)
pauses with an MCQ clarify popup ("Which location should this restock
order ship to?", core/graph.py's resolve_location node) before the
approval card ever renders, reusing the exact same typed-clarify mechanism
and client UI as scope clarification — crediting stock to the wrong
physical place is a real operational error, not a cosmetic one, so this
is never guessed.
No native Supplier object either, but Your.Store keeps its own. Every
vendor string is normalized into a reusable $app:supplier metaobject
(get_or_create_supplier, deduplicated by a handle derived from the
vendor name — live-verified: calling it twice with the same name reuses
the same record, never creates a duplicate) — but this is not Shopify's
native Supplier object. Confirmed live that Shopify has zero
Supplier-related types, queries, or mutations anywhere in the schema
(a full schema-wide type-name scan, not just Query/Mutation fields), so
the native Purchase Orders screen's own supplier records share the same
no-API fate as the screen itself — this app's own record is worth having
regardless, since it's what lets get_vendor_cost_history and a future
reorder say "from Acme again" instead of retyping vendor details cold
every time. Deliberately kept separate from Product.vendor (never
collapsed into one field): Shopify's own native supplier concept can
group several vendor labels under one supplier, so a 1:1 assumption would
be wrong even if that object were reachable.
Vendor cost history. get_vendor_cost_history(vendor, variant_id)
queries this app's own past $app:restock_order records (oldest to
newest) — no native Shopify autofill exists for this either (a
native-Purchase-Orders-screen-only feature, and that screen has no API).
Wired into recommend()'s prompt (app/service.py:_recommend_with_cost_history)
so a reorder proposal can say "last ordered at $X from this vendor"
instead of asking cold every time.
Export to supplier: export_purchase_order (MCP) /
app/tools/writes.py:po_export_text produces a plain-text summary suitable
for pasting into an email — the same workaround every competitor in this
space (Prediko, Cogsy, Inventory Planner, …) has to build, since none of
them can write into the native screen either. get_supplier (MCP) resolves
a supplier_id to full name/contact/currency/payment_terms on demand.
Explicitly out of scope for this pass — named here rather than left for a merchant to discover by hitting the boundary: PDF/email export (the plain-text form above is as far as this goes — PDF/HTML would need a new library dependency, not added speculatively), CSV bulk import, POS-specific barcode flows, multi-currency remittance, and grouping several vendors under one multi-vendor supplier. For any of those, use Shopify's native Purchase Orders screen directly — same underlying transfer/shipment object either way, no conflict.
Requirements: Python 3.11+, a Shopify Dev Dashboard app + dev store in the same org, and an OpenRouter API key.
Auth model: this app uses the Shopify client-credentials grant — no OAuth redirect, no static admin token. The app requests a fresh Admin API access token (client ID + secret → token, cached ~24h) on demand.
-
Create the Dev Dashboard app and grant it these Admin API scopes:
read_orders, read_products, read_inventory, read_locations, write_draft_orders, write_products, write_inventory, write_discounts(+ optionallyread_reportsfor ShopifyQL,read_metaobjects, write_metaobjectsfor cross-session memory). Copy the client ID and client secret. Note: after adding a new scope (e.g.read_reports) to an already-created app, saving the scope alone isn't enough — the app must be reinstalled on the store for the change to actually apply to the running install, same as any other scope change (§ install step below). Confirmed live:analytics_reportreturnedACCESS_DENIEDon every retry (including a fully fresh token) until the app was reinstalled, at which point it started returning real data immediately. -
Dev store — must be created from the same Dev Dashboard org as the app; otherwise the token endpoint returns
shop_not_permitted. -
Memory metaobject (optional) — Settings → Custom data → Metaobjects → add a definition with type
$app:ops_logand a text fieldpayload. Without it, memory writes fail silently and briefing/chat still work — outcomes just aren't persisted across sessions. -
Supplier lead time metafield (optional) — Settings → Custom data → Products → add a definition with namespace
custom, keysupplier_lead_time_days, type "Integer". Set it per product to size that product's reorder point and suggested quantity from its real supply chain instead of the 7-day default (app/planning.py:DEFAULT_LEAD_TIME_DAYS). Products without it just use the default — nothing else changes. A value outside 1–180 or that doesn't parse as an integer also falls back to the default rather than reaching the reorder math (validate_lead_time). -
Configure
cp .env.example .env
Variable Description SHOPIFY_SHOPStore subdomain only, e.g. your-store(not the full.myshopify.com)SHOPIFY_CLIENT_IDDev Dashboard app client ID SHOPIFY_CLIENT_SECRETDev Dashboard app client secret SHOPIFY_API_VERSIONAdmin API version, e.g. 2026-07OPENROUTER_API_KEYOpenRouter API key OPENROUTER_MODELAny OpenRouter model id, e.g. openai/gpt-oss-120bWEEKLY_BRIEFING_CRONOptional, off by default. e.g. MON:09runs the briefing every Monday at 09:00 UTC — reuses the exact same briefing path as a manualPOST /briefing, just on a schedule (app/scheduler.py) -
Install and verify auth
python -m venv .venv .venv\Scripts\activate # Windows; use source .venv/bin/activate elsewhere pip install -r requirements.txt python -m scripts.check_shopify # must print the shop name before you go further
This also reports the granted scopes, whether
read_reports(needed for ShopifyQL analytics) is among them, whether the plan supports ShopifyQL, and — if both of those pass — runs a live ShopifyQL probe and prints the actual reason if it fails (a missing scope, unconfigured protected customer data, or plan). Only a missing scope exits non-zero; a plan limit or an unconfigured-PCD probe failure exits 0 with a warning — the app still runs and analytics degrades honestly either way. If the probe fails withnot_configured: open the app in the Partner/Dev Dashboard, select a distribution method, then select the protected customer data and fields it needs (dev stores need this configuration step but not app review) — ShopifyQL requires PCD access for every query, even ones that touch no customer data. -
Run
uvicorn app.service:app --reload --port 8000
Open http://localhost:8000 — the briefing loads first, chat is below it.
pip install -r requirements-dev.txt
pytest -qFully offline and deterministic — no Shopify or OpenRouter calls. Covers pure
metrics math (tests/test_l1_metrics.py), graph-level invariants
(tests/test_l2_invariants.py) built against the real graph, registry, and
write tools with only the LLM calls faked — most importantly, that no
side-effectful write can ever run without an explicit approval — plus the
throttle/backoff/retry contract of gql() (tests/test_shopify_client.py),
the numeric-grounding check (tests/test_grounding.py), mutation chunking
(tests/test_writes_chunking.py), the Bulk Operations orchestration and
large-store switchover (tests/test_bulk.py), and the ShopifyQL tool itself
(tests/test_shopifyql.py). tests/test_capabilities.py covers the
scope → plan → live-probe detection order (each later check never runs once
an earlier one already found the cause), classify_gql_errors against a
real captured scope-denial payload, the caching/TTL/mark_unavailable
behavior (including that it never downgrades an already-specific reason to
a vaguer one), and — the regression that matters most — that the
not_configured narration branch never tells the merchant to upgrade their
plan, and states the actual Dashboard fix directly. MCP is covered by tests/test_pending.py
(the approval store), tests/test_mcp_bridge.py (read/write gating, the
preview/execution-desync fix, runner isolation), tests/test_mcp_auth.py
(dev-open default, enforced keys, constant-time comparison), and
tests/test_mcp_integration.py (drives the real MCP JSON-RPC protocol
against the actual app.service:app over HTTP — tool listing, a live read,
write → pending → approve → executes, write → reject → never executes, and
auth enforcement). The OWASP-hardening pass adds tests/test_mcp_guard.py
(exfiltration/injection scrubbing), tests/test_mcp_session.py (session-
ownership binding), tests/test_mcp_ratelimit.py (per-client/per-tool
limits), tests/test_mcp_audit.py (keys-only logging), and
tests/test_mcp_startup_guard.py (the public-bind refusal, via a real
subprocess so it can't corrupt the shared test session's app singleton) —
plus tests/test_mcp_security_integration.py, which drives session
hijacking, rate limiting, read scoping, timeouts, and output scrubbing all
over the real wire protocol against the real app. All MCP-over-HTTP test
files share one session-scoped mcp_client fixture (tests/conftest.py):
FastMCP's session manager can only be started once per process, so only one
TestClient may ever enter app.service.app's lifespan across the whole
test run. Inventory planning is covered by tests/test_planning.py — the
app/planning.py formulas (ceil rounding, percentile-based safety stock,
Decimal money), the velocity join and cancelled/test/refund exclusion from
orders_in_range, the insufficient_history/stockout_suspected/
no_demand disambiguation, on-order netting from Shopify's own incoming
inventory level, lead-time metafield validation, the dynamic per-SKU
threshold, the dual revenue/margin ranking, and — built against the real
graph — that create_purchase_order is sized from planning's
suggested_qty, never a flat default. tests/test_guardrails.py covers the
approval-card guardrail (rejects an invented target, a mismatched quantity,
a flagged row, an over-the-cap quantity, or a duplicate pending restock
order — and the deterministic preview enrichment), and
tests/test_reads_planning.py
covers the gift-card/untracked filtering and the shop_info tool. The
optional scheduler is covered by tests/test_scheduler.py (schedule
parsing, disabled-by-default, fires at most once per matching day, a
failing run doesn't crash the loop). tests/test_session_threads.py
proves the per-turn thread_id fix both ways — reproduces the original
cross-turn gathered leak against the real graph/checkpointer, then proves
new_turn_cfg prevents it. tests/test_conversation_hints.py covers the
bounded offer queue (offers across turns merge rather than replace, a
repeated action updates in place, the queue evicts oldest-first beyond its
cap, and a bare "yes" only ever resolves when exactly one candidate is
pending); tests/test_conversation_memory.py covers deriving facts from
compute_metrics (never fabricating one from absent data), updating a fact
in place vs. accumulating distinct ones, and FIFO eviction beyond the cap;
tests/test_l2_invariants.py adds the proof that a force_intent-routed
turn still requires human approval for any write it recommends, exactly
like an LLM-classified one.
What happens when the network, the store's data, or the model itself misbehaves:
- Rate limits — Shopify's Admin API is cost-based, not request-based.
gql()tracks the last-seenthrottleStatus, pre-flight-sleeps if the estimated bucket is low, and retries throttled/5xx/transport failures with exponential backoff (capped retries) — a genuine GraphQL error (bad field, bad query) is never retried, only surfaced. - Partial failure — each node wraps only its own external-call boundary
(an LLM call, a Shopify call) in a narrow try/except; a failure there
degrades to an honest
{"error": ...}entry thatsummarize/analyzename explicitly, while a bug in our own code (wrong type, missing key) still crashes and logs loudly instead of being silently absorbed. This is distinct fromgql()'s own retry: oncegql()gives up and raises, the graph does not re-attempt that same call within the hop — the loop just moves to the next tool. The adaptive loop may retry it on a later hop, but only if the model itself decides to (capped atMAX_HOPS), never automatically. The one exception is capability-gated tools (ShopifyQL):access_checkflips the capability off for the rest of the capabilities cache's 10-minute window, then it's offered again fresh — a bounded, self-healing "retry later" that ordinary tools don't get; an ordinary tool's next attempt (next question/briefing) is just a normal fresh call with no cross-turn cooldown or backoff memory. - Untrustworthy data —
compute_metricsnever fabricates a number: a variant with no cost set is omitted from margins (never priced at 0), zero orders is labeled "no sales in this window," and a failed fetch is never counted as if it were empty-but-successful. - Ungrounded narration —
app/grounding.pychecks every generated answer for numbers that don't trace back tocompute_metrics' output and logs a warning when one shows up — a soft, diagnostic check, not a hard block. - Scale — whole-catalog reads (low stock, margins) escalate to an async Bulk Operation instead of a cursor loop once a store no longer fits in one page, so a large catalog can't throttle mid-scan or simply never finish.
- Mutation limits — write tools chunk array inputs to Shopify's 250-item
cap automatically (
app/tools/writes.py).
Not done (out of scope for a single local dev store): a durable
(non-MemorySaver) checkpointer, state-schema versioning, per-tenant
credential resolution, and webhook-driven (vs. on-demand) reads — all listed
in the production checklist below or deferred until this is actually hosted
or serving more than one store.
Inventory planning's own honest limitations, flagged rather than faked:
seasonality isn't modeled (a flat window over/understocks seasonal goods —
detecting and flagging it is a roadmap item, not silently pretended away);
multi-location inventory is aggregated store-wide, not computed per
location (planning_scope: "store_wide"); the per-SKU history window is
always whatever orders_in_range actually fetched (30 days by default) —
a slow mover that would benefit from a longer lookback gets window_too_short
flagged rather than a second fetch invented for it; and safety stock's
variability formula uses only demand variability (which real daily-sales
history supports) — lead-time variability is assumed zero because this app
tracks a single lead-time estimate per product, not a distribution of past
supplier deliveries (app/planning.py docstring has the full reasoning).
Capability-reason detection's own honest limitation: classify_gql_errors's
NOT_CONFIGURED markers (app/shopify_client.py:PCD_MARKERS) are
best-effort text matches, not verified against a real PCD-denied response —
this project's own dev store already has protected customer data configured
for its app, so that exact error has never actually been captured live. What
is verified live: the scope → plan → probe check ordering, and the
general shape of a Shopify access-denial error (extensions.code == "ACCESS_DENIED", captured from a genuine missing-scope call). If a probe
ever misclassifies in practice, scripts/check_shopify.py prints the raw
errors hash verbatim — that's the input needed to correct the markers.
This repo runs as a local single-process service by default. Before exposing it beyond your own machine:
- Auth —
/briefing,/chat,/approve,/pending, and/pending/{id}/approvehave no authentication of their own. Put them behind your own auth/session layer before any public deployment. The MCP transport at/mcphas its own separate gate (MCP_DEV_OPEN/MCP_CLIENT_KEYS/MCP_CLIENT_SCOPES, see "MCP server" above and SECURITY.md) — setMCP_DEV_OPEN=0, configure real per-client keys and scopes, and setMCP_PUBLIC_BIND=1(the app refuses to start otherwise) before exposing it beyond localhost. TLS is mandatory the moment/mcpis reachable off this machine. - Persistence — swap
MemorySaver()for a durable LangGraph checkpointer (PostgresSaver.from_conn_string(...)) so approval state survives a restart. Use managed Postgres, not a container-local SQLite file — it won't survive a redeploy. - Embed in the Shopify admin — for a merchant-facing app rather than a
standalone tool, add a thin App Bridge shell (React Router) that iframes
this service into the Shopify admin and forwards a session token. The
shell is a dumb renderer; all logic stays in
core/andapp/unchanged. - Scope down write access — grant only the write scopes the deployed
feature set actually uses, and audit
CAPABILITYinapp/registry.pyagainst what's really wired up before enabling a recommendation kind.
.envis git-ignored; only.env.example(empty keys) is committed.- Start every Dev Dashboard app with read-only scopes; add write scopes one at a time, only for the feature being enabled.
- The client secret is as sensitive as a password — it's exchanged for a fresh access token on demand and is never itself sent to Shopify's GraphQL endpoint.
- Every write tool checks Shopify's
userErrorsand reports failure even on an HTTP 200 (app/tools/writes.py) — a populateduserErrorsis treated as a failed write, not a success. - Report suspected vulnerabilities before opening a public issue.
Shopify's own Agentic Storefronts work is front-of-house: syndicating a store's catalog out to external AI shopping assistants. Your.Store is the back-of-house counterpart: the merchant's assistant reaching in to run operations — briefing, analysis, and approve-to-execute actions on their own store.