botanary-mcp
v0.10.4
Published
Botanary's local MCP server for an outside coding agent (Claude Code, Codex, Cursor, or a custom build): an AGENT LANE that generates its own signing key and spends unattended under whatever grant its owner gave it, and a WALLET LANE that lets the human o
Maintainers
Readme
botanary-mcp
A local MCP server that lets an outside coding agent - Claude Code, Codex, Cursor, or something you wrote yourself - act on a Botanary account. It has two lanes, backed by two independent credentials:
- The agent lane. This machine holds its own secp256k1 signing key, proves who it is, pairs with a Botanary account, reads its balance, and spends unattended under whatever grant its owner gave it - all without Botanary ever holding, seeing, or backing up that key.
- The wallet lane. The human owner logs in through their own browser (
wallet_login) - the same provider consent they already use - and this machine holds an opaque, revocable session that can read and build on the owner's behalf, but can never sign as the owner. Every owner-authorized money movement ends in a signature the owner makes themselves, in their own browser, against their own embedded wallet.
These are independent credentials that can point at different Botanary accounts. The agent key is
paired to whatever account its owner paired it to; the wallet session operates on whatever account was
picked at login. Nothing forces them to agree - wallet_status prints both bindings side by side and
flags a mismatch as a first-class finding, and wallet_send's own lane arbitration (below) refuses to
let a mandate on one account authorize a spend on the other, no matter how "helpful" that would be.
Full documentation: https://docs.botanary.xyz/mcp - install recipes per client, the two lanes, the trust model, and a tool reference generated from this package.
Tools
botanary-mcp advertises a subset of its tools at any moment - a small starter set when nothing is
logged in yet, the wallet tools once wallet_login succeeds, the agent tools once this machine has a
local identity - and pushes notifications/tools/list_changed when that set changes. This is a listing
optimization, not a security boundary: every tool below is always reachable by name, and a hidden one
called anyway answers honestly ("log in first") rather than pretending not to exist. See "Why the
advertised tool list changes" further down.
Agent lane (this machine acting as a connected agent, under a grant)
| Tool | What it does |
|---|---|
| diagnose | START HERE when anything is unclear or an action failed. Single call answers: who is this agent bound to, is the account funded on the grant's chain, is that chain usable, and what - ranked - is blocking the next action. Read-only: never signs or mutates. |
| get_identity | Reports this agent's address/public key/fingerprint. Generates the key on first call. No network call. |
| get_pairing_code / regenerate_pairing_code | Shows (or rotates) the short code the owner enters under "Connected agents", registers it with the backend so their claim can find it, and opens their browser on that screen with the code already filled in - once per code, and never for a code the backend could not register. open: false suppresses the browser; wait: false returns the code without blocking on the claim. |
| pair | Signs the pairing code and submits the proof to POST /agents/pair. |
| whoami | Calls GET /agents/me - this agent's own identity, account, and live grant (or an honest grant: null). |
| get_balance | Calls GET /balance under this agent's session. |
| list_requests | Calls GET /agents/requests - every approval request this agent has filed and the owner's verdict on each. The read half of request_approval. |
| list_chains | Calls GET /chains - every chain this backend serves, each with the chainTier that decides what it can do. |
| get_gas_methods | Calls GET /gas/methods - only the gas methods available for this account on a chain (the backend filters out unavailable ones). |
| get_account | Calls GET /account - the ONE account this agent is bound to and its address and deployment status. |
| propose_payment | Reads the grant's bounds first; refuses honestly (citing the backend's own numbers) when there is none or the amount is out of bounds; otherwise builds against THIS agent's own grant id (POST /delegations/{delegationId}/actions - the session-key-validatable lane, never the owner-lane /money/send/build) and relays (POST /userops) signed with the grant's own session key. |
| propose_swap | The same shape as propose_payment, over a grant's SECOND on-chain action (executeUnderGrantWithAllowance). Reads the venue the grant pinned (policySet.swapVenue) first and refuses honestly - naming the backend's own numbers - when the grant names no venue at all, is on another chain, sells a different token, or the amount is over the venue's per-swap ceiling; otherwise builds action: 'swap' on the same delegated-action lane and relays it with the grant's own session key. The route is the backend's to pick: the grant pins one router, and a best route through any other is declined there by name. |
| request_approval | Raises a request for an action outside the grant (POST /agents/requests) - the "ask" half of Flow 7d. |
| what_may_i_do | Renders the grant in plain terms, or an honest "nothing yet" - a convenience read, never the check. |
| forget | STEP 1 of 2: preview what would be destroyed and get a single-use confirmation token. Deletes nothing on its own. |
| confirm_forget | STEP 2 of 2: actually delete the agent key from this machine. Requires the token from forget. |
| list_apis | Calls GET /apis/list - the paid (x402) third-party API endpoints this agent may call on a chain, each with its live price and this agent's remaining budget. Reads only; calls nothing and spends nothing. |
| call_api | Calls POST /apis/calls - call one of those endpoints and pay for it, inside the budget the OWNER committed on-chain (X402PaymentValidator). Signs the EIP-3009 authorization with this agent's own key; the owner never signs, and the on-chain budget - not this tool - is what bounds it. A response marked simulated is synthetic test data, and says so. |
| get_api_budget | Calls GET /apis/budget - remaining authorizations, per-call maximum, expiry and epoch for this agent on a chain. Does NOT say which endpoints are enabled (list_apis does). |
Wallet lane (the human owner's own session, after wallet_login)
| Tool | What it does |
|---|---|
| wallet_login | Device-style browser login: opens the owner's browser, waits for them to authorize, stores the resulting session in the OS keychain. No browser available (SSH, a container)? Prints the URL and code instead - same flow, no second code path. |
| wallet_logout | Revokes the session (DELETE /auth/session) and clears it locally - even if the network call fails, so a dead network can never strand a live credential on disk. |
| wallet_status | Prints the wallet session's account AND the agent's bound account side by side, and flags a mismatch explicitly. Safe to call regardless of which lane(s), if any, are set up. |
| wallet_use_account | Switch which of the owner's accounts every subsequent wallet_* call uses - including which account wallet_send's lane arbitration compares a paired agent's mandate against. Validates the id against GET /accounts first; persists to the same keychain item wallet_login writes. |
| wallet_send | Sends tokens from the owner's own account. See "Lane arbitration" below - this is the tool the safety property in this README is really about. |
| wallet_portfolio | Reads GET /balance + GET /chains: balances across all chains and each chain's tier (watch/basic/botanary). Raw balance and tier data - it does not itself evaluate whether a send would succeed. |
| wallet_activity | Reads GET /history: the owner's recent sends, swaps, and yield transactions with timestamps, amounts, and final status. |
| wallet_markets | Reads GET /markets/tokens: public market data (prices, symbols) - not account-scoped. |
| wallet_yield | Reads GET /yield/pools + GET /yield/shortlist + GET /farm/positions: available pools, a recommended shortlist, and this account's farming positions. shortlist is ranked off the caller's own holdings server-side and is NOT scoped to the account wallet_use_account most recently switched to - the result's own scopeCaveats field says so explicitly. |
| wallet_mandates | Reads GET /delegations + GET /mandates: what the agent lane may spend unattended - active delegations with budget info, and any outstanding mandates. |
| wallet_agents | Reads GET /agents + GET /agents/requests: connected agents and any pending approval requests they've filed. |
| wallet_api_get | Read ANY GET endpoint in Botanary's frozen OpenAPI contract, authenticated as the owner. GET-only, deliberately - see below. |
| wallet_api_write | Call a genuinely administrative write endpoint - claim an agent, mark a notification read, rename an account, edit a pay-sh allowlist, manage conversations - authenticated as the owner. Every route whose response is an unsigned build, or that the contract marks x-client-signed, is excluded by construction; a small explicit denylist covers what that mechanical rule cannot see. Never a fund-moving or authority-granting write - see below. |
| list_sign_kinds | Reads GET /sign-kinds: every sign-request kind this backend currently registers, each with a summary, the routes it builds and relays through, and whether it is available right now. Call this before wallet_sign_request to learn what a kind takes. |
| wallet_sign_request | Park a typed, kind-discriminated intent (POST /sign-requests) and hand it to the owner to review and sign in their own browser. The one write primitive covering every owner-authorized action that is not wallet_send. Cannot sign, cannot relay - see below. |
| resolve_token | Resolve a token address or CAIP-19 asset ref to its full identity - symbol, name, decimals, and which source vouches for it. Refuses bare symbols: a symbol is a label a contract picked for itself, and two contracts on one chain can share one, so the product will not guess. Call list_tokens when you only have a symbol. |
| list_tokens | Every token this account holds on a chain, with the contract address and CAIP-19 asset ref you need to spend it. This is the discovery command for wallet_send, which takes an address and refuses a symbol. When two rows share a symbol, show both and let the user choose; never guess. |
Why wallet_send requires a token address, not a symbol
The wallet_send tool requires a contract address or CAIP-19 asset ref for the token parameter, never a symbol. This is by design: a symbol is a label a contract picks for itself, and two contracts on one chain can legally share the same symbol. The product will not guess which one you meant. Use resolve_token to turn a symbol into a full identity, or call list_tokens to discover every token this account holds on a chain, each with the address you need.
Lane arbitration: how wallet_send decides who signs
wallet_send resolves one of exactly two lanes, in this order, every time it's called:
- This machine holds a paired agent identity with a live mandate that covers the action, ON THE SAME ACCOUNT the wallet session is presently using. Then it signs locally with the agent's session key and relays - no browser, no human click.
- Otherwise - no paired agent, no live grant, the mandate is out of bounds for this exact request
(wrong chain, over budget, over the per-action cap), or the mandate is on a DIFFERENT account -
it parks a typed intent (
POST /sign-requests), opens the owner's browser to review and sign it there, and polls to a terminal result.
The same-account condition is not incidental - it is the whole safety argument. The two credentials
are independent (see the top of this README): an agent paired to one account and a browser session open
on another is not a bug to route around, it's the scenario this check exists to catch. Without it, "it
signed without asking me" could mean money moved out of an account the owner was not even looking at -
which is exactly what happened once (an agent paired to an empty account while the owner's real funds
sat elsewhere, surfacing as a cryptic AA21 didn't pay prefund three Postgres queries later). Every
wallet_send result names the lane it took (lane: "agent" | "browser"), and when a mandate existed but
was refused for the agent lane, the result says exactly why.
A local balance/chain-tier check runs before opening a browser, purely as a courtesy so a doomed request
doesn't cost the owner a browser trip - it is never the authorization. The real check is the build
the browser page itself does against the live backend, and beneath that, on-chain enforcement. A green
result from this preflight proves nothing by itself, the same discipline propose_payment's own
client-side bounds check documents on the agent lane.
Waiting for results: handles, streams, and why elicitation is not approval
Several tools (wallet_login, wallet_send, pair, request_approval, propose_payment, propose_swap)
do not return immediately - they need human action, on-chain confirmation, or both. These tools now WAIT
for completion instead of handing back a reference and walking away.
When a tool waits, it:
- Reports progress - periodically sends heartbeats so the client knows it is still alive and waiting, never going silent for minutes at a time.
- Watches the backend's declared deadline - the server tells the tool how long it is willing to hold the
operation open. The tool will wait until that deadline, then stop, and the client can join the same wait
at any time by calling
botanary_waitwith the returned handle. - Respects an abort signal - if the client has to stop (interrupt, timeout, preemption by a newer task), it can abort the wait without breaking the backend operation. The handle stays live, and the wait can be rejoined from where it left off.
- Runs a stream when the server supports it - most operations have a Server-Sent Events stream endpoint that delivers updates in real time. When a stream is not available (old backend, network lost), the tool automatically falls back to polling, asking the backend "is this operation done?" at regular intervals.
Handles, and why a handle is not a secret
A handle is an opaque reference to an ongoing operation at the backend - a place to rejoin a wait that was
interrupted. The handle file itself carries no secret. Any credential the operation needs (a session
token, a signer's key, an approval credential) lives in the same keychain chain wallet_login uses, and is
deleted the moment the operation terminates - the handle cannot be replayed from an old transcript.
To rejoin a wait: call botanary_wait with the handle - never re-call the original tool (wallet_send,
get_pairing_code, request_approval, propose_payment, wallet_sign_request). Re-calling starts a
brand-new operation; the wait will not pick up where it left off.
wallet_login is the one flow that opens no handle, so there is nothing to rejoin: a login that drops
is a login you run again. That is deliberate - resuming one would mean re-reading the freshly minted
session token, and a session token belongs in the keychain and the Authorization header, never in a tool
result.
Why elicitation is never an approval
When a tool waits through the wallet_send browser handoff, it may elicit - show the caller where a
signature is being requested, with a cancel affordance. Elicitation is strictly presentational. It never
asks for an approval and never authorizes anything. It only tells the caller: "The signature is needed in
your browser, here is a link or a code to review it."
- If the caller cancels the elicitation, the wait stops locally, but the browser tab stays live and the owner can still sign it there.
- If the owner signs in the browser, the elicitation on the model's side gets the result.
- If the owner rejects it in the browser, the wait gets the rejection and surfaces it as the final result.
The only boundary that counts is the one on-chain.
The write boundary: three primitives, never a generic api_post
There is no GENERIC write counterpart, and there must not be one. A tool that took an arbitrary path
and body and forwarded it to any mutating endpoint would let a model reach any mutation - freeze the
account, remove a signer, drain a grant - with no typed intent, no review panel, and no lane arbitration.
That argument hasn't changed. What has changed is that it is no longer served by a single refusal -
wallet_api_get being GET-only and nothing else. It is now served by THREE primitives, each admitting a
different, narrow slice of what a caller can reach, with the dangerous middle - anything that could move
funds or grant authority on its own - structurally unreachable by all three:
| Primitive | What it reaches | How the boundary holds |
|---|---|---|
| wallet_api_get | Any documented GET | Read-only. There is no body to send, no method but GET. |
| wallet_sign_request | Any typed sign-kind | Never signs, never relays - returns a URL the OWNER opens and signs in their own browser. |
| wallet_api_write | A small set of administrative POST/PUT/PATCH/DELETE routes | Every route that returns an unsigned build for the owner to sign is excluded from its manifest by construction - see below. |
wallet_api_get is GET-only, deliberately
Every path is validated against a manifest generated from the frozen OpenAPI contract
(openapi/botanary-v1.yaml, via pnpm generate:routes - see "Development" below) before anything
reaches the network. An undocumented path, or any method other than GET, is refused. wallet_api_get
is deliberately incapable of writing anything, and always will be.
One parse: the string that is validated is the string that is requested
Both path allowlists - wallet_api_get's and wallet_api_write's - share a single canonicalisation
step (src/http-path.ts) that runs BEFORE any manifest is consulted, and both then match and request
the same canonical string. This is not a detail: a path that one layer validates and another layer
re-parses differently is an allowlist that allows something other than what it approved. fetch
re-parses whatever it is given with the WHATWG URL parser, which resolves . and .. (percent-encoded
forms included), normalises \ to /, and truncates at # - so a regex allowlist that treats those as
ordinary characters and then rebuilds the request from the caller's raw string is checking one route and
calling another.
So a caller-supplied path is refused unless it is canonical: absolute, never beginning //, no
fragment, no empty segment, every segment drawn from unreserved/sub-delim characters or well-formed
%XX escapes that do not decode - through any number of layers - to a separator, a fragment marker or a
./.. traversal, and finally a string the URL parser reproduces byte for byte. A {param} in a
manifest template compiles to that same charset, so a path parameter structurally cannot hold a
separator. The denylists are enforced as refusals rather than as mere omissions, so a denylisted literal
cannot come back through a parameterised sibling that happens to match it. src/api-client.ts re-checks
the same property immediately before calling fetch, as a second layer for callers other than these
two. A percent-encoded character that is genuinely part of an id (%3A for a CAIP-style :) passes and
is transmitted verbatim - never decoded, never re-encoded.
wallet_sign_request: the typed-intent lane
It is the write primitive this package has had the longest, and it covers every owner-authorized action
other than a send (see the tools table above and "Lane arbitration" below for why wallet_send stays
separate). Read closely, it does not weaken the argument above - it satisfies every part of it:
- Typed intent.
wallet_sign_requesttakes akindand aparamsobject, never a path and a raw body. The backend validatesparamsserver-side against that kind's own DTO (one shape per kind,SIGN_KIND_DTOSin the contract) before anything is stored; an unregistered kind, or a body that does not match the registered one, is refused before the owner is involved at all. Calllist_sign_kindsfirst to see every kind currently registered and exactly what it takes. - Review panel. This tool never builds calldata and never signs. What it returns is a URL - the
SAME
/signhandoffwallet_send's browser lane already uses - that the OWNER opens in their own browser, where the page builds the operation, simulates it, and asks for their signature. A model calling this tool can make the owner see a request; it cannot make anything happen without them. - Lane arbitration.
wallet_sign_requesthas none to weaken, because it has no agent lane to arbitrate into: it is the browser handoff, always, for every action it covers.wallet_sendkeeps its own arbitration (agent-vs-owner routing) untouched, because send is the one action where that routing is load-bearing - see "Lane arbitration" below.
So the worst a compromised model achieves through wallet_sign_request is ASKING the owner to sign
something - the same authority a stranger with the owner's phone number has.
wallet_api_write: plain session writes that need no signature
Everything left over from the two primitives above is administrative bookkeeping with no fund movement
and no authority grant of its own: claim an agent, mark a notification read, rename an account, edit a
pay-sh allowlist, manage conversations. wallet_api_write reaches exactly that set, and the property
that keeps it there is mechanical, not a promise: every authority action in this backend returns an
UNSIGNED build for the owner to sign (build -> sign -> relay, the invariant botanary-be/AGENTS.md
states and test/no-custody.spec.ts pins). So a route can be excluded from WRITE_ROUTES
(src/wallet/write-routes.manifest.ts, generated by pnpm generate:write-routes - see "Development"
below) using nothing but the contract itself:
- Build-shaped response. Its success response resolves - directly, through an array's
items, or through anyoneOf/anyOf/allOfbranch - to a component schema named*Build:UserOpBuild,DelegationBuild,GrantBuild,ApiBudgetBuild, and every other one. Freeze, initial account setup, guardian install, add-signer, budget commit, delegation/grant creation - all named this way, all excluded automatically. x-client-signed: true. The contract's own flag for "hands back or consumes something a client must sign" - it catches real gaps signal 1 alone misses, because not every build-shaped response is named*Build(POST /account'sAccountDeployIntentembeds an unsigneddeployUserOp; pay.sh's own withdraw-build response is namedPayShWithdrawBuildResponse, breaking the naming convention by one word) and it also catches every RELAY call (POST /delegations, pay.sh's own relay and manual-sign lanes) - the same category/useropsis in, just with nothing to build because there is only something to relay.
A small explicit denylist covers what neither mechanical signal can see - it exists precisely BECAUSE the
two rules above are mechanical: a route can pass both (no *Build response, no x-client-signed flag)
and still hand back a live session credential, mint session authority for someone else, relay an
already-signed payload, or move funds through a custodial signer this backend holds itself (the Virtuals
agent-wallet withdraw/trade routes - the one deliberately custodial exception this backend carries). One
more entry (/sign-requests) is denylisted for a different reason: admitting it would let a caller
construct an arbitrary sign-request intent through an untyped path, duplicating wallet_sign_request's own
typed-intent lane rather than going through it. Every entry is justified individually in
scripts/generate-write-routes.mjs's own header comment and its DENYLIST object.
The boundary is two mechanical rules plus this denylist, not one rule - the numbers, read straight off
the frozen contract by pnpm generate:write-routes (src/wallet/write-routes.manifest.ts's own generated
banner records them on every run):
| | Write operations (POST/PUT/PATCH/DELETE) |
|---|---|
| Total in the contract | 131 |
| Excluded - build-shaped response (*Build, signal 1) | 57 |
| Excluded - x-client-signed: true, not caught by signal 1 (signal 2) | 9 |
| Excluded - explicit denylist | 18 (across 17 distinct paths - /auth/session denylists both its POST and DELETE) |
| Admitted into WRITE_ROUTES | 47 |
The result: wallet_api_write can be talked into marking a notification read. It cannot be talked into
anything that moves a token or grants an agent, a signer, or a device new authority - not because the
tool refuses to try, but because the route to do so was never in its manifest to begin with.
Two admitted routes still refuse at the HTTP layer, and that is a second layer working, not a manifest
gap. /pay-sh/accounts/{accountId}/allowlist and /pay-sh/accounts/{accountId}/settings pass both
mechanical checks (neither is *Build-shaped nor x-client-signed) and so ARE in WRITE_ROUTES - but
wallet_login mints the same kind: 'cli' session botanary login does (this package and botanary-cli
share one identity and session store), and the backend's own NoCliWritesGuard 403s any write from a
kind: 'cli' session on the pay-sh and agent-wallet controllers, precisely because those routes move a
Privy-custodied balance or widen an agent wallet's spending fence with no owner signature anywhere in the
loop. The manifest is the first layer, not the only one; a route being admitted here says "shape-safe to
attempt," never "guaranteed to succeed."
Why the advertised tool list changes
This package ships close to twenty tools. Advertising all of them at once - most of which are unusable
in the caller's current state (no wallet session yet, no paired agent yet) - is exactly the kind of
overlapping-description clutter that degrades tool selection in a client with many MCP servers attached.
So the advertised list is gated by state: a small starter set (wallet_login, get_pairing_code,
diagnose, wallet_status, ...) is always visible; the wallet tools appear once wallet_login
succeeds; the agent tools appear once this machine has a local identity. wallet_login/wallet_logout
push notifications/tools/list_changed so a client that implements it can re-fetch immediately.
Not every client implements that notification, and a hidden tool must still work when called. If
your client cached the list from before you logged in and you (or the model) call wallet_send anyway,
it does not 404 or pretend the tool doesn't exist - it answers honestly ("not logged in - run
wallet_login first"). The gating is a UX optimization on top of a surface that is always fully reachable,
never a second, hidden permission system.
Add it to your agent
botanary-mcp is published on npm - no clone, no build, no local install step. npx fetches and
runs it on demand, so the one-time setup is the one command per client below.
# Claude Code
claude mcp add --transport stdio botanary -- npx -y botanary-mcp
# Codex
codex mcp add botanary -- npx -y botanary-mcpThe server talks to https://api.app.botanary.xyz by default. Point it somewhere else with
BOTANARY_API_URL:
claude mcp add --transport stdio botanary \
-e BOTANARY_API_URL=http://localhost:3000 \
-- npx -y botanary-mcpCursor has no CLI equivalent - add this block to .cursor/mcp.json (project) or ~/.cursor/mcp.json
(global) instead:
{
"mcpServers": {
"botanary": {
"command": "npx",
"args": ["-y", "botanary-mcp"]
}
}
}Claude Desktop is likewise config-file only - add this block to
~/Library/Application Support/Claude/claude_desktop_config.json (create it if it does not exist yet):
{
"mcpServers": {
"botanary": {
"command": "npx",
"args": ["-y", "botanary-mcp"],
"env": {
"BOTANARY_API_URL": "https://api.app.botanary.xyz"
}
}
}
}Restart the client so it picks up the new server. From here, two independent things you can ask for:
- "What's your Botanary identity / pairing code?" - the AGENT lane. It calls
get_identity/get_pairing_codeand reads the key straight out of wherever this machine's OS keeps secrets. The first call generates the key; nothing before that point touches disk or asks any question. - "Log me into Botanary" - the WALLET lane. It calls
wallet_login, opens your own browser to the provider login you already use, and waits for you to authorize. Nothing is generated on this machine; the session it stores is revocable from Botanary's Settings → Connected apps at any time.
What a freshly-connected agent can and cannot do
This is the product's own promise (Flow 7c/7d), and every tool in this package exists to make it true:
- Connecting is harmless by itself. A newly connected, ungranted agent can read balances
(
get_balance) and read its own bounds (whoami/what_may_i_do) -propose_paymentrefuses honestly, citing the backend's own "you have no grant" answer, rather than pretending. It cannot move a cent. - What it's granted, it can spend - unattended, signed with its own key.
propose_paymentbuilds and relays a payment under the grant when the amount is within its bounds. Nothing outside that grant works;request_approvalturns it into a request the owner approves as themselves, or it doesn't happen. - What it can never do, no matter what it was granted: sign in as the owner, add or remove a signer, write or change a policy, grant access to another agent, or unfreeze the account. A grant is permission to spend inside a fence, never permission to move the fence. None of these tools exist in this package - there is nothing here that could call them even if a prompt tried to talk it into it.
- The bound it reads is a convenience, not the check.
whoami/what_may_i_do/propose_payment's own pre-check all read the grant's bounds from the backend, but the actual enforcement happens on-chain. A bug or a lie in what any of them reports changes nothing about what this agent can actually get away with.
Pairing opens a browser, and why that is not a new power
get_pairing_code launches the owner's default browser on <app>/agents?pair=<code>, the same way
wallet_login, wallet_send and wallet_sign_request already launch one on the URL they need the
owner to visit. Pairing was the odd one out: it returned a URL and left the person who had never used
this package before to click or copy-paste it out of a tool result.
Three limits keep that from being a way to point someone's browser somewhere:
- The URL is not model-controlled. It is the configured API origin (
BOTANARY_API_URL, mapped to the app origin byderiveAppOrigin) plus a locally minted code. Nothing a model saw, said or was told reaches it. openBrowserrefuses anything that is not a parseable absolutehttp(s)URL, and never involves a shell - it passes the URL as a singleexecFileargv element. That check is why a mistyped or hostileBOTANARY_API_URLcannot turn a deep link into a command.- A code the backend never acknowledged opens nothing. Registration fails soft, and a window onto a form that will reject the code stages a failure rather than a pairing.
It also opens once per code. get_pairing_code is deliberately idempotent - the same code comes
back until it expires - so a repeated call is the normal case, not a mistake, and each one must not add
another identical tab.
Why intercepting the pairing code alone grants nothing
The short code this server shows (get_pairing_code) is built from two parts, and neither one is a
secret:
- A fingerprint - a few characters derived from the agent's public key. It exists so a human can
visually confirm "yes, this is the code my agent just showed me," the same role an SSH host-key
fingerprint plays. It is only ever a function of information that's already public (the address
itself is shared openly by
get_identity), so there is nothing about it worth hiding to begin with. - A nonce - fresh randomness, generated new each time a pairing attempt starts, with a short (10-minute default) expiry. This is what makes the code single-use and short-lived: once it expires, or once a fresh one is requested, the old code stops being the one anything checks against.
Neither piece is derived from the private key, and there's no computation that gets you from "fingerprint + nonce" back to the 32 bytes that would let something sign as this agent. The code isn't an obfuscated secret - it was never built out of one.
That's what makes the rest of the claim hold: the code identifies, the signature authenticates.
Completing a connection requires the agent to sign the code together with a timestamp, using the key
that never left this machine, and submit that signature with its public key - proof of possession, not
proof of having seen a string. (The signed message is code|timestamp; the code is minted locally, so
this is not a server-issued challenge. mintSession is the separate flow that does fetch a server
nonce before signing.) Someone who only
intercepted the code cannot produce that signature, because they don't have the key. The worst they can
do is type the code into their own Botanary account's "Connected agents" box - which, per the product
rule above, gets them nothing: a connection with no grant can do nothing, and it takes nothing away
from the real owner, whose agent still holds the only key that can ever complete a real pairing for that
identity. There is no password, token, or secret anywhere in this exchange for anyone to steal.
(The pair tool is what actually submits the signed challenge - POST /agents/pair - to complete this
half of a pairing. The cryptographic property above does not depend on that call existing: the code is
derived only from public information, so intercepting it is intercepting nothing, whether or not
anything has submitted a proof yet.)
The key: generated here, stored here, never sent anywhere
This is a property to preserve, not an implementation detail. There is no code path in this package
that sends the private key anywhere - no telemetry, no crash reporting, no "just in case" backup, no
cloud sync. test/no-leak.spec.ts exists specifically to keep that true: it drives every tool, the real
MCP protocol, the CLI, and a deliberately misbehaving backend that tries to leak the key through an
error message, then greps everything that came out for it. If you're extending this package, that test
is the one to think hardest about before touching.
The key is generated locally on first use (secp256k1, the same curve/derivation as every other signer in
this system - see src/identity/keypair.ts) and handed to the best available OS secret store:
| Platform | Backend | Mechanism |
|---|---|---|
| macOS | Keychain | the security CLI (add-generic-password / find-generic-password / delete-generic-password) |
| Linux | Secret Service (GNOME Keyring, KWallet's libsecret shim, ...) | the secret-tool CLI, secret piped over stdin |
| Windows | DPAPI, current-user scope | a short PowerShell call to ProtectedData.Protect/Unprotect, secret piped over stdin; only the ciphertext touches disk |
| any platform, if none of the above is available | a local file, mode 0600, parent dir 0700 | plain file, last resort only |
No native addon is linked for any of this - every backend shells out to a platform CLI that's already
there, which is also why npm install never needs a compiler. The trade-off is documented rather than
hidden: macOS's security CLI has no way to pass the password except as an argument, so it's briefly
visible in this process's own argv (to anything else on the same machine that can list processes) for
the moment that one command runs - secret-tool and the Windows path both avoid this by using stdin.
See the comments in src/identity/backends/*.ts for the full reasoning per backend.
Two more things worth knowing:
- Exactly one copy, always. A new key is written to the first available backend and stops there -
never a redundant "backup" copy in a second place.
src/identity/store.tsand its tests (test/identity/store.spec.ts) pin this down explicitly. - The key is read fresh for every signing operation and never cached in memory. Only
store.sign()(EIP-191 personal-message signing) andstore.signHash()(raw ECDSA over an exact 32-byte hash - whatpair/session-minting/propose_payment's spend all actually use, since the backend recovers over the raw hash with no prefix) ever touch it, and only for the duration of that one call. Identity lookups (get_identity,get_pairing_code) never touch the keychain at all - they read a small, non-secret metadata file (address / public key / fingerprint / when it was created / which backend holds the key) that's written once alongside the real key and never contains it.
The links this server opens are never handed to a shell
Two flows end with this process opening a URL in the owner's own browser: wallet_login's
verificationUrl and wallet_send's browser handoff. Both URLs are chosen by the backend, which
makes the launcher a place where "a compromised backend fails to availability, never to authority"
could quietly stop being true - a URL interpolated into a shell command string is arbitrary code
execution on the owner's laptop, and "..." quoting does not prevent it ($(...) and backticks still
expand inside double quotes).
So src/wallet/browser.ts uses execFile, never exec: the opener is spawned directly with an argv
array, so a URL is one opaque argument no matter what characters are in it, and no shell exists to
interpret them. On Windows that means rundll32 url.dll,FileProtocolHandler rather than start, which
is a cmd.exe builtin and would have needed one. On top of that, the URL must parse as an absolute
http/https URL before anything is launched at all - which also refuses a bare -flag that
open/xdg-open would otherwise read as its own argument. test/wallet-browser.spec.ts pins both
halves: the argv shape, and that the real spawn primitive leaves a substitution payload literal.
Deleting the key on its own machine
npx -y botanary-mcp forgetThis deletes the private key from wherever it's stored (every backend candidate is swept, not just the
one currently in use, so this also cleans up after a platform change or a partial past failure) and
clears the local identity. It does not touch any grant a Botanary account still has on file for that
address - this machine never had the authority to revoke that, only the key. That's the whole point:
after this command, nothing on this machine can produce a signature for the old address, which is the
part anyone can verify for themselves without trusting Botanary's word for it. test/identity/store.spec.ts
and test/no-leak.spec.ts both exercise this directly: after forget(), signing fails, and the next
identity created is a different address - proof the old key is really gone, not just hidden.
Why forget IS a tool, and what that costs
forget was deliberately CLI-only for most of this package's life. The reasoning was sound and is worth
keeping on the record: an agent that can erase its own identity on request is one an injected instruction
(a poisoned webpage, a malicious dependency's README, anything it reads as part of normal work) can
silence. "Forget your Botanary identity" is exactly the kind of one-line instruction a prompt injection
would try.
It is now a tool, at the owner's explicit direction, because the alternative cost more in practice: an agent paired to the wrong account could not reset itself without a human dropping to a shell, and that dead-end is common enough to matter.
What mitigates it:
- Two steps, never one.
forgetdeletes nothing. It returns a preview of what would be destroyed, what would be left behind, and a single-useconfirmationToken. Onlyconfirm_forget, given that token, deletes anything. - The token is in-memory and expires (5 minutes, single-use), so it cannot be replayed from a transcript or survive a restart.
What this honestly does NOT do: stop a determined injection. A model can call forget, read the token,
and call confirm_forget in the same turn. What the two-step buys is that no single instruction destroys
the key, and that the consequences are forced into the transcript before the destructive call. Real
protection is the host's permission prompt on MCP tool calls - the two-step matters most for installs
that have allowlisted this server.
forget also remains a CLI command (npx -y botanary-mcp forget), unchanged.
Development
The commands below are for working on this package's own source in a checkout of this repo - not for installing it as a user. If you just want to connect an agent, use "Add it to your agent" above; you don't need any of this.
pnpm install # installs deps and builds dist/ (the "prepare" script)
pnpm build # rebuild dist/ by hand
pnpm dev # run bin/botanary-mcp.ts directly, watching for changes (no MCP client attached)
pnpm typecheck # tsc --noEmit, strict (matches the backend repo's compiler settings)
pnpm test # vitest - no network, no real keychain (every OS call is mocked; see
# test/fixtures/fake-exec.ts and test/fixtures/fake-backend.ts)
pnpm generate:routes # regenerate src/wallet/routes.manifest.ts from the sibling botanary-be
# checkout's openapi/botanary-v1.yaml - run this and commit the result whenever
# the contract changes; it never runs automatically (a published install has no
# sibling openapi/ directory to read it from)
pnpm generate:write-routes # same thing for src/wallet/write-routes.manifest.ts - see "The write
# boundary" above for the exclusion rule it applies while doing soNeither generator runs from test, build or prepare, deliberately - a published npx botanary-mcp
install has no sibling botanary-be checkout to read the contract from. The cost of that correct
decision is that the committed output can rot silently, and it did (GET_ROUTES once sat nine routes
behind the contract, refusing routes the same branch had shipped). test/manifest-freshness.spec.ts
regenerates both manifests into a scratch directory and byte-compares - it never repairs the file it
checks - and skips, loudly and with a stated reason, where the sibling contract is absent. Same guard,
same reasoning as botanary-fe/tests/api/schema-drift.test.ts.
BOTANARY_MCP_HOME overrides where the non-secret metadata file (and the file-fallback secret, if it's
ever in use) live - defaults to ~/.botanary-mcp. It exists mainly for tests and for running this
server inside a container with an isolated home; a normal install never needs to set it.
Do not reach for it to separate two coding tools. It moves the metadata file but NOT the keychain
item, which is keyed by name (identity/backends/types.ts) - so a second home used to mint a fresh
keypair and save it with security add-generic-password -U, overwriting the first one's private key in
place. Use a profile instead; it moves both.
Profiles - one identity per agent, not one per machine
Every coding tool that connects to this server gets its own keypair, its own ConnectedAgent row on the
backend, its own mandate and its own revoke button. Before profiles they all shared one address, so the
backend could not tell Claude Code from Codex even in principle, and disconnecting one disconnected all
of them.
A profile is resolved once, at the MCP initialize handshake:
| Precedence | Source | Result |
|---|---|---|
| 1 | BOTANARY_AGENT_PROFILE | that agent name, under the reporting tool |
| 2 | a pre-profiles ~/.botanary-mcp/identity.json exists | default - the identity this machine already has |
| 3 | the MCP clientInfo.name the client sent | one identity per tool, with no configuration |
| 4 | nothing | default |
Storage follows the resolved key. default is byte-identical to what shipped before profiles:
~/.botanary-mcp/identity.json profile "default"
~/.botanary-mcp/profiles/codex/identity.json profile "codex"
keychain botanary-mcp / agent-identity profile "default"
keychain botanary-mcp / agent-identity:codex
keychain botanary-mcp / agent-identity:claude-code.trading
keychain botanary-mcp / wallet-session ONE, shared by every profileStep 2 outranks step 3, and that is the whole upgrade story. A machine that already paired has a
ConnectedAgent on the backend and possibly a live on-chain grant naming its address as
delegateeAddress. Auto-deriving a fresh identity would leave that grant pointing at an address no key
on the machine can sign for - real, dead, and with no error to explain it. So an existing install stays
exactly where it is, and splitting it is opt-in.
Several agents per tool is just several profiles. The tool half comes from clientInfo, the agent
half from the env, so the same name under two tools is two different identities:
// botanary-be/.mcp.json - this repo's Claude Code gets its own agent
"env": { "BOTANARY_AGENT_PROFILE": "trading" } // -> claude-code.tradingEach distinct profile is a fresh address, so it needs its own pairing once. That is the cost, and it is the point: the owner authorizes each one deliberately.
What a profile is worth, and what it is not
- Cryptographic: Codex's grant cannot be spent by Claude Code's key. Different private key, different
address, and
MandateExecutoris bound to the delegatee. This holds even against a fully compromised backend. - Server-enforced: a disabled agent cannot mint a session, and disabling revokes its live tokens. The client cannot bypass it, because the token comes from the server.
- NOT enforced, and not enforceable: which local process may read which key. The OS keychain is
per-user, not per-binary - any process that can run
security find-generic-passwordcan read every item this package stores. That is no worse than before (a hostile local process already had the one shared identity), but it means the tool an agent reports is hygiene and honest bookkeeping, never a security boundary.clientInfois self-reported; it selects which local key to load and nothing more, and the app renders it as a quoted claim for that reason.
get_identity and diagnose both report the resolved profile and where it came from, so "which
identity is this process using, and why" never has to be reverse-engineered from which keychain item
happens to exist.
What's deliberately not here
Everything the original design called out as "later work" is now built: the pairing HTTP exchange
(pair), reading balances (get_balance), building and relaying under a grant (propose_payment), and
the out-of-grant request lane (request_approval, Flow 7d step 5 - "ask, when it needs more").
What stays out on purpose:
- An agent-initiated disconnect -
DELETE /agents/{id}is owner-only and stays that way.forgetdeletes a local key; it never closes the owner-side connection, and the two must not be confused. - AGENT-LANE authority beyond a grant. Nothing the agent lane does can add or remove a signer, write or change a policy, grant another agent access, or unfreeze the account - not because those endpoints are hard to call, but because an agent's grant is authority to spend inside a fence, never authority to move the fence. There is no agent-lane tool here that could be talked into trying.
- A cached or session-spanning bounds check as the real gate.
propose_payment's pre-check (andwhat_may_i_do's rendering) readsGET /agents/mefresh viaAgentRuntime.me()and refuses using whatever the backend reports at that moment - it never assumes a bound it read earlier still holds. The chain is still the only real enforcement either way (see "The bound it reads is a convenience, not the check" above). The wallet lane's ownwallet_sendmakes the SAME promise for the mandate lane it can take (see "Lane arbitration" above), and its browser-lane fallback is likewise never a shortcut: every fund-moving or authority-granting wallet-lane write terminates in the owner's own browser signature, never in anything this package executes on its own.wallet_api_writereaches a small, mechanically-excluded set of administrative writes only - see "The write boundary" above.
src/runtime.ts's AgentRuntime is the seam every tool in src/tools.ts is built on: it owns identity,
signing (store.sign()/store.signHash()), a cached-with-retry agent session, and one method per
backend call a tool needs (me, getBalance, buildDelegatedAction, raiseRequest, spendUnderGrant) -
a future tool extends this class rather than reaching for fetch directly.
buildDelegatedAction (POST /delegations/{delegationId}/actions), not /money/send/build, is the
build call propose_payment uses, and deliberately so: /money/send/build builds an owner-lane op in
the Kernel account's ROOT nonce lane, which a session-key signature can never validate (it routes
validation to the root ECDSA validator, which cannot parse the USE-mode (bytes1, bytes32, bytes)
envelope spendUnderGrant wraps every signature in as anything resembling a valid 65-byte ECDSA
signature). /delegations/{delegationId}/actions builds in the delegation's own Smart Sessions nonce
lane with fixed native gas instead - the one lane this package's session key can actually sign for. The
backend additionally scopes this route to the caller's OWN grant: an agent session naming a different
agent's delegation id is refused (403, named reason) before any build happens at all.
