AIDEVELOPER TOOLS

Recursive Epistemic Market MCP Server

Recursive epistemic market microstructure analysis is now available as an MCP server your AI agent can call directly. This server exposes 8 tools that apply advanced mathematical finance models — Soros reflexivity fixed-point iteration, Harsanyi type space belief hierarchies, minority game spin glass phase transitions, rough volatility (fBm with H<0.5), entropic optimal transport, regression discontinuity for regulatory impact, and the Kyle continuous insider trading model — each calibrated from

Try on Apify Store
$0.10per event
0
Users (30d)
0
Runs (30d)
90
Actively maintained
Maintenance Pulse
$0.10
Per event

Maintenance Pulse

90/100
Last Build
Today
Last Version
1d ago
Builds (30d)
8
Issue Response
N/A

Cost Estimate

How many results do you need?

detect-reflexive-dynamicss
Estimated cost:$10.00

Pricing

Pay Per Event model. You only pay for what you use.

EventDescriptionPrice
detect-reflexive-dynamicsSoros reflexivity fixed-point detection$0.10
compute-belief-hierarchyHarsanyi type space projective limit$0.10
simulate-minority-gameSpin glass minority game with phase transition$0.10
analyze-insider-topologyPersistent homology insider trading detection$0.08
assess-rough-volatilityFractional Brownian motion rough path analysis$0.10
compute-entropic-transportSinkhorn entropic optimal transport$0.08
evaluate-regulatory-impactRegression discontinuity causal impact$0.06
forecast-fixed-point-priceKakutani fixed-point price convergence$0.10

Example: 100 events = $10.00 · 1,000 events = $100.00

Connect to your AI agent

Add this MCP server to Claude Desktop, Cursor, Windsurf, or any MCP-compatible client.

MCP Endpoint
https://ryanclinton--recursive-epistemic-market-mcp.apify.actor/mcp
Claude Desktop Config
{
  "mcpServers": {
    "recursive-epistemic-market-mcp": {
      "url": "https://ryanclinton--recursive-epistemic-market-mcp.apify.actor/mcp"
    }
  }
}

Documentation

Recursive epistemic market microstructure analysis is now available as an MCP server your AI agent can call directly. This server exposes 8 tools that apply advanced mathematical finance models — Soros reflexivity fixed-point iteration, Harsanyi type space belief hierarchies, minority game spin glass phase transitions, rough volatility (fBm with H<0.5), entropic optimal transport, regression discontinuity for regulatory impact, and the Kyle continuous insider trading model — each calibrated from 16 live public data sources spanning SEC filings, FDIC bank records, congressional stock trades, FRED macro indicators, and exchange rate history.

Connect once via the MCP protocol and your AI agent gains structured, quantitative market microstructure intelligence without managing data pipelines, API integrations, or financial math implementations. Every tool is pay-per-call with no subscription required.

What data can you access?

Data PointSourceExample
📊 SEC 10-K, 10-Q, 8-K filings and analysisSEC EDGAR AnalyzerEarnings quality scores, risk flag counts
📄 SEC filing full text and metadataSEC EDGAR Filing SearchForm type, filing date, CIK, accession number
👤 Executive insider stock transactionsSEC Insider Trading (Form 4)50,000 shares sold by CFO at $142.30
🏦 US bank financial statementsFDIC Bank DataTotal assets, Tier 1 capital, loan loss reserves
🏛️ Congressional stock trading disclosuresCongressional Stock TrackerRepresentative name, ticker, trade date, amount range
📈 Stock prices, quotes, and financialsFinnhubAAPL last: $185.42, P/E: 28.6, beta: 1.24
🪙 Cryptocurrency prices and market capCoinGeckoBTC $67,240, 24h vol $38.4B, market cap $1.32T
💱 Current foreign exchange ratesExchange Rate TrackerUSD/EUR: 0.9214, USD/JPY: 149.82
📉 Historical exchange rate time seriesExchange Rate History365-day USD/EUR daily close series
🏛️ US economic indicators (GDP, CPI, rates)FREDFed Funds rate: 5.33%, CPI YoY: 3.1%
👷 Employment and inflation statisticsBLSUnemployment: 3.7%, wage growth: 4.1%
📋 Federal rules and regulationsFederal RegisterDodd-Frank amendment, effective date, CFR citation
🏢 Global corporate registrationsOpenCorporatesJurisdiction, incorporation date, officers
⚠️ Consumer financial complaintsCFPBProduct type, issue, company response, resolution
🇪🇺 ECB reference exchange ratesECB RatesEUR/USD reference, date, change from prior day
📜 Congressional bill introductions and statusCongress Bill TrackerBill number, sponsor, committee, latest action

Why use this MCP server for market microstructure analysis?

Building quantitative market microstructure intelligence from scratch means integrating 16 separate APIs, implementing fixed-point iteration algorithms, calibrating Hurst exponent estimators, and coding Sinkhorn divergence solvers — weeks of work before writing a single line of domain analysis. Commercial alternatives like Bloomberg Terminal charge $24,000/year; even lighter tools like Refinitiv or FactSet run $1,000+/month, with no AI-native interface.

This MCP server plugs directly into Claude, Cursor, or any MCP-compatible AI client. Your agent issues a single tool call and receives structured JSON with regime classifications, fixed-point prices, informed trading probabilities, and volatility roughness scores — all derived from live data across 16 sources processed in parallel.

  • Always-on availability — runs in Apify Standby mode, ready for requests within milliseconds
  • Parallel data fetching — up to 16 actors called simultaneously per tool invocation, reducing latency
  • Structured JSON output — every tool returns typed, consistently-formatted output your agent can reason over directly
  • Pay-per-call pricing — $0.10 per tool call, no subscription, no minimum commitment
  • Spending limits — set a per-run cap in Apify to prevent runaway agent loops from accumulating cost
  • API and webhook access — trigger from any HTTP client, Zapier, Make, or LLM orchestration framework

Features

  • Soros reflexivity detection — models price as p(t+1) = f(p(t), E[p(t+1)|p(t)]) and finds the fixed point p* via Picard iteration, computing a reflexivity gap that measures divergence between market price and rational equilibrium
  • Three reflexivity regimes — classifies markets into CONVERGENT (gap shrinking), DIVERGENT (bubble/crash dynamics), or OSCILLATING (cyclical feedback)
  • Harsanyi type space construction — builds K-depth belief hierarchies via projective limit truncation, computing Bayesian Nash equilibrium strategies and a common knowledge gap score across all identified market participants
  • Minority game simulation — El Farol / Minority Game with N agents (51-501, odd), S random strategies per agent, and phase transition detection at alpha = P/N where P = 2^M; spin glass order parameter measures strategy crowding
  • Two minority game regimes — identifies whether the market is below the critical alpha (herding, high volatility, inefficient) or above it (efficient, low excess volatility, strategy diversity)
  • Kyle (1985) continuous insider model — computes price impact lambda = sigma_v / (2sigma_u), information revelation rate via backward induction, expected insider profit, market maker loss, and Probability of Informed Trading (PIN = alphadelta / (alphadelta + 2epsilon))
  • Three informedness regimes — LOW_INFO, MODERATE_INFO, HIGH_INFO based on PIN and signal-to-noise ratio
  • Rough volatility estimation — Hurst exponent from log-variogram regression: V(delta) ~ Cdelta^(2H), with volatility model sigma(t) = sigma_0exp(etaW_H(t) - eta^2t^(2H)/2)
  • Three roughness regimes — SMOOTH (H>0.5), ROUGH (0.15<H<0.5), ULTRA_ROUGH (H<0.15), with implied skew from rough Bergomi model
  • Entropic optimal transport — Sinkhorn divergence between BULL, BEAR, VOLATILE, and STABLE regime distributions; builds Gibbs kernel K_ij = exp(-C_ij/epsilon) and iterates u <- a/(Kv), v <- b/(K^Tu) to convergence
  • Regime transition probabilities — Sinkhorn divergence S_eps removes entropic bias and produces calibrated transition probability estimates between regimes
  • Sharp regression discontinuity — tau = lim_{x->c+} E[Y|X=x] - lim_{x->c-} E[Y|X=x] for regulatory impact, using local linear regression with Imbens-Kalyanaraman optimal bandwidth and McCrary density test for running variable manipulation
  • Full recursive epistemic forecastforecast_fixed_point_price orchestrates all four core algorithms (reflexivity + belief hierarchy + rough volatility + Kyle model) in a single call across 16 actors for a unified multi-factor price forecast
  • 16 live data sources — SEC EDGAR (analysis + filings), SEC Insider Trading, FDIC, Congressional Stock, Finnhub, CoinGecko, Exchange Rates (current + historical), FRED, BLS, Federal Register, OpenCorporates, CFPB, ECB Rates, Congress Bills

Use cases for recursive epistemic market microstructure analysis

Quantitative hedge fund research

Quantitative researchers use detect_reflexive_dynamics to identify when expectations are driving prices away from fundamental value, and assess_rough_volatility to obtain Hurst exponents for options pricing with rough Bergomi rather than Black-Scholes. Both tools pull live FRED macro data, Finnhub quotes, and SEC filings in parallel, so the output is calibrated to current market conditions, not historical backtests.

Market surveillance and compliance

Regulators and compliance teams use analyze_insider_topology to screen for elevated Probability of Informed Trading (PIN) and large price impact lambda values across SEC Form 4 filings, congressional stock trades, and EDGAR filings. Assets flagged with HIGH_INFO regime classification warrant deeper review. The tool's Kyle model outputs — insider profit estimates and market maker loss — provide quantitative anchors for enforcement referrals.

AI agent financial reasoning

AI agents built with Claude, GPT-4, or open-source models can call these tools directly through the MCP protocol to ground financial analysis in live data and rigorous models. Instead of hallucinating market dynamics from training data, the agent calls compute_belief_hierarchy and receives structured type space outputs describing actual participant belief divergence, or calls simulate_minority_game to get a current herding/efficiency classification before generating investment commentary.

Macro research and policy analysis

Economists and policy analysts use evaluate_regulatory_impact to estimate the causal effect of specific Federal Register regulations on market outcomes. The sharp RD estimator with Imbens-Kalyanaraman optimal bandwidth and McCrary density test for manipulation ensures methodologically sound causal inference from public data — at a fraction of the cost of proprietary econometric datasets.

Volatility trading and options desks

Options traders use assess_rough_volatility to classify equity and FX assets by roughness regime. Assets in ULTRA_ROUGH territory (H < 0.15) require rough Bergomi or similar models for accurate implied vol surface calibration. The tool returns per-asset Hurst exponents, vol-of-vol estimates, and rough Bergomi implied skew inputs across stocks, crypto, and FX — all from a single MCP tool call.

Regime change and crisis early warning

Risk managers use compute_entropic_transport to monitor the Sinkhorn divergence between the current market regime distribution and alternative states (BULL, BEAR, VOLATILE, STABLE). When transition probabilities to VOLATILE or BEAR regimes spike, it provides a quantitative early warning signal grounded in optimal transport theory rather than simple threshold rules.

How to connect this MCP server to your AI client

  1. Get your Apify API token — sign up at apify.com, go to Settings > Integrations, and copy your API token.
  2. Add the server URL to your AI client — the MCP endpoint is https://recursive-epistemic-market-mcp.apify.actor/mcp. Paste this into your client's MCP server configuration (see examples below).
  3. Authenticate the connection — pass your Apify token as the Authorization: Bearer YOUR_TOKEN header, or use the token query parameter where your client requires it.
  4. Start calling tools — ask your AI assistant to "detect reflexive dynamics for AAPL technology stocks" or "run a minority game simulation for the current S&P 500 market", and it will invoke the corresponding tool automatically.

Claude Desktop

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "recursive-epistemic-market": {
      "url": "https://recursive-epistemic-market-mcp.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}

Cursor

Add to your Cursor MCP settings (.cursor/mcp.json):

{
  "mcpServers": {
    "recursive-epistemic-market": {
      "url": "https://recursive-epistemic-market-mcp.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_APIFY_TOKEN"
      }
    }
  }
}

Other MCP clients

Any client implementing the MCP specification (Windsurf, Cline, LangChain MCP adapter, LlamaIndex tool wrappers) can connect using the url configuration above. The server uses stateless Streamable HTTP transport — no session management required.

MCP tools reference

ToolPriceActors calledDescription
detect_reflexive_dynamics$0.108Soros reflexivity fixed-point iteration. Classifies markets: CONVERGENT, DIVERGENT, OSCILLATING.
compute_belief_hierarchy$0.106Harsanyi type spaces, K-depth belief hierarchy, Bayesian Nash equilibrium, common knowledge gap.
simulate_minority_game$0.104El Farol minority game phase transition. Spin glass order parameter, herding detection, efficiency regime.
analyze_insider_topology$0.107Kyle (1985) model. Price impact lambda, PIN, information revelation rate, insider profit estimate.
assess_rough_volatility$0.106Fractional Brownian motion Hurst exponent, rough Bergomi implied skew, SMOOTH/ROUGH/ULTRA_ROUGH regime.
compute_entropic_transport$0.106Sinkhorn divergence between BULL/BEAR/VOLATILE/STABLE regimes. Transition probability matrix.
evaluate_regulatory_impact$0.107Sharp regression discontinuity with IK optimal bandwidth and McCrary density test.
forecast_fixed_point_price$0.1016Full recursive epistemic forecast combining all four core algorithms. Most comprehensive tool.

Tool input parameters

ParameterTypeTool(s)DefaultDescription
querystringAll toolsMarket query, company, ticker, or sector (e.g. "AAPL MSFT technology stocks")
sectorstringdetect_reflexive_dynamics, evaluate_regulatory_impactSector to narrow the analysis (e.g. "technology", "finance")
hierarchy_depthnumbercompute_belief_hierarchy5Depth of Harsanyi belief hierarchy (1-10)
num_agentsnumbersimulate_minority_game101Number of minority game agents (odd integer, 51-501)
memory_lengthnumbersimulate_minority_game6Memory length M; generates P = 2^M possible histories (3-10)
num_roundsnumbersimulate_minority_game200Simulation rounds (50-1000)
epsilonnumbercompute_entropic_transport0.1Sinkhorn entropic regularization parameter (0.01-1.0; lower = more precise, slower)

Input examples

Detect reflexive dynamics in the banking sector:

{
  "query": "JPMorgan Goldman Sachs banking",
  "sector": "finance"
}

Simulate minority game with custom parameters:

{
  "query": "S&P 500 US equities",
  "num_agents": 201,
  "memory_length": 8,
  "num_rounds": 500
}

Full recursive epistemic forecast (all algorithms, 16 actors):

{
  "query": "NVDA AMD semiconductor AI chips"
}

Regulatory impact of Dodd-Frank on banks:

{
  "query": "Dodd-Frank capital requirements",
  "sector": "banking"
}

Input tips

  • Use specific queries for sharper results — "AAPL MSFT technology stocks" produces more calibrated output than "stocks". Include tickers alongside company names for better Finnhub matching.
  • Start with detect_reflexive_dynamics or assess_rough_volatility — these are the fastest tools to interpret and give a clear regime classification before diving into the more complex multi-algorithm outputs.
  • Use forecast_fixed_point_price for comprehensive analysis — it calls all four core algorithms across 16 actors in a single invocation, so the cost is the same $0.10 as any individual tool.
  • Tune epsilon for Sinkhorn convergence — values between 0.05 and 0.2 balance precision and stability. Very low epsilon (0.01) can cause numerical instability; very high (1.0) blurs regime boundaries.
  • Odd agent counts for minority game — the minority game requires an odd number of agents so ties cannot occur. The default 101 is appropriate for most analyses; increase to 501 for smoother phase transition detection.

Output example

detect_reflexive_dynamics — NVDA semiconductor query:

{
  "systemReflexivity": 0.73,
  "dominantRegime": "DIVERGENT",
  "assetCount": 6,
  "states": [
    {
      "ticker": "NVDA",
      "fixedPoint": 892.40,
      "reflexivityGap": 0.18,
      "feedbackStrength": 0.81,
      "regime": "DIVERGENT",
      "convergenceIterations": 47
    },
    {
      "ticker": "AMD",
      "fixedPoint": 168.30,
      "reflexivityGap": 0.09,
      "feedbackStrength": 0.54,
      "regime": "CONVERGENT",
      "convergenceIterations": 12
    },
    {
      "ticker": "INTC",
      "fixedPoint": 34.10,
      "reflexivityGap": 0.04,
      "feedbackStrength": 0.29,
      "regime": "CONVERGENT",
      "convergenceIterations": 8
    }
  ]
}

analyze_insider_topology — banking query:

{
  "systemInformedness": 0.62,
  "averageLambda": 0.041,
  "dominantRegime": "MODERATE_INFO",
  "assetCount": 4,
  "assets": [
    {
      "ticker": "JPM",
      "lambda": 0.058,
      "informedTradingProbability": 0.71,
      "insiderProfit": 184200,
      "priceEfficiency": 0.44,
      "signalToNoise": 2.31,
      "regime": "HIGH_INFO"
    },
    {
      "ticker": "GS",
      "lambda": 0.033,
      "informedTradingProbability": 0.48,
      "insiderProfit": 92800,
      "priceEfficiency": 0.67,
      "signalToNoise": 1.12,
      "regime": "MODERATE_INFO"
    }
  ]
}

simulate_minority_game — S&P 500 query:

{
  "alpha": 0.64,
  "phaseTransitionPoint": 0.34,
  "regime": "ASYMMETRIC",
  "volatilityRatio": 0.82,
  "informationContent": 0.71,
  "crowdingMeasure": 0.29,
  "topAgents": [
    { "agentId": 42, "strategy": 1, "score": 147 },
    { "agentId": 78, "strategy": 0, "score": 139 }
  ],
  "recentAttendance": [48, 53, 45, 51, 49, 55, 47, 52, 50, 48]
}

forecast_fixed_point_price — full recursive epistemic forecast:

{
  "systemForecast": {
    "forecastHorizon": "30d",
    "consensusDirection": "BULLISH",
    "confidenceScore": 0.61,
    "epistemicUncertainty": 0.38
  },
  "reflexivitySummary": {
    "systemReflexivity": 0.68,
    "dominantRegime": "DIVERGENT"
  },
  "beliefSummary": {
    "commonKnowledgeGap": 0.44,
    "agentCount": 12,
    "hierarchyDepth": 5
  },
  "volatilitySummary": {
    "systemRoughness": 0.19,
    "dominantRegime": "ROUGH"
  },
  "insiderSummary": {
    "systemInformedness": 0.57,
    "averageLambda": 0.036,
    "dominantRegime": "MODERATE_INFO"
  },
  "forecasts": [
    {
      "ticker": "NVDA",
      "fixedPointPrice": 892.40,
      "beliefAdjustedPrice": 871.20,
      "volAdjustedRange": [834.10, 910.50],
      "insiderAdjustment": -0.023,
      "compositeConfidence": 0.58
    }
  ]
}

Output fields

FieldTypeDescription
systemReflexivitynumberSystem-wide reflexivity score 0-1; higher = stronger feedback loops
dominantRegimestringMajority regime across analyzed assets
states[].tickerstringAsset identifier
states[].fixedPointnumberFixed-point price p* where p = f(p, E[p|p])
states[].reflexivityGapnumberNormalized distance between market price and rational equilibrium
states[].feedbackStrengthnumberMagnitude of price-expectation feedback (0-1)
states[].regimestringCONVERGENT, DIVERGENT, or OSCILLATING
states[].convergenceIterationsnumberPicard iterations to reach fixed point (or max 100 if non-convergent)
commonKnowledgeGapnumberAverage divergence in higher-order beliefs across agent types
bayesianNashEquilibrium[].strategynumberOptimal strategy for each agent type under BNE
types[].privateValuenumberAgent-specific fundamental value estimate
types[].rationalityBoundnumberLevel-k rationality bound (0=naive, 1=fully rational)
alphanumberMinority game complexity ratio P/N
phaseTransitionPointnumberCritical alpha_c below which herding dominates
crowdingMeasurenumberSpin glass order parameter; higher = more crowded strategies
volatilityRationumberExcess volatility relative to efficient market benchmark
assets[].hurstExponentnumberHurst exponent H; <0.5 = rough, =0.5 = standard BM, >0.5 = trending
assets[].roughnessIndexnumberNormalized roughness score 0-1
assets[].volOfVolnumberVolatility of volatility (vol clustering measure)
assets[].skewImpliednumberImplied skew from rough Bergomi model
assets[].lambdanumberKyle price impact coefficient ($/share per unit order flow)
assets[].informedTradingProbabilitynumberPIN — Probability of Informed Trading (0-1)
assets[].insiderProfitnumberEstimated expected insider profit per trading window ($)
assets[].priceEfficiencynumberPrice efficiency score 0-1; lower = more mispricing
comparisons[].sinkhornDivergencenumberSinkhorn divergence S_eps between two regime distributions
comparisons[].transitionProbabilitynumberEstimated probability of transitioning between the two regimes
estimates[].treatmentEffectnumberRD causal estimate tau of regulatory impact
estimates[].tStatisticnumbert-statistic for treatment effect significance test
estimates[].significantbooleanTrue if
estimates[].mcCraryDensityTestnumberMcCrary test statistic for running variable manipulation
forecasts[].fixedPointPricenumberReflexivity-adjusted fixed-point price forecast
forecasts[].compositeConfidencenumberCombined confidence score from all four algorithms (0-1)

How much does it cost to use this MCP server?

This MCP server uses pay-per-event pricing — you pay $0.10 per tool call. Platform compute costs are included. All 8 tools cost the same $0.10 regardless of how many actors they invoke in the background.

ScenarioTool callsCost per callTotal cost
Quick test — single reflexivity check1$0.10$0.10
Single-stock deep dive (all 8 tools)8$0.10$0.80
Daily sector scan (10 queries/day)10$0.10$1.00/day
Weekly research workflow (50 calls)50$0.10$5.00
Active quant research (500 calls/month)500$0.10$50.00/month

You can set a maximum spending limit per run to control costs. The server stops charging when your budget is reached.

Apify's free tier includes $5 of monthly platform credits — enough for 50 tool calls per month at no cost. Compare this to Bloomberg Terminal at $2,000/month or Refinitiv Eikon at $1,200/month. Most users running daily research workflows spend $5-50/month with no subscription commitment.

Using the MCP server via API

Python

from apify_client import ApifyClient

client = ApifyClient("YOUR_API_TOKEN")

# Start the MCP server actor in standby mode, then call via MCP protocol
# Or trigger a direct run for testing
run = client.actor("ryanclinton/recursive-epistemic-market-mcp").call(run_input={})

# For programmatic MCP tool calls, use an HTTP client against the standby URL
import requests

response = requests.post(
    "https://recursive-epistemic-market-mcp.apify.actor/mcp",
    headers={
        "Authorization": "Bearer YOUR_API_TOKEN",
        "Content-Type": "application/json",
    },
    json={
        "jsonrpc": "2.0",
        "method": "tools/call",
        "id": 1,
        "params": {
            "name": "detect_reflexive_dynamics",
            "arguments": {
                "query": "AAPL MSFT technology stocks",
                "sector": "technology"
            }
        }
    }
)

result = response.json()
data = result["result"]["content"][0]["text"]
import json
parsed = json.loads(data)
print(f"System reflexivity: {parsed['systemReflexivity']:.2f}")
print(f"Dominant regime: {parsed['dominantRegime']}")
for state in parsed["states"]:
    print(f"  {state['ticker']}: fixed point {state['fixedPoint']:.2f}, gap {state['reflexivityGap']:.3f}, regime {state['regime']}")

JavaScript

import fetch from "node-fetch";

const MCP_URL = "https://recursive-epistemic-market-mcp.apify.actor/mcp";
const TOKEN = "YOUR_API_TOKEN";

async function callTool(toolName, args) {
    const response = await fetch(MCP_URL, {
        method: "POST",
        headers: {
            "Authorization": `Bearer ${TOKEN}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            jsonrpc: "2.0",
            method: "tools/call",
            id: 1,
            params: { name: toolName, arguments: args }
        }),
    });
    const result = await response.json();
    return JSON.parse(result.result.content[0].text);
}

// Detect reflexive dynamics for semiconductor stocks
const reflexive = await callTool("detect_reflexive_dynamics", {
    query: "NVDA AMD Intel semiconductor",
    sector: "technology"
});
console.log(`System reflexivity: ${reflexive.systemReflexivity.toFixed(2)}`);
console.log(`Dominant regime: ${reflexive.dominantRegime}`);
for (const state of reflexive.states) {
    console.log(`  ${state.ticker}: p*=${state.fixedPoint.toFixed(2)}, gap=${state.reflexivityGap.toFixed(3)}, ${state.regime}`);
}

// Run full forecast
const forecast = await callTool("forecast_fixed_point_price", {
    query: "NVDA AMD Intel semiconductor"
});
console.log(`Consensus direction: ${forecast.systemForecast.consensusDirection}`);
console.log(`Epistemic uncertainty: ${forecast.systemForecast.epistemicUncertainty.toFixed(2)}`);

cURL

# Call detect_reflexive_dynamics
curl -X POST "https://recursive-epistemic-market-mcp.apify.actor/mcp" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "id": 1,
    "params": {
      "name": "detect_reflexive_dynamics",
      "arguments": {
        "query": "JPMorgan Goldman Sachs banking",
        "sector": "finance"
      }
    }
  }'

# List all available tools
curl -X POST "https://recursive-epistemic-market-mcp.apify.actor/mcp" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/list",
    "id": 1,
    "params": {}
  }'

How this MCP server works

Phase 1: parallel data collection across 16 actors

Each tool call dispatches concurrent HTTP requests to between 4 and 16 Apify actors via runActorsParallel, which wraps Promise.all over the apify-client SDK. Each downstream actor runs with a 180-second timeout and 256MB memory allocation. The actor client (actor-client.ts) handles error isolation — if any single source fails, it returns an empty array rather than aborting the entire call, so partial results always flow through to the analysis layer.

The 16 data sources cover four data categories: market prices (Finnhub, CoinGecko, Exchange Rates, ECB Rates), corporate and regulatory filings (SEC EDGAR Analyzer, SEC EDGAR Filing Search, SEC Insider Trading, FDIC, Congressional Stock, OpenCorporates), macroeconomic series (FRED, BLS, Exchange Rate History), and regulatory/legislative events (Federal Register, CFPB, Congress Bills).

Phase 2: algorithm execution in scoring.ts

The scoring engine (scoring.ts) implements eight algorithms. All use a seeded Mulberry32 pseudo-random number generator to produce deterministic results across identical inputs.

Reflexivity detection extracts per-asset price series from the aggregated market data, seeds initial expectations via autocorrelation, and runs Picard iteration p_{n+1} = (1-feedback)p_n + feedbackE[p_n+1|p_n] until |p_{n+1} - p_n| < 1e-8 or 100 iterations are exhausted. The reflexivity gap is normalized as |p* - p_fundamental| / p_fundamental.

Belief hierarchy construction builds Harsanyi type objects from insider transaction records (SEC Form 4, congressional trades) treating each transaction as a revealed private value signal. The projective limit truncation approximates the infinite hierarchy at depth K by computing the L2 norm of successive belief layers. The Bayesian Nash equilibrium is solved via iterated best-response.

Minority game simulation generates each agent's S=2 strategies as random binary functions on binary histories of length M, creating P=2^M possible history patterns. The simulation runs num_rounds rounds: each round, every agent picks the strategy with the highest historical score, the minority action wins, scores update, and attendance is recorded. The spin glass order parameter (strategy crowding) is computed as the variance of strategy score distributions across agents.

Rough volatility fits the log-variogram V(delta) = E[(log(sigma(t+delta)) - log(sigma(t)))^2] ~ Cdelta^(2H) via OLS regression on log-log space over multiple lag scales derived from exchange rate and price return series. The rough Bergomi implied skew is approximated as skew ~ -etaH*sqrt(T)*rho where rho is estimated correlation between returns and variance increments.

Kyle insider model calibrates sigma_v (fundamental value noise) and sigma_u (uninformed order flow noise) from FDIC balance sheet volatility and trading volume proxies, then computes lambda = sigma_v / (2sigma_u), information revelation rate via discrete-time backward induction, and PIN using the EKOP model parameterization alphadelta / (alphadelta + 2epsilon).

Sinkhorn divergence builds a feature matrix from market and macro data, assigns each observation to a regime label (BULL/BEAR/VOLATILE/STABLE) based on return and volatility thresholds, then applies 50 iterations of Sinkhorn scaling on the Gibbs kernel K_ij = exp(-||x_i - x_j||^2 / epsilon). The debiased Sinkhorn divergence S_eps removes the self-transport terms.

Regression discontinuity identifies regulatory events from Federal Register data as cutoff dates, constructs a running variable (days since event), and fits local linear regressions on either side using Imbens-Kalyanaraman optimal bandwidth. The McCrary density test checks for heaping in the running variable distribution near the cutoff.

Phase 3: output assembly and MCP response

Each tool assembles its typed result into a JSON object and returns it wrapped in the MCP CallToolResult format: { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] }. The forecast_fixed_point_price tool additionally calls forecastFixedPointPrice(reflexive, beliefs, roughVol, insider) which computes a per-asset composite price forecast by weighting the reflexivity fixed-point price by (1 - commonKnowledgeGap), adjusting downward for high PIN values, and widening the confidence interval by the roughnessIndex.

Server architecture

The server runs Express on Apify's Standby mode, keeping a persistent HTTP server alive between calls. Each MCP request to POST /mcp creates a new McpServer instance with a StreamableHTTPServerTransport (stateless, no session ID), handles the request, then closes both the transport and server. This ensures no state leaks between calls. The server responds to Apify's container readiness probe on GET / by checking for the x-apify-container-server-readiness-probe header.

Tips for best results

  1. Include tickers in queries for Finnhub matching. The Finnhub actor matches most reliably on standard ticker symbols. Queries like "AAPL Apple technology" produce better-calibrated output than "Apple technology" alone.

  2. Use detect_reflexive_dynamics first as a screening tool. The reflexivity regime (CONVERGENT/DIVERGENT/OSCILLATING) tells you whether a market is in a feedback-driven state before committing to a full forecast_fixed_point_price call.

  3. The full forecast costs the same as any single tool. forecast_fixed_point_price runs all four algorithms in one call at $0.10 — the same price as calling any single tool. Use it whenever you want a comprehensive view rather than calling four tools separately.

  4. Tune epsilon for Sinkhorn stability. For financial data with large price magnitudes, use epsilon = 0.05-0.1. For normalized return data, epsilon = 0.1-0.2 works well. If you see NaN in sinkhornDivergence, raise epsilon by 0.05.

  5. Minority game memory length affects sensitivity. M=6 (P=64 histories) balances sensitivity and computational cost. Increase to M=8 or M=10 for finer phase transition detection, particularly useful for high-frequency or intraday contexts.

  6. Cross-reference insider topology with reflexivity. Assets showing DIVERGENT reflexivity and HIGH_INFO insider regime simultaneously are the most actionable: expectations-driven price divergence compounded by informed trading suggests strong mispricing dynamics.

  7. For regulatory queries, be specific about the regulation name and sector. "Dodd-Frank banking capital requirements" outperforms "financial regulation" because it lets the Federal Register and CFPB actors return more targeted event data for the RD cutoff identification.

  8. Set a per-run spending limit for agent workflows. AI agents calling tools in loops can accumulate costs quickly. Use Apify's run-level spending limit to cap spend at $1-5 for exploratory sessions.

Combine with other Apify actors

ActorHow to combine
SEC EDGAR Filing AnalyzerFeed raw EDGAR output directly into reflexivity detection; compare fundamental earnings signals against the fixed-point price forecast
Waterfall Contact EnrichmentAfter identifying HIGH_INFO insider topology assets, enrich the insider trading counterparties with contact and organizational data for further research
Company Deep ResearchUse rough volatility and reflexivity regime outputs to flag assets for deeper qualitative research; pass ticker and regime classification as context
B2B Lead QualifierFor fintech and financial services go-to-market workflows, combine regulatory impact estimates with lead qualification scores to prioritize outreach to firms most affected by new rules
Website Tech Stack DetectorIdentify which fintech companies are building on specific technology stacks to cross-reference with minority game crowding metrics and regulatory RD estimates
Trustpilot Review AnalyzerCombine consumer sentiment signals from Trustpilot with CFPB complaint data used in regulatory impact analysis for a fuller picture of regulated entity performance
WHOIS Domain LookupCross-reference OpenCorporates company data (used in belief hierarchy construction) with WHOIS domain registration records for entity verification

Limitations

  • Public data only — all 16 data sources are public databases. The server does not access proprietary order flow, Level 2 market data, or private institutional positions. PIN and lambda estimates are calibrated proxies, not direct measurements.
  • Reflexivity fixed-point iteration may not converge — for highly unstable or illiquid markets, the Picard iteration may oscillate without reaching p*. Non-convergent assets are still returned with convergenceIterations: 100 and an OSCILLATING regime classification.
  • Rough volatility requires sufficient price history — Hurst exponent estimation via log-variogram regression needs at least 20-30 price observations for reliable results. Newly listed assets or thinly traded instruments may produce unreliable H estimates.
  • Minority game is a stylized model — the simulation provides a regime classification (herding vs. efficient) calibrated by macro data, not a literal representation of actual agent behavior. Treat outputs as ordinal signals, not exact probability estimates.
  • Regulatory RD requires a clear cutoff date — diffuse, phased-in, or informally implemented regulations are harder to evaluate with a sharp RD estimator. The tool performs best with regulations that have a specific effective date in the Federal Register.
  • No intraday or tick data — the server operates on daily-frequency data from public APIs. High-frequency microstructure analysis requiring tick-by-tick order flow is outside scope.
  • Downstream actor availability — if one or more of the 16 underlying actors is temporarily unavailable, the corresponding data slice returns empty and the algorithms proceed with reduced input. Results are still returned but with lower statistical power.
  • Not investment advice — all outputs are analytical and quantitative. They do not constitute financial advice, trading recommendations, or investment research under applicable securities law.

Integrations

  • Claude Desktop — add the MCP server URL to claude_desktop_config.json to give Claude direct access to all 8 market microstructure tools in any conversation
  • Cursor — connect via .cursor/mcp.json to enable reflexivity and insider topology analysis during quantitative coding sessions
  • Apify API — trigger the standby server or individual runs programmatically from any HTTP client or orchestration system
  • LangChain / LangGraph — use the MCP adapter to expose all 8 tools as LangChain tools in multi-agent financial research pipelines
  • LlamaIndex — wrap tools via the MCP tool spec for RAG-augmented market analysis workflows
  • Webhooks — trigger downstream notifications when a regulatory impact run completes or when the reflexivity system score exceeds a threshold
  • Make (Integromat) — build automated market monitoring workflows that call minority game or Sinkhorn divergence tools on a schedule and push results to Slack or Google Sheets

Troubleshooting

  • Tool returns empty states or assets array — one or more upstream actors returned no data for the query. Try a more specific query including ticker symbols (e.g. "AAPL" rather than "Apple"). Check that your Apify API token has permission to call the downstream actors.

  • sinkhornDivergence is NaN or very large — the Sinkhorn algorithm diverged due to a low epsilon relative to the scale of the cost matrix. Increase epsilon to 0.2 or 0.5 and retry. This is most common with broad market queries that produce widely dispersed regime distributions.

  • forecast_fixed_point_price is slow or times out — this tool calls 16 actors in parallel and can take 60-120 seconds on cold starts. If you experience timeouts, check the Apify platform status page. The 180-second per-actor timeout should accommodate normal latency; increase if you are on a slow network.

  • evaluate_regulatory_impact returns all significant: false — regulatory impact requires a clear cutoff date in the Federal Register data. Broad queries like "financial regulation" may not surface a specific enough regulatory event. Narrow the query to a specific rule (e.g. "Volcker Rule proprietary trading") with a known effective date.

  • Server returns HTTP 405 on GET /mcp — the MCP endpoint only accepts POST requests (per MCP specification). Ensure your client is using POST /mcp and not GET /mcp. The health check endpoint is GET /.

Responsible use

  • This server only accesses publicly available government databases and open market data APIs.
  • All 16 underlying data sources are official public datasets (SEC, FDIC, Federal Reserve, BLS, Federal Register, CFPB, ECB) or public market data feeds.
  • Do not use the outputs of this server as the sole basis for investment decisions. Outputs are analytical estimates derived from public data and mathematical models with known limitations.
  • Comply with applicable securities laws, including restrictions on trading on material non-public information. PIN and insider topology scores are derived from public Form 4 filings — they do not grant access to private information.
  • For guidance on web scraping and data usage legality, see Apify's guide.

FAQ

What is recursive epistemic market microstructure analysis? It refers to applying recursive game theory (players reasoning about others' reasoning) to financial microstructure (how prices form from individual trading decisions). The server models markets where each participant's beliefs about other participants' beliefs affect prices, creating higher-order feedback loops that classical models miss.

What is Soros reflexivity and how does this server detect it? George Soros's reflexivity theory holds that market prices affect the fundamentals they are supposed to reflect (e.g., rising prices improve credit ratings, which justify the higher prices). This server detects it mathematically by modeling p(t+1) = f(p(t), E[p(t+1)|p(t)]) and finding the fixed point p* via Picard iteration. A large reflexivity gap between p* and the observed price indicates active reflexive dynamics — a potential bubble or crash signal.

How accurate is the Hurst exponent estimate for rough volatility? The estimate is derived from log-variogram regression on publicly available price and exchange rate data. Empirical finance research consistently finds equity market Hurst exponents of 0.10-0.20, much rougher than the classical H=0.5 assumption. The estimate is calibrated to current data rather than long historical averages, making it responsive to changing microstructure conditions. Standard errors are not currently reported in the output.

What does a high PIN (Probability of Informed Trading) mean for an asset? PIN above 0.5 indicates that more than half of observed trading activity in the calibration sample is estimated to be information-motivated rather than liquidity-motivated. For the Kyle model, this corresponds to a high lambda (price impact per unit order flow) and lower price efficiency. High PIN assets typically see larger bid-ask spreads, greater adverse selection, and more volatile price discovery.

How is Sinkhorn divergence different from correlation or covariance? Sinkhorn divergence is an optimal transport metric between probability distributions — it measures the minimum cost of transforming one distribution into another. Unlike correlation, it is non-linear, handles multimodal distributions, and is sensitive to the geometric structure of the distributions rather than just their moments. A large Sinkhorn divergence between the current market regime and the STABLE regime means the two distributions are structurally different, not just correlated differently.

Can I use this with any MCP-compatible AI client? Yes. The server implements the standard MCP Streamable HTTP transport (stateless POST). Any client supporting MCP over HTTP will work: Claude Desktop, Cursor, Windsurf, Cline, LangChain's MCP adapter, LlamaIndex's MCP tool wrapper, or any custom client built against the MCP SDK.

How many tool calls does a typical research session use? A focused single-stock analysis using 4 tools (reflexivity, insider topology, rough volatility, belief hierarchy) costs $0.40. A comprehensive 8-tool suite costs $0.80. Daily sector scans calling detect_reflexive_dynamics across 5 sectors cost $0.50/day ($15/month). Most research users spend $5-20/month.

How is this different from Bloomberg or Refinitiv? Bloomberg Terminal and Refinitiv Eikon provide raw data; this server applies specific mathematical finance algorithms (Soros reflexivity, Kyle model, minority game, rough volatility) to public data and returns regime classifications and model outputs your AI agent can reason over directly. Bloomberg costs ~$2,000/month with no AI-native interface. This server costs $0.10 per analysis call with no subscription.

Does the minority game simulation change between runs for the same query? No. The scoring engine uses a seeded Mulberry32 pseudo-random number generator initialized from a hash of the input market data. Identical input data produces identical simulation results, making outputs reproducible and comparable across time.

Is it legal to use SEC EDGAR, FDIC, FRED, and the other data sources? Yes. All 16 data sources are official US government public databases or open market data APIs with no restrictions on programmatic access. SEC EDGAR, FRED, BLS, Federal Register, CFPB, and FDIC explicitly provide public API access. Congressional stock trades are published under the STOCK Act. See Apify's guide on web scraping legality.

What happens if a downstream actor is unavailable during a call? The actor client (actor-client.ts) wraps each downstream call in a try-catch. If any actor fails or times out, it returns an empty array for that data source rather than aborting the entire call. The algorithms proceed with whatever data is available. For forecast_fixed_point_price calling 16 actors, losing 1-2 sources typically has modest impact on the final output; losing the primary market data source (Finnhub) will significantly reduce the number of assets in the output.

Help us improve

If you encounter issues, you can help us debug faster by enabling run sharing in your Apify account:

  1. Go to Account Settings > Privacy
  2. Enable Share runs with public Actor creators

This lets us see your run details when something goes wrong, so we can fix issues faster. Your data is only visible to the actor developer, not publicly.

Support

Found a bug or have a feature request? Open an issue in the Issues tab on this actor's page. For custom solutions, additional algorithm implementations, or enterprise integrations, reach out through the Apify platform.

How it works

01

Configure

Set your parameters in the Apify Console or pass them via API.

02

Run

Click Start, trigger via API, webhook, or set up a schedule.

03

Get results

Download as JSON, CSV, or Excel. Integrate with 1,000+ apps.

Use cases

Sales Teams

Build targeted lead lists with verified contact data.

Marketing

Research competitors and identify outreach opportunities.

Data Teams

Automate data collection pipelines with scheduled runs.

Developers

Integrate via REST API or use as an MCP tool in AI workflows.

Ready to try Recursive Epistemic Market MCP Server?

Start for free on Apify. No credit card required.

Open on Apify Store