MCP Server — connecting AI agents to Mirabelle¶
Who this is for: developers and administrators who want an AI agent — an assistant, an internal copilot, a script — to read Mirabelle's planning data, and (with a second scope the planner grants explicitly) to act on that planner's review queue, through the standard Model Context Protocol (MCP). Planners do not need this page.
What an agent can do. With the default mcp:read scope it asks for the planner's review queue,
one order and the reasons behind it, an item's stock, the supply plan, the forecast of a series, the
weekly demand basis, the safety-stock buffers and the supply exceptions, and gets structured answers
it can reason about. With the consented mcp:write scope it can additionally act exactly like the
planner's phone app: accept an order into the approval cart, edit a cart line, cancel and restore an
order, and submit the final approval — every guard, rate limit and audit row of the phone applies, and
the planner can end the authorization at any time.
Whose authority it uses. A planner approves the agent once, in the browser they already use for Mirabelle — one Approve click on a page that lists exactly what is being granted (read-only, or read + write). From then on the agent acts as that planner, on that planner's scope only: production pipelines, and only the segments the planner may see (the same rules the phone app applies). The planner can end the authorization at any time — from the console page's your agent authorizations panel or the Security page — and disabling the planner's account ends it too.
Status: Phase 1 + 2
Ten read-only tools (Phase 0), seven write tools behind the consented mcp:write scope (Phase 1),
the authorization registry with its management surfaces, the tenant kill-switch, and Mirabelle as
an MCP client (Phase 2: the registered servers the chat and jam steps may call). Verified with
the official MCP Python SDK and the login helper. Agent products such as Claude Code, Claude
Desktop, Cursor or MCP Inspector have not been tried — see
what is not covered.
Quick start. (1) Get a token with the login helper. (2) Connect any
MCP client to https://app.mirabelle.es/api/mcp with the header Authorization: Bearer <access token> — the
verified Python example shows how. (3) Call get_planning_context
first: every other tool needs the pipeline_id it returns.
The tools¶
The server lives at https://app.mirabelle.es/api/mcp (/api/mcp/ works too) and speaks streamable HTTP
in stateless mode: every request is independent and authorized by its own Bearer token — there is no
session and no Mcp-Session-Id — and every POST is answered with a plain JSON document, not an event stream. The protocol version is
negotiated by the official mcp SDK the server is built on (the client verified here negotiated
2025-11-25). The server identifies itself as mirabelle, version 1.1.0-mcp-phase1, and tells every client
to start with get_planning_context.
Ten read-only tools, seven write tools. The read tools declare the MCP annotations
readOnlyHint: true, destructiveHint: false, idempotentHint: true and openWorldHint: false;
the write tools carry readOnlyHint: false so a client keeps its confirmation step for them
(submit_approvals, the one committing step, is honestly not flagged idempotent — a second call
on a refilled cart approves more). The hints are not the safeguard — the tool layer runs the
phone app's own write path through the planner-decisions state machine (see
Security rules). The agent sees production pipelines only and only the data the
authorizing planner's segment scope allows.
| Tool | Arguments (* = required) |
What comes back |
|---|---|---|
get_planning_context |
none | Who the authorized planner is (id, e-mail, role, tenant), the production pipelines that can be reviewed (those with an approval scenario) with their planning date, the plan archive each is pinned to and the review window, the tenant currency and the planner's segment scope. Call it first: every other tool takes its pipeline_id from it. With no such pipeline it answers pipelines: [] with empty_reason: no_production_pipeline and a detail — usually the agent was authorized for the wrong tenant. |
get_review_queue |
pipeline_id*, state (default pending; also in_cart, to_review, approved, canceled, all), sort (default release; also value, item, site, qty), segment_id (one of your own), site_id (destination), item_id, q, limit (default 100, 1–500), offset |
The planner's review queue: the orders that need a decision (released within the pipeline's review window) and those already in the cart, approved or canceled, one page at a time. q: every word you give (case-insensitive) must appear in the item, site or source name, the order type, the order id or the item id. Each row carries an order_key; the answer has total, has_more, counts, window_counts, the filters applied and, for an empty page, an empty_reason. |
get_order_detail |
pipeline_id, order_id, key (the row's order_key), orders_limit (default 20, 1–100) |
Everything about one order of the current plan that is still planned and of a reviewable type (BUY, BUILD, TRANSFER, BALANCING, ZONE_BALANCING): header and why it is up for review, stock at the site and at the source, service-level facts, the 52-week good-stock projection, the demand basis, and the planned and firm ERP orders into and out of the node. Pass the queue's order_key as key: if the plan was recomputed and the id now names another order, the call fails with plan_changed instead of describing the wrong order. |
get_item_overview |
pipeline_id, and exactly one* of item_id, barcode, name |
The item's card(s): every site where it is present with good and bad on-hand and the resolved unit cost, plus its orders in the current plan. name is a case-insensitive fragment with at most 20 matches (matches = cards returned, truncated only when more exist). A planner with assigned segments sees only their sites (hidden_sites counts the rest). No match: items: [] with a reason; an unknown item_id is an error. |
get_supply_orders |
pipeline_id*, item_id, site_id (the receiving site), order_type (exact text, case-sensitive, e.g. BUY), week_from, week_to (plan week numbers, on the arrival week; 0 = the plan's first Monday), limit (default 200, 1–1000) |
The orders of the pipeline's latest supply run (BUY, TRANSFER, BALANCING, REPAIR, …) sorted by arrival week, with total and qty for everything that matches. Orders of quantity 0 are not listed. With both item_id and site_id, the open firm ERP orders into that node (up to 20, with PO number and line) come as firm_orders_in. |
get_series_forecast |
pipeline_id, item_id, site_id*, weeks (default 52, 1–52) |
The demand history (closed weeks before the planning week, the newest 2 × weeks) and the best-method point forecast of one (item, site) series from the latest forecast run, with interval_low / interval_high (the widest configured prediction interval). The method is the one the latest method selection chose for the series; a planner's manual method lock does not override it, so for a locked series the answer can differ from the Forecast screen. Warehouses and other pass-through nodes are not forecast directly (their demand is rolled up from the sites they supply): use get_netting for them. When no forecast is stored the answer is available: false with a reason, a detail and the best_method when known; the history is still returned. |
get_netting |
pipeline_id, item_id, site_id* |
The weekly demand basis the engines plan on, on the plan's 52-week Monday grid: statistical, maintenance and causal (the forecast streams after the pipeline's blend weights, before orders consume them), firm_demand (the order book) and supply_plan (the net quantity the supply engines plan on: what is left of the forecast after the order book and approved replenishments took their share, plus the firm demand). How much was consumed is not returned: there is no consumption, approved-replenishment or return column. statistical follows the pipeline's pinned (frozen) forecast version when it has one, so it can differ from the number get_series_forecast shows. writer is the id of the pipeline's own series scenario, the only one read; other_writers and conflict only report other versions. |
get_meio |
pipeline_id*, item_id, site_id, limit (default 200, 1–1000) |
Reorder point, safety stock, expected fill rate, wait time and lead time (weeks) of the latest MEIO run, with is_direct_demand (false marks a pass-through node whose fill rate is not a customer service level). Both ids: that pair plus its segment-group targets (group_targets). One id or none: a list — every in-scope site of the item, every item of the site, or everything — one capped page at a time. |
get_stock |
pipeline_id, item_id, site_id |
Current physical stock of one item per site: the good (serviceable) and bad (repair, scrap) pools from master on-hand, with the resolved unit cost. Without site_id, every site that holds the item; with it, that one site. hidden_sites counts the sites outside a scoped planner's segments. |
get_exceptions |
pipeline_id*, item_id, site_id, exception_type (exact text, case-sensitive, e.g. Shortage), week_from, week_to (plan week numbers; 0 = the plan's first Monday), limit (default 200, 1–1000) |
The supply exceptions of the latest supply run (shortages, unmet demand, component shortages on builds, capacity and depot limits) for the good-stock condition, sorted by week, with week_date — the exception week's Monday label, the date the planner screens show. |
The write tools (mcp:write)¶
These need the mcp:write scope — a scope that exists only when the planner consented to it (the
approval page lists the write powers), and that a renewal can never grant. A read-only authorization
is refused by every write tool with the re-authorize remedy. Every guard of the phone app runs
unchanged: production pipeline, approval scenario, the live segment scope (fail-closed), the order-key
identity check (plan_changed), the per-order recommendation link, the state machine's row locks, and
the phone's rate limits (120 changes / 60 s and 10 approvals / 60 s on top of the shared 60 calls /
60 s). Each decision writes the SAME audit rows the phone writes (the planner's trail is one, whichever
door was used) plus the mcp call row.
| Tool | Arguments (* = required) |
What it does |
|---|---|---|
get_cart |
pipeline_id* (read scope) |
The planner's approval cart: lines with edits, value and any problem that would keep a line from being approved, plus the live totals. |
accept_order |
pipeline_id, order_id, order_key*, qty, release_date |
Accept an order into the cart (idempotent), optionally with a quantity / order-date edit that rides along. The order is not approved yet. |
edit_cart_line |
pipeline_id, line_id, qty, release_date |
Change a cart line's quantity / order date (a value equal to the plan's clears that part of the edit). |
remove_cart_line |
pipeline_id, line_id |
Take a line out of the cart; the order simply returns to pending. |
submit_approvals |
pipeline_id*, line_ids |
The FINAL approval — the phone's Approve-all. line_ids absent approves the whole cart; an empty list approves nothing. Per line, in its own transaction; the answer lists every line (approved / stale / error / skipped), never silent. |
cancel_order |
pipeline_id, order_id, order_key* |
Reject the order at once with the planner's name on it; undo with restore_order. |
restore_order |
pipeline_id, order_id, order_key* |
Undo a cancel made by this agent (only the planner who canceled — or an admin — and only while it is still canceled). |
The natural flow is get_review_queue → get_order_detail → accept_order / cancel_order →
get_cart → submit_approvals. Always pass the order_key from the queue / detail rows: a plan
recomputed between your reads and your write answers plan_changed and has changed nothing.
How answers look¶
- Plain JSON. Every tool returns one JSON object (the MCP result's text). Dates are ISO dates; plan weeks are the Mondays of the plan's grid, week 0 being the plan's first Monday.
- Errors are results, not HTTP failures. A tool that fails answers HTTP 200 with
isError: trueand a text that startsError executing tool <name>:followed by the reason — an unknownitem_id, a value the tool does not accept (state must be one of […]),no segments assigned - ask an admin,plan_changed, or the rate-limit message. A crash that is not an anticipated error is reported only asError executing tool <name>; the details stay in the server log. Authentication problems are different: they are refused at the door with HTTP401before any tool runs. -
Honest empty answers. When there is nothing to show, the answer says why — a machine-readable
reason(orempty_reason) and usually a plain-languagedetail— and an agent should not retry it:Tool Values get_planning_contextempty_reason:no_production_pipelineget_review_queueempty_reason:no_approval_scenario,no_segments_assigned,no_supply_run,nothing_in_window,nothing_matches_filters,nothing_in_this_view,not_evaluated_yet,all_reviewed,nothing_for_youget_series_forecastavailable: false,reason:no_forecast_run,no_stored_forecast,no_best_method,no_direct_forecastget_nettingavailable: false,reason:no_rows_from_pipeline_writer,no_netting_rowsget_meioreason:no_meio_run(withavailable: false),no_matchget_stockreason:no_record_at_site,hidden_by_scope,no_stock_rowsget_supply_orders,get_exceptionstotal: 0withreason: no_matchget_item_overviewitems: []with a plain-languagereason(no item carries this barcode / no item name matches) -
A missing id is an error, an empty list is not. Looking up ONE item, site, order or series whose id does not exist is an error; a list filter that matches nothing answers an empty list with a
reason. - Lists say how much was cut.
totalcounts everything that matches within the caller's scope,limitis the page size actually used, andtruncatedis true only when more rows exist than were returned (the queue useshas_moreandoffset; the item overview usesmatchesandtruncated). Numbers outside the allowed range are clamped, not refused:limit0 becomes 1, 5000 becomes 1000 (500 for the queue),weeksis held to 1–52. - The
filtersecho. An argument name a tool does not know is ignored, not refused. The list tools therefore echo the filters they applied: if a filter you passed is missing from the echo, it did not arrive — check the spelling.
Audit and limits¶
- Audit. One row per tool call that reaches the tool, in the tenant's audit log: entity
mcp, action = the tool name, who = the planner's e-mail (their id if they have none),outcomesuccessorerror, andnew_value={"rows": <number of list items in the answer, null when there is no list>, "ms": <duration>}plus, on an error only,detail= the reason capped at 400 characters. Never the arguments and never the results. Calls refused before the tool runs write no row: a401at the door, the tool's own token check, the rate limit, and arguments the server rejects as invalid. The OAuth events (oauth_consent,oauth_token_issued,oauth_refresh_reuse,oauth_revoke) are written under entityauth. - Rate limit. 60 tool calls per 60 seconds per planner (counted per tenant and user, as a sliding window);
only tool calls count, not
initializeortools/list. Over the limit the call is refused as a tool error —Too many Mirabelle tool calls in a short time. Nothing was changed - wait N seconds and try again.— with HTTP 200 and noRetry-Afterheader. The counter lives in the server's memory.
How an agent connects (OAuth 2.1)¶
Access is per planner and revocable: the agent never holds a password, only an access token granted through a standard OAuth 2.1 authorization-code flow with PKCE. The access token lasts 8 hours by default and is renewed silently with a refresh token; the whole login ends 90 days at the latest after the approval (exact numbers: Lifetimes). The consent page reuses the planner's existing Mirabelle browser session — one Approve click.
%%{init: {'flowchart': {'wrappingWidth': 340}}}%%
flowchart TD
accTitle: How an agent gets access and calls a tool
accDescr: The agent starts a login and the planner approves it in a browser signed in to Mirabelle. The agent exchanges the single-use code for an access token and a refresh token, calls the tools with the access token, which is checked on every call, and renews or revokes it later.
A["1. The agent starts the login with a PKCE secret and a loopback address on the planner's computer"]
B["2. The planner's browser opens<br/>the consent page<br/>(signed in to Mirabelle)"]
C["3. The planner clicks Approve<br/>(Deny ends the login)"]
D["Single-use code<br/>sent to the loopback address"]
E["4. The agent exchanges the code<br/>and its PKCE secret<br/>at the token endpoint"]
F["Access token (8 h by default)<br/>+ refresh token<br/>(30 days sliding, login ends after 90 days)"]
G["5. The agent calls a tool<br/>Authorization: Bearer access token"]
H["Checked on every call<br/>token type and address, revocation,<br/>live user, scope, rate limit"]
I["Read-only answer<br/>+ one audit row"]
J["6. Renew with the refresh token<br/>(a new pair) or revoke<br/>(ends the whole login)"]
A --> B --> C --> D --> E --> F --> G --> H --> I
F -.-> J
classDef io fill:#e7f6f0,stroke:#10b981,color:#1b4332;
classDef proc fill:#eef2ff,stroke:#6366f1,color:#312e81;
class D,F,I io;
class A,B,C,E,G,H,J proc;
- The agent starts the login. The login helper (or an OAuth-capable client) makes a random PKCE secret, listens on a loopback address of the planner's own computer and sends the planner's browser to the authorization address.
- The consent page. It shows who is approving, the tenant, and that the agent gets read-only access to the planner's planning data, with Approve and Deny. It runs on the planner's existing Mirabelle session; a browser that is not signed in gets a Sign in first page instead: sign in, then start the login again.
- Approve or Deny. Each approval request can be used once. Approve sends the browser back to the loopback address with a single-use code (valid 10 minutes); Deny sends back an error and nothing is issued.
- Code for tokens. The agent trades the code, together with its PKCE secret, for an access token and a refresh token. A code is consumed by the first attempt, successful or not.
- Tool calls. The agent sends the access token as a Bearer header to the MCP endpoint. Every call is checked (see Security rules) and audited, and the answer is read-only.
- Renew or revoke. Before the access token expires, the refresh token is traded for a new pair; revoking the refresh token ends the whole login, including every access token issued under it.
Get a token with the login helper¶
files/scripts/mcp_login.py runs the whole OAuth flow for a script or an agent that cannot do it by itself.
It needs Python 3.10 or newer (standard library only — nothing to install) and a browser on the same
computer, because the approval comes back to a loopback address.
python files/scripts/mcp_login.py # read-only, https://app.mirabelle.es
python files/scripts/mcp_login.py --scopes write # read + WRITE (the approval page lists the powers)
python files/scripts/mcp_login.py --base https://<your deployment> # another deployment
python files/scripts/mcp_login.py --refresh # rotate: print a fresh access token
python files/scripts/mcp_login.py --revoke # end the authorization (both tokens)
| Option | Meaning |
|---|---|
--base URL |
the Mirabelle origin; default https://app.mirabelle.es. For --refresh and --revoke the default is the origin stored at login (a different --base prints a warning) |
--out FILE |
where the tokens are kept; default ~/.mirabelle-mcp-token.json. Use the same file for --refresh and --revoke |
--timeout SECONDS |
how long a login waits for the browser; default 300, more than 0 and at most 86400 |
--scopes read\|write\|read,write |
what the agent may do. read (the default) keeps it read-only; write adds the phone app's write path (the cart, cancels, the final approval) — the consent page shows exactly what you are granting, and only the planner's Approve grants it |
--refresh / --revoke |
the two other modes; they exclude each other |
What happens during a login
- The helper starts a listener on
127.0.0.1(a free port the system picks), builds the authorization address with a fresh PKCE challenge and a randomstatevalue for this run, prints the address and asks your default browser to open it. If no browser can be opened it says so — open the printed address yourself, in a browser on this computer. - The browser shows the consent page: who you are, your tenant, what the agent will be able to do, and Approve / Deny. A browser that is not signed in to Mirabelle gets a sign-in page instead: sign in, then run the command again.
- Approve sends the browser back to the listener with a single-use code. The helper exchanges it, stores the tokens and prints the header line below; the tab says Connected. You can close this tab. After Deny the tab says Authorization denied. An approval request can be used once and lives ten minutes; after that, clicking Approve shows Authorization request expired — run the command again.
- The wait is bounded and
Ctrl+Ccancels it. A callback that does not carry this run'sstatevalue is answered with an error page and ignored: the helper keeps waiting, so a stale tab or another program on the machine can neither end the wait nor supply a code.
| Outcome | What the helper prints | Exit code |
|---|---|---|
| Approved | Authorized. Use this header on your MCP client (valid N minutes, --refresh renews silently):, then Authorization: Bearer <access token>, then Tokens stored in <file> - renew with --refresh, end with --revoke. |
0 |
| Denied | Authorization refused: access_denied |
1 |
| Timed out | Timed out after N seconds waiting for the browser - nothing was stored. and Run the command again (--timeout SECONDS waits longer). |
1 |
Ctrl+C |
Cancelled - nothing was stored. |
1 |
A denied, cancelled or timed-out login stores nothing.
The token store. The file holds access_token, refresh_token, scope, expires_in, base (the
deployment that issued them) and stored_at. It is written in one step (a temporary file, then a replace), so
an interruption cannot lose the only refresh token, and its permissions are restricted to the owner where the
operating system supports it. It is a credential: keep it out of repositories and shared folders. To copy the
access token out of the store without printing it (PowerShell):
Renewing and ending
--refreshsends the stored refresh token. The server answers with a new access token and a new refresh token (the old one is consumed) and both replace the stored ones. If the server cannot be reached or fails, the helper saysRefresh failed (…)andNothing was changed - try again in a moment.; if the refresh token is refused it saysRefresh refused (<error>): <reason>andRun again without --refresh to re-consent.--revokerevokes the access token (Access token: revoked.) and then the refresh token (Refresh token: revoked - this authorization is ended.), which ends the whole login, and empties the store. If a revocation fails the helper exits with code 1 and keeps what is still alive in the store, so that running--revokeagain retries (The stored tokens were kept - run --revoke again.when the refresh token's revocation failed).
Then send the access token on every request as a Bearer header:
The endpoint is https://app.mirabelle.es/api/mcp (/api/mcp/ is served too, without a redirect). When the
access token expires (8 hours by default) run --refresh, or let a client that speaks OAuth renew it itself.
A verified client: the official Python SDK¶
The one client that has been run end to end against this server is the official MCP Python SDK
(pip install mcp; tested with version 2.3.0 on Python 3.13, with a static Bearer header). The script below
connects, lists the tools and calls get_planning_context. The token is read from an environment variable —
never paste a token into a script:
import asyncio
import json
import os
import sys
import httpx2
from mcp.client.session import ClientSession
from mcp.client.streamable_http import streamable_http_client
URL = os.environ.get("MCP_URL", "https://app.mirabelle.es/api/mcp")
TOKEN = os.environ.get("MCP_TOKEN") or sys.exit("Set the MCP_TOKEN environment variable first.")
async def main():
headers = {"Authorization": f"Bearer {TOKEN}"}
async with httpx2.AsyncClient(headers=headers, timeout=60) as http:
async with streamable_http_client(URL, http_client=http) as (read, write):
async with ClientSession(read, write) as session:
init = await session.initialize()
print(f"server : {init.server_info.name} {init.server_info.version} (protocol {init.protocol_version})")
tools = await session.list_tools()
print(f"tools : {len(tools.tools)} -> " + ", ".join(t.name for t in tools.tools))
result = await session.call_tool("get_planning_context", {})
print(f"isError : {result.is_error}")
ctx = json.loads(result.content[0].text)
print(f"acting as: {ctx['user']['role']} in tenant {ctx['user']['account_name']}")
for p in ctx["pipelines"]:
print(f"pipeline : {p['pipeline_id']} '{p['name']}' planning date {p['planning_date']} plan archive {p['plan_archive_date']}")
asyncio.run(main())
Run it with MCP_TOKEN set to the access token the login helper printed (PowerShell:
$env:MCP_TOKEN = '<access token>'; bash: export MCP_TOKEN='<access token>'); MCP_URL points it at another
deployment. Expected output — names, ids and dates come from your own data:
server : mirabelle 1.1.0-mcp-phase1 (protocol 2025-11-25)
tools : 17 -> get_planning_context, get_review_queue, get_order_detail, get_item_overview, get_supply_orders, get_series_forecast, get_netting, get_meio, get_stock, get_exceptions, get_cart, accept_order, edit_cart_line, remove_cart_line, submit_approvals, cancel_order, restore_order
isError : False
acting as: <role> in tenant <your tenant>
pipeline : <id> '<name>' planning date <date> plan archive <date>
Two details: the SDK's HTTP layer is httpx2 (installed together with mcp), not httpx; and the protocol
version is negotiated, so the number printed depends on the SDK version.
The OAuth client id, and what it means for other clients¶
Mirabelle's authorization server knows exactly one client:
| Client id | mirabelle-mcp (the consent page shows it as Mirabelle planning agent) |
| Type | public client — no client secret; PKCE with S256 is mandatory |
| Scopes | mcp:read (the default; the ten read-only tools) and mcp:write (the seven write tools — granted only by explicit consent, never by a silent client default and never by a renewal) |
| Redirect address | loopback only: http on 127.0.0.1, localhost or [::1], any port and path. Anything else (https, another host, a custom scheme) is refused with an error page — never with a redirect — and the redirect given when the code is exchanged must be identical to the one given when it was requested |
| Grants | authorization_code and refresh_token |
There is no dynamic client registration (RFC 7591): the
discovery documents carry no registration_endpoint and the server has no registration route. For a
third-party MCP client that means:
- A client that lets you set the client id to
mirabelle-mcpand receives the redirect on a loopback address can run the whole authorization flow itself. Checked with the official Python SDK's OAuth client: discovery, token, the ten tools and automatic renewal all worked once the id was configured (the browser approval was replaced by the two HTTP calls the Approve button makes). - A client that only needs a Bearer token needs no OAuth support at all: give it the access token the login helper printed.
- A client that insists on registering itself stops at once — for example with
Registration failed: 404, seen with the official Python SDK's OAuth client when left to register on its own. This is a known Phase-0 limit; whether to add registration is a Phase-1 decision.
Not tested: Claude Code, Claude Desktop, Cursor, MCP Inspector
No agent product has been run against this server — only the official Python SDK (above) and the login helper. Whether a given product "connects automatically" is therefore unverified, and a product that registers itself fails as described above. No product-specific recipe is given here; treat any you find elsewhere as unverified until it has been run.
Security rules¶
The short version: an agent holds a separate, narrow credential — never the planner's own sign-in — that works at one address only, can be taken away at any time, and is checked against the live user on every call.
Which credential works where¶
Mirabelle signs several kinds of token with the same key, so the server checks the type of every token against the address it is presented at. The check is an allow-list: a type that is not explicitly allowed for an address is refused, and the check runs before the database is touched.
| Credential | Accepted at | Refused everywhere else with |
|---|---|---|
Agent access token (type mcp) |
the MCP endpoint only: /api/mcp and /api/mcp/ (both spellings are served directly, with no redirect) |
401 This token is only valid for the Mirabelle MCP endpoint (/api/mcp). — this includes the rest of the REST API and the test console page |
| Planner's browser session (the normal sign-in) | the web app and the REST API, except the MCP endpoint | at the MCP endpoint: 401 The Mirabelle MCP endpoint accepts agent tokens only - approve one via the OAuth flow … |
Agent refresh token (type mcp_refresh) |
nowhere as a Bearer — the token and revocation endpoints read it from the request body | 401 Invalid or expired token |
Phone-app refresh token (type refresh) |
nowhere as a Bearer — the phone app's renewal endpoint reads it from its own cookie | 401 Invalid or expired token |
| Any other or unknown type | nowhere | 401 Invalid or expired token |
A second check sits inside the tools: every tool call needs an access token of type mcp with the
mcp:read scope, so even a session token that reached the tool layer would be refused there.
Ending an authorization, and the registry¶
- Revoking the refresh token ends the whole login: the refresh token, all of its renewals and every
access token issued under it (RFC 7009 §2.1).
Every login has one family id; the access tokens carry it, and each call is checked against both the
token's own id and the family id. Revoke with the login helper's
--revoke, the console's your agent authorizations panel, the Security page's Agent Access tab, or the revocation endpoint called with the refresh token. - The registry. Every authorization family a planner approves has a registry row (what was consented,
when it was last refreshed, when its token was last used, whether it has been ended and why). The
console page shows every planner their own authorizations with a Revoke button; the
Security → Agent Access tab (admins) lists every planner's grants, the revoke, and the tenant
kill-switch. Authorizations approved before Phase 1 (before 2 Dec 2026) have no registry row — end them
with
mcp_login.py --revoke. - Revoking an access token ends that one token only.
- A refresh token works once: each renewal consumes it and returns a new pair in the same family. If a
refresh token that was already used is presented again more than 20 seconds later, the server assumes
it was copied: the whole family is ended (access tokens included) and an audit row is written (action
oauth_refresh_reuse, outcome denied). Within 20 seconds it is treated as two renewals racing — only the loser is refused and nothing is ended. - The consent request behind the Approve button and the authorization code it produces are each single-use: the request is consumed by the first Approve or Deny, the code by its first exchange — successful or not.
- Live user checks. For a tenant user, every call verifies that the user still exists, is still active and
has not changed their password since the token was issued; otherwise the call is refused with
401. Superadmin tokens are not checked against a tenant user row (they come from the central list): a superadmin's access token ends at revocation or expiry, and every renewal re-checks that the superadmin is still active. - A change of a planner's role reaches the agent when the access token is renewed. The segment scope is different: it is read from the live user row at call time, not from the token.
Lifetimes¶
| What | Lasts | Notes |
|---|---|---|
| Approval request and authorization code | 10 minutes, single use | |
| Access token | 8 hours by default | It is the same lifetime as a browser sign-in: the token_expiry_minutes value of the platform's authentication (auth) parameters, 480 minutes unless an administrator changed it. The token answer states the exact value in expires_in (seconds); a client should read it rather than assume 8 hours. |
| Refresh token | 30 days, sliding | each renewal issues a new refresh token that again lasts 30 days |
| The whole login (family) | 90 days at most, counted from the approval | no number of renewals extends it; after that the planner approves again |
| Race window for a repeated refresh token | 20 seconds | see above |
Upgrading from an earlier Phase-0 build
Access tokens issued before the family-id change carry no family id, so revoking their login does not
reach them: they stop at their own expiry (at most 8 hours by default). To end one at once, revoke that
access token itself. Earlier builds were also less strict about refresh tokens presented as a Bearer credential;
the allow-list above refuses them everywhere. If you ran an earlier build and want certainty about the
credentials it issued, revoke the login (--revoke) and connect again.
Data scope, audit and the write guarantee¶
- The agent sees production pipelines only, and only what the authorizing planner's segment scope
allows. A planner with no assigned segments sees nothing (the tools answer no segments assigned - ask an
admin or
empty_reason: no_segments_assigned); an administrator is not restricted. - Every tool call is audited — who, which tool, how many rows, how long, the outcome; never the
arguments or the results — and so are the OAuth events (consent, token issue, refresh reuse, revocation)
and every grant revoke. Write decisions additionally write the SAME decision-audit rows the phone app
writes (
mobile_cart/recommendation): the planner's trail is one, whichever door was used. - Read-only is a scope, not a guess: the read tools' layer holds no write SQL at all (a static test
pins it), and the write tools hold no SQL either — they call the phone app's own implementations
(
api/mobile_router.py's write path over theplanner_decisionsstate machine), pinned by a source scan. - The tenant kill-switch. An administrator can switch the whole MCP door off (Settings → AI, or the
Security page's Agent Access tab, key
ai.mcp_enabled). Off means: every tool call is refused with the remedy, and NEW consents are refused with a page that says so — tokens already issued keep working until they expire or are revoked, so nothing is deleted. The switch takes effect within ~30 seconds (the read is cached that long, per tenant, in the one API process). - The transport's DNS-rebinding protection stays on with an explicit Host / Origin allow-list. A deployment
behind another front door sets
MCP_ALLOWED_HOSTS/MCP_ALLOWED_ORIGINS; a variable that is set replaces the whole default list, so list every host you need.
The test console¶
A self-service way to check that the door works end to end, without writing any code. Sign in to
Mirabelle in a normal browser tab and open /api/mcp/console on your deployment
(https://app.mirabelle.es/api/mcp/console); a browser that is not signed in gets a plain 401. The page
walks the path an agent takes:
- Your agent authorizations — the registry rows of the signed-in planner (scopes, last refresh, last
use, active or ended) with a Revoke button; pre-Phase-1 authorizations have no row (end them with
mcp_login.py --revoke). - Agent token — the console never creates a token. Run the login helper and paste the access token into the page; it is kept in this browser tab's session storage only. You can also paste the refresh token to Renew the access token or to Revoke family (end the whole login).
- Transport gates — checks that a call without a token is refused with
401, that a plainGETwith a token is refused with405or406, and that both discovery documents answer. - Handshake —
initializeandtools/list. - Tools — one form per tool, generated from the live
tools/listschemas (required fields are marked); the answer and the elapsed time are shown. The write tools' forms refuse to run without themcp:writescope, exactly like a real client. - Raw JSON-RPC — any method with JSON parameters, for power checks.
The page is an ordinary app page: it runs on your browser session, and an agent token is refused on the page itself. Any signed-in Mirabelle user can open it; it shows nothing by itself, because every call it makes needs an agent token that only an approved OAuth flow produces.
Mirabelle as an MCP client (Phase 2)¶
The other direction: Mirabelle connects out to MCP servers an administrator registers, and the planner-facing AI may call their tools.
%%{init: {'flowchart': {'wrappingWidth': 340}}}%%
flowchart LR
accTitle: How Mirabelle calls a registered MCP server
accDescr: An administrator registers the server in Settings AI with its address and optional secret header. When chat tool-calling is on, the chat assistant may first call the server's tools through the bounded client layer, whose every call is audited, and the gathered context is added to the answer. A jam's model step declares its servers in the jam spec and the same client layer gathers before the step answers.
REG["1. Settings > AI > MCP Connections<br/>an administrator registers the server<br/>(address, optional secret header)"]
CHAT["A chat turn<br/>(ai.mcp_tools_enabled = on)"]
JAM["A jam LLM step<br/>(its spec declares the servers)"]
CLIENT["The client layer<br/>at most 2 rounds / 5 calls,<br/>every result size-capped,<br/>ONE audit row per call"]
EXT["The external MCP server<br/>(its tools)"]
CTX["The gathered context,<br/>added to the answer / the step prompt"]
REG --> EXT
CHAT --> CLIENT
JAM --> CLIENT
CLIENT --> EXT
EXT --> CTX
CTX --> CHAT
CTX --> JAM
classDef io fill:#e7f6f0,stroke:#10b981,color:#1b4332;
classDef proc fill:#eef2ff,stroke:#6366f1,color:#312e81;
class REG,EXT,CTX io;
class CHAT,JAM,CLIENT proc;
- The registry. Settings → AI → MCP Connections (admins): name, streamable-HTTP URL, enabled
flag, authentication (
none, or one outbound header whose value is a masked secret — it leaves the database only as that header, never in logs, audit rows or prompts), and a per-call timeout. Test connects and lists the tool names the agent would see. Removing a server is allowed; jam steps that still declare it refuse to run until it is back — loudly, never silently. - The chat. With Chat tool-calling switched on (Settings → AI → Connectivity,
ai.mcp_tools_enabled, off by default), a chat turn first offers the registered servers' tools to the model — a strict text protocol (TOOL_CALL {json}/DONE), at most 2 rounds and 5 calls per question, every result size-capped — and hands the gathered material to the answer as additive context. A model that declines changes nothing: with the switch off, no server, or a declined question, the turn is byte-identical to the ordinary chat. Every executed call writes one audit row (entitymcp_client, actionserver.tool) — never arguments or results. The answer'stool_callsfield lists the calls it made (names only). - Jams. An LLM step of a jam may declare the servers it may call:
"tools": [{"server": "quintus-dev", "tools": ["add", "price"]}](or"*"for every tool the server offers). The declaration is validated with the spec (structure at parse; the registry at the run's preflight — a deleted or disabled server refuses the run before any step costs anything, naming the remedy). At the step, the model may call the DECLARED tools before answering; the answer is still exactly one JSON document against the step's output schema — the contract holds, and a declared server that is unreachable fails the step loudly (an automated step must not produce an answer whose declared context was silently missing). The tool calls charge the run's token budget and deadline like any model call; a dry run gathers for real but writes no audit row (nothing persists in a dry run).
The bundled email connector (two doors)¶
The first connector that ships in the repository: one mailbox behind five tools —
list_recent_messages, search_messages, read_message, send_message, mark_read — with three
backends over ONE implementation (files/mcp_connectors/email_backends.py): IMAP/SMTP (any
provider, Python stdlib only), Microsoft 365 (the Graph API, tokens from a one-time device-code
flow) and Gmail (its API, tokens from a one-time PKCE flow). The same five tools serve through
BOTH doors; a chat answer or a jam step never learns which mail system is behind them.
Door A — the connector process (Settings → AI → MCP Connections → register it):
- Authorize once (only the OAuth backends need it) — on the Mirabelle computer:
The Graph flow prints a code you enter at
python files/mcp_connectors/email_server.py --authorize-graph --tenant-id <id> --client-id <id> python files/mcp_connectors/email_server.py --authorize-gmail --client-id <id> --client-secret <s>microsoft.com/devicelogin; the Gmail flow opens a browser. Tokens land under%LOCALAPPDATA%\Mirabelle\mcp-email-connector\(owner-only). - Start it (the owner starts it; an agent never does):
The IMAP config JSON:
python files/mcp_connectors/email_server.py --backend imap --config mailbox.json python files/mcp_connectors/email_server.py --backend graph --tenant-id <id> --client-id <id> python files/mcp_connectors/email_server.py --backend gmail --client-id <id> --client-secret <s>{"host": "outlook.office365.com", "port": 993, "user": "box@x.y", "password": "...", "smtp_host": "smtp.office365.com", "smtp_port": 587}. Starting without--tokengenerates a random bearer and prints it once — copy it then. - Register it in MCP Connections: the connector's URL (default
http://127.0.0.1:8766/mcp) and theAuthorization: Bearer <the printed token>as the masked header value. Every existing bound and audit rule now applies, and any other MCP-capable agent can use the same connector.
Door B — the tenant's native mailbox (Settings → AI → Mailbox, admins; no process to run):
configure the mailbox and the built-in email server joins the chat tool loop's catalog and any jam
step that declares {"server": "email", ...} — executed in-process through the same backends.
IMAP is a form (host, user, password — or a password_env variable name so the secret never enters
the database); Microsoft 365 authorizes right on the tab (device code); Gmail takes the refresh
token from door A's --authorize-gmail as a pasted masked secret. Test lists the three newest
messages through the same backend the chat and jams use.
The honest limits (identical through both doors):
- Search is the backend's own syntax — IMAP SEARCH keys (
SUBJECT "invoice" UNSEEN), Graph KQL (from:alice invoice), Gmail operators (from:alice has:attachment). No invented cross-backend query language. - Read is plain text — the text/plain part, capped; a message without one says so. Attachment content is never fetched in v1 (filenames only).
- Ids: IMAP ids are folder UIDs (of the folder they were listed from); Graph/Gmail ids are stable.
- Audit: door A calls are
mcp_clientrows; door B's areconnector_emailrows — in both cases action{server}.{tool}, ms + outcome, never the message content, never a credential. - Credentials never travel: door A's live in its local files, door B's in the masked row; no log, audit row or prompt ever shows one.
Configure and test — the exact steps¶
Both directions, end to end. The planner-facing version of the same procedures (no commands) is in chapter 12.
A. Authorize an AI app to read (or act) for a planner
- On the planner's computer, run the login helper — read-only by default,
--scopes writeto grant the write tools: - The browser opens the consent page signed in to the planner's own Mirabelle session. Check the planner and the tenant, read the powers (the write consent lists them), click Approve.
- Connect the client to
https://app.mirabelle.es/api/mcpwith the printedAuthorization: Bearer <access token>— the verified SDK example is the reference path. Start withget_planning_context; every other tool needs itspipeline_id. - Test by hand, without code: open
https://app.mirabelle.es/api/mcp/console(signed in), paste the access token, and run any tool from its form — including the write tools, which the console offers with the same gates. The console also lists your agent authorizations with the Revoke button. - End it when done: the console's panel, the Security page's Agent Access tab, or
python files/scripts/mcp_login.py --revoke.
B. Let Mirabelle call other MCP servers
- Settings → AI → MCP Connections → Add an MCP server: the registry name (lowercase-dashed —
jam steps reference it), the streamable-HTTP URL,
headerauthentication when the server needs a credential (the value is masked after save), a timeout. Press Test — the page must answerok: truewith the tool names. - Settings → AI → Connectivity → Chat tool-calling → On. Takes effect on the next question.
- Test the chat: ask something whose answer needs the outside server, and read the answer — the
tool_callsit made are listed with it (names only). A model that declines or a server that is down is said in the answer's context notes, never guessed. - (Optional, jams) declare the server on an LLM step of the jam spec:
The built-in tenant mailbox is declared the same way:
{"server": "email"}(see the bundled email connector). Validate/approve the version as usual; a dry run proves the tools resolve without persisting anything. A run whose declared server is gone refuses at preflight with the remedy. - Verify the plumbing from the developer seat (after a backend restart): It asserts the 17-tool catalog, one read of every read tool, and that its own read-only token is refused by a write tool with the re-authorize remedy.
Discovery documents¶
Agents find the server's OAuth endpoints from two public JSON documents (no sign-in needed, never cached):
| Document | Standard | What it says |
|---|---|---|
/.well-known/oauth-protected-resource |
RFC 9728 | the resource (…/api/mcp), its authorization server and the supported scopes mcp:read and mcp:write |
/.well-known/oauth-authorization-server |
RFC 8414 | the authorize, token and revocation endpoints; response type code; grants authorization_code and refresh_token; PKCE method S256 only; token-endpoint authentication none (public clients) |
Two things to know. The documents exist at the root only — the path-aware variants such as
/.well-known/oauth-protected-resource/api/mcp answer 404 — and the 401 at the MCP endpoint carries
no WWW-Authenticate header. A client that follows the specifications' root fallback discovers
everything (the official Python SDK does: 401, then the path-aware address, then the root document); a
client that requires the challenge header will not find the metadata by itself. There is also no
registration_endpoint (see the OAuth client id).
What is not covered — known limits¶
- No dynamic client registration. One fixed client id; a client that insists on registering itself fails
with
Registration failed: 404. - Agent products are untested. Only the official Python SDK and the login helper have been run against the server — not Claude Code, Claude Desktop, Cursor or MCP Inspector. The write tools have been verified through the same SDK and the test suites, not through a product UI.
- Discovery is root-only and there is no
WWW-Authenticatechallenge (see above). - No audience binding. Some clients send the
resourceparameter (RFC 8707); the server accepts and ignores it. There is one resource, so nothing is lost today. - Segment-limited planners. The scope is enforced fail-closed from the live user row and is covered by automated tests, but it has not been exercised live: no planner on the pilot tenant is limited to segments.
- One API process is assumed. The rate-limit counters, the pending consent requests and the authorization codes live in the memory of the API process. With several processes the limit would apply per process and an approval started on one process could not be completed on another.
- Audit Log page filters. The rows are written (entity
mcp,mcp_client, theoauth_*actions, outcomeerror), but the Audit Log page's filter lists do not offer them yet. - Client-side tools are text-protocol. The chat and jam tool-calling uses a strict text protocol rather than native model function-calling, so it works with every provider (the local Ollama model included); a model that does not follow the protocol simply declines, and the turn answers without tool context.
When something goes wrong¶
| What you see | What it means | What to do |
|---|---|---|
401 The Mirabelle MCP endpoint accepts agent tokens only … |
the request carried a browser session, or no agent token | send the access token from the login helper as Authorization: Bearer … |
401 This token is only valid for the Mirabelle MCP endpoint (/api/mcp). |
an agent access token was sent somewhere other than the MCP endpoint | use it only at /api/mcp; for the web app or the REST API sign in normally |
401 Invalid or expired token |
the access token has expired, is damaged, or is not an access token (a refresh token sent as a Bearer is refused too) | run the login helper with --refresh and use the new access token |
401 Token has been revoked |
the authorization was ended (--revoke, a detected token replay, or the console's Revoke family) |
log in again |
401 Account is disabled / Password has changed |
the planner's account was disabled, or the planner changed their password after the token was issued | an administrator re-enables the account, or the planner approves the agent again |
Refresh refused (…) from the login helper |
the refresh token was already used, is expired or revoked, or the planner's account is no longer active | run the helper again without --refresh and approve again |
get_planning_context answers pipelines: [] with no_production_pipeline |
the authorized tenant has no production pipeline with an approval scenario | check which tenant the planner approved (the consent page names it); mark the pipeline as production and link an approval scenario to it |
A tool error that starts Error executing tool … |
a rejected argument, an unknown id, plan_changed, no segments assigned - ask an admin, or the rate limit |
read the text after the colon; it says what to change |
Registration failed: 404 in a client |
the client tried to register itself | see the OAuth client id: set the client id to mirabelle-mcp or pass a Bearer token |
421 Invalid Host header / 403 Invalid Origin header |
the deployment's host name is not in the allow-list | set MCP_ALLOWED_HOSTS / MCP_ALLOWED_ORIGINS (see below) |
For developers¶
| Piece | Where |
|---|---|
Server (official mcp SDK, stateless streamable HTTP); api/main.py mounts it as two exact routes, /api/mcp and /api/mcp/ |
files/mcp_server/server.py, _mount_mcp_endpoint in files/api/main.py |
| The read-tool catalog and the shared wrapper (token gate, scopes, rate limits, kill-switch, account bind, audit) | files/mcp_server/tools.py |
| The write tools (the phone app's write path, one implementation with two doors) | files/mcp_server/write_tools.py, the _cart_add_impl … _checkout_impl functions in files/api/mobile_router.py, the state machine in files/auto_approval/planner_decisions.py |
| OAuth 2.1 (discovery, scope-aware consent, code and refresh grants, revocation) | files/api/oauth_router.py |
| The grant registry lifecycle + the tenant kill-switch read | files/api/agent_grants.py, the sys_agent_grant DDL in files/DDL/migrations/add_agent_grants.sql |
| Grant management API (the console's own-authorizations panel + the Security tab) | files/api/mcp_admin_router.py, files/api/mcp_console.py, files/frontend/src/components/security/AgentAccessTab.jsx |
| Mirabelle as a client: the outbound client layer, the chat pre-pass, the registry CRUD | files/mirabelle/mcp_client.py, files/mirabelle/tool_loop.py, files/api/mcp_connections_router.py, files/frontend/src/components/McpConnectionsTab.jsx, the config_mcp_server DDL in files/DDL/migrations/add_mcp_connections.sql |
| The bundled email connector (both doors: the connector process, the tenant mailbox, the shared backends, the OAuth flows) | files/mcp_connectors/ (email_server.py, email_backends.py, email_native.py, mail_oauth.py), files/api/mailbox_router.py, files/frontend/src/components/MailboxTab.jsx, the config_mailbox DDL in files/DDL/migrations/add_config_mailbox.sql |
| Jam LLM-step tools (spec key, resolution, the tool stage) | files/jams/spec.py (ToolUse), files/jams/step_tools.py, the preflight + _llm wiring in files/jams/engine.py |
Token minting (typ = mcp / mcp_refresh) and the refresh verdicts |
files/api/auth.py (_create_mcp_token, _create_refresh_token, _classify_refresh) |
| The allow-list of token types per address | files/utils/token_types.py, applied by files/api/auth_middleware.py |
| The test console | files/api/mcp_console.py |
| Login helper | files/scripts/mcp_login.py |
| Live checks (development machine only — they mint tokens from the local secret) | files/scripts/mcp_live_check.py, files/scripts/mcp_oauth_live_check.py |
| Tests | files/tests/test_mcp_interop.py (protocol through the real SDK client), test_mcp_oauth.py (OAuth + scopes on a scratch PostgreSQL), test_mcp_tools.py and test_mcp_tools_polish.py (tool guards, answer vocabulary, the annotations), test_mcp_write_tools.py (the write door), test_mcp_grants_admin.py + test_mcp_grants_ddl.py (the registry + kill-switch), test_mcp_client.py (the outbound client against a real stub server), test_mcp_tool_loop.py (the chat pre-pass), test_jams_step_tools.py (jam tools), test_mcp_login.py, test_mcp_console.py, test_auth_token_types.py (the allow-list and the trailing-slash route) |
| Call | Purpose |
|---|---|
POST /api/mcp (also /api/mcp/) |
the MCP endpoint (JSON-RPC over streamable HTTP); Bearer = an agent access token |
GET /api/oauth/authorize |
authorization endpoint: the consent page, for a browser signed in to Mirabelle |
POST /api/oauth/authorize |
the consent form's Approve / Deny |
POST /api/oauth/token |
token endpoint (form-encoded): authorization_code with code_verifier, and refresh_token |
POST /api/oauth/revoke |
revocation (RFC 7009): always 200 {} so a token's validity is never revealed, 503 when the revocation could not be stored; a refresh token ends its family, an access token only itself |
GET /.well-known/oauth-protected-resource, GET /.well-known/oauth-authorization-server |
the discovery documents |
GET /api/mcp/console |
the test console (browser session) |
GET /api/mcp-admin/grants, POST /api/mcp-admin/grants/{fid}/revoke, GET /api/mcp-admin/status |
the grant registry: own grants for every planner (admins: all + the kill-switch state); browser session — an agent token is refused there |
GET/POST/PUT/DELETE /api/mcp-connections, POST /api/mcp-connections/test |
the outbound MCP server registry (admins, browser session) |
On the wire (/api/mcp, observed against the real SDK):
| Request | Answer |
|---|---|
POST without Content-Type: application/json |
400 |
POST whose Accept has neither application/json nor a wildcard |
406 |
POST with a JSON-RPC notification (no id) |
202, empty body |
POST with an unknown method |
200 with a JSON-RPC error -32601 — a protocol error is not isError |
GET accepting text/event-stream (a bare Accept: */* counts) |
opens a server-sent-events stream that never ends: do not open the endpoint in a browser address bar or call it without a timeout |
GET accepting JSON only |
406 |
DELETE |
405 (session termination is not supported) |
An unknown Host / Origin header |
421 Invalid Host header / 403 Invalid Origin header |
An invented MCP-Protocol-Version header |
400 with a misleading _meta message — omit the header, or send 2025-06-18 or 2025-11-25 |
prompts/list and resources/list answer empty lists: the server advertises those capabilities but has none.
Host and Origin allow-list. The default list covers the loopback forms at any port and the public front door
app.mirabelle.es. A deployment under another host name must set MCP_ALLOWED_HOSTS and
MCP_ALLOWED_ORIGINS (comma-separated; host:* allows any port), or every request is refused with 421 /
403. A variable that is set replaces the whole default list.
Behind the development proxies. The discovery documents build their addresses from the
X-Forwarded-Proto and X-Forwarded-Host headers the front door sets (Caddy sets them), else from the
request itself. Reaching the API through the Vite development server alone therefore advertises
http://localhost:8002, which strict clients refuse because the resource address does not match the one they
used. This is a development-only quirk; the public address is correct.
Roadmap¶
Phase 1 (write tools behind the consented mcp:write scope, the authorization registry with its
management surfaces, the tenant kill-switch) and Phase 2 (Mirabelle as an MCP client: the server
registry, chat tool-calling, jam LLM-step tools) are built — this page documents what runs.
What is deliberately not built yet: dynamic client registration, the Audit Log page's entity filters
for mcp / mcp_client / the oauth_* actions, and any agent-product-specific recipe.