polefinance-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ .output
14
+ .vinxi
15
+ .tanstack/**
16
+ .nitro
17
+ *.local
18
+
19
+ # Wrangler / Cloudflare
20
+ .wrangler/
21
+ .dev.vars
22
+
23
+ # Editor directories and files
24
+ .vscode/*
25
+ !.vscode/extensions.json
26
+ .idea
27
+ .DS_Store
28
+ *.suo
29
+ *.ntvs*
30
+ *.njsproj
31
+ *.sln
32
+ *.sw?
33
+ .env
34
+
35
+ # Supabase CLI local state (project ref, cached versions) — machine-local, not shared config
36
+ supabase/.temp/
37
+
38
+ # Local R2/S3 emulator data (bun run r2:local)
39
+ .s3rver-data/
40
+
41
+ # Python bytecode from the quant reference implementation. The fixtures it generates ARE
42
+ # committed — they are the contract the TS suite is tested against — but the cache is not.
43
+ __pycache__/
44
+ *.py[cod]
45
+ *.egg-info/
46
+
47
+ # Python virtualenvs (python-sdk, mcp-server) — created locally with `uv venv`, never committed.
48
+ .venv/
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.5
2
+ Name: polefinance-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for the Pôle Finance public API — exchanges, instruments, quotes, technical indicators, risk metrics, portfolio optimization and backtests.
5
+ Author: PoleFinance
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Typing :: Typed
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: mcp<3,>=2.0
11
+ Requires-Dist: polefinance>=0.1.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'test'
14
+ Requires-Dist: pytest>=7; extra == 'test'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # polefinance-mcp
18
+
19
+ MCP server for the [Pôle Finance public API](https://polefinance-invest.com/developers/docs) —
20
+ exchanges, instruments, delayed quotes (once enabled), technical indicators, risk metrics,
21
+ portfolio optimization and backtests. A thin wrapper over the official
22
+ [`polefinance`](../python-sdk) Python SDK: every tool call hits the real API with your own key;
23
+ nothing is computed or fabricated here.
24
+
25
+ ## Install
26
+
27
+ **From PyPI (recommended — no repo access needed):**
28
+
29
+ ```bash
30
+ uv pip install polefinance-mcp
31
+ ```
32
+
33
+ **From source (for contributors working on this repo):**
34
+
35
+ ```bash
36
+ cd mcp-server
37
+ uv venv
38
+ source .venv/bin/activate
39
+ uv pip install -e ../python-sdk -e .
40
+ ```
41
+
42
+ ## Get an API key
43
+
44
+ Create a project and key at https://polefinance-invest.com/developers/dashboard (scopes
45
+ `instruments:read` and `analytics:compute` cover every tool below except quotes, which also
46
+ needs `market_data:read` and is not yet enabled in production).
47
+
48
+ ## Run it
49
+
50
+ ```bash
51
+ POLEFINANCE_API_KEY=pf_live_... polefinance-mcp
52
+ ```
53
+
54
+ This starts a stdio MCP server — it's meant to be launched by an MCP client, not run standalone
55
+ in a terminal for long.
56
+
57
+ ## Configure a client
58
+
59
+ **Claude Desktop / Claude Code** — add to the client's MCP config (e.g.
60
+ `claude_desktop_config.json`):
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "polefinance": {
66
+ "command": "polefinance-mcp",
67
+ "env": { "POLEFINANCE_API_KEY": "pf_live_..." }
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ If `polefinance-mcp` isn't on the client's PATH, point `command` at the venv's copy instead, e.g.
74
+ `"/absolute/path/to/mcp-server/.venv/bin/polefinance-mcp"`.
75
+
76
+ ## Tools
77
+
78
+ | Tool | Scope needed | Maps to |
79
+ |---|---|---|
80
+ | `list_exchanges` | `instruments:read` | `GET /exchanges` |
81
+ | `search_instruments` | `instruments:read` | `GET /instruments` |
82
+ | `get_instrument` | `instruments:read` | `GET /instruments/{id}` |
83
+ | `get_quotes` | `market_data:read` (disabled in prod) | `GET /market-data/quotes` |
84
+ | `compute_technical_indicators` | `analytics:compute` | `POST /technical/indicators` |
85
+ | `compute_risk_metrics` | `analytics:compute` | `POST /risk/metrics` |
86
+ | `optimize_portfolio` | `analytics:compute` | `POST /optimization/portfolio` |
87
+ | `run_backtest` | `analytics:compute` | `POST /backtests/run` |
88
+
89
+ The four `analytics:compute` tools are rate-limited to 10 calls/minute per key and accept at most
90
+ 10 assets × 2,520 bars (same limits as the API itself — see `../docs/DEVELOPER_PLATFORM.md`).
91
+
92
+ ## Tests
93
+
94
+ ```bash
95
+ cd mcp-server && source .venv/bin/activate && pytest
96
+ ```
97
+
98
+ The tests only check that the server starts and the tool list/schemas are well-formed — they do
99
+ not call the live API (no key is required to run them).
@@ -0,0 +1,83 @@
1
+ # polefinance-mcp
2
+
3
+ MCP server for the [Pôle Finance public API](https://polefinance-invest.com/developers/docs) —
4
+ exchanges, instruments, delayed quotes (once enabled), technical indicators, risk metrics,
5
+ portfolio optimization and backtests. A thin wrapper over the official
6
+ [`polefinance`](../python-sdk) Python SDK: every tool call hits the real API with your own key;
7
+ nothing is computed or fabricated here.
8
+
9
+ ## Install
10
+
11
+ **From PyPI (recommended — no repo access needed):**
12
+
13
+ ```bash
14
+ uv pip install polefinance-mcp
15
+ ```
16
+
17
+ **From source (for contributors working on this repo):**
18
+
19
+ ```bash
20
+ cd mcp-server
21
+ uv venv
22
+ source .venv/bin/activate
23
+ uv pip install -e ../python-sdk -e .
24
+ ```
25
+
26
+ ## Get an API key
27
+
28
+ Create a project and key at https://polefinance-invest.com/developers/dashboard (scopes
29
+ `instruments:read` and `analytics:compute` cover every tool below except quotes, which also
30
+ needs `market_data:read` and is not yet enabled in production).
31
+
32
+ ## Run it
33
+
34
+ ```bash
35
+ POLEFINANCE_API_KEY=pf_live_... polefinance-mcp
36
+ ```
37
+
38
+ This starts a stdio MCP server — it's meant to be launched by an MCP client, not run standalone
39
+ in a terminal for long.
40
+
41
+ ## Configure a client
42
+
43
+ **Claude Desktop / Claude Code** — add to the client's MCP config (e.g.
44
+ `claude_desktop_config.json`):
45
+
46
+ ```json
47
+ {
48
+ "mcpServers": {
49
+ "polefinance": {
50
+ "command": "polefinance-mcp",
51
+ "env": { "POLEFINANCE_API_KEY": "pf_live_..." }
52
+ }
53
+ }
54
+ }
55
+ ```
56
+
57
+ If `polefinance-mcp` isn't on the client's PATH, point `command` at the venv's copy instead, e.g.
58
+ `"/absolute/path/to/mcp-server/.venv/bin/polefinance-mcp"`.
59
+
60
+ ## Tools
61
+
62
+ | Tool | Scope needed | Maps to |
63
+ |---|---|---|
64
+ | `list_exchanges` | `instruments:read` | `GET /exchanges` |
65
+ | `search_instruments` | `instruments:read` | `GET /instruments` |
66
+ | `get_instrument` | `instruments:read` | `GET /instruments/{id}` |
67
+ | `get_quotes` | `market_data:read` (disabled in prod) | `GET /market-data/quotes` |
68
+ | `compute_technical_indicators` | `analytics:compute` | `POST /technical/indicators` |
69
+ | `compute_risk_metrics` | `analytics:compute` | `POST /risk/metrics` |
70
+ | `optimize_portfolio` | `analytics:compute` | `POST /optimization/portfolio` |
71
+ | `run_backtest` | `analytics:compute` | `POST /backtests/run` |
72
+
73
+ The four `analytics:compute` tools are rate-limited to 10 calls/minute per key and accept at most
74
+ 10 assets × 2,520 bars (same limits as the API itself — see `../docs/DEVELOPER_PLATFORM.md`).
75
+
76
+ ## Tests
77
+
78
+ ```bash
79
+ cd mcp-server && source .venv/bin/activate && pytest
80
+ ```
81
+
82
+ The tests only check that the server starts and the tool list/schemas are well-formed — they do
83
+ not call the live API (no key is required to run them).
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "polefinance-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for the Pôle Finance public API — exchanges, instruments, quotes, technical indicators, risk metrics, portfolio optimization and backtests."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "PoleFinance" }]
13
+ dependencies = ["mcp>=2.0,<3", "polefinance>=0.1.0"]
14
+ classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed"]
15
+
16
+ [project.scripts]
17
+ polefinance-mcp = "polefinance_mcp.server:main"
18
+
19
+ [project.optional-dependencies]
20
+ test = ["pytest>=7", "pytest-asyncio>=0.21"]
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/polefinance_mcp"]
24
+
25
+ [tool.pytest.ini_options]
26
+ asyncio_mode = "auto"
27
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,3 @@
1
+ from .server import main, server
2
+
3
+ __all__ = ["main", "server"]
@@ -0,0 +1,181 @@
1
+ """MCP server exposing the Pôle Finance public API as tools.
2
+
3
+ Thin wrapper around the already-published `polefinance` Python SDK (`python-sdk/`) — no HTTP
4
+ logic duplicated here. Every tool call goes through the real API at polefinance-invest.com,
5
+ using the caller's own API key (read from POLEFINANCE_API_KEY, same as the SDK). Nothing here
6
+ fabricates data: a tool returns exactly what the API returns, or raises the API's own error.
7
+
8
+ Run locally (stdio transport, for Claude Desktop / Claude Code / any MCP client):
9
+
10
+ POLEFINANCE_API_KEY=pf_live_... uv run polefinance-mcp
11
+
12
+ See README.md for client configuration.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import asdict
18
+ from typing import Any, Dict, List, Optional
19
+
20
+ from mcp.server.mcpserver import MCPServer
21
+ from polefinance import PermissionDeniedError, PoleFinance, PoleFinanceError
22
+
23
+ server = MCPServer(
24
+ name="polefinance",
25
+ instructions=(
26
+ "Tools for the BRVM/UEMOA market and quantitative analytics exposed by the Pôle Finance "
27
+ "public API (https://polefinance-invest.com/developers/docs). Reference data (exchanges, "
28
+ "instruments) needs scope instruments:read; quotes need market_data:read and are not yet "
29
+ "available in production; the compute tools (technical indicators, risk metrics, portfolio "
30
+ "optimization, backtests) need scope analytics:compute and run on price/return series the "
31
+ "caller supplies — they do not fetch market data themselves. All compute tools are rate-"
32
+ "limited to 10 calls/minute per key and accept at most 10 assets × 2,520 bars."
33
+ ),
34
+ )
35
+
36
+
37
+ def _client() -> PoleFinance:
38
+ # Reads POLEFINANCE_API_KEY itself if api_key is omitted — fails fast with a clear message
39
+ # if neither is set, rather than letting a vague 401 surface later.
40
+ return PoleFinance()
41
+
42
+
43
+ def _err(e: PoleFinanceError) -> str:
44
+ return str(e)
45
+
46
+
47
+ @server.tool()
48
+ def list_exchanges() -> List[Dict[str, Any]]:
49
+ """List the exchanges covered by Pôle Finance (currently BRVM), with instrument counts."""
50
+ with _client() as c:
51
+ return [asdict(ex) for ex in c.exchanges.list()]
52
+
53
+
54
+ @server.tool()
55
+ def search_instruments(
56
+ q: Optional[str] = None,
57
+ exchange: Optional[str] = None,
58
+ limit: int = 20,
59
+ ) -> List[Dict[str, Any]]:
60
+ """Search instruments by name/symbol, optionally filtered to one exchange (e.g. "BRVM").
61
+
62
+ Use this to find an instrument's id (e.g. "BRVM:SNTS") before calling get_instrument or
63
+ the compute tools.
64
+ """
65
+ with _client() as c:
66
+ return [asdict(i) for i in c.instruments.search(q or "", exchange=exchange, limit=limit)]
67
+
68
+
69
+ @server.tool()
70
+ def get_instrument(instrument_id: str) -> Dict[str, Any]:
71
+ """Get one instrument by id (e.g. "BRVM:SNTS")."""
72
+ with _client() as c:
73
+ return asdict(c.instruments.get(instrument_id))
74
+
75
+
76
+ @server.tool()
77
+ def get_quotes(instrument_ids: List[str]) -> List[Dict[str, Any]]:
78
+ """Latest delayed quotes for the given instrument ids.
79
+
80
+ Market data is currently disabled in production (pending redistribution rights) — this will
81
+ raise a permission error until Pôle Finance turns it on; it is not a bug in this tool.
82
+ """
83
+ with _client() as c:
84
+ try:
85
+ return [asdict(q) for q in c.market_data.quotes(instrument_ids)]
86
+ except PermissionDeniedError as e:
87
+ raise RuntimeError(f"Market data not available yet: {_err(e)}") from e
88
+
89
+
90
+ @server.tool()
91
+ def compute_technical_indicators(
92
+ close: List[float],
93
+ indicators: List[Dict[str, Any]],
94
+ high: Optional[List[float]] = None,
95
+ low: Optional[List[float]] = None,
96
+ ) -> Dict[str, Any]:
97
+ """SMA, EMA, RSI, MACD, Bollinger or ATR on a price series you supply.
98
+
99
+ `indicators` is a list like [{"name": "rsi", "period": 14}, {"name": "sma", "period": 20}].
100
+ ATR needs `high` and `low` alongside `close`. Values are null during the warm-up window.
101
+ """
102
+ with _client() as c:
103
+ body: Dict[str, Any] = {"close": close, "indicators": indicators}
104
+ if high is not None:
105
+ body["high"] = high
106
+ if low is not None:
107
+ body["low"] = low
108
+ return c.technical(**body)
109
+
110
+
111
+ @server.tool()
112
+ def compute_risk_metrics(
113
+ prices: List[float],
114
+ periods_per_year: int = 252,
115
+ risk_free_rate: float = 0.0,
116
+ confidence: float = 0.95,
117
+ ) -> Dict[str, Any]:
118
+ """Volatility, Sharpe, Sortino, max drawdown, historical VaR and ES on a price series."""
119
+ with _client() as c:
120
+ return c.risk(
121
+ prices=prices,
122
+ periods_per_year=periods_per_year,
123
+ risk_free_rate=risk_free_rate,
124
+ confidence=confidence,
125
+ )
126
+
127
+
128
+ @server.tool()
129
+ def optimize_portfolio(
130
+ returns_by_id: Dict[str, List[float]],
131
+ method: str = "min_variance",
132
+ periods_per_year: Optional[int] = None,
133
+ risk_free_rate: Optional[float] = None,
134
+ ) -> Dict[str, Any]:
135
+ """Long-only portfolio weights from each asset's return series.
136
+
137
+ `returns_by_id` maps an instrument id (or any label) to its list of period returns — e.g.
138
+ {"BRVM:SNTS": [0.01, -0.004, 0.006], "BRVM:ORAC": [0.002, 0.003, -0.001]}. `method` is one of
139
+ min_variance, max_sharpe, risk_parity, equal_weight. Returns weights, expected risk/return and
140
+ any warnings (e.g. a short history).
141
+ """
142
+ with _client() as c:
143
+ return c.optimization.portfolio(
144
+ returns_by_id,
145
+ method=method,
146
+ periods_per_year=periods_per_year,
147
+ risk_free_rate=risk_free_rate,
148
+ )
149
+
150
+
151
+ @server.tool()
152
+ def run_backtest(
153
+ dates: List[str],
154
+ assets: List[Dict[str, Any]],
155
+ strategy: str = "min_variance",
156
+ rebalance: str = "monthly",
157
+ fees: float = 0.0,
158
+ ) -> Dict[str, Any]:
159
+ """Backtest a strategy on price series you supply: metrics, equity curve, drawdown, allocations.
160
+
161
+ `assets` is a list like [{"id": "BRVM:SNTS", "closes": [17500, 17550, ...]}, ...], aligned to
162
+ `dates` (one close per date, per asset). `fees` is a one-way rate (e.g. 0.012 for 1.2%) — pass
163
+ the real rate for whichever broker/market the series represents; do not leave it at 0 and
164
+ call the result cost-free.
165
+ """
166
+ with _client() as c:
167
+ return c.backtests(
168
+ dates=dates,
169
+ assets=assets,
170
+ strategy=strategy,
171
+ rebalance=rebalance,
172
+ fees=fees,
173
+ )
174
+
175
+
176
+ def main() -> None:
177
+ server.run()
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
@@ -0,0 +1,35 @@
1
+ """No live API calls here — these only check that the server starts and its tool schemas are
2
+ well-formed, so CI doesn't need a real POLEFINANCE_API_KEY."""
3
+
4
+ import pytest
5
+
6
+ from polefinance_mcp.server import server
7
+
8
+ EXPECTED_TOOLS = {
9
+ "list_exchanges",
10
+ "search_instruments",
11
+ "get_instrument",
12
+ "get_quotes",
13
+ "compute_technical_indicators",
14
+ "compute_risk_metrics",
15
+ "optimize_portfolio",
16
+ "run_backtest",
17
+ }
18
+
19
+
20
+ @pytest.mark.asyncio
21
+ async def test_lists_every_tool_with_a_description():
22
+ tools = await server.list_tools()
23
+ names = {t.name for t in tools}
24
+ assert names == EXPECTED_TOOLS
25
+ for t in tools:
26
+ assert t.description, f"{t.name} has no description"
27
+ assert t.input_schema.get("type") == "object"
28
+
29
+
30
+ @pytest.mark.asyncio
31
+ async def test_search_instruments_schema_has_defaults():
32
+ tools = await server.list_tools()
33
+ by_name = {t.name: t for t in tools}
34
+ props = by_name["search_instruments"].input_schema["properties"]
35
+ assert "q" in props and "exchange" in props and "limit" in props