SimpleFunctions Agent Reference

Prediction market intelligence engine. Your agent reads thesis state, injects observations, and reacts to edge changes. The backend handles news scanning, price monitoring, and evaluation continuously.

Venues: Kalshi + Polymarket. All prices in cents (0-100).


Connect

claude mcp add simplefunctions --url https://simplefunctions.dev/api/mcp/mcp

For Cursor/Cline, add to MCP config:

{"mcpServers": {"simplefunctions": {"url": "https://simplefunctions.dev/api/mcp/mcp"}}}

CLI

npm install -g @spfunctions/cli
sf setup          # interactive wizard, 2 min

Every command supports --json for machine-readable output.

REST API

Base URL: https://simplefunctions.dev. Auth: Authorization: Bearer sf_live_xxx.


Core Workflow

No thesis needed — start here

# Global market snapshot — movers, expiring, milestones, liquidity
sf context --json

# LLM-enhanced knowledge search — markets + content + synthesized answer
sf query "iran oil" --json

With a thesis — richer context

# 1. READ — thesis state (causal tree, edges, orderbook, evaluation)
sf context <id> --json

# 2. WRITE — inject your observations
sf signal <id> "Iran deploys coastal missiles near Hormuz" --type news

# 3. REACT — force deep analysis when something big happens
sf evaluate <id>

For efficient polling, use the delta endpoint instead of full context:

GET /api/thesis/:id/changes?since=2026-03-23T00:00:00Z
# Nothing changed: {"changed": false} — 50 bytes
# Changed: {"changed": true, "confidence": 0.89, "confidenceDelta": 0.02, ...}

MCP Tools (44)

ToolWhat it doesAuth
get_world_stateReal-time world model (~800 tokens): prediction index, traditional markets, topic summaries, divergences. ?focus=energy,geo for deeper coverageNo
get_world_deltaIncremental world state update — only what changed since timestamp (~30-50 tokens)No
monitor_the_situationUniversal web intelligence: scrape any URL (Firecrawl), analyze with any LLM, cross-reference with thousands of markets, push to webhookYes
enrich_contentPaste text + topics → prediction market divergence analysis. No Firecrawl needed. Free (rate limited), or pass API key for no limit.No
get_trade_ideasS&T-style trade pitches: conviction, catalyst, direction, riskNo
get_contextWithout thesisId: global market snapshot. With thesisId: thesis-specific contextOptional
queryLLM-enhanced prediction market knowledge search (Kalshi + Polymarket + X + traditional + content)No
list_thesesAll theses with status, confidence, position countYes
create_thesisCreate thesis, run formation (causal tree + market scan + edges)Yes
inject_signalFeed an observation into the thesis signal queueYes
trigger_evaluationForce immediate evaluation with heavy modelYes
augment_treeReview suggested nodes from evaluations, merge into causal treeYes
update_nodesDirectly set causal tree node probabilities (zero LLM). The lock field is advisory — pins a node as stable but evidence can still revise it.Yes
fork_thesisClone a public thesis OR evolve your own into a new frame (pass newRawThesis). Evolve-mode parks the parent in dormant mode and re-runs formation on the child.Yes
what_ifOverride node probabilities, see edge impact (zero LLM cost)Yes
update_thesisUpdate title, status (active/paused/archived), webhookUrlYes
configure_heartbeatAdjust heartbeat: news interval, model tier, budget, pause/resumeYes
get_heartbeat_statusHeartbeat config + monthly cost summaryYes
get_evaluation_historyConfidence trajectory over time (daily aggregated)Yes
add_positionRecord a new position for trackingYes
update_positionUpdate position: price, edge, status (open→closed)Yes
close_positionRemove a position recordYes
scan_marketsSearch Kalshi + Polymarket by keywordNo
explore_publicBrowse published thesesNo
create_strategyDefine trading strategy with entry/exit/sizing rulesYes
list_strategiesList strategies for a thesisYes
update_strategyUpdate strategy parameters or statusYes
create_intentDeclare execution intent with trigger conditionsYes
list_intentsList intents: pending, armed, triggered, filledYes
cancel_intentCancel an active intentYes
get_edgesAggregated edges sorted byexecutableEdge
get_milestonesUpcoming Kalshi calendar eventsNo
get_forecastP50/P75/P90 market distributionYes
get_settlementsSettled contracts with realized P&LYes
get_balanceAccount balanceYes
get_ordersCurrent resting ordersYes
get_fillsRecent trade executionsYes
get_marketsTraditional market prices (SPY, VIX, Treasury, Gold, Oil via Databento)No
get_scheduleExchange trading hours and statusNo
search_xSearch X discussions — posts, sentiment, volume, newsNo
x_volumeDiscussion volume trend — timeseries, velocity, peak detectionNo
x_newsX news stories — headlines, summaries, ticker mentionsNo
x_accountRecent posts from a specific X accountNo
browse_public_skillsBrowse community skills: filter by category, search, sort by popular/newNo
create_skillCreate a custom agent skill (reusable prompt triggered via slash command)Yes
list_skillsList built-in + user-created skillsYes
run_skillGet skill by ID to retrieve prompt and metadata for executionYes
publish_skillPublish a skill for community browsing and forkingYes
fork_skillFork a public skill into your collectionYes
fork_thesisFork a public thesis: copies thesis + causal tree, run formation for fresh edgesYes
daemon_commandSend command to running daemon (runtime, telegram): pause, resume, scan_nowYes
set_wake_conditionSet alert condition: price threshold, time, or natural language (LLM-evaluated)Yes
check_daemon_alertsRead alerts and observations from running daemonsYes

Tools marked "No" work without an API key. get_context works both ways.


CLI Commands (43)

Thesis

CommandDescription
sf thesis list [--json]List all theses
sf thesis get <id> [--json]Full thesis details
sf thesis context <id> [--json]Thesis snapshot — primary read endpoint for agents
sf thesis create "thesis text" [--async]Create new thesis (sync waits for formation)
sf thesis signal <id> "content" [--type news]Inject signal (types: news, user_note, external, price_move, upcoming_event)
sf thesis evaluate <id>Trigger deep evaluation (heavy model)
sf thesis augment <id> [--dry-run]Review + merge suggested causal tree nodes
sf prompt [id]Get dynamic system prompt with live thesis state
sf thesis publish <id> --slug <slug>Publish thesis publicly
sf thesis unpublish <id>Remove from public

Markets

CommandDescription
sf scan "keywords"Search Kalshi + Polymarket (no auth needed)
sf scan --series TICKERBrowse series events + prices
sf scan --market TICKERSingle market detail
sf scan "btc" --expires-before 24h --price-min 3 --price-max 9 --vol24h-min 100Server-side filters: expiry window, price range, volume floor
sf scan "governor" --include-subcentSurface markets trading below 1¢ (priceMillicents)
sf book <ticker> [ticker2...]Orderbook depth, spread, liquidity (accepts kalshi:/poly: prefix or bare ticker)
sf book --poly "oil price"Search + show Polymarket orderbooks
sf overround <event>Sum YES asks across multi-leg event; flag arb when total ≠ 100¢
sf newmarkets [--hours 24] [--venue polymarket] [--min-liquidity 1000]Newly listed markets in last N hours
sf screen [--iy-min 200] [--tau-max 7] [--without-thesis]Indicator screener: filter universe by IY, EE, OR, LAS, CRI, RV, VR, IAR, Adj IY, Residual VR, τ — the math labels behind every strategy
sf screen --or-min 0.05Find events whose YES legs sum to ≥ 105% — book-maker margin or live arb
sf screen --without-thesis --venue polymarketUnloved Polymarket markets — strategy 2/3 long-tail entry
sf edges [--json]Top edges across all theses
sf whatif <id> --set "n1=0.1"What-if scenario (zero LLM cost)
sf liquidity [topic]Orderbook scanner across 18 topics
sf explore [slug]Browse public theses (no auth)
sf forecast <eventTicker>P50/P75/P90 market distribution
sf milestonesUpcoming Kalshi calendar events
sf install-completionInstall zsh tab completion (one-shot)

Analysis

CommandDescription
sf contagion [--window 6h]Markets that should have moved but didn't (contagion gaps)
sf cross-venue [--preset arb]Kalshi vs Polymarket price comparison
sf yield-curve [event]Implied yield curve for multi-outcome events
sf calibrationBrier scores + calibration metrics on settled markets
sf regime [ticker] [--history]Market regime analysis
sf calendarStructured event calendar

Knowledge

CommandDescription
sf concepts [slug]Prediction market concepts + indicator definitions
sf technicals [slug]Technical analysis methodology
sf opinions [slug]Published market commentary
sf blog [slug]Blog articles + research notes

Forum + Tracking

CommandDescription
sf forum channelsList channels + subscription state
sf forum inboxUnread messages across subscriptions
sf forum post <channel> "message"Post to a channel
sf forum join <channel>Subscribe to a channel
sf watchlist [--add/--remove <ticker>]Manage saved markets
sf discuss <topic>Public market discussion

Portfolio

CommandDescription
sf positionsKalshi + Polymarket positions with thesis edge overlay
sf balanceAccount balance
sf ordersResting orders
sf fillsRecent trade fills
sf settlementsSettled contracts with P&L
sf performanceP&L over time with sparklines
sf statusHealth check: API, auth, Kalshi, Polymarket, theses, trading
sf dashboardInteractive Bloomberg-style TUI (j/k navigate, Enter detail, l liquidity, w what-if)
sf feed [--hours 24]Evaluation history stream

Intents + Execution

CommandDescription
sf intent buy <ticker> <qty> --price <cents>Create buy intent
sf intent sell <ticker> <qty> --trigger below:40Sell intent with price trigger
sf intent list [--all]Active intents (--all for history)
sf intent status <id>Detailed status with fills
sf intent cancel <id>Cancel an intent
sf runtime start [--daemon] [--smart]Start execution daemon (--smart enables LLM intelligence)
sf runtime stopStop daemon
sf runtime statusRuntime state + active intents

Watch (smart monitoring)

CommandDescription
sf watch "query" [mode]Modes: (default), orderbook, flow, cross-venue, all
sf watch "fed" orderbookLive bid/ask/spread/depth tracking (30s poll)
sf watch "fed" flowMomentum detection, volume spikes, reversals
sf watch "fed" cross-venueKalshi vs Polymarket spread tracking
sf watch "fed" allAll modes combined

Agent Runtime (smart daemons)

The agent runtime is a multi-daemon architecture. Your main agent (sf agent) orchestrates background daemons that monitor, reason, and execute autonomously.

Architecture:

  • Main agent (sf agent) — interactive TUI, sets wake conditions, reads daemon alerts
  • Runtime daemon (sf runtime start --smart --daemon) — evaluates intent triggers, LLM-gates soft conditions, periodic smart scans
  • Telegram daemon (sf telegram --daemon) — push notifications, agent bridge for mobile
  • Watch daemon (sf watch) — market monitoring across modes

Smart mode (--smart) adds an LLM intelligence layer to daemons:

  • Soft conditions: Intents can have natural language conditions (e.g. "only if oil above $95"). When a hard trigger fires, the runtime asks a cheap LLM whether the soft condition is met before executing.
  • Periodic scan: Every ~5 minutes, the runtime summarizes all active intents + market state and sends observations to the agent via the message bus.
  • Wake conditions: The agent can set rules for when to be alerted — price thresholds, time triggers, or natural language conditions evaluated by LLM.

Communication: File-based message bus for IPC. Daemons write observations; the agent reads them. The agent writes commands; daemons read them. Agent presence detected via heartbeat file.

Config (~/.sf/config.json):

{
  "smartDaemons": true,
  "smartModel": "your-preferred-model",
  "smartScanInterval": 10,
  "smartBudgetUsd": "your_budget"
}
Agent ToolDescription
daemon_commandSend command to daemon: pause, resume, scan_now
set_wake_conditionPrice, time, or LLM-evaluated alert condition
check_daemon_alertsRead daemon observations and alerts

Trading (requires sf setup --enable-trading)

CommandDescription
sf buy <ticker> <qty> --price <cents>Buy contracts directly (3s countdown)
sf sell <ticker> <qty> --price <cents>Sell contracts directly
sf cancel [orderId]Cancel order(s)
sf rfq <ticker> <qty>Request for quote (large orders)

Query & X

CommandDescription
sf query "gold price"LLM-enhanced knowledge search — Kalshi + Polymarket + X + traditional + content
sf query "fed rate" --jsonJSON output for agents
sf x "oil"Search X discussions — posts, sentiment, themes
sf x-volume "oil"Discussion volume trend with histogram
sf x-news "oil"X news stories with ticker mentions
sf x-account @zerohedgeRecent posts from a specific account

Other

CommandDescription
sf setupInteractive config wizard
sf agent [id]Interactive agent (natural language + 95 tools)
sf agent --headlessTool-only mode: NDJSON stdin/stdout protocol, no LLM. External LLM integration.
sf agent --record-trace /tmp/t.ndjsonRecord all tool calls + LLM messages to NDJSON
sf agent --replay-trace /tmp/t.ndjsonReplay recorded tool outputs (deterministic backtest)
sf agent --budget-usd 5 --deny orderConstrained agent: spending ceiling + permission capsule
sf describe [tool] --jsonMachine-readable tool schema. --all for full 95-tool catalog.
sf subscribe listActive event subscriptions
sf --remote <cmd>Route any command through cloud runtime (Fly.io)
sf setup --cloudEncrypt + upload exchange keys for cloud runtime (BYOK)
sf telegramTelegram bot for monitoring
sf scheduleExchange status
sf announcementsExchange announcements
sf history <ticker>Historical market data

Global Flags

FlagDescription
--jsonJSON output (prefix or suffix: sf --json world or sf world --json)
--quietSuppress progress output (banners, spinners)
--remoteRoute command through cloud runtime

REST API Endpoints

All require Authorization: Bearer sf_live_xxx unless noted.

Thesis

MethodEndpointDescription
POST/api/thesis/create[?sync=true]Create thesis. Sync waits up to 5 min.
GET/api/thesis/:id/contextThesis snapshot (primary read endpoint)
GET/api/thesis/:id/changes?since=ISOLightweight delta check (~50 bytes if no change)
POST/api/thesis/:id/signalInject signal. Body: {"type":"news","content":"...","source":"agent"}
POST/api/thesis/:id/evaluateForce evaluation (heavy model, up to 2 min)
POST/api/thesis/:id/augment[?dryRun=true]Review + merge suggested tree nodes
POST/api/thesis/:id/nodes/updateDirect node mutation (zero LLM cost). lock is advisory (pin, not freeze). Body: {"updates":[{"nodeId":"n3","probability":0.99}],"lock":["n3"]}
POST/api/thesis/:id/forkClone (empty body) or Evolve ({newRawThesis, newTitle?, reason?, inheritEdgeMarketIds?}). Evolve parks parent in dormant; child re-runs formation.
GET/api/thesis/:id/evaluations[?limit=200]Daily-aggregated evaluation history. Each row carries optional evolutionType (stable, refinement, fork, large_move) for gitMode theses.
GET/api/thesis/:id/prompt[?sections=thesis,edges&maxLength=3000]Dynamic system prompt
GET/api/thesisList all theses
PATCH/api/thesis/:idUpdate status, webhookUrl, metadata
DELETE/api/thesis/:idDelete thesis

Feed & Prompt

MethodEndpointDescription
GET/api/feed?hours=24&limit=200Evaluation history stream
GET/api/prompt[?maxLength=4000]Combined prompt for all active theses

Intents & Execution

MethodEndpointDescription
POST/api/intentsCreate execution intent with trigger conditions
GET/api/intents[?active=true&status=&venue=]List intents
GET/api/intents/:idIntent detail with fills
DELETE/api/intents/:idCancel an intent

Public (no auth)

MethodEndpointDescription
GET/api/agent/worldReal-time world model (~800 tokens). Anchor contracts always present. ?focus=energy,geo for deeper topic coverage.
GET/api/agent/world/delta?since=1hIncremental update (~30-50 tokens). Only what changed since timestamp.
GET/api/public/thesesList published theses
GET/api/public/thesis/:slugFull public thesis data
GET/api/public/ideasTrade ideas: S&T-style pitches (12h cache)
GET/api/public/ideas/:idSingle idea with live market data
GET/api/public/trad-marketsTraditional market prices (SPY, VIX, GLD, TLT, USO)
GET/api/public/scan?q=...[&venue=&limit=]Cross-venue market search with relevance ranking
GET/api/public/market/:ticker[?depth=true]Single market profile: price, spread, volume, orderbook, thesis edges
GET/api/public/index[?history=true]SF Index v2: disagreement (0-100), geo_risk (0-100, signed basket), breadth (-1..+1), activity (0-100 percentile)
GET/api/public/contagion[?topic=iran&window=6h]Cross-market contagion: movers + lagging connected markets + gap size
GET/api/public/diff?tickers=X,Y&window=24hMarket derivatives: price/volume/spread/depth deltas over time window
GET/api/public/briefing?topic=iran[&window=24h]Daily topic briefing with LLM synthesis (10 topics available)
GET/api/edgesAggregated edges across all theses (public subset without auth)

Context Response Shape

GET /api/thesis/:id/context returns:

{
  "thesisId": "f582bf76-...",
  "thesis": "Trump cannot exit the Iran war gracefully...",
  "status": "active",
  "confidence": 0.82,
  "causalTree": {
    "rootClaim": "...",
    "nodes": [
      {"id": "n1", "label": "...", "probability": 0.85, "importance": 0.3, "depth": 0, "childCount": 3}
    ]
  },
  "edges": [
    {
      "marketId": "KXRECSSNBER-26",
      "market": "Will there be a recession in 2026?",
      "venue": "kalshi",
      "direction": "yes",
      "marketPrice": 34,
      "thesisPrice": 55,
      "edge": 21,
      "executableEdge": 20,
      "orderbook": {"bidPrice": 33, "askPrice": 35, "spread": 2, "bidDepth": 814, "askDepth": 500, "liquidityScore": "high"}
    }
  ],
  "lastEvaluation": {
    "summary": "...",
    "confidenceDelta": 0.10,
    "updatedNodes": [{"nodeId": "n3", "previousProbability": 0.6, "newProbability": 0.75, "reason": "..."}]
  },
  "suggestedTreeExtensions": [
    {"label": "...", "description": "...", "parentNodeId": "n2", "estimatedProbability": 0.7}
  ],
  "trackRecord": {
    "hitRate": 67,
    "edgesTracked": 49,
    "movedToward": 33,
    "movedAway": 16,
    "avgMovement": 3,
    "bestEdge": {"market": "...", "delta": 21},
    "worstEdge": {"market": "...", "delta": -12}
  }
}

What The Backend Does Automatically

The heartbeat engine runs every 15 minutes for each active thesis. Your agent does NOT need to do any of this:

  1. News scan — 3 targeted queries (including one adversarial/contrarian). Filters with cheap LLM. Never excludes contradictory news.
  2. Price rescan — Live prices from Kalshi API + Polymarket CLOB. Injects changes >= 3 cents.
  3. Orderbook enrichment — Bid/ask/depth for edges with |edge| > 5 cents.
  4. Evaluation — LLM evaluates signals against causal tree. Checks kill conditions first. Updates node probabilities and confidence.
  5. Track record — Computes batting average (edges that moved toward the thesis) and injects into next evaluation as feedback loop. 5b. Evolution classification (gitMode) — The LLM classifies each cycle as stable, refinement, or discontinuous. Discontinuous cycles auto-fork into a new child thesis with the same market coverage; parent enters dormant.
  6. Edge discovery — Daily (6 UTC): scans for new markets matching thesis.
  7. Tree augmentation — Weekly (Monday 6 UTC): reviews suggested nodes, merges accepted ones (append-only).
  8. Settlement sync — Checks settled contracts, records realized returns.
  9. Strategy review — Reviews strategies against updated edges.

Edge diagnosis types

Each edge is classified as: consensus_gap (market/thesis disagree), attention_gap (market hasn't reacted), timing_gap (short vs long term), or risk_premium (fear/greed premium).

Kill conditions

Before every evaluation: "Does any event fundamentally break a core assumption?" If yes, flags prominently.


Rules for Agents

  1. Don't poll prices — the heartbeat does it every 15 min
  2. Don't search news — the heartbeat does it with adversarial queries
  3. Do inject observations immediatelyinject_signal with type user_note or news
  4. Only call evaluate for breaking events — routine evaluation is automatic
  5. Use what_if before trades — zero LLM cost scenario analysis
  6. Call get_positions before discussing trades — positions are local (Kalshi private key), backend can't see them
  7. Use /changes for polling — 100x smaller than full context
  8. Use short thesis IDs — first 8 chars work everywhere (e.g. f582bf76)

Writing good theses

  • Be specific and directional: "Oil stays above $100 for 6 months" not "Oil prices"
  • Include timeframe: helps match contracts
  • One thesis = one view: don't mix unrelated predictions

Signal types

TypeWhen to use
newsExternal events, articles, data releases
user_noteYour agent's own analysis or observations
externalSignals from other systems
price_moveAuto-injected by heartbeat (>= 3 cent change)
upcoming_eventAuto-injected by heartbeat (Kalshi milestone matching edges)

Interactive Agent

sf agent [id] launches a natural language session with 40+ tools. Supports TUI mode (default) and plain mode (--plain for pipes).

Slash commands: /tree, /edges, /pos, /eval, /buy TICKER QTY PRICE, /sell, /cancel, /switch <id>, /compact, /model <name>, /exit.

Sessions persist at ~/.sf/sessions/. Use --new for fresh session.


Telegram Bot

sf telegram --token TOKEN — runs locally, credentials stay on your machine.

Commands: /context, /positions, /edges, /balance, /orders, /eval, /list, /switch.

Natural language works too — same tools as sf agent. Auto-pushes confidence alerts every 60s.


Webhook

Configure when creating thesis: {"rawThesis": "...", "webhookUrl": "https://..."}

POSTs on confidence changes >= 5% and non-hold position recommendations.