Skip to main content
Glama
lockout-mcp

lockout-mcp

README.md
<p align="center">
  <img src=".github/lockout.png" width="880" alt="lockout. Same lock bit for you and your agent. A silicon die in cross-section: the agent's bus, from lockout-mcp, and the owner's bus run into the same row of 21 buy() gates and stop at gate 03, AccountHalted(), with gate 05 latched beside it. Below them only the owner's sell bus runs on, through gates 06, 07, 09 and 20, to the exit pad.">
</p>

<h3 align="center">Let your agent trade, and keep the limits in the contract it trades through.</h3>

<p align="center">
  <a href="https://repo.sourcify.dev/4663/0xeAD444A07f59C89Fb4454F28854245D5D8E1f456"><img alt="sourcify" src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsourcify.dev%2Fserver%2Fv2%2Fcontract%2F4663%2F0xeAD444A07f59C89Fb4454F28854245D5D8E1f456&query=%24.match&label=sourcify&style=flat&labelColor=07050d&color=b8924a"></a>
  <a href="https://www.npmjs.com/package/lockout-mcp"><img alt="npm lockout-mcp" src="https://img.shields.io/npm/v/lockout-mcp?style=flat&labelColor=07050d&color=b8924a"></a>
  <a href="LICENSE"><img alt="license MIT" src="https://img.shields.io/badge/license-MIT-2a2150?style=flat&labelColor=07050d"></a>
</p>

<p align="center">
  <a href="https://lockout.exchange">Site</a> ·
  <a href="https://lockout.exchange/#sessions">Bench</a> ·
  <a href="https://lockout.exchange/#datasheet">Datasheet</a> ·
  <a href="https://www.npmjs.com/package/lockout-mcp">npm</a> ·
  <a href="https://glama.ai/mcp/servers/lockoutgate/lockout">Glama</a> ·
  <a href="#verify-the-bytes">Verify the bytes</a>
</p>

lockout is a stock-token account on Robinhood Chain for an owner who lets an AI agent trade. Before a session the owner calls `seal()` with ten rules, a bell (`unlockAt`) and a $LOCKOUT bond. Until the bell the rules only tighten, and every buy, the agent's or the owner's own, goes through the same `buy()` and its 21 gates. The buy that meets the loss limit trades nothing and halts the account; from then until the bell every buy reverts, while the account can still sell: the owner's sells under four checks, the agent's inside the feed band. `contracts/` holds the factory, the account and a read-only Lens. `mcp/` is `lockout-mcp`, the MCP server that gives an agent seven tools on one account.

```sh
rpc=https://rpc.mainnet.chain.robinhood.com
# the bond floor: $LOCKOUT base units per day sealed
cast call 0xeAD444A07f59C89Fb4454F28854245D5D8E1f456 'minBondPerDay()(uint256)' --rpc-url $rpc
# each listed stock: its feed, its pools, the chain's gates on it now, and whether an agent may buy or sell it
cast call 0xfbCAcd8748a473a4778a43B1bCd2dB3B563daA42 'markets()((address,address,bytes32[],(bool,bool,bool,bool,bool,bool,bool,uint256,uint256),bool,bool)[])' --rpc-url $rpc
```

## Contracts

Robinhood Chain, chain id `4663`, deployed in block `123592326`.

| Contract | Address | Source |
|---|---|---|
| `LockoutFactory` | `0xeAD444A07f59C89Fb4454F28854245D5D8E1f456` | [`LockoutFactory.sol`](contracts/src/LockoutFactory.sol) |
| `LockoutAccount` implementation | `0x451725A29F3Fa20d075CC171991b746d3406A757` | [`LockoutAccount.sol`](contracts/src/LockoutAccount.sol) |
| `LockoutLens` | `0xfbCAcd8748a473a4778a43B1bCd2dB3B563daA42` | [`LockoutLens.sol`](contracts/src/LockoutLens.sol) |

[`createAccount(agent)`](contracts/src/LockoutFactory.sol#L80-L86) clones the implementation (OpenZeppelin `Clones`) for the caller, who becomes the account's owner, and names the agent key; the agent cannot be the owner. The factory keeps the lists every account reads live: listed stocks, their USDG pools on Uniswap v3, MetaDEX and Uniswap v4, one Chainlink feed per stock, the bond token and its per-day floor. Its `usdg`, `registry`, `accountImplementation` and the three venue addresses are immutable. The account enforces the rules. The Lens only reads: [`previewBuy` and `previewSell`](contracts/src/LockoutLens.sol#L78-L115) run the account's own `simulateBuy` and `simulateSell` and return the gate that would stop an order, and [`accountState`](contracts/src/LockoutLens.sol#L131) and [`markets`](contracts/src/LockoutLens.sol#L210-L217) gather a page's or an agent's reads into one call. Nothing upgrades, and the factory owner has no function that reaches into an account.

## The seal

[`seal(rules, unlockAt, bond)`](contracts/src/LockoutAccount.sol#L171-L204) opens a session:

```solidity
function seal(Rules calldata next, uint64 bell, uint256 bond) external locked onlyOwner {
    if (sealed_) revert AlreadySealed();
    address token = factory.token();
    if (token == address(0)) revert TokenNotSet();
    if (bell < block.timestamp + MIN_SEAL_DURATION || bell > block.timestamp + MAX_SEAL_DURATION) {
        revert BadDuration();
    }
    if (next.maxDailyLossUsdg == 0 || next.maxPerTradeUsdg == 0 || next.maxOpenCostBasisUsdg == 0) {
        revert ZeroLimit();
    }
    if (next.maxDailyLossUsdg > uint256(type(int256).max)) revert LimitTooLarge();
    if (next.maxSlippageBps > MarketChecks.BPS) revert RuleOutOfRange();
    uint256 required = factory.minBondPerDay() * Math.ceilDiv(bell - block.timestamp, 1 days);
    if (bond < required) revert InsufficientBond(bond, required);
    uint256 received = _receive(IERC20(token), bond);
    if (received < required) revert InsufficientBond(received, required);
    ...
}
```

- The bell is at least `MIN_SEAL_DURATION` (1 hours) and at most `MAX_SEAL_DURATION` (7 days) away.
- The bond is `minBondPerDay × ceil((unlockAt − now) / 1 day)` in $LOCKOUT, counted as the balance the account actually received.
- The session uses the feeds the factory had set when it was sealed; a feed set later counts from the next session ([`sessionFeed`](contracts/src/LockoutAccount.sol#L521-L525)).
- While sealed, [`setAgent`](contracts/src/LockoutAccount.sol#L164-L169) can only clear the agent, never name a new one.

The ten rules, and what [`tighten(rules)`](contracts/src/LockoutAccount.sol#L206-L224) accepts while sealed. Anything else reverts with `CannotLoosenWhileSealed()`, and every accepted call runs the halt check at once.

| Rule | Limits | 0 means | `tighten()` accepts |
|---|---|---|---|
| `maxDailyLossUsdg` | realized loss plus the open positions' mark loss, net of realized gains | refused by `seal` (`ZeroLimit()`) | equal or lower |
| `maxPerTradeUsdg` | USDG spent in one buy | refused (`ZeroLimit()`) | equal or lower |
| `maxOpenCostBasisUsdg` | cost basis of everything held | refused (`ZeroLimit()`) | equal or lower |
| `maxConsecutiveLosses` | losing sells in a row before the halt | off | switched on, or lower; never back to 0 |
| `maxTradesPerSession` | buys in the session; the last one halts | off | switched on, or lower; never back to 0 |
| `cooldownSec` | pause on buys after a losing sell | no pause | equal or longer |
| `maxFeedAgeSec` | oldest feed answer a buy accepts | no limit on owner buys; the agent's is 90,000 s | switched on, or lower; never back to 0 |
| `maxSlippageBps` | fill against the feed price, at most 10,000 | no band, and the agent cannot trade | equal or lower, never 0 |
| `requireLiveFeed` | a buy of a stock that has a feed needs that feed live | | switched on, never off |
| `blockOutsideMintWindow` | buys only from Monday 02:00 to Saturday 02:00 Central European time ([`MintWindow.isOutside`](contracts/src/lib/MintWindow.sol#L37-L40), CET or CEST) | | switched on, never off |

## Gates

Every buy runs [`_buy`](contracts/src/LockoutAccount.sol#L341-L370) and [`_buyOrderChecks`](contracts/src/LockoutAccount.sol#L372-L403): 21 gates, the owner's buys and the agent's alike, in this order: 01 to 05, 06 to 19, the swap, then 20 and 21. Gate 13 applies only to the agent key. A failing gate reverts with its error. The numbers are the `@gate` tags in the source and [`contracts/gate-lines.json`](contracts/gate-lines.json).

| Gate | Stops when | Error | Line |
|---|---|---|---|
| 01 | `!sealed_` | `NotSealed()` | [345](contracts/src/LockoutAccount.sol#L345) |
| 02 | `now >= unlockAt` | `SessionEnded()` | [347](contracts/src/LockoutAccount.sol#L347) |
| 03 | `halted \|\| sessionBroken` | `AccountHalted()` | [348](contracts/src/LockoutAccount.sol#L348) |
| 04 | `trade count reached cap` | `AccountHalted()` | [350](contracts/src/LockoutAccount.sol#L350) |
| 05 | `MTM loss reached limit or held mark unavailable` | the latch, or `MarkUnavailable(address)` | [354](contracts/src/LockoutAccount.sol#L354-L357), [360](contracts/src/LockoutAccount.sol#L360) |
| 06 | `usdgIn == 0` | `ZeroAmount()` | [376](contracts/src/LockoutAccount.sol#L376) |
| 07 | `usdgIn > trackedUsdg` | `InsufficientTracked()` | [377](contracts/src/LockoutAccount.sol#L377) |
| 08 | `!isListed(stock)` | `AssetNotListed(address)` | [378](contracts/src/LockoutAccount.sol#L378) |
| 09 | `pool.stock != stock` | `PoolNotListed(address,bytes32)` | [380](contracts/src/LockoutAccount.sol#L380) |
| 10 | `now < cooldownUntil` | `CooldownActive(uint64)` | [382](contracts/src/LockoutAccount.sol#L382) |
| 11 | `usdgIn > maxPerTradeUsdg` | `OverPerTradeCap()` | [383](contracts/src/LockoutAccount.sol#L383) |
| 12 | `open cost + usdgIn > maxOpenCostBasisUsdg` | `OverOpenCostCap()` | [386](contracts/src/LockoutAccount.sol#L386) |
| 13 | `agent without eligible live feed` | `AgentNeedsLiveFeed(address)` | [390](contracts/src/LockoutAccount.sol#L390) |
| 14 | `stock.paused()` | `TokenPaused(address)` | [392](contracts/src/LockoutAccount.sol#L392) |
| 15 | `stock.oraclePaused()` | `OracleFlagged(address)` | [394](contracts/src/LockoutAccount.sol#L394) |
| 16 | `registry.isBlocked(account)` | `AccountBlocked()` | [396](contracts/src/LockoutAccount.sol#L396) |
| 17 | `mint window required and outside` | `OutsideMintWindow()` | [398](contracts/src/LockoutAccount.sol#L398) |
| 18 | `required feed missing or stale` | `FeedRequiredOrStale(address,uint256)` | [400](contracts/src/LockoutAccount.sol#L400) |
| 19 | `no feed && minSharesOut == 0` | `MinOutNotMet()` | [402](contracts/src/LockoutAccount.sol#L402) |
| 20 | `sharesOut == 0 \|\| sharesOut < minSharesOut` | `MinOutNotMet()` | [365](contracts/src/LockoutAccount.sol#L365) |
| 21 | `fill above feed band` | `SlippageVsFeedExceeded()` | [368](contracts/src/LockoutAccount.sol#L368) |

Gate 05 has two outcomes. If the effective loss has reached `maxDailyLossUsdg`, the buy does not revert: it latches the halt and returns with nothing bought (next section). Otherwise, if a held stock's feed cannot be read, the buy reverts with `MarkUnavailable(address)`.

The agent key's buys and sells also need, for that stock ([`agentEligible`](contracts/src/lib/MarketChecks.sol#L31-L35)): a feed answer no older than `maxFeedAgeSec`, capped at `AGENT_MAX_FEED_AGE` (90,000 s, which also stands in for 0); the token's oracle not paused; and `maxSlippageBps` above 0. So the agent cannot trade a stock that has no feed.

A sell runs [`_sell`](contracts/src/LockoutAccount.sol#L419-L445): seven gates. The owner's sells meet four of them: an amount, a tracked balance, a listed pool and the owner's own minimum. The agent's meet all seven: a sealed session, a live feed and a fill inside `maxSlippageBps` of the feed price.

| Gate | Stops when | Error | Line | Owner's sells |
|---|---|---|---|---|
| 01 | `sharesIn == 0` | `ZeroAmount()` | [424](contracts/src/LockoutAccount.sol#L424) | yes |
| 02 | `sharesIn > trackedShares` | `InsufficientTracked()` | [425](contracts/src/LockoutAccount.sol#L425) | yes |
| 03 | `pool.stock != stock` | `PoolNotListed(address,bytes32)` | [427](contracts/src/LockoutAccount.sol#L427) | yes |
| 04 | `agent && !sealed_` | `NotSealed()` | [428](contracts/src/LockoutAccount.sol#L428) | no |
| 05 | `agent without eligible live feed or a carried mark is pending` | `AgentNeedsLiveFeed(address)` | [435](contracts/src/LockoutAccount.sol#L435) | no |
| 06 | `usdgOut < minUsdgOut` | `MinOutNotMet()` | [440](contracts/src/LockoutAccount.sol#L440) | yes |
| 07 | `agent fill below feed band` | `SlippageVsFeedExceeded()` | [442](contracts/src/LockoutAccount.sol#L442) | no |

## The latch

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/readme/fig1-session-dark.svg">
    <img src=".github/readme/fig1-session-light.svg" width="880" alt="FIG. 1. One session as a timing diagram, one row each for the owner, the agent key, the account's sealed_, halted and cooldownUntil, the bond, and anyone. seal() raises sealed_ and takes the bond. Owner and agent buys pass. An agent sell at a loss raises cooldownUntil for cooldownSec, and an agent buy inside it reverts at gate 10. The agent's next buy meets the loss limit: gate 05, no fill, LockoutTriggered, and halted goes high. After that the agent's buy and the owner's buy both revert at gate 03, while an owner sell and an agent sell still go through. anyone can call tripIfBreached() during the session. At unlockAt, the bell, anyone calls release(): sealed_ and halted fall and the bond goes back to the owner. A dashed mark shows the other way out: emergencyWithdraw() before the bell, which burns the bond.">
  </picture>
</p>

<sub>FIG. 1. One session, from the state changes in `LockoutAccount.sol`. A diagram of the rules: the spacing is not to scale and it shows no amounts.</sub>

The loss check runs inside every buy, ahead of the order's own gates ([`L352-L357`](contracts/src/LockoutAccount.sol#L352-L357)):

```solidity
address unavailable = _rebasePending();
Mark memory mark = _marks();
if (_effectiveLoss(mark.unrealized) >= rules.maxDailyLossUsdg) {
    _halt(REASON_MTM_LOSS, mark.unrealized);
    return (0, 0, REASON_MTM_LOSS);
}
```

- The effective loss is the open positions' loss at their feed prices plus any realized loss, less any realized gain ([`_effectiveLoss`](contracts/src/LockoutAccount.sol#L608-L617)).
- The buy that finds it at the limit trades nothing. Its transaction succeeds, sets `halted` and emits `LockoutTriggered(sessionId, 2, …)`.
- From then until the bell every buy, the owner's included, stops at gate 03 with `AccountHalted()`. Nothing clears `halted` before `release()`.
- The same check runs after every trade and every `tighten()` ([`_trip`](contracts/src/LockoutAccount.sol#L619-L627)). Its reasons: realized loss at the limit (1), effective loss at the limit (2), `maxConsecutiveLosses` losing sells in a row (3), `maxTradesPerSession` buys (4). The owner can halt by hand with `manualHalt()` (5); `emergencyWithdraw()` halts with 6.
- [`tripIfBreached()`](contracts/src/LockoutAccount.sol#L236-L241) lets anyone run that check, so a breach left by a price move alone is recorded without waiting for the next trade.

## Ending a session

After the bell anyone can call [`release()`](contracts/src/LockoutAccount.sol#L243-L255). The session ends, `halted` clears, and the bond goes back to the owner in full, whether or not the account halted.

Before the bell the owner's only way out is [`emergencyWithdraw(token, amount)`](contracts/src/LockoutAccount.sol#L262-L280):

```solidity
if (!sessionBroken) {
    uint256 amountToBurn = bondAmount;
    bondAmount = 0;
    sessionBroken = true;
    uint256 supply = IERC20(bondToken).totalSupply();
    IBurnable(bondToken).burn(amountToBurn);
    uint256 remaining = IERC20(bondToken).totalSupply();
    if (remaining > supply || supply - remaining != amountToBurn) revert BurnNotVerified();
    emit SessionBrokenAndBurned(sessionId, amountToBurn);
    _halt(REASON_EMERGENCY_BROKEN, _marks().unrealized);
}
_withdraw(token, amount);
```

The first call burns the whole bond with the $LOCKOUT token's own `burn` and reverts unless the total supply fell by exactly that amount. It marks the session broken and halts with reason 6. Later calls before the bell only move funds to the owner. `withdraw` and `sweep` work only outside a session (`SessionNotEnded()` while sealed); `sweep` returns tokens that reached the account outside its ledger.

## Who moves what

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset=".github/readme/fig2-who-dark.svg">
    <img src=".github/readme/fig2-who-light.svg" width="880" alt="FIG. 2. Who can move what in one account. In the middle, LockoutAccount, a clone per owner, holding tracked USDG, tracked stock tokens and the bond in $LOCKOUT, under rules that only tighten. The owner calls seal, tighten, manualHalt, setAgent, depositUsdg, buy and sell, and is the only account paid out: withdraw, sweep, emergencyWithdraw, and the bond on release. The agent key calls buy and sell; anything else reverts with NotOwner(). Anyone calls tripIfBreached, and release after the bell. Tokens move out only in swaps with the listed pools, to the owner, or as a burned bond. The account reads Chainlink feeds and the factory live. The factory owner calls setToken, setMinBondPerDay, listAsset, listPool and setFeedOnce: nothing is ever unlisted, setToken and setFeedOnce work once, the bond floor stays at or under supply / 1000 and rises at most 2x per 24 hours. The Lens only reads and previews.">
  </picture>
</p>

<sub>FIG. 2. From the access checks in `LockoutAccount.sol` and `LockoutFactory.sol`: solid gold arrows move tokens, thin arrows call, dashed arrows read.</sub>

- **Owner** (`onlyOwner`): `depositUsdg`, `seal`, `tighten`, `manualHalt`, `setAgent`, `buy`, `sell`, `emergencyWithdraw`, and outside a session `withdraw` and `sweep`. The account pays out only to the owner.
- **Agent key**: `buy` and `sell`. Every other function reverts with `NotOwner()`, and tokens never move to the agent.
- **Anyone**: `tripIfBreached()`, and `release()` once the bell has passed.
- **Factory owner** (`Ownable2Step`), on the factory only:
  - [`setToken`](contracts/src/LockoutFactory.sol#L88-L101), once: the bond token. The bond floor's cap becomes a thousandth of its supply at that moment.
  - [`setMinBondPerDay`](contracts/src/LockoutFactory.sol#L103-L117): at or under that cap. A raise waits 24 hours after the last raise and at most doubles the floor; a cut takes effect at once. It applies to later seals.
  - [`listAsset`](contracts/src/LockoutFactory.sol#L119-L127), [`setFeedOnce`](contracts/src/LockoutFactory.sol#L129-L133) and [`listPool`](contracts/src/LockoutFactory.sol#L144-L169): an 18-decimal stock, at most one 8-decimal feed for it, and USDG pools on Uniswap v3, MetaDEX, or Uniswap v4 without hooks or a dynamic fee. Nothing is ever unlisted or replaced.

## Agent tools

`mcp/` is `lockout-mcp`, an MCP server over stdio that trades one account with its agent key.
Run `npx -y lockout-mcp init` to create a local agent key and print client setup and a lock page link that fills in the agent address.

```sh
claude mcp add lockout -e LOCKOUT_FACTORY=0xeAD444A07f59C89Fb4454F28854245D5D8E1f456 -e LOCKOUT_LENS=0xfbCAcd8748a473a4778a43B1bCd2dB3B563daA42 \
  -e LOCKOUT_ACCOUNT=<your account> -e LOCKOUT_AGENT_KEY_FILE=<absolute path of the key file> -- npx -y lockout-mcp
```

| Tool | Does |
|---|---|
| `account_status` | Reads the session's rules, balances and lockout state |
| `markets` | Reads listed stocks, pools and feed conditions |
| `quote` | Simulates an order on every listed pool, best output first |
| `preview_buy`, `preview_sell` | Reads the account's verdict on one order, with no transaction |
| `buy`, `sell` | Sends the order with the agent key and reports the verdict from its receipt |

[`config.ts`](mcp/src/config.ts) reads `LOCKOUT_FACTORY`, `LOCKOUT_LENS` and `LOCKOUT_ACCOUNT`; `LOCKOUT_AGENT_KEY_FILE`, an absolute path, is needed only to trade; `LOCKOUT_RPC_URL` replaces the public endpoint. A trade comes back `EXECUTED`, `REJECTED_HALT_LATCHED` or `REJECTED_REVERT`. [`mcp/README.md`](mcp/README.md) covers the settings, FIG. 3 and how to read the three; [`mcp/skill/SKILL.md`](mcp/skill/SKILL.md) is the procedure for the agent.

## Verify the bytes

You need Foundry, Node.js 20 or newer, git, curl and jq.

```sh
bash contracts/script/install-deps.sh          # forge-std and OpenZeppelin at the commits it names
(cd contracts && forge build && forge test --no-match-path 'test/fork/*')
(cd mcp && npm ci && npm test)
```

`forge build` compiles with solc 0.8.35, Cancun, 200 optimizer runs and no IR ([`foundry.toml`](contracts/foundry.toml)). Sourcify holds the verified source of the three contracts; the bytes `forge build` writes are the bytes it recompiled:

```sh
cd contracts
sourcify=https://sourcify.dev/server/v2/contract/4663
forge inspect LockoutAccount deployedBytecode > account.hex
curl -s "$sourcify/0x451725A29F3Fa20d075CC171991b746d3406A757?fields=runtimeBytecode" \
  | jq -r .runtimeBytecode.recompiledBytecode | cmp - account.hex   # silent if equal
curl -s "$sourcify/0xeAD444A07f59C89Fb4454F28854245D5D8E1f456" | jq '{match, runtimeMatch, creationMatch}'
curl -s "$sourcify/0xfbCAcd8748a473a4778a43B1bCd2dB3B563daA42" | jq '{match, runtimeMatch, creationMatch}'
```

`lockout-mcp` is published from this repository by [`publish.yml`](.github/workflows/publish.yml), which runs `npm ci`, the build and the tests before `npm publish --provenance`. The registry keeps the provenance; this prints the repository, workflow and commit a release was built from:

```sh
curl -s "$(npm view lockout-mcp dist.attestations.url)" \
  | jq -r '.attestations[] | select(.predicateType | startswith("https://slsa.dev/provenance")) | .bundle.dsseEnvelope.payload' \
  | base64 -d \
  | jq '.predicate.buildDefinition | {repository: .externalParameters.workflow.repository,
      workflow: .externalParameters.workflow.path, commit: .resolvedDependencies[0].digest.gitCommit}'
```

## What it relies on

| You rely on | For |
|---|---|
| Each listed stock's Chainlink feed | The loss mark, the agent's eligibility and band, and `requireLiveFeed`. While a held stock's feed cannot be read, buys revert at gate 05 and the agent cannot trade that stock. |
| Each stock token's issuer | `paused`, `oraclePaused` and the registry's `isBlocked` (gates 14 to 16). While an issuer pauses its token, it cannot be bought or sold anywhere, here included. |
| The listed pools | Fill prices. The feed band bounds a fill; it never sets one. A MetaDEX pool's swap hook can raise that pool's fee, up to 10% on each side, or refuse its swaps; it cannot move the account's tokens. |
| The factory owner | Which stocks, pools and feeds are listed (only ever added) and the bond floor for later seals |
| `$LOCKOUT`'s `burn` | The emergency burn. The account checks the total supply after the call. |
| Robinhood Chain's sequencer | Block time: the bell, the cooldown, feed age and the mint window are all measured against it |

## License

MIT