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 automatically every 15 minutes.

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


Connect

MCP (recommended for Claude Code, Cursor, Cline)

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 (25)

ToolWhat it doesAuth
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
what_ifOverride node probabilities, see edge impact (zero LLM cost)Yes
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
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

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


CLI Commands (42)

Thesis

CommandDescription
sf list [--json]List all theses
sf get <id> [--json]Full thesis details
sf context <id> [--json]Thesis snapshot — primary read endpoint for agents
sf create "thesis text" [--async]Create new thesis (sync waits for formation)
sf signal <id> "content" [--type news]Inject signal (types: news, user_note, external, price_move, upcoming_event)
sf evaluate <id>Trigger deep evaluation (heavy model)
sf augment <id> [--dry-run]Review + merge suggested causal tree nodes
sf prompt [id]Get dynamic system prompt with live thesis state
sf publish <id> --slug <slug>Publish thesis publicly
sf 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 book <ticker> [ticker2...]Orderbook depth, spread, liquidity for specific markets
sf book --poly "oil price"Search + show Polymarket orderbooks
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

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 dashboardInteractive Bloomberg-style TUI (j/k navigate, Enter detail, l liquidity, w what-if)
sf feed [--hours 24]Evaluation history stream

Trading (requires sf setup --enable-trading)

CommandDescription
sf buy <ticker> <qty> --price <cents>Buy contracts (3s countdown)
sf sell <ticker> <qty> --price <cents>Sell contracts
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 + 25 tools)
sf telegramTelegram bot for monitoring
sf scheduleExchange status
sf announcementsExchange announcements
sf history <ticker>Historical market data

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
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

Public (no auth)

MethodEndpointDescription
GET/api/public/thesesList published theses
GET/api/public/thesis/:slugFull public thesis data

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 hit rate and injects into next evaluation as feedback loop.
  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 25 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.