okama MCP
okama-mcp

MCP (Model Context Protocol) server that exposes the okama investment portfolio toolkit and okama Planner to AI assistants — Claude Desktop, Claude Code, Cursor, Codex, and any other MCP-compatible client.
With okama-mcp installed, you can ask an AI things like:
"Backtest a portfolio of 30% gold and 70% real estate over the last 15 years."
"Run a Monte Carlo retirement forecast on that portfolio, withdrawing $1,000/month indexed to inflation, over 25 years."
"What's the tangency portfolio of SPY, BND, and GLD with a 3% risk-free rate?"
…and the AI uses the MCP tools to call okama directly — no Python code needed.
Built on FastMCP. Single codebase, two transports:
stdio (for local clients) and streamable-http (for self-hosting).
okama-mcp is free and open source. Run it locally or on your own server. The HTTP
transport is intended for self-hosting; mcp.okama.io serves the project
landing page, not a public MCP endpoint. Client registry tools and Excel exports
require a compatible Planner companion and a configured local stdio installation.
Install
Development status (26 October 2026): main prepares MCP 3.1.0 with Planner
0.5.0; neither version has been published yet. Use the source setup below.
PyPI still provides MCP 3.0.0 with Planner 0.4.1 and its earlier contracts.
Requires Python ≥ 3.11 (same floor as okama itself); okama ≥ 4.0.0 and
okama-planner[reports]>=0.5.0,<0.6.0 are required.
Client data modes (source checkout): local MCP defaults to anonymous reads.
client_data_mode_set({"mode":"personal_data"}) enables full client CRUD;
{"mode":"anonymous"} disables client writes again. The setting persists per
database across connections. uv sync installs a pinned Planner 0.5.0 source
revision with the required access API. PyPI still provides Planner 0.4.1, so the prepared release remains blocked until the compatible companion is published;
see installation and release gates.
Market and finplan_* tools remain available independently. See the
3.0 migration notes for the earlier release behavior.
The easiest way — no clone, no venv — is uv or pipx:
uvx okama-mcp stdio # run straight from PyPI
# or
pipx install okama-mcpPlain pip works too:
pip install okama-mcpWith pip, prefer a dedicated virtual environment: on most modern Linux distros the
system Python is marked externally managed (PEP 668), so pip install outside a venv
fails, and a shared environment risks dependency conflicts. In your MCP client config,
point command at the absolute path of the okama-mcp script inside the venv — GUI
clients don't see your shell PATH. uvx and pipx avoid all of this by isolating
the install automatically.
To work on the code, install from source instead:
git clone https://github.com/mbk-dev/okama-mcp
cd okama-mcp
uv python install 3.14
uv sync --python 3.14 --all-groupsUntil Planner 0.5.0 is published, tool.uv.sources pins an immutable development
companion. Release gates use uv sync --all-groups --no-sources and require
published dependencies; no source substitution is used for publication.
Remove the development pin after published-pair acceptance passes.
Related MCP server: FinanceMarker MCP Server
Run
# stdio — for Claude Desktop, Claude Code, Cursor (local IPC)
okama-mcp stdio
# streamable HTTP — for self-hosting on your own server
okama-mcp http --host 127.0.0.1 --port 8765When running from a source checkout, prefix each command with uv run.
Each worktree has its own .venv; test and dev groups are installed by default.
uv.lock is generated locally and is not committed, so fresh checkouts resolve
compatible versions independently. Orca runs the bootstrap in orca.yaml before
starting the agent; its source MCP configuration uses uv run --no-sync after setup.
Connect a client
Claude Desktop
Edit ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or
%APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"okama": {
"command": "uvx",
"args": ["okama-mcp", "stdio"]
}
}
}Restart Claude Desktop; the server appears in the tools menu.
Claude Code
To make the server available in every project (works from any directory):
claude mcp add --scope user okama -- uvx okama-mcp stdioDevelopers running from a source checkout can use claude mcp add okama -- uv run okama-mcp stdio from the project root instead.
Or commit a .mcp.json at the project root so the whole team picks it up:
{
"mcpServers": {
"okama": {
"command": "uvx",
"args": ["okama-mcp", "stdio"]
}
}
}Cursor
Add the server to .cursor/mcp.json in your project (or ~/.cursor/mcp.json to make
it global):
{
"mcpServers": {
"okama": {
"command": "uvx",
"args": ["okama-mcp", "stdio"]
}
}
}Codex (CLI & Desktop)
Add the server with one command:
codex mcp add okama -- uvx okama-mcp stdioOr declare it in ~/.codex/config.toml (or a project-scoped .codex/config.toml
in trusted projects):
[mcp_servers.okama]
command = "uvx"
args = ["okama-mcp", "stdio"]The Codex CLI, desktop app, and IDE extension share this configuration — set it up once and it works in all three.
Self-hosting (streamable HTTP)
Run okama-mcp on your own server and share it across your MCP clients:
okama-mcp http --host 127.0.0.1 --port 8765 --path /mcp(From source: uv run okama-mcp http ...)
Then point your MCP client at http://<your-server>:8765/mcp. For a production
setup put nginx + TLS in front; ready-made examples live in deploy/:
deploy/systemd/okama-mcp.service— systemd unit (hardened, runs as a dedicated user)deploy/nginx/self-hosted.conf— nginx vhost: TLS, SSE-friendly proxying of/mcp
The server is open by design — free to run, no registration. If your instance must not be public, restrict access at the nginx level (allow-list, VPN, or HTTP basic auth).
Tool catalog
A multi-stage financial plan (contribute $1,000/month for 20 years into a 70/30 SPY/AGG portfolio, then withdraw $6,000/month indexed to inflation for 25 years), a Monte Carlo retirement forecast (30% gold / 70% real estate, withdrawing $1,000/month indexed to inflation over 25 years) and the efficient frontier of SPY/BND/GLD:



Financial tools are stateless — pass the full portfolio specification with every call.
Optional local client tools use stable registry codes and a persistent, database-scoped access mode.
Client creation is not idempotent: inspect the registry before retrying an ambiguous creation result.
The server caches expensive okama objects (Portfolio, EfficientFrontier) by content
hash, so repeated calls on the same spec are fast.
Nested portfolios. Wherever a list of assets is accepted — the assets field of
PortfolioSpec/FrontierSpec, or the portfolios argument on the comparison tools —
an entry may be a ticker string or a nested portfolio object (the same spec shape).
This lets you treat a whole portfolio as a single component: e.g. compare a 60/40
portfolio against gold, or put a sub-portfolio on the efficient frontier.
Search & metadata
Tool | Purpose |
| Search by name / local name / ticker / ISIN, with exact identifiers and names ranked first; follow |
| Show namespace descriptions plus |
| Metadata for one symbol — name, country, currency, type, date range. |
Single asset & comparisons
Tool | Purpose |
| Time series for one asset. |
| Side-by-side statistics ( |
| Correlation matrix of monthly returns. |
| Rolling annualized risk per asset. |
| Return metrics per asset: CAGR, cumulative return, mean / real mean return, monthly geometric mean, annual returns table. With |
| Rolling CAGR and rolling cumulative return per asset. |
| Beta, correlation, annualized tracking difference and tracking error of each asset vs a benchmark/index. |
| LTM dividend yield, 5y mean yield, paying/growing streaks per asset. |
Portfolio backtest
Tool | Purpose |
| Headline metrics (CAGR, annual mean/risk, Sharpe, Sortino) + full |
| Drawdown time series + max drawdown / recovery period. |
| Historical Value at Risk and CVaR. |
| Wealth-index series (cumulative growth of 1000). |
| Rolling CAGR time series (optionally inflation-adjusted). |
| Historical probability of CAGR below a target (e.g. of a loss) over N-year periods. |
Monte Carlo DCF
Tool | Purpose |
| Forward simulation with one of five cash-flow strategies ( |
| Historical money-weighted return (IRR) for a contribution/withdrawal plan. |
| Largest sustainable withdrawal (Monte Carlo) for a |
| Monte Carlo distribution of future cash flows over time (percentile bands). |
The mc argument accepts distribution_parameters to override the fitted distribution (e.g. a fixed Student-t df); see the MCSpec shape below.
Financial plan (multi-stage)
A plan is an ordered sequence of stages, each with its own portfolio, horizon and
cash-flow regime. Scenarios are chained: the balance a Monte Carlo scenario ends a
stage with is the balance it starts the next one with, so the retirement stage is
funded by whatever the accumulation stage produced in that same scenario — not by
a percentile of it. Use these instead of monte_carlo_forecast whenever the portfolio
or the contribution/withdrawal regime changes partway through the horizon.
Tool | Purpose |
| Monte Carlo forecast of the whole plan: percentile wealth bands, terminal-wealth stats, survival metrics, the share of scenarios finishing above |
| Replay the same plan over real history — a glide-path backtest. Requires the window covered by every stage portfolio to be at least as long as the plan. |
Distribution diagnostics
Tool | Purpose |
| Goodness-of-fit for the return distribution: fitted parameters, Jarque-Bera, Kolmogorov-Smirnov (chosen + all distributions), and backtesting error (theoretical vs empirical mean/VaR/CVaR). |
| Skewness & kurtosis time series — expanding, or rolling when a window (months) is given. |
| Degrees of freedom for a Student-t that best matches empirical VaR/CVaR. |
| Simulated CAGR at each percentile, plus the probability of a CAGR at/below |
DCF (historical cash-flow analysis)
Tool | Purpose |
| Historical wealth index with the cash-flow plan (FV nominal or PV discounted). |
| Historical contribution/withdrawal time series (FV or PV). |
| Historical wealth index for the portfolio and each underlying asset. |
| Historical longevity: survival period (years) and depletion date. |
| Present value (PV) and future value (FV) of the initial investment. |
Efficient Frontier
Tool | Purpose |
| Full EF point table (Risk / Mean return / CAGR + per-asset weights). |
| Max-Sharpe portfolio on the EF. |
| Global Minimum Variance portfolio. |
| Most Diversified Portfolio (maximises the diversification ratio) on the EF. |
Macro
Tool | Purpose |
| Inflation series for a currency ( |
| Central-bank policy rate ( |
| Macro indicator from the RATIO namespace (e.g. |
Charts
Each tool renders a PNG (default 1500×900) and returns it as MCP image content —
clients like Claude Desktop display it inline. Every chart tool also accepts
optional width / height (pixels, 300–4000) for custom sizes and aspect ratios,
and an optional save_path — the chart is then also written to that file and the
path reported back. Use save_path in clients that don't render MCP images in
their UI (e.g. Claude Code's terminal): ask for a chart "saved to /tmp/chart.png"
and open the file reference. Note: in self-hosted (streamable-http) deployments
save_path is written on the server's filesystem, not the client's machine.
Tool | Chart |
| Portfolio wealth index (+ inflation line). |
| Drawdown depth over time. |
| Monte Carlo forecast fan (percentile bands). |
| Financial-plan forecast fan: percentile bands with dashed stage boundaries and stage labels. |
| Histogram of IRR across Monte Carlo scenarios (percentile markers). |
| Q-Q plot of historical returns against the fitted distribution (norm/lognorm/t). |
| Histogram of historical returns with the fitted distribution PDF overlaid. |
| EF curve with individual asset points. |
| Transition map: asset weights along the efficient frontier (x-axis = risk or CAGR). |
| Wealth-index comparison of individual assets. |
| Line chart of inflation / central-bank rate / CAPE10 series. Overlay multiple symbols (e.g. |
Finding symbols and choosing tools
Start with list_namespaces(): its original namespaces description mapping is
preserved, and usage explains what each namespace supports. Use
search_assets(namespace="INDX") to browse an index catalog, or
search_assets(query="bitcoin", namespace="CC") for cryptocurrencies. Search rows
include namespace and supports_asset_returns (null when unknown).
Search is case-insensitive; exact symbol/ticker/ISIN matches rank first, then
exact names, prefixes and other matches. Scoped queries match punctuation
literally. With oldest_first=true, date order takes precedence. Symbol order
breaks ties. Results are ordered before paging: repeat the same query and filters
with offset=next_offset until has_more=false. count describes all filtered
matches; truncated means the current page is not the entire result set, including
the last page of a multi-page result. Pages reflect the current catalog, so data
updates between calls can move page boundaries.
RATE, INFL and RATIO are macroeconomic series. Read their values and metadata
with get_central_bank_rate, get_inflation and get_indicator, respectively.
For example, RUS_RUB.RATE describes a deposit rate, whereas OKID.INDX is an
investment-return index: they are different inputs. Asset tools reject a macro
symbol with the appropriate next call; they never replace it with an index.
Discover the intended index separately before comparing returns. Unknown upstream
namespaces have no advertised MCP routes until support is implemented.
Spec shapes
The complex tools accept JSON objects described by complete Pydantic-generated
input schemas in MCP tools/list: nested fields, required values, constraints,
defaults and cash-flow variants are visible to the client. Definitions live in
src/okama_mcp/schemas.py; here are the headline shapes:
// PortfolioSpec
{
"assets": ["GLD.US", "VNQ.US"], // each entry: a ticker OR a nested PortfolioSpec
"weights": [0.3, 0.7], // optional, must sum to 1.0
"ccy": "USD",
"first_date": "2010-01",
"last_date": "2024-12",
"rebalancing_strategy": { // mirrors okama.Rebalance
"period": "year", // month | quarter | half-year | year | none
"abs_deviation": 0.05, // optional, |actual - target| threshold, 0 < x <= 1
"rel_deviation": 0.1 // optional, |actual / target - 1| threshold, > 0
},
"inflation": true
}
// MCSpec
{
"distribution": "norm", // norm | lognorm | t
"period_years": 25,
"scenarios": 500, // ≥ 1, no upper limit
"percentiles": [5, 50, 95],
"random_seed": 42, // optional, for reproducibility
"distribution_parameters": null // optional; null = fit from history (MLE). Lengths: norm [mu, sigma]; lognorm/t [shape|df, loc, scale]. Any element null = fit that one (e.g. [4, null, null])
}
// CashflowSpec — discriminated by `type`
{ "type": "indexation", "initial_investment": 1000000, "frequency": "month", "amount": -1000, "indexation": "inflation" }
{ "type": "percentage", "initial_investment": 1000000, "frequency": "year", "percentage": -0.04 }
{ "type": "time_series", "initial_investment": 100000, "events": { "2030-06": -50000 }, "time_series_discounted_values": false }
{ "type": "vanguard", "initial_investment": 1000000, "percentage": -0.04, "floor_ceiling": [-0.025, 0.05], "indexation": "inflation" }
{ "type": "cut_if_drawdown", "initial_investment": 1000000, "frequency": "year", "amount": -60000, "indexation": "inflation",
"crash_threshold_reduction": [[0.2, 0.4], [0.5, 1.0]] }
// FinPlanSpec — a plan is a sequence of stages, chained per scenario
{
"stages": [
{ "portfolio": { "assets": ["SPY.US", "AGG.US"], "weights": [0.7, 0.3] },
"period_years": 20, "name": "accumulation",
"cashflow": { "type": "indexation", "initial_investment": 100000, "frequency": "year", "amount": 12000, "indexation": 0.03 } },
{ "portfolio": { "assets": ["SPY.US", "AGG.US"], "weights": [0.3, 0.7] },
"period_years": 25, "name": "retirement",
"distribution": "t", "distribution_parameters": [5, null, null],
"cashflow": { "type": "percentage", "initial_investment": 100000, "frequency": "year", "percentage": -0.04 } }
],
"initial_investment": 100000, // balance the first stage starts with
"discount_rate": null, // optional; null lets okama use inflation
"scenarios": 500,
"random_seed": 42, // optional
"percentiles": [10, 50, 90],
"name": "retirement plan"
}
// FrontierSpec
{
"assets": ["SPY.US", "BND.US", "GLD.US"],
"ccy": "USD",
"bounds": [[0.0, 0.7], [0.1, 1.0], [0.0, 0.3]], // optional
"n_points": 20,
"rebalancing_strategy": { "period": "year" },
"inflation": false
}
// Nesting — a portfolio used as a single component (works in PortfolioSpec /
// FrontierSpec `assets`, and the `portfolios` argument of the comparison tools):
{
"assets": [
"GLD.US",
{ "assets": ["SPY.US", "AGG.US"], "weights": [0.6, 0.4], "symbol": "bench6040.PF" }
],
"weights": [0.3, 0.7] // one weight per top-level entry
}Development
The project follows TDD (see AGENTS.md). After every code change run:
uv run pytest -q
uv run ruff check .To run the live-API integration test (hits api.okama.io):
uv run pytest -m integrationProject layout
src/okama_mcp/
├── server.py # FastMCP instance + registration entry point
├── transport.py # CLI: `okama-mcp stdio | http`
├── schemas.py # PortfolioSpec, MCSpec, CashflowSpec, FrontierSpec, FinPlanSpec
├── cache.py # TTL+LRU cache keyed by sha256 of canonical spec
├── serialization.py # pandas → JSON-safe with smart truncation
├── errors.py # Translate okama exceptions to actionable MCP errors
└── tools/
├── search.py, asset.py, asset_list.py
├── portfolio.py, monte_carlo.py, finplan.py
├── frontier.py, macro.py
└── plots.pyLicense
MIT — same license as okama itself.
Planner and local client workflows
Planner tools require a companion providing okama_planner.ai; local client
modes additionally require PlannerClientAccess. uv sync resolves the pinned
compatible source. Missing APIs fail closed. Configured local stdio exposes
17 client tools and Excel export (70 tools total); HTTP has no client or local report tools.
The default anonymous mode returns pseudonyms and refuses all persistent client
writes. Personal details are maintained in Planner. Call client_data_mode_set
with mode="personal_data" to read full records, create, update or delete clients,
and save residency notes and plan versions through Planner's API. Call it with
mode="anonymous" to return to anonymous access. client_data_mode_get shows the
saved mode, shared by connections using the same database and retained on restart.
Deletion includes the selected client's linked Planner records. Sparse updates
preserve omitted fields; explicit null clears an optional field where Planner
permits it. Forecasts and reports stay anonymous in both modes. Errors use fixed
messages without private values, database details or filesystem paths.
The legacy --allow-personal-data flag only initializes a missing saved setting;
it never overrides a mode explicitly saved through MCP. Meetings and bounded
history pages use the same access policy. The former packaged intake skill remains retired.
See configuration and tool contracts and
language behavior.
Explore the okama family
Tools for investing and financial planning.
Project | What it helps you do |
Explore portfolios with interactive web tools. | |
Analyze investments and portfolios in Python. | |
Access historical market and economic data. | |
Work with inflation and central-bank rate series. | |
Build financial plans and manage client planning history. |
Ask questions, share examples and discuss financial planning.
This server cannot be deployed
Maintenance
Related MCP Connectors
MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents
MCP server exposing the Backtest360 engine API as tools for AI agents.
- FensoryOAuthcom.fensory
Trading MCP server for AI agents, with live market data, account reads and controlled execution.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceFastMCP server exposing brokerage and market tools (Angel One, Coinbase, News) via the Model Context Protocol, enabling portfolio queries and trade execution through natural language.1MIT
- AlicenseNot gradedqualityDmaintenanceMCP server for integrating FinanceMarker.ru with LLM agents, IDEs, n8n, and other MCP-compatible clients. It proxies the FinanceMarker REST API and exposes it as a set of MCP tools.1 npmMIT

atpar-mcp-serverofficial
AlicenseAqualityDmaintenanceMCP server for the At Par Trading API — trade crypto, manage portfolios, and access market data from any MCP-compatible AI agent.16MIT
wealthapi-mcpofficial
AlicenseAqualityDmaintenanceMCP server that enables AI assistants to answer portfolio questions about a wealthAPI account, with read-only tools for accounts, transactions, investments, dividends, and market data.2130 npmMIT