Smart Kiosk — QSR Model Context Protocol (MCP) Surface#
Exposes kiosk-core to the Central QSR Agent
directly via fastmcp — the same MCP framework already used by
kiosk_core/ordering/mcp_server.py’s internal /mcp mount. This is a
separate MCP surface from that ordering mount, which is only for the
internal RAG-service ordering agent.
Previously, this surface was built on the external mcp-service-sdk
package (as Order Accuracy’s dine-in/take-away MCP services still are).
It has since been migrated to a direct fastmcp implementation that owns
its own durable event log, delivery fan-out, and action policy gate
in-tree (see Module layout), removing the mcp-service-sdk dependency
entirely. Tool names, descriptions, input schemas, event types, and the
durable SQLite/JSONL log’s on-disk format are unchanged by this migration.
Module Layout#
File |
Responsibility |
|---|---|
|
|
|
Durable event log (SQLite/JSONL), same on-disk format as the former |
|
Multi-sink event delivery with retry + ordered background dispatch (off by default) |
|
Outbound event autonomy push to the Central QSR Agent’s |
|
Action policy gate ( |
|
Runs the MCP application + queue-depth sampling poller on background threads |
|
Durable (JSON-file) kiosk menu-board mode: |
|
Menu actuation — add/update catalog items (synchronous |
|
Durable queue of menu changes awaiting operator approval |
|
Operator-only REST endpoints to approve/reject those requests |
|
Crash-safe JSON writes (temporary file + |
|
HTTP client to the standalone |
Initialization is explicit. Importing mcp_service is side-effect free:
mcp_service.init() is what opens the durable log, builds the delivery sinks
and the queue-service client, points board_state / menu_requests at their
configured paths, and registers the policy gates. main.py calls it during
startup (and run_mcp_server / start_queue_poller call it too). It is
idempotent, and takes force=True to rebuild — which closes the previous log
and stops the previous dispatcher threads rather than leaking them. Every
runtime entry point also self-initializes, so a direct tool call still works
standalone.
init() re-reads per-call configuration, but a handful of values are still
bound at import time and a rebuild will not pick them up:
MCP_SERVICE_ENABLED, STORE_ID, and MCP_HOST / MCP_PORT /
MCP_TRANSPORT. Changing any of those needs a process restart.
Gate levels are refreshed by init(), which is why the configurable act
tools do not carry a [gate=…] prefix in their MCP descriptions: a tool
description is fixed when the module is imported, so a baked-in level would
drift from the live one after a rebuild. describe() is the authoritative
answer. set_board_mode keeps its prefix because its level is the literal
automatic and cannot change.
The service is started from main.py’s lifespan when KIOSK_CORE_QSR_MCP_ENABLED=true
(default). It listens on KIOSK_CORE_QSR_MCP_PORT (default 8014,
streamable-http transport) — distinct from the ordering feature’s /mcp.
Contract (describe)#
Event types:
queue_depth_sample—{count, nearby, status}, emitted everyKIOSK_CORE_QSR_MCP_QUEUE_POLL_SECONDS(default 30s) by polling queue-service.board_mode_changed—{mode, reason}, emitted wheneverset_board_moderuns.menu_item_added—{product_id, name, category, price, reason}.menu_item_updated—{product_id, changed, reason}, wherechangedis a{field: {from, to}}diff.menu_change_requested—{request_id, action, payload, reason}, emitted when a gated menu change is parked for operator approval.menu_change_resolved—{request_id, action, payload, outcome, status, note}, emitted when an operator closes out an interrupted execution.
Read tools:
get_queue_depth()— current count/status from queue-service.get_queue_history(period)— sample count, average, and maximum fortoday|yesterday|all|YYYY-MM-DD. On the SQLite backend this is a singleCOUNT/AVG/MAXoverjson_extract(envelope, '$.payload.count'), soallstays O(1) in memory however long the log grows; the JSONL backend falls back to reducing rows in Python. Both paths count only integer/real values, so a malformed string payload cannot skew the average or (since text sorts above numbers in SQLite) break the maximum.get_order_stats(period, top_n)— confirmed order count, revenue, and top items from the existing ordering SQLite database.get_board_state()— current board mode and when/why it last changed.get_menu_requests(status)— menu changes awaiting (or past) operator approval;pending(default),executing,approved,rejected, orall. The response also carries anincompletelist of requests stuck inexecutingfrom an interrupted run.
Act tools:
set_board_mode (gate: AUTOMATIC, rate-limited to 20 calls/60s)
set_board_mode(mode, reason=None)—modeis"full"or"simplified". Implements qsr-design’s autonomous action #6: “Kiosk queue deep/short -> Kiosk board simplify”. The actual MCP wire response wraps the result:{"executed": true, "level": "automatic", "result": {...}}on success, or{"executed": false, "level": "automatic", "reason": "rate limit exceeded"}when the 20-calls/60s limit is hit.
Interrupted Executions#
A claim is held only for the length of a single menu write, so an executing
request is almost always one that is simply still running. A claim is
reported as abandoned — listed under incomplete — only when it cannot
plausibly still be live: it was made by an earlier process run, or it has
been held longer than STALE_CLAIM_SECONDS (300s, covering a hung thread
within the current run). Without that distinction, any listing taken during
an approval would wrongly accuse that approval of having crashed.
Abandoned claims are never auto-recovered: whether the half-done write landed
is unknown, and a blind retry could double-apply it. Only an operator can
tell, so they close it out with
POST /menu/requests/{id}/resolve-incomplete?outcome=…:
|
Meaning |
Result |
|---|---|---|
|
The change is in the catalog |
|
|
It never landed; retry it |
|
|
Give up on it |
|
This route exists because approve and reject only accept pending
requests — without it a stuck request could be seen forever but never
cleared. Pruning also skips executing, so the evidence of an interrupted
write is never evicted by the resolved-history cap.
It accepts only requests listed under incomplete, returning 409
otherwise. Resolving a claim that is still running would corrupt it:
not_applied returns it to pending, the in-flight write then finds it no
longer claimed and loses its result, and approving it again applies the
change twice. force=true overrides the check and asserts the owning
execution is genuinely gone.
Resolving emits a menu_change_resolved event. This matters most for
applied: the catalog changed, but the interrupted run never emitted its
menu_item_added / menu_item_updated event, so without this neither the
audit trail nor the agent would learn of a change that really happened. It
is deliberately not a replayed menu_item_* event — the operator is
attesting to the outcome of a request, and the field-level diff that
menu_item_updated carries is not knowable after the fact.
Conversely, if an operator resolves a claim while its write is genuinely in
flight (via force, or past the timeout), approve_menu_request can no
longer record its result. It does not report a plain success: the response
carries a conflict field saying the change was applied but the request no
longer holds that result.
The two failure modes are then kept apart. A caller-fixable rejection
(MenuError — duplicate identifier, bad price, unknown product) marks the request
rejected with the error, since re-approving it unchanged would fail
identically. Any other failure (a locked database, a disk error) releases
the request back to pending, so a transient fault really is retryable
rather than consuming the approval.
Persistence vs. products.yaml. The YAML is the default catalog and
is re-applied on every startup. A row is marked source='agent' — which
SqliteProductRepository.seed_upsert then skips — only when the agent changes
a field the seeder would otherwise re-apply (name, category, price,
is_bestseller, is_veg). So an agent’s price change is not silently
reverted by the next restart, while editing the YAML remains the normal
operator workflow for every item the agent has not taken over.
An availability-only change deliberately does not claim the row: the
seeder never writes is_available, so a removed menu item stays removed across a
restart without permanently detaching it from YAML control. To hand a claimed
row back, POST /api/v1/qsr/menu/items/{id}/release — without it, a single
price change would make that item ignore products.yaml forever. The release
is operator-only, like approve/reject: letting the agent release its own
claim would allow a restart to undo a change it had just made.
Variable |
Default |
Effect |
|---|---|---|
|
|
Gate for |
|
|
Gate for |
|
|
Rate limit (calls per window) |
|
|
Rate-limit window |
|
|
Approval queue file |
Also exposed (unchanged by the migration): describe() (self-description)
and subscribe(event_type, condition, callback_url). subscribe is a
declared no-op. It validates its arguments and returns
{"subscribed": false, "implemented": false, "reason": ...} rather than a
success acknowledgment, because nothing dispatches on those registrations —
acknowledging a subscription that never fires is worse than refusing it. Use
the autonomy push below for server-initiated events.
Warning
Breaking change. subscribed previously returned the event-type string
(truthy); it is now the boolean false. A caller doing
if response["subscribed"] now correctly sees that nothing was registered,
but a caller using the value as an identifier will break. Nothing in this
repository consumes it — verify against the Central QSR Agent, which
lives outside this tree, before deploying.
Event Autonomy (Push to the Central QSR Agent)#
The tools above are pull: the agent calls the kiosk. Event autonomy adds the push direction, so the kiosk reports observations without being polled. It mirrors the pattern in order-accuracy#214.
The agent’s autonomy process has no source polling loop — per its
SERVICE_OWNER_GUIDE, the event producer owns change detection and
delivery. The kiosk’s queue poller samples on a fixed interval, and a camera
count jitters by a person or two, while every forwarded event costs the agent
a model run and the operator a review. AutonomyEventSink therefore takes the
queue depth as the median of the last QUEUE_SMOOTHING_SAMPLES polls (a
miscounted frame or a person walking past is not a change) and forwards a
queue_count_changed only when that depth moved by QUEUE_MIN_DELTA or more
and at least QUEUE_MIN_INTERVAL_SECONDS passed since the last queue event.
The forwarded sample is the latest one at the median, so count, nearby,
status, and estimated_wait_minutes describe the same reading.
QUEUE_CONFIRM_SECONDS after a change, the depth is resent once, so the agent
sees whether a long queue persists or a recovery holds (previous_queue_count
and queue_count both low). After a restart, change detection resumes from the
last logged sample, so a restart does not send an event by itself.
queue-service refreshes its reading’s timestamp on every processed frame. A
reading older than KIOSK_CORE_QSR_QUEUE_MAX_AGE_SECONDS means the camera
stream has stalled: it is not logged or forwarded, and get_queue_depth and
get_kiosk_context report the queue as unavailable.
Flow — emit() writes to the durable log first (authoritative), then
hands the event to a background FIFO worker per destination. Delivery is
best-effort and never blocks the queue poller or a set_board_mode call.
A single ordered worker (rather than a thread per event) ensures a retrying
older sample cannot arrive after a newer one and leave the agent acting on
a stale queue depth.
The Two Store IDs#
There are two distinct store identifiers, and mixing them up is the easiest misconfiguration to make. They are separate because they answer to different owners:
Setting |
Default |
Who defines the value |
What it labels |
|---|---|---|---|
|
|
We do. Local bookkeeping only. |
The |
|
|
The agent does. Must equal its |
The |
Symptom of getting it wrong: events appear in the local log but the agent
never sees them, and [QSR-AUTONOMY] event ... rejected: HTTP 4xx is logged.
If you have no reason to keep them apart, set both to the same value — the only cost is that the local log is relabeled, which nothing depends on:
KIOSK_CORE_QSR_MCP_STORE_ID=qsr-001
KIOSK_CORE_QSR_AUTONOMY_STORE_ID=qsr-001
Envelope posted to POST {url} (the agent replies 202 Accepted):
{
"event_id": "smart_kiosk-queue_count_changed-<ref_id>",
"event_type": "queue_count_changed",
"store_id": "qsr-001",
"occurred_at": "2025-01-01T12:00:00Z",
"data": {"queue_count": 11, "source": "smart_kiosk", "source_event_type": "queue_depth_sample", "...": "original payload"}
}
event_id is stable across retries so the agent can de-duplicate. Internal
event types map to the agent’s vocabulary: queue_depth_sample →
queue_count_changed; board_mode_changed passes through unchanged (the
agent’s event policy is a wildcard, so unregistered names are safe and
simply yield a no-action explanation).
A 4xx other than 429 is treated as a permanent rejection and stops
retries — resending a payload the agent refuses to parse cannot succeed.
Variable |
Default |
Effect |
|---|---|---|
|
(empty) |
Agent inbox URL, e.g., |
|
(empty) |
Optional bearer token |
|
|
Must equal the agent’s |
|
|
Which internal events to forward |
|
|
Minimum change of the queue depth before forwarding |
|
|
Polls whose median is the queue depth |
|
|
Minimum time between queue events |
|
|
Resend the depth once this long after a change; |
|
|
Older queue-service readings are treated as unavailable |
|
|
Per-request timeout |
|
(empty) |
Appended to kiosk-core’s |
QSR Agent Contract (agent_tools.py)#
The Central QSR Agent’s built-in kiosk capability uses three tools that map its
contract onto this kiosk’s real state. Point the agent at this surface with
QSR_KIOSK_MCP_URL=http://<kiosk-host>:8014/mcp; it then replaces the agent’s
local kiosk simulation.
Tool |
Kind |
Behavior |
|---|---|---|
|
read |
|
|
act |
Up to three |
|
act (automatic, 20 calls/60s) |
|
The agent proposes these actions and calls them only after an operator approves.
Forwarded events carry "service": "kiosk"; queue_count_changed also carries
previous_queue_count (the depth in the previous queue event) and
estimated_wait_minutes.
With a live agent, set KIOSK_CORE_QSR_AUTONOMY_EVENT_TYPES=queue_depth_sample:
otherwise each board change the agent applies comes back to it as a
board_mode_changed event, and every forwarded event costs a model call. Lower
KIOSK_CORE_QSR_MCP_QUEUE_POLL_SECONDS (default 30) for faster reaction. After
restarting kiosk-core, restart the agent so it reconnects to this MCP surface.
Variable |
Default |
Effect |
|---|---|---|
|
(empty) |
Optional |
|
|
Upper bound for |
|
|
Initial |
|
|
Wait estimate = queue × this ÷ active kiosks |
Configuration#
See kiosk_core/config.py (QSR_MCP_* and QSR_AUTONOMY_* constants) /
.env.example for all KIOSK_CORE_QSR_* environment variables.
Notes / Follow-Ups#
Tool names/schemas were derived from
qsr-designand the Order Accuracy reference implementation, since retail-use-cases#100/#103 were not reachable from this environment (org SAML SSO). Revisit against the ticket text once accessible.set_board_modeonly flips a backend flag today; wiring kiosk-ui to visibly react toboard_modeis a follow-up.An existing, populated
qsr_mcp_events.db(or JSONL log file) from before thefastmcpmigration keeps working unmodified: the SQLite table/columns and JSONL record shape inevent_log.pyare byte-for-byte identical to the formermcp_service_sdk-backed log.