lob-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@lob-mcp Submit a limit order to buy 10 AAPL at $150 and show me the resulting book."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
lob-mcp — a limit order book exchange as an MCP server
A deterministic limit order book matching engine exposed to language models as a set of MCP tools. The point is that a model can run real experiments against an exchange — build a book, cross the spread, provoke a rejection, roll the venue back and try the other branch — entirely through tool calls, with nobody editing code between steps.
Not a real venue: no money, no connectivity, no fees, no latency model.
What MCP is, in one section
The Model Context Protocol is a JSON-RPC 2.0 protocol that lets a model's host application talk to an external process that supplies capabilities.
The server (this repo) is a process that exposes capabilities and answers requests. It never initiates work.
The client (Claude Code, MCP Inspector, your own script) launches the server and drives it.
Under the stdio transport, the client spawns the server as a subprocess and speaks JSON-RPC over its stdin and stdout. No ports, no auth, no CORS, and the process lives exactly as long as the client session. That is why it is the default for local tools — and why stdout is the wire: a stray
print()corrupts the protocol. Every log line in this server goes to stderr.The initialize handshake is the first exchange: the client sends its protocol version and capabilities, the server replies with its own plus its name and instructions, and the client confirms with an
initializednotification. Only afterwards may either side send anything else.
A server can expose three kinds of thing, and the distinction is about who decides:
Primitive | Controlled by | In this project |
Tool | the model — a verb it chooses to invoke, possibly with side effects |
|
Resource | the application — a noun addressed by URI that the host may attach to context; read-only by contract |
|
Prompt | the user — a template a person invokes, e.g. a slash command |
|
The book is exposed both as a resource and as a tool, on purpose.
book://AAPL is "attach the current state so the model starts the turn
knowing it"; get_book(symbol, depth) is "the model decided it needs to
look, at a depth it chose, right now". Same data, different control.
Related MCP server: MetaTrader MCP Server
Quick start
git clone https://github.com/pranjalsharma-6/mcp.git && cd mcp
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest -q # 65 tests
python -m evals.demo # a full scripted session
python -m evals.run_eval --mode referenceAdd it to Claude Code
claude mcp add lob -- python -m mcp_server.serveror, in .mcp.json / claude_desktop_config.json:
{
"mcpServers": {
"lob": {
"command": "python",
"args": ["-m", "mcp_server.server"],
"cwd": "/absolute/path/to/mcp",
"env": { "PYTHONPATH": "/absolute/path/to/mcp", "LOB_SEED": "0" }
}
}
}Read-only: add "LOB_READ_ONLY": "1" to env, or pass --read-only.
Debug with MCP Inspector
npx @modelcontextprotocol/inspector python -m mcp_server.serverInspector opens a browser UI that performs the handshake and lets you list and call tools by hand, with the raw JSON-RPC visible. Use it before wiring the server into a model — it separates "my tool is broken" from "the model called it wrong", which are very different bugs.
Debugging notes. The server logs to stderr at INFO; if the client shows
nothing at all, run the command by hand and check it starts. If the handshake
succeeds but every call fails, you almost certainly have a PYTHONPATH
problem, since the client's working directory is not yours. If the handshake
itself fails, suspect something writing to stdout.
Tool surface
Read (always registered)
Tool | Signature | Notes |
|
| Aggregated levels, best first. Depth capped at 20; truncation is announced in the output. |
|
| Status, filled/remaining, trade ids. |
|
| Page forward with |
|
| Symbols and their tick/lot rules, spreads, volume, rejection tally. |
Mutating (registered only when not read-only)
Tool | Signature | Notes |
|
| Idempotent on |
|
| Idempotent: re-cancelling returns |
|
| Reports whether queue priority was kept or lost. |
|
| Destructive. Clears book, tape and the id ledger. |
|
| Named starting books. No args lists them. |
|
| Returns a snapshot id. |
|
| No args lists available snapshots. |
Resources
docs://matching-rules · book://{symbol} · tape://{symbol}
Prompts
explain_order(order_ref) — trace one order's life from the tape.
stress_book(symbol) — systematic edge cases, report anomalies. Withheld in
read-only mode, since it instructs the model to submit orders.
Agent-facing API design notes
The surface is designed for a language model, not a browser. That changes things.
Output is bounded, and truncation announces itself
get_book returns top-N levels, capped at 20; get_trades caps at 100. Every
truncated response ends with a line saying what was withheld and which
argument reveals more:
[showing depth 3: 2 more bid level(s), 2 more ask level(s) not shown. raise `depth` (max 20) to see them]Without that line, a model shown 3 of 12 levels will state, confidently and wrongly, that the book is 3 deep. Silent truncation is worse than a small window.
Every result carries text and structure
Tools return both a compact text rendering and structuredContent. The text
is what the model skims; the JSON is what code indexes. Columns are aligned
because alignment is what lets a model compare adjacent levels without doing
arithmetic:
BOOK AAPL seq=10 bid=99.99 ask=100.01 spread=0.02
BIDS | ASKS
-------------------------------------------------------
99.99 500 (1) | 100.01 300 (1)
99.98 1200 (1) | 100.02 900 (1)Rejections are data, not exceptions
{
"status": "REJECTED",
"reason": "TICK_SIZE_VIOLATION",
"message": "price 100.005 has more decimal places than AAPL supports (price_scale=2)",
"field": "price",
"suggestion": "round to 2 decimals, e.g. 100.00",
"suggested_value": "100.00"
}isError is deliberately not set. isError means "the tool
malfunctioned" — a client may retry it, log it as a fault or hide it. A
tick-size violation is not a malfunction; it is the correct answer to an
incorrect order, and the model has to read it and adapt.
suggested_value exists because of a finding from the evals: recovering from
a rejection used to require float(suggestion.split()[-1]), pulling a number
out of an English sentence. The prose is for the reader; the value is for the
retry.
Two failure classes, kept distinct
A schema violation (negative qty, side="SIDEWAYS") never reaches the
engine — the MCP layer rejects it and it surfaces as isError. A venue
rejection is a well-formed call the exchange declines, and comes back as an
ordinary result. Keeping these apart is what lets a model tell "I called the
tool wrong" from "the venue said no".
Anything expressible in the JSON Schema lives there, because the model reads the schema before calling — a constraint stated in the schema costs zero tool calls, the same constraint discovered through a rejection costs a round trip.
Idempotency, and the failure mode it prevents
submit_order takes a caller-supplied client_order_id. The server
stores the result of the first call bearing each id; a repeat returns that
stored result marked DUPLICATE and creates nothing.
This is not the HTTP retry story. In HTTP, retries come from network layers you control. Here the retry comes from the model, and models retry on ambiguity, not just on error: the result was truncated, the turn was interrupted, or the plan step "submit the buy" got re-read after context was compacted. Without an id, that retry is a second real order and you have bought 200 instead of 100 — and the model is now reasoning about a book that does not exist, so every conclusion afterwards is wrong, silently.
The id must be model-supplied. A server-generated id cannot deduplicate a call whose response the caller never saw.
Two consequences worth knowing:
A rejected submit also consumes its id. Retrying the identical wrong call is therefore always safe, and a corrected order is forced to be a genuinely new order.
Reusing an id for a different order silently returns the old result. That is the sharp edge of the design; the tool description says so explicitly and
test_a_different_order_under_a_reused_id_is_not_submittedpins it.
cancel_order takes the other route to idempotency: cancelling an
already-cancelled order returns NOOP, not a rejection, so a model can reach
a known state without first working out whether its earlier cancel landed.
Read-only mode unregisters rather than refuses
With LOB_READ_ONLY=1 the mutating tools are not registered. They are
absent from tools/list — 11 tools become 4.
Refusing at call time is the weaker design:
A registered tool is in the model's context. It plans with it, calls it, reads the refusal, and retries with different arguments — because refusals read like "you did that wrong", not "this is impossible". You pay tokens and turns litigating something that was never negotiable.
An unregistered tool cannot be planned with at all. The model sees a read-only venue at handshake time and builds a read-only plan from its first move. Constraints are cheapest when visible before planning.
Authorisation by absence of a code path beats authorisation by an
if. There is no branch to get wrong and no future refactor that moves the check after the mutation.
The cost: flipping the flag needs a restart, since clients cache tools/list
after the handshake. For a per-process stdio server that is the right trade.
Tool descriptions are prompts
Every mutating tool's description ends with an explicit Side effects: block,
enforced by a test. A model plans by reading descriptions, and a tool whose
description does not say it mutates shared state will be called
speculatively, mid-plan, to "check" something.
The descriptions also carry the non-obvious semantics. modify_order spends a
paragraph on queue priority — that a price change or size increase re-queues
the order at the back of its level while a size reduction keeps its place —
because a model will otherwise treat modify as free.
Determinism
Nothing reads a clock or an unseeded random source. Events are ordered by a
monotonic integer seq, order ids come from a counter, and money is integer
ticks internally with decimals only at the render boundary — float prices
produce fills off by 1e-13 and comparisons that flip with operand order, which
would quietly destroy reproducibility. take_snapshot / restore_snapshot
round-trip the whole mutable state, so two experiment arms can start from an
identical book rather than a reconstructed one.
test_the_same_call_sequence_replays_identically asserts it.
Layout
engine/ pure Python matching engine. No MCP imports.
types.py Order, Trade, Side, TIF, SymbolSpec, tick arithmetic
book.py price levels, FIFO queues
engine.py matching loop, validation, snapshot/restore
errors.py structured rejections
mcp_server/
server.py registration, READ_ONLY gate, transport bootstrap
tools_read.py always registered
tools_write.py registered only when not read-only
resources.py book, tape, matching-rules doc
prompts.py explain_order, stress_book
render.py the LLM-facing formatting layer
schemas.py pydantic models -> published JSON Schema
config.py get_engine(session_id) indirection
tests/ 65 tests, driven through the MCP client SDK
evals/ 4 tasks, graders, reference solutions, demo
docs/ matching rules, captured demo sessionThe engine never imports MCP, and the tool layer never imports the transport.
build_server() assembles capabilities; main() picks stdio. Adding
streamable-HTTP is a change to main() plus handing get_engine() a real
session id instead of a constant — no tool changes. That indirection exists
from day one because the thing HTTP actually breaks is state scope: stdio
means one engine per process, HTTP means many clients sharing one.
Tests
pytest -q # 65 passedTests drive the server through the real MCP client SDK, not by calling
tool functions, so schema validation, result serialisation and the handshake
are all exercised. test_stdio.py additionally runs the server as a real
subprocess over stdio — the only way to catch a stray write to stdout.
Two bugs the suite caught while being written:
Retrying a submit that was rejected the first time crashed, because the duplicate path assumed a stored order existed. Precisely the case the design promises is safe.
Float representation error (
99.99 - 0.02 == 99.97000000000001) was rejected as sub-tick. Now absorbed, while a genuine sub-tick price like100.005still rejects.
Evals
python -m evals.run_eval --mode reference # 4/4
python -m evals.run_eval --mode model # needs ANTHROPIC_API_KEYFour tasks with programmatic graders that read the tool-call log and engine
state, never the model's prose as evidence of what it did. idempotent_retry
fails a run where every submit used a distinct id even if the final volume is
correct — getting the right answer by luck is not passing.
Reference mode passes 4/4. The model-in-the-loop run has not been
performed — the environment this was built in has no API key — and that is
the mode that actually answers whether the descriptions are unambiguous, since
a scripted solution never reads them. See
evals/FINDINGS.md for the two ambiguities that writing
the reference solutions exposed, both since fixed, and for the description most
likely to fail a real run.
Demo
docs/demo_session.txt is a captured 13-step session:
learn the venue, build a book, get rejected twice and recover, snapshot, sweep
the offers, retry the same id without double-filling, roll back. Regenerate it
with python -m evals.demo.
It is a scripted session, not a recording of Claude driving the exchange —
same tool calls, same real responses, but the driver is a script. A recording
of a model needs --mode model with an API key.
Available Tools
11 toolscancel_orderCancel orderADestructiveIdempotent
Remove an order's remaining quantity from the book. Already-filled quantity is not undone -- a cancel only affects what has not traded yet.
Identify the order by EITHER order_id OR client_order_id.
Safe to retry: cancelling an order that is already cancelled or filled returns status NOOP, not a rejection, so you can reach a known state without first working out whether your earlier cancel landed.
Side effects: MUTATES the book. Removes resting liquidity, which widens the spread or empties a level. Never creates trades.
Inputs: order_id, client_order_id.
get_bookGet order bookARead-onlyIdempotent
Show the top price levels of one symbol's order book, best price first.
Returns aggregated levels, not individual orders: each row is a price with the total resting quantity there and how many orders are queued at it. Use get_order to inspect a specific order.
Output is deliberately bounded. If levels exist beyond depth the response says so explicitly -- do not assume the book ends where the listing ends.
Prices come back as decimal STRINGS ('100.01'), exactly as the venue quotes them. Pass them straight back to submit_order or modify_order unchanged -- those tools accept a string price, and doing so avoids introducing floating-point error.
Side effects: none. Reading the book never changes it.
Inputs: symbol (required), depth.
get_orderGet orderARead-onlyIdempotent
Look up one order's current state: status, how much filled, how much remains, whether it is still resting on the book, and the ids of the trades it took part in.
Identify the order by EITHER order_id (the venue's id, like 'O7') OR client_order_id (the id you supplied when submitting). Supply at least one.
This is the tool to use after a submit whose result you did not see -- it tells you what actually happened without changing anything.
Side effects: none.
Inputs: order_id, client_order_id.
get_statsGet venue statsARead-onlyIdempotent
Venue-wide summary: which symbols exist and their trading rules, best bid/ask and spread per symbol, resting depth, traded volume, and a tally of how many orders were rejected for each reason.
Call this first in a fresh session -- it is the cheapest way to learn what is tradable and what the tick and lot sizes are before you submit anything.
Side effects: none.
Inputs: symbol.
get_tradesGet trade tapeARead-onlyIdempotent
Read the trade tape: executions in the order they happened.
Page through it with since_seq: pass 0 for the beginning, then pass the seq of the last trade you saw to get only what is new. The response tells you when it truncated and which since_seq to use next.
Trades print at the MAKER's resting price, not the aggressor's limit. An order that crosses with a generous limit still pays only the prices already on the book.
Side effects: none.
Inputs: limit, symbol, since_seq.
load_scenarioLoad scenarioADestructive
Build a known starting book in one call, by replaying a fixed list of orders through the normal submit path. Use this instead of hand-placing ten orders when you want a reproducible starting point.
Call with no arguments to list the available scenarios and what each one is for.
Scenarios are deterministic: the same name on a freshly reset book always produces the same levels and the same sequence numbers.
Side effects: MUTATES the book. Resets the target symbol first, then submits the scenario's orders. Any existing orders on that symbol are destroyed.
Inputs: name, symbol.
modify_orderModify orderADestructive
Change a resting order's price and/or quantity in place.
QUEUE PRIORITY -- this is the part that surprises people. Orders at the same price are filled in arrival order. Changing the PRICE, or INCREASING the quantity, re-queues the order at the BACK of its price level: you lose your place to everyone already there. Only REDUCING the quantity keeps your position. The response states which happened.
A modify that moves the price across the spread will match immediately, exactly as a new order would.
Side effects: MUTATES the book. May create trades. May lose queue priority irreversibly -- restoring the old price does NOT restore the old position.
Inputs: new_qty, order_id, new_price, client_order_id.
reset_bookReset bookADestructiveIdempotent
Wipe state and start clean. Removes all resting orders, clears the trade tape, forgets every client_order_id, and restarts the sequence counter.
Pass symbol to clear one instrument only; omit it to clear everything and reseed the engine. Use this between independent experiments so results are comparable.
Side effects: DESTRUCTIVE and irreversible. Everything not captured in a snapshot is gone, including the tape you may still want to read. Take a snapshot first if you might need the old state.
Inputs: seed, symbol.
restore_snapshotRestore snapshotADestructiveIdempotent
Roll the entire engine back to a previous snapshot. Book, resting orders, trade tape and sequence counter all return to exactly what they were.
Call with no snapshot_id to list what is available.
Side effects: DESTRUCTIVE to current state -- everything that happened after the snapshot is discarded, including trades. Snapshot ids are never reused, so the snapshot you restore from stays valid and you can restore it repeatedly.
Inputs: snapshot_id.
submit_orderSubmit orderADestructiveIdempotent
Submit a new order to the matching engine. It matches immediately against resting liquidity on the opposite side, and whatever does not trade either rests on the book or is cancelled back, depending on tif.
IDEMPOTENCY -- read this before retrying anything. You choose client_order_id. The server remembers the result of the first call carrying each id. If you call again with the same id, you get that ORIGINAL result back, marked duplicate, and no second order is created and nothing extra is matched. So: if a submit's outcome was lost or you are unsure whether it went through, RETRY WITH THE SAME id -- that is safe and it tells you what happened. Use a NEW id only for a genuinely different order. Reusing an id for a different order will NOT submit it; you will silently get the old result.
Rejections come back as data, not errors: a reason code, the offending field, a suggestion in words, and suggested_value -- a value you can drop straight into that field and retry, with no parsing. Read it and retry with a FRESH client_order_id (the rejected one is spent).
Side effects: MUTATES the book. May create trades, may consume other orders' resting quantity, advances the sequence number, and appends to the trade tape. Not reversible except via restore_snapshot or reset_book.
Inputs: qty (required), side (required), symbol (required), order_type (required), +3 more.
take_snapshotTake snapshotA
Freeze the complete engine state -- book, orders, tape, sequence counter, client_order_id ledger -- and get back a snapshot id.
This is how you run a controlled experiment: snapshot, try something, restore, try the alternative, and compare against an identical starting point rather than a reconstructed one.
Side effects: does not change the book. Adds to the server's snapshot store, which lives in memory and dies with the process.
Inputs: label.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
Each tool maps to one distinct action or query: order lifecycle, market data, and state management are cleanly separated, and even the reset/snapshot tools are differentiated by their intended use (wipe vs. reproducible starting point vs. rollback). No two tools appear to do the same thing.
All tools use a consistent snake_case verb_noun pattern: get_* for read-only queries, submit/cancel/modify_order for order mutations, and reset/load/take/restore for state management. This makes the set predictable and easy for an agent to select from.
11 tools is a well-scoped count for a limit-order-book control server: no bloat, and every tool serves a distinct operational need covering order entry, cancellation, modification, data reads, and state management.
The set covers the full order lifecycle (submit/get/cancel/modify), comprehensive market-data reads (book, trades, stats), and thorough state management (reset, scenario loading, snapshot/restore). There are no obvious dead ends: actions can be queried, reversed, or reproduced.
Maintenance
Related MCP Connectors
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
Place and inspect orders on your own exchange accounts from an MCP-connected agent.
MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents
Live prices, perps, prediction markets and a paper trading desk over one MCP.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to interact with Interactive Brokers through 48 tools for market data, orders, account management, and more, via the MCP protocol.MIT
- FlicenseNot gradedqualityDmaintenanceEnables LLMs to trade on MetaTrader 5 via REST API or MCP tools, supporting market/pending orders, position management, and account info retrieval.-
- FlicenseNot gradedqualityCmaintenanceEnables agents to access live crypto market data and execute risk-controlled paper trades through standardized MCP tool calls.-
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to discover trading domains, inspect bots, backtest and submit crypto trading strategies for validation and live deployment, and monitor tournament and leaderboard status via MCP tools.9MIT